libbpf.c 390 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592
  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 "libbpf_internal.h"
  51. #include "hashmap.h"
  52. #include "bpf_gen_internal.h"
  53. #include "zip.h"
  54. #ifndef BPF_FS_MAGIC
  55. #define BPF_FS_MAGIC 0xcafe4a11
  56. #endif
  57. #define MAX_EVENT_NAME_LEN 64
  58. #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
  59. #define BPF_INSN_SZ (sizeof(struct bpf_insn))
  60. /* vsprintf() in __base_pr() uses nonliteral format string. It may break
  61. * compilation if user enables corresponding warning. Disable it explicitly.
  62. */
  63. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  64. #define __printf(a, b) __attribute__((format(printf, a, b)))
  65. static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
  66. static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
  67. static int map_set_def_max_entries(struct bpf_map *map);
  68. static const char * const attach_type_name[] = {
  69. [BPF_CGROUP_INET_INGRESS] = "cgroup_inet_ingress",
  70. [BPF_CGROUP_INET_EGRESS] = "cgroup_inet_egress",
  71. [BPF_CGROUP_INET_SOCK_CREATE] = "cgroup_inet_sock_create",
  72. [BPF_CGROUP_INET_SOCK_RELEASE] = "cgroup_inet_sock_release",
  73. [BPF_CGROUP_SOCK_OPS] = "cgroup_sock_ops",
  74. [BPF_CGROUP_DEVICE] = "cgroup_device",
  75. [BPF_CGROUP_INET4_BIND] = "cgroup_inet4_bind",
  76. [BPF_CGROUP_INET6_BIND] = "cgroup_inet6_bind",
  77. [BPF_CGROUP_INET4_CONNECT] = "cgroup_inet4_connect",
  78. [BPF_CGROUP_INET6_CONNECT] = "cgroup_inet6_connect",
  79. [BPF_CGROUP_UNIX_CONNECT] = "cgroup_unix_connect",
  80. [BPF_CGROUP_INET4_POST_BIND] = "cgroup_inet4_post_bind",
  81. [BPF_CGROUP_INET6_POST_BIND] = "cgroup_inet6_post_bind",
  82. [BPF_CGROUP_INET4_GETPEERNAME] = "cgroup_inet4_getpeername",
  83. [BPF_CGROUP_INET6_GETPEERNAME] = "cgroup_inet6_getpeername",
  84. [BPF_CGROUP_UNIX_GETPEERNAME] = "cgroup_unix_getpeername",
  85. [BPF_CGROUP_INET4_GETSOCKNAME] = "cgroup_inet4_getsockname",
  86. [BPF_CGROUP_INET6_GETSOCKNAME] = "cgroup_inet6_getsockname",
  87. [BPF_CGROUP_UNIX_GETSOCKNAME] = "cgroup_unix_getsockname",
  88. [BPF_CGROUP_UDP4_SENDMSG] = "cgroup_udp4_sendmsg",
  89. [BPF_CGROUP_UDP6_SENDMSG] = "cgroup_udp6_sendmsg",
  90. [BPF_CGROUP_UNIX_SENDMSG] = "cgroup_unix_sendmsg",
  91. [BPF_CGROUP_SYSCTL] = "cgroup_sysctl",
  92. [BPF_CGROUP_UDP4_RECVMSG] = "cgroup_udp4_recvmsg",
  93. [BPF_CGROUP_UDP6_RECVMSG] = "cgroup_udp6_recvmsg",
  94. [BPF_CGROUP_UNIX_RECVMSG] = "cgroup_unix_recvmsg",
  95. [BPF_CGROUP_GETSOCKOPT] = "cgroup_getsockopt",
  96. [BPF_CGROUP_SETSOCKOPT] = "cgroup_setsockopt",
  97. [BPF_SK_SKB_STREAM_PARSER] = "sk_skb_stream_parser",
  98. [BPF_SK_SKB_STREAM_VERDICT] = "sk_skb_stream_verdict",
  99. [BPF_SK_SKB_VERDICT] = "sk_skb_verdict",
  100. [BPF_SK_MSG_VERDICT] = "sk_msg_verdict",
  101. [BPF_LIRC_MODE2] = "lirc_mode2",
  102. [BPF_FLOW_DISSECTOR] = "flow_dissector",
  103. [BPF_TRACE_RAW_TP] = "trace_raw_tp",
  104. [BPF_TRACE_FENTRY] = "trace_fentry",
  105. [BPF_TRACE_FEXIT] = "trace_fexit",
  106. [BPF_MODIFY_RETURN] = "modify_return",
  107. [BPF_TRACE_FSESSION] = "trace_fsession",
  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. [BPF_TRACE_UPROBE_SESSION] = "trace_uprobe_session",
  128. };
  129. static const char * const link_type_name[] = {
  130. [BPF_LINK_TYPE_UNSPEC] = "unspec",
  131. [BPF_LINK_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
  132. [BPF_LINK_TYPE_TRACING] = "tracing",
  133. [BPF_LINK_TYPE_CGROUP] = "cgroup",
  134. [BPF_LINK_TYPE_ITER] = "iter",
  135. [BPF_LINK_TYPE_NETNS] = "netns",
  136. [BPF_LINK_TYPE_XDP] = "xdp",
  137. [BPF_LINK_TYPE_PERF_EVENT] = "perf_event",
  138. [BPF_LINK_TYPE_KPROBE_MULTI] = "kprobe_multi",
  139. [BPF_LINK_TYPE_STRUCT_OPS] = "struct_ops",
  140. [BPF_LINK_TYPE_NETFILTER] = "netfilter",
  141. [BPF_LINK_TYPE_TCX] = "tcx",
  142. [BPF_LINK_TYPE_UPROBE_MULTI] = "uprobe_multi",
  143. [BPF_LINK_TYPE_NETKIT] = "netkit",
  144. [BPF_LINK_TYPE_SOCKMAP] = "sockmap",
  145. };
  146. static const char * const map_type_name[] = {
  147. [BPF_MAP_TYPE_UNSPEC] = "unspec",
  148. [BPF_MAP_TYPE_HASH] = "hash",
  149. [BPF_MAP_TYPE_ARRAY] = "array",
  150. [BPF_MAP_TYPE_PROG_ARRAY] = "prog_array",
  151. [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
  152. [BPF_MAP_TYPE_PERCPU_HASH] = "percpu_hash",
  153. [BPF_MAP_TYPE_PERCPU_ARRAY] = "percpu_array",
  154. [BPF_MAP_TYPE_STACK_TRACE] = "stack_trace",
  155. [BPF_MAP_TYPE_CGROUP_ARRAY] = "cgroup_array",
  156. [BPF_MAP_TYPE_LRU_HASH] = "lru_hash",
  157. [BPF_MAP_TYPE_LRU_PERCPU_HASH] = "lru_percpu_hash",
  158. [BPF_MAP_TYPE_LPM_TRIE] = "lpm_trie",
  159. [BPF_MAP_TYPE_ARRAY_OF_MAPS] = "array_of_maps",
  160. [BPF_MAP_TYPE_HASH_OF_MAPS] = "hash_of_maps",
  161. [BPF_MAP_TYPE_DEVMAP] = "devmap",
  162. [BPF_MAP_TYPE_DEVMAP_HASH] = "devmap_hash",
  163. [BPF_MAP_TYPE_SOCKMAP] = "sockmap",
  164. [BPF_MAP_TYPE_CPUMAP] = "cpumap",
  165. [BPF_MAP_TYPE_XSKMAP] = "xskmap",
  166. [BPF_MAP_TYPE_SOCKHASH] = "sockhash",
  167. [BPF_MAP_TYPE_CGROUP_STORAGE] = "cgroup_storage",
  168. [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY] = "reuseport_sockarray",
  169. [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE] = "percpu_cgroup_storage",
  170. [BPF_MAP_TYPE_QUEUE] = "queue",
  171. [BPF_MAP_TYPE_STACK] = "stack",
  172. [BPF_MAP_TYPE_SK_STORAGE] = "sk_storage",
  173. [BPF_MAP_TYPE_STRUCT_OPS] = "struct_ops",
  174. [BPF_MAP_TYPE_RINGBUF] = "ringbuf",
  175. [BPF_MAP_TYPE_INODE_STORAGE] = "inode_storage",
  176. [BPF_MAP_TYPE_TASK_STORAGE] = "task_storage",
  177. [BPF_MAP_TYPE_BLOOM_FILTER] = "bloom_filter",
  178. [BPF_MAP_TYPE_USER_RINGBUF] = "user_ringbuf",
  179. [BPF_MAP_TYPE_CGRP_STORAGE] = "cgrp_storage",
  180. [BPF_MAP_TYPE_ARENA] = "arena",
  181. [BPF_MAP_TYPE_INSN_ARRAY] = "insn_array",
  182. };
  183. static const char * const prog_type_name[] = {
  184. [BPF_PROG_TYPE_UNSPEC] = "unspec",
  185. [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
  186. [BPF_PROG_TYPE_KPROBE] = "kprobe",
  187. [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
  188. [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
  189. [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
  190. [BPF_PROG_TYPE_XDP] = "xdp",
  191. [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
  192. [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
  193. [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
  194. [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
  195. [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
  196. [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
  197. [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
  198. [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
  199. [BPF_PROG_TYPE_CGROUP_DEVICE] = "cgroup_device",
  200. [BPF_PROG_TYPE_SK_MSG] = "sk_msg",
  201. [BPF_PROG_TYPE_RAW_TRACEPOINT] = "raw_tracepoint",
  202. [BPF_PROG_TYPE_CGROUP_SOCK_ADDR] = "cgroup_sock_addr",
  203. [BPF_PROG_TYPE_LWT_SEG6LOCAL] = "lwt_seg6local",
  204. [BPF_PROG_TYPE_LIRC_MODE2] = "lirc_mode2",
  205. [BPF_PROG_TYPE_SK_REUSEPORT] = "sk_reuseport",
  206. [BPF_PROG_TYPE_FLOW_DISSECTOR] = "flow_dissector",
  207. [BPF_PROG_TYPE_CGROUP_SYSCTL] = "cgroup_sysctl",
  208. [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
  209. [BPF_PROG_TYPE_CGROUP_SOCKOPT] = "cgroup_sockopt",
  210. [BPF_PROG_TYPE_TRACING] = "tracing",
  211. [BPF_PROG_TYPE_STRUCT_OPS] = "struct_ops",
  212. [BPF_PROG_TYPE_EXT] = "ext",
  213. [BPF_PROG_TYPE_LSM] = "lsm",
  214. [BPF_PROG_TYPE_SK_LOOKUP] = "sk_lookup",
  215. [BPF_PROG_TYPE_SYSCALL] = "syscall",
  216. [BPF_PROG_TYPE_NETFILTER] = "netfilter",
  217. };
  218. static int __base_pr(enum libbpf_print_level level, const char *format,
  219. va_list args)
  220. {
  221. const char *env_var = "LIBBPF_LOG_LEVEL";
  222. static enum libbpf_print_level min_level = LIBBPF_INFO;
  223. static bool initialized;
  224. if (!initialized) {
  225. char *verbosity;
  226. initialized = true;
  227. verbosity = getenv(env_var);
  228. if (verbosity) {
  229. if (strcasecmp(verbosity, "warn") == 0)
  230. min_level = LIBBPF_WARN;
  231. else if (strcasecmp(verbosity, "debug") == 0)
  232. min_level = LIBBPF_DEBUG;
  233. else if (strcasecmp(verbosity, "info") == 0)
  234. min_level = LIBBPF_INFO;
  235. else
  236. fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
  237. env_var, verbosity);
  238. }
  239. }
  240. /* if too verbose, skip logging */
  241. if (level > min_level)
  242. return 0;
  243. return vfprintf(stderr, format, args);
  244. }
  245. static libbpf_print_fn_t __libbpf_pr = __base_pr;
  246. libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
  247. {
  248. libbpf_print_fn_t old_print_fn;
  249. old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
  250. return old_print_fn;
  251. }
  252. __printf(2, 3)
  253. void libbpf_print(enum libbpf_print_level level, const char *format, ...)
  254. {
  255. va_list args;
  256. int old_errno;
  257. libbpf_print_fn_t print_fn;
  258. print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
  259. if (!print_fn)
  260. return;
  261. old_errno = errno;
  262. va_start(args, format);
  263. print_fn(level, format, args);
  264. va_end(args);
  265. errno = old_errno;
  266. }
  267. static void pr_perm_msg(int err)
  268. {
  269. struct rlimit limit;
  270. char buf[100];
  271. if (err != -EPERM || geteuid() != 0)
  272. return;
  273. err = getrlimit(RLIMIT_MEMLOCK, &limit);
  274. if (err)
  275. return;
  276. if (limit.rlim_cur == RLIM_INFINITY)
  277. return;
  278. if (limit.rlim_cur < 1024)
  279. snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
  280. else if (limit.rlim_cur < 1024*1024)
  281. snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
  282. else
  283. snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
  284. pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
  285. buf);
  286. }
  287. /* Copied from tools/perf/util/util.h */
  288. #ifndef zfree
  289. # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
  290. #endif
  291. #ifndef zclose
  292. # define zclose(fd) ({ \
  293. int ___err = 0; \
  294. if ((fd) >= 0) \
  295. ___err = close((fd)); \
  296. fd = -1; \
  297. ___err; })
  298. #endif
  299. static inline __u64 ptr_to_u64(const void *ptr)
  300. {
  301. return (__u64) (unsigned long) ptr;
  302. }
  303. int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
  304. {
  305. /* as of v1.0 libbpf_set_strict_mode() is a no-op */
  306. return 0;
  307. }
  308. __u32 libbpf_major_version(void)
  309. {
  310. return LIBBPF_MAJOR_VERSION;
  311. }
  312. __u32 libbpf_minor_version(void)
  313. {
  314. return LIBBPF_MINOR_VERSION;
  315. }
  316. const char *libbpf_version_string(void)
  317. {
  318. #define __S(X) #X
  319. #define _S(X) __S(X)
  320. return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
  321. #undef _S
  322. #undef __S
  323. }
  324. enum reloc_type {
  325. RELO_LD64,
  326. RELO_CALL,
  327. RELO_DATA,
  328. RELO_EXTERN_LD64,
  329. RELO_EXTERN_CALL,
  330. RELO_SUBPROG_ADDR,
  331. RELO_CORE,
  332. RELO_INSN_ARRAY,
  333. };
  334. struct reloc_desc {
  335. enum reloc_type type;
  336. int insn_idx;
  337. union {
  338. const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
  339. struct {
  340. int map_idx;
  341. unsigned int sym_off;
  342. /*
  343. * The following two fields can be unionized, as the
  344. * ext_idx field is used for extern symbols, and the
  345. * sym_size is used for jump tables, which are never
  346. * extern
  347. */
  348. union {
  349. int ext_idx;
  350. int sym_size;
  351. };
  352. };
  353. };
  354. };
  355. /* stored as sec_def->cookie for all libbpf-supported SEC()s */
  356. enum sec_def_flags {
  357. SEC_NONE = 0,
  358. /* expected_attach_type is optional, if kernel doesn't support that */
  359. SEC_EXP_ATTACH_OPT = 1,
  360. /* legacy, only used by libbpf_get_type_names() and
  361. * libbpf_attach_type_by_name(), not used by libbpf itself at all.
  362. * This used to be associated with cgroup (and few other) BPF programs
  363. * that were attachable through BPF_PROG_ATTACH command. Pretty
  364. * meaningless nowadays, though.
  365. */
  366. SEC_ATTACHABLE = 2,
  367. SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
  368. /* attachment target is specified through BTF ID in either kernel or
  369. * other BPF program's BTF object
  370. */
  371. SEC_ATTACH_BTF = 4,
  372. /* BPF program type allows sleeping/blocking in kernel */
  373. SEC_SLEEPABLE = 8,
  374. /* BPF program support non-linear XDP buffer */
  375. SEC_XDP_FRAGS = 16,
  376. /* Setup proper attach type for usdt probes. */
  377. SEC_USDT = 32,
  378. };
  379. struct bpf_sec_def {
  380. char *sec;
  381. enum bpf_prog_type prog_type;
  382. enum bpf_attach_type expected_attach_type;
  383. long cookie;
  384. int handler_id;
  385. libbpf_prog_setup_fn_t prog_setup_fn;
  386. libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
  387. libbpf_prog_attach_fn_t prog_attach_fn;
  388. };
  389. struct bpf_light_subprog {
  390. __u32 sec_insn_off;
  391. __u32 sub_insn_off;
  392. };
  393. /*
  394. * bpf_prog should be a better name but it has been used in
  395. * linux/filter.h.
  396. */
  397. struct bpf_program {
  398. char *name;
  399. char *sec_name;
  400. size_t sec_idx;
  401. const struct bpf_sec_def *sec_def;
  402. /* this program's instruction offset (in number of instructions)
  403. * within its containing ELF section
  404. */
  405. size_t sec_insn_off;
  406. /* number of original instructions in ELF section belonging to this
  407. * program, not taking into account subprogram instructions possible
  408. * appended later during relocation
  409. */
  410. size_t sec_insn_cnt;
  411. /* Offset (in number of instructions) of the start of instruction
  412. * belonging to this BPF program within its containing main BPF
  413. * program. For the entry-point (main) BPF program, this is always
  414. * zero. For a sub-program, this gets reset before each of main BPF
  415. * programs are processed and relocated and is used to determined
  416. * whether sub-program was already appended to the main program, and
  417. * if yes, at which instruction offset.
  418. */
  419. size_t sub_insn_off;
  420. /* instructions that belong to BPF program; insns[0] is located at
  421. * sec_insn_off instruction within its ELF section in ELF file, so
  422. * when mapping ELF file instruction index to the local instruction,
  423. * one needs to subtract sec_insn_off; and vice versa.
  424. */
  425. struct bpf_insn *insns;
  426. /* actual number of instruction in this BPF program's image; for
  427. * entry-point BPF programs this includes the size of main program
  428. * itself plus all the used sub-programs, appended at the end
  429. */
  430. size_t insns_cnt;
  431. struct reloc_desc *reloc_desc;
  432. int nr_reloc;
  433. /* BPF verifier log settings */
  434. char *log_buf;
  435. size_t log_size;
  436. __u32 log_level;
  437. struct bpf_object *obj;
  438. int fd;
  439. bool autoload;
  440. bool autoattach;
  441. bool sym_global;
  442. bool mark_btf_static;
  443. enum bpf_prog_type type;
  444. enum bpf_attach_type expected_attach_type;
  445. int exception_cb_idx;
  446. int prog_ifindex;
  447. __u32 attach_btf_obj_fd;
  448. __u32 attach_btf_id;
  449. __u32 attach_prog_fd;
  450. void *func_info;
  451. __u32 func_info_rec_size;
  452. __u32 func_info_cnt;
  453. void *line_info;
  454. __u32 line_info_rec_size;
  455. __u32 line_info_cnt;
  456. __u32 prog_flags;
  457. __u8 hash[SHA256_DIGEST_LENGTH];
  458. struct bpf_light_subprog *subprogs;
  459. __u32 subprog_cnt;
  460. };
  461. struct bpf_struct_ops {
  462. struct bpf_program **progs;
  463. __u32 *kern_func_off;
  464. /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
  465. void *data;
  466. /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
  467. * btf_vmlinux's format.
  468. * struct bpf_struct_ops_tcp_congestion_ops {
  469. * [... some other kernel fields ...]
  470. * struct tcp_congestion_ops data;
  471. * }
  472. * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
  473. * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
  474. * from "data".
  475. */
  476. void *kern_vdata;
  477. __u32 type_id;
  478. };
  479. #define DATA_SEC ".data"
  480. #define BSS_SEC ".bss"
  481. #define RODATA_SEC ".rodata"
  482. #define KCONFIG_SEC ".kconfig"
  483. #define KSYMS_SEC ".ksyms"
  484. #define STRUCT_OPS_SEC ".struct_ops"
  485. #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
  486. #define ARENA_SEC ".addr_space.1"
  487. enum libbpf_map_type {
  488. LIBBPF_MAP_UNSPEC,
  489. LIBBPF_MAP_DATA,
  490. LIBBPF_MAP_BSS,
  491. LIBBPF_MAP_RODATA,
  492. LIBBPF_MAP_KCONFIG,
  493. };
  494. struct bpf_map_def {
  495. unsigned int type;
  496. unsigned int key_size;
  497. unsigned int value_size;
  498. unsigned int max_entries;
  499. unsigned int map_flags;
  500. };
  501. struct bpf_map {
  502. struct bpf_object *obj;
  503. char *name;
  504. /* real_name is defined for special internal maps (.rodata*,
  505. * .data*, .bss, .kconfig) and preserves their original ELF section
  506. * name. This is important to be able to find corresponding BTF
  507. * DATASEC information.
  508. */
  509. char *real_name;
  510. int fd;
  511. int sec_idx;
  512. size_t sec_offset;
  513. int map_ifindex;
  514. int inner_map_fd;
  515. struct bpf_map_def def;
  516. __u32 numa_node;
  517. __u32 btf_var_idx;
  518. int mod_btf_fd;
  519. __u32 btf_key_type_id;
  520. __u32 btf_value_type_id;
  521. __u32 btf_vmlinux_value_type_id;
  522. enum libbpf_map_type libbpf_type;
  523. void *mmaped;
  524. struct bpf_struct_ops *st_ops;
  525. struct bpf_map *inner_map;
  526. void **init_slots;
  527. int init_slots_sz;
  528. char *pin_path;
  529. bool pinned;
  530. bool reused;
  531. bool autocreate;
  532. bool autoattach;
  533. __u64 map_extra;
  534. struct bpf_program *excl_prog;
  535. };
  536. enum extern_type {
  537. EXT_UNKNOWN,
  538. EXT_KCFG,
  539. EXT_KSYM,
  540. };
  541. enum kcfg_type {
  542. KCFG_UNKNOWN,
  543. KCFG_CHAR,
  544. KCFG_BOOL,
  545. KCFG_INT,
  546. KCFG_TRISTATE,
  547. KCFG_CHAR_ARR,
  548. };
  549. struct extern_desc {
  550. enum extern_type type;
  551. int sym_idx;
  552. int btf_id;
  553. int sec_btf_id;
  554. char *name;
  555. char *essent_name;
  556. bool is_set;
  557. bool is_weak;
  558. union {
  559. struct {
  560. enum kcfg_type type;
  561. int sz;
  562. int align;
  563. int data_off;
  564. bool is_signed;
  565. } kcfg;
  566. struct {
  567. unsigned long long addr;
  568. /* target btf_id of the corresponding kernel var. */
  569. int kernel_btf_obj_fd;
  570. int kernel_btf_id;
  571. /* local btf_id of the ksym extern's type. */
  572. __u32 type_id;
  573. /* BTF fd index to be patched in for insn->off, this is
  574. * 0 for vmlinux BTF, index in obj->fd_array for module
  575. * BTF
  576. */
  577. __s16 btf_fd_idx;
  578. } ksym;
  579. };
  580. };
  581. struct module_btf {
  582. struct btf *btf;
  583. char *name;
  584. __u32 id;
  585. int fd;
  586. int fd_array_idx;
  587. };
  588. enum sec_type {
  589. SEC_UNUSED = 0,
  590. SEC_RELO,
  591. SEC_BSS,
  592. SEC_DATA,
  593. SEC_RODATA,
  594. SEC_ST_OPS,
  595. };
  596. struct elf_sec_desc {
  597. enum sec_type sec_type;
  598. Elf64_Shdr *shdr;
  599. Elf_Data *data;
  600. };
  601. struct elf_state {
  602. int fd;
  603. const void *obj_buf;
  604. size_t obj_buf_sz;
  605. Elf *elf;
  606. Elf64_Ehdr *ehdr;
  607. Elf_Data *symbols;
  608. Elf_Data *arena_data;
  609. size_t shstrndx; /* section index for section name strings */
  610. size_t strtabidx;
  611. struct elf_sec_desc *secs;
  612. size_t sec_cnt;
  613. int btf_maps_shndx;
  614. __u32 btf_maps_sec_btf_id;
  615. int text_shndx;
  616. int symbols_shndx;
  617. bool has_st_ops;
  618. int arena_data_shndx;
  619. int jumptables_data_shndx;
  620. };
  621. struct usdt_manager;
  622. enum bpf_object_state {
  623. OBJ_OPEN,
  624. OBJ_PREPARED,
  625. OBJ_LOADED,
  626. };
  627. struct bpf_object {
  628. char name[BPF_OBJ_NAME_LEN];
  629. char license[64];
  630. __u32 kern_version;
  631. enum bpf_object_state state;
  632. struct bpf_program *programs;
  633. size_t nr_programs;
  634. struct bpf_map *maps;
  635. size_t nr_maps;
  636. size_t maps_cap;
  637. char *kconfig;
  638. struct extern_desc *externs;
  639. int nr_extern;
  640. int kconfig_map_idx;
  641. bool has_subcalls;
  642. bool has_rodata;
  643. struct bpf_gen *gen_loader;
  644. /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
  645. struct elf_state efile;
  646. unsigned char byteorder;
  647. struct btf *btf;
  648. struct btf_ext *btf_ext;
  649. /* Parse and load BTF vmlinux if any of the programs in the object need
  650. * it at load time.
  651. */
  652. struct btf *btf_vmlinux;
  653. /* Path to the custom BTF to be used for BPF CO-RE relocations as an
  654. * override for vmlinux BTF.
  655. */
  656. char *btf_custom_path;
  657. /* vmlinux BTF override for CO-RE relocations */
  658. struct btf *btf_vmlinux_override;
  659. /* Lazily initialized kernel module BTFs */
  660. struct module_btf *btf_modules;
  661. bool btf_modules_loaded;
  662. size_t btf_module_cnt;
  663. size_t btf_module_cap;
  664. /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
  665. char *log_buf;
  666. size_t log_size;
  667. __u32 log_level;
  668. int *fd_array;
  669. size_t fd_array_cap;
  670. size_t fd_array_cnt;
  671. struct usdt_manager *usdt_man;
  672. int arena_map_idx;
  673. void *arena_data;
  674. size_t arena_data_sz;
  675. size_t arena_data_off;
  676. void *jumptables_data;
  677. size_t jumptables_data_sz;
  678. struct {
  679. struct bpf_program *prog;
  680. unsigned int sym_off;
  681. int fd;
  682. } *jumptable_maps;
  683. size_t jumptable_map_cnt;
  684. struct kern_feature_cache *feat_cache;
  685. char *token_path;
  686. int token_fd;
  687. char path[];
  688. };
  689. static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
  690. static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
  691. static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
  692. static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
  693. static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
  694. static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
  695. static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
  696. static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
  697. static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
  698. void bpf_program__unload(struct bpf_program *prog)
  699. {
  700. if (!prog)
  701. return;
  702. zclose(prog->fd);
  703. zfree(&prog->func_info);
  704. zfree(&prog->line_info);
  705. zfree(&prog->subprogs);
  706. }
  707. static void bpf_program__exit(struct bpf_program *prog)
  708. {
  709. if (!prog)
  710. return;
  711. bpf_program__unload(prog);
  712. zfree(&prog->name);
  713. zfree(&prog->sec_name);
  714. zfree(&prog->insns);
  715. zfree(&prog->reloc_desc);
  716. prog->nr_reloc = 0;
  717. prog->insns_cnt = 0;
  718. prog->sec_idx = -1;
  719. }
  720. static bool insn_is_subprog_call(const struct bpf_insn *insn)
  721. {
  722. return BPF_CLASS(insn->code) == BPF_JMP &&
  723. BPF_OP(insn->code) == BPF_CALL &&
  724. BPF_SRC(insn->code) == BPF_K &&
  725. insn->src_reg == BPF_PSEUDO_CALL &&
  726. insn->dst_reg == 0 &&
  727. insn->off == 0;
  728. }
  729. static bool is_call_insn(const struct bpf_insn *insn)
  730. {
  731. return insn->code == (BPF_JMP | BPF_CALL);
  732. }
  733. static bool insn_is_pseudo_func(struct bpf_insn *insn)
  734. {
  735. return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
  736. }
  737. static int
  738. bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
  739. const char *name, size_t sec_idx, const char *sec_name,
  740. size_t sec_off, void *insn_data, size_t insn_data_sz)
  741. {
  742. if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
  743. pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
  744. sec_name, name, sec_off, insn_data_sz);
  745. return -EINVAL;
  746. }
  747. memset(prog, 0, sizeof(*prog));
  748. prog->obj = obj;
  749. prog->sec_idx = sec_idx;
  750. prog->sec_insn_off = sec_off / BPF_INSN_SZ;
  751. prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
  752. /* insns_cnt can later be increased by appending used subprograms */
  753. prog->insns_cnt = prog->sec_insn_cnt;
  754. prog->type = BPF_PROG_TYPE_UNSPEC;
  755. prog->fd = -1;
  756. prog->exception_cb_idx = -1;
  757. /* libbpf's convention for SEC("?abc...") is that it's just like
  758. * SEC("abc...") but the corresponding bpf_program starts out with
  759. * autoload set to false.
  760. */
  761. if (sec_name[0] == '?') {
  762. prog->autoload = false;
  763. /* from now on forget there was ? in section name */
  764. sec_name++;
  765. } else {
  766. prog->autoload = true;
  767. }
  768. prog->autoattach = true;
  769. /* inherit object's log_level */
  770. prog->log_level = obj->log_level;
  771. prog->sec_name = strdup(sec_name);
  772. if (!prog->sec_name)
  773. goto errout;
  774. prog->name = strdup(name);
  775. if (!prog->name)
  776. goto errout;
  777. prog->insns = malloc(insn_data_sz);
  778. if (!prog->insns)
  779. goto errout;
  780. memcpy(prog->insns, insn_data, insn_data_sz);
  781. return 0;
  782. errout:
  783. pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
  784. bpf_program__exit(prog);
  785. return -ENOMEM;
  786. }
  787. static int
  788. bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
  789. const char *sec_name, int sec_idx)
  790. {
  791. Elf_Data *symbols = obj->efile.symbols;
  792. struct bpf_program *prog, *progs;
  793. void *data = sec_data->d_buf;
  794. size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
  795. int nr_progs, err, i;
  796. const char *name;
  797. Elf64_Sym *sym;
  798. progs = obj->programs;
  799. nr_progs = obj->nr_programs;
  800. nr_syms = symbols->d_size / sizeof(Elf64_Sym);
  801. for (i = 0; i < nr_syms; i++) {
  802. sym = elf_sym_by_idx(obj, i);
  803. if (sym->st_shndx != sec_idx)
  804. continue;
  805. if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
  806. continue;
  807. prog_sz = sym->st_size;
  808. sec_off = sym->st_value;
  809. name = elf_sym_str(obj, sym->st_name);
  810. if (!name) {
  811. pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
  812. sec_name, sec_off);
  813. return -LIBBPF_ERRNO__FORMAT;
  814. }
  815. if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
  816. pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
  817. sec_name, sec_off);
  818. return -LIBBPF_ERRNO__FORMAT;
  819. }
  820. if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
  821. pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
  822. return -ENOTSUP;
  823. }
  824. pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
  825. sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
  826. progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
  827. if (!progs) {
  828. /*
  829. * In this case the original obj->programs
  830. * is still valid, so don't need special treat for
  831. * bpf_close_object().
  832. */
  833. pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
  834. sec_name, name);
  835. return -ENOMEM;
  836. }
  837. obj->programs = progs;
  838. prog = &progs[nr_progs];
  839. err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
  840. sec_off, data + sec_off, prog_sz);
  841. if (err)
  842. return err;
  843. if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
  844. prog->sym_global = true;
  845. /* if function is a global/weak symbol, but has restricted
  846. * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
  847. * as static to enable more permissive BPF verification mode
  848. * with more outside context available to BPF verifier
  849. */
  850. if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
  851. || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
  852. prog->mark_btf_static = true;
  853. nr_progs++;
  854. obj->nr_programs = nr_progs;
  855. }
  856. return 0;
  857. }
  858. static void bpf_object_bswap_progs(struct bpf_object *obj)
  859. {
  860. struct bpf_program *prog = obj->programs;
  861. struct bpf_insn *insn;
  862. int p, i;
  863. for (p = 0; p < obj->nr_programs; p++, prog++) {
  864. insn = prog->insns;
  865. for (i = 0; i < prog->insns_cnt; i++, insn++)
  866. bpf_insn_bswap(insn);
  867. }
  868. pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
  869. }
  870. static const struct btf_member *
  871. find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
  872. {
  873. struct btf_member *m;
  874. int i;
  875. for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
  876. if (btf_member_bit_offset(t, i) == bit_offset)
  877. return m;
  878. }
  879. return NULL;
  880. }
  881. static const struct btf_member *
  882. find_member_by_name(const struct btf *btf, const struct btf_type *t,
  883. const char *name)
  884. {
  885. struct btf_member *m;
  886. int i;
  887. for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
  888. if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
  889. return m;
  890. }
  891. return NULL;
  892. }
  893. static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
  894. __u16 kind, struct btf **res_btf,
  895. struct module_btf **res_mod_btf);
  896. #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
  897. static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
  898. const char *name, __u32 kind);
  899. static int
  900. find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
  901. struct module_btf **mod_btf,
  902. const struct btf_type **type, __u32 *type_id,
  903. const struct btf_type **vtype, __u32 *vtype_id,
  904. const struct btf_member **data_member)
  905. {
  906. const struct btf_type *kern_type, *kern_vtype;
  907. const struct btf_member *kern_data_member;
  908. struct btf *btf = NULL;
  909. __s32 kern_vtype_id, kern_type_id;
  910. char tname[192], stname[256];
  911. __u32 i;
  912. snprintf(tname, sizeof(tname), "%.*s",
  913. (int)bpf_core_essential_name_len(tname_raw), tname_raw);
  914. snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
  915. /* Look for the corresponding "map_value" type that will be used
  916. * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
  917. * and the mod_btf.
  918. * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
  919. */
  920. kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
  921. if (kern_vtype_id < 0) {
  922. pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
  923. return kern_vtype_id;
  924. }
  925. kern_vtype = btf__type_by_id(btf, kern_vtype_id);
  926. kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
  927. if (kern_type_id < 0) {
  928. pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
  929. return kern_type_id;
  930. }
  931. kern_type = btf__type_by_id(btf, kern_type_id);
  932. /* Find "struct tcp_congestion_ops" from
  933. * struct bpf_struct_ops_tcp_congestion_ops {
  934. * [ ... ]
  935. * struct tcp_congestion_ops data;
  936. * }
  937. */
  938. kern_data_member = btf_members(kern_vtype);
  939. for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
  940. if (kern_data_member->type == kern_type_id)
  941. break;
  942. }
  943. if (i == btf_vlen(kern_vtype)) {
  944. pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
  945. tname, stname);
  946. return -EINVAL;
  947. }
  948. *type = kern_type;
  949. *type_id = kern_type_id;
  950. *vtype = kern_vtype;
  951. *vtype_id = kern_vtype_id;
  952. *data_member = kern_data_member;
  953. return 0;
  954. }
  955. static bool bpf_map__is_struct_ops(const struct bpf_map *map)
  956. {
  957. return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
  958. }
  959. static bool is_valid_st_ops_program(struct bpf_object *obj,
  960. const struct bpf_program *prog)
  961. {
  962. int i;
  963. for (i = 0; i < obj->nr_programs; i++) {
  964. if (&obj->programs[i] == prog)
  965. return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
  966. }
  967. return false;
  968. }
  969. /* For each struct_ops program P, referenced from some struct_ops map M,
  970. * enable P.autoload if there are Ms for which M.autocreate is true,
  971. * disable P.autoload if for all Ms M.autocreate is false.
  972. * Don't change P.autoload for programs that are not referenced from any maps.
  973. */
  974. static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
  975. {
  976. struct bpf_program *prog, *slot_prog;
  977. struct bpf_map *map;
  978. int i, j, k, vlen;
  979. for (i = 0; i < obj->nr_programs; ++i) {
  980. int should_load = false;
  981. int use_cnt = 0;
  982. prog = &obj->programs[i];
  983. if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
  984. continue;
  985. for (j = 0; j < obj->nr_maps; ++j) {
  986. const struct btf_type *type;
  987. map = &obj->maps[j];
  988. if (!bpf_map__is_struct_ops(map))
  989. continue;
  990. type = btf__type_by_id(obj->btf, map->st_ops->type_id);
  991. vlen = btf_vlen(type);
  992. for (k = 0; k < vlen; ++k) {
  993. slot_prog = map->st_ops->progs[k];
  994. if (prog != slot_prog)
  995. continue;
  996. use_cnt++;
  997. if (map->autocreate)
  998. should_load = true;
  999. }
  1000. }
  1001. if (use_cnt)
  1002. prog->autoload = should_load;
  1003. }
  1004. return 0;
  1005. }
  1006. /* Init the map's fields that depend on kern_btf */
  1007. static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
  1008. {
  1009. const struct btf_member *member, *kern_member, *kern_data_member;
  1010. const struct btf_type *type, *kern_type, *kern_vtype;
  1011. __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
  1012. struct bpf_object *obj = map->obj;
  1013. const struct btf *btf = obj->btf;
  1014. struct bpf_struct_ops *st_ops;
  1015. const struct btf *kern_btf;
  1016. struct module_btf *mod_btf = NULL;
  1017. void *data, *kern_data;
  1018. const char *tname;
  1019. int err;
  1020. st_ops = map->st_ops;
  1021. type = btf__type_by_id(btf, st_ops->type_id);
  1022. tname = btf__name_by_offset(btf, type->name_off);
  1023. err = find_struct_ops_kern_types(obj, tname, &mod_btf,
  1024. &kern_type, &kern_type_id,
  1025. &kern_vtype, &kern_vtype_id,
  1026. &kern_data_member);
  1027. if (err)
  1028. return err;
  1029. kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
  1030. pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
  1031. map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
  1032. map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
  1033. map->def.value_size = kern_vtype->size;
  1034. map->btf_vmlinux_value_type_id = kern_vtype_id;
  1035. st_ops->kern_vdata = calloc(1, kern_vtype->size);
  1036. if (!st_ops->kern_vdata)
  1037. return -ENOMEM;
  1038. data = st_ops->data;
  1039. kern_data_off = kern_data_member->offset / 8;
  1040. kern_data = st_ops->kern_vdata + kern_data_off;
  1041. member = btf_members(type);
  1042. for (i = 0; i < btf_vlen(type); i++, member++) {
  1043. const struct btf_type *mtype, *kern_mtype;
  1044. __u32 mtype_id, kern_mtype_id;
  1045. void *mdata, *kern_mdata;
  1046. struct bpf_program *prog;
  1047. __s64 msize, kern_msize;
  1048. __u32 moff, kern_moff;
  1049. __u32 kern_member_idx;
  1050. const char *mname;
  1051. mname = btf__name_by_offset(btf, member->name_off);
  1052. moff = member->offset / 8;
  1053. mdata = data + moff;
  1054. msize = btf__resolve_size(btf, member->type);
  1055. if (msize < 0) {
  1056. pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
  1057. map->name, mname);
  1058. return msize;
  1059. }
  1060. kern_member = find_member_by_name(kern_btf, kern_type, mname);
  1061. if (!kern_member) {
  1062. if (!libbpf_is_mem_zeroed(mdata, msize)) {
  1063. pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
  1064. map->name, mname);
  1065. return -ENOTSUP;
  1066. }
  1067. if (st_ops->progs[i]) {
  1068. /* If we had declaratively set struct_ops callback, we need to
  1069. * force its autoload to false, because it doesn't have
  1070. * a chance of succeeding from POV of the current struct_ops map.
  1071. * If this program is still referenced somewhere else, though,
  1072. * then bpf_object_adjust_struct_ops_autoload() will update its
  1073. * autoload accordingly.
  1074. */
  1075. st_ops->progs[i]->autoload = false;
  1076. st_ops->progs[i] = NULL;
  1077. }
  1078. /* Skip all-zero/NULL fields if they are not present in the kernel BTF */
  1079. pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
  1080. map->name, mname);
  1081. continue;
  1082. }
  1083. kern_member_idx = kern_member - btf_members(kern_type);
  1084. if (btf_member_bitfield_size(type, i) ||
  1085. btf_member_bitfield_size(kern_type, kern_member_idx)) {
  1086. pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
  1087. map->name, mname);
  1088. return -ENOTSUP;
  1089. }
  1090. kern_moff = kern_member->offset / 8;
  1091. kern_mdata = kern_data + kern_moff;
  1092. mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
  1093. kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
  1094. &kern_mtype_id);
  1095. if (BTF_INFO_KIND(mtype->info) !=
  1096. BTF_INFO_KIND(kern_mtype->info)) {
  1097. pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
  1098. map->name, mname, BTF_INFO_KIND(mtype->info),
  1099. BTF_INFO_KIND(kern_mtype->info));
  1100. return -ENOTSUP;
  1101. }
  1102. if (btf_is_ptr(mtype)) {
  1103. prog = *(void **)mdata;
  1104. /* just like for !kern_member case above, reset declaratively
  1105. * set (at compile time) program's autload to false,
  1106. * if user replaced it with another program or NULL
  1107. */
  1108. if (st_ops->progs[i] && st_ops->progs[i] != prog)
  1109. st_ops->progs[i]->autoload = false;
  1110. /* Update the value from the shadow type */
  1111. st_ops->progs[i] = prog;
  1112. if (!prog)
  1113. continue;
  1114. if (!is_valid_st_ops_program(obj, prog)) {
  1115. pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
  1116. map->name, mname);
  1117. return -ENOTSUP;
  1118. }
  1119. kern_mtype = skip_mods_and_typedefs(kern_btf,
  1120. kern_mtype->type,
  1121. &kern_mtype_id);
  1122. /* mtype->type must be a func_proto which was
  1123. * guaranteed in bpf_object__collect_st_ops_relos(),
  1124. * so only check kern_mtype for func_proto here.
  1125. */
  1126. if (!btf_is_func_proto(kern_mtype)) {
  1127. pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
  1128. map->name, mname);
  1129. return -ENOTSUP;
  1130. }
  1131. if (mod_btf)
  1132. prog->attach_btf_obj_fd = mod_btf->fd;
  1133. /* if we haven't yet processed this BPF program, record proper
  1134. * attach_btf_id and member_idx
  1135. */
  1136. if (!prog->attach_btf_id) {
  1137. prog->attach_btf_id = kern_type_id;
  1138. prog->expected_attach_type = kern_member_idx;
  1139. }
  1140. /* struct_ops BPF prog can be re-used between multiple
  1141. * .struct_ops & .struct_ops.link as long as it's the
  1142. * same struct_ops struct definition and the same
  1143. * function pointer field
  1144. */
  1145. if (prog->attach_btf_id != kern_type_id) {
  1146. 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",
  1147. map->name, mname, prog->name, prog->sec_name, prog->type,
  1148. prog->attach_btf_id, kern_type_id);
  1149. return -EINVAL;
  1150. }
  1151. if (prog->expected_attach_type != kern_member_idx) {
  1152. 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",
  1153. map->name, mname, prog->name, prog->sec_name, prog->type,
  1154. prog->expected_attach_type, kern_member_idx);
  1155. return -EINVAL;
  1156. }
  1157. st_ops->kern_func_off[i] = kern_data_off + kern_moff;
  1158. pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
  1159. map->name, mname, prog->name, moff,
  1160. kern_moff);
  1161. continue;
  1162. }
  1163. kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
  1164. if (kern_msize < 0 || msize != kern_msize) {
  1165. pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
  1166. map->name, mname, (ssize_t)msize,
  1167. (ssize_t)kern_msize);
  1168. return -ENOTSUP;
  1169. }
  1170. pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
  1171. map->name, mname, (unsigned int)msize,
  1172. moff, kern_moff);
  1173. memcpy(kern_mdata, mdata, msize);
  1174. }
  1175. return 0;
  1176. }
  1177. static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
  1178. {
  1179. struct bpf_map *map;
  1180. size_t i;
  1181. int err;
  1182. for (i = 0; i < obj->nr_maps; i++) {
  1183. map = &obj->maps[i];
  1184. if (!bpf_map__is_struct_ops(map))
  1185. continue;
  1186. if (!map->autocreate)
  1187. continue;
  1188. err = bpf_map__init_kern_struct_ops(map);
  1189. if (err)
  1190. return err;
  1191. }
  1192. return 0;
  1193. }
  1194. static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
  1195. int shndx, Elf_Data *data)
  1196. {
  1197. const struct btf_type *type, *datasec;
  1198. const struct btf_var_secinfo *vsi;
  1199. struct bpf_struct_ops *st_ops;
  1200. const char *tname, *var_name;
  1201. __s32 type_id, datasec_id;
  1202. const struct btf *btf;
  1203. struct bpf_map *map;
  1204. __u32 i;
  1205. if (shndx == -1)
  1206. return 0;
  1207. btf = obj->btf;
  1208. datasec_id = btf__find_by_name_kind(btf, sec_name,
  1209. BTF_KIND_DATASEC);
  1210. if (datasec_id < 0) {
  1211. pr_warn("struct_ops init: DATASEC %s not found\n",
  1212. sec_name);
  1213. return -EINVAL;
  1214. }
  1215. datasec = btf__type_by_id(btf, datasec_id);
  1216. vsi = btf_var_secinfos(datasec);
  1217. for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
  1218. type = btf__type_by_id(obj->btf, vsi->type);
  1219. var_name = btf__name_by_offset(obj->btf, type->name_off);
  1220. type_id = btf__resolve_type(obj->btf, vsi->type);
  1221. if (type_id < 0) {
  1222. pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
  1223. vsi->type, sec_name);
  1224. return -EINVAL;
  1225. }
  1226. type = btf__type_by_id(obj->btf, type_id);
  1227. tname = btf__name_by_offset(obj->btf, type->name_off);
  1228. if (!tname[0]) {
  1229. pr_warn("struct_ops init: anonymous type is not supported\n");
  1230. return -ENOTSUP;
  1231. }
  1232. if (!btf_is_struct(type)) {
  1233. pr_warn("struct_ops init: %s is not a struct\n", tname);
  1234. return -EINVAL;
  1235. }
  1236. map = bpf_object__add_map(obj);
  1237. if (IS_ERR(map))
  1238. return PTR_ERR(map);
  1239. map->sec_idx = shndx;
  1240. map->sec_offset = vsi->offset;
  1241. map->name = strdup(var_name);
  1242. if (!map->name)
  1243. return -ENOMEM;
  1244. map->btf_value_type_id = type_id;
  1245. /* Follow same convention as for programs autoload:
  1246. * SEC("?.struct_ops") means map is not created by default.
  1247. */
  1248. if (sec_name[0] == '?') {
  1249. map->autocreate = false;
  1250. /* from now on forget there was ? in section name */
  1251. sec_name++;
  1252. }
  1253. map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
  1254. map->def.key_size = sizeof(int);
  1255. map->def.value_size = type->size;
  1256. map->def.max_entries = 1;
  1257. map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
  1258. map->autoattach = true;
  1259. map->st_ops = calloc(1, sizeof(*map->st_ops));
  1260. if (!map->st_ops)
  1261. return -ENOMEM;
  1262. st_ops = map->st_ops;
  1263. st_ops->data = malloc(type->size);
  1264. st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
  1265. st_ops->kern_func_off = malloc(btf_vlen(type) *
  1266. sizeof(*st_ops->kern_func_off));
  1267. if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
  1268. return -ENOMEM;
  1269. if (vsi->offset + type->size > data->d_size) {
  1270. pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
  1271. var_name, sec_name);
  1272. return -EINVAL;
  1273. }
  1274. memcpy(st_ops->data,
  1275. data->d_buf + vsi->offset,
  1276. type->size);
  1277. st_ops->type_id = type_id;
  1278. pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
  1279. tname, type_id, var_name, vsi->offset);
  1280. }
  1281. return 0;
  1282. }
  1283. static int bpf_object_init_struct_ops(struct bpf_object *obj)
  1284. {
  1285. const char *sec_name;
  1286. int sec_idx, err;
  1287. for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
  1288. struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
  1289. if (desc->sec_type != SEC_ST_OPS)
  1290. continue;
  1291. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1292. if (!sec_name)
  1293. return -LIBBPF_ERRNO__FORMAT;
  1294. err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
  1295. if (err)
  1296. return err;
  1297. }
  1298. return 0;
  1299. }
  1300. static struct bpf_object *bpf_object__new(const char *path,
  1301. const void *obj_buf,
  1302. size_t obj_buf_sz,
  1303. const char *obj_name)
  1304. {
  1305. struct bpf_object *obj;
  1306. char *end;
  1307. obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
  1308. if (!obj) {
  1309. pr_warn("alloc memory failed for %s\n", path);
  1310. return ERR_PTR(-ENOMEM);
  1311. }
  1312. strcpy(obj->path, path);
  1313. if (obj_name) {
  1314. libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
  1315. } else {
  1316. /* Using basename() GNU version which doesn't modify arg. */
  1317. libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
  1318. end = strchr(obj->name, '.');
  1319. if (end)
  1320. *end = 0;
  1321. }
  1322. obj->efile.fd = -1;
  1323. /*
  1324. * Caller of this function should also call
  1325. * bpf_object__elf_finish() after data collection to return
  1326. * obj_buf to user. If not, we should duplicate the buffer to
  1327. * avoid user freeing them before elf finish.
  1328. */
  1329. obj->efile.obj_buf = obj_buf;
  1330. obj->efile.obj_buf_sz = obj_buf_sz;
  1331. obj->efile.btf_maps_shndx = -1;
  1332. obj->kconfig_map_idx = -1;
  1333. obj->arena_map_idx = -1;
  1334. obj->kern_version = get_kernel_version();
  1335. obj->state = OBJ_OPEN;
  1336. return obj;
  1337. }
  1338. static void bpf_object__elf_finish(struct bpf_object *obj)
  1339. {
  1340. if (!obj->efile.elf)
  1341. return;
  1342. elf_end(obj->efile.elf);
  1343. obj->efile.elf = NULL;
  1344. obj->efile.ehdr = NULL;
  1345. obj->efile.symbols = NULL;
  1346. obj->efile.arena_data = NULL;
  1347. zfree(&obj->efile.secs);
  1348. obj->efile.sec_cnt = 0;
  1349. zclose(obj->efile.fd);
  1350. obj->efile.obj_buf = NULL;
  1351. obj->efile.obj_buf_sz = 0;
  1352. }
  1353. static int bpf_object__elf_init(struct bpf_object *obj)
  1354. {
  1355. Elf64_Ehdr *ehdr;
  1356. int err = 0;
  1357. Elf *elf;
  1358. if (obj->efile.elf) {
  1359. pr_warn("elf: init internal error\n");
  1360. return -LIBBPF_ERRNO__LIBELF;
  1361. }
  1362. if (obj->efile.obj_buf_sz > 0) {
  1363. /* obj_buf should have been validated by bpf_object__open_mem(). */
  1364. elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
  1365. } else {
  1366. obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
  1367. if (obj->efile.fd < 0) {
  1368. err = -errno;
  1369. pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
  1370. return err;
  1371. }
  1372. elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
  1373. }
  1374. if (!elf) {
  1375. pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
  1376. err = -LIBBPF_ERRNO__LIBELF;
  1377. goto errout;
  1378. }
  1379. obj->efile.elf = elf;
  1380. if (elf_kind(elf) != ELF_K_ELF) {
  1381. err = -LIBBPF_ERRNO__FORMAT;
  1382. pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
  1383. goto errout;
  1384. }
  1385. if (gelf_getclass(elf) != ELFCLASS64) {
  1386. err = -LIBBPF_ERRNO__FORMAT;
  1387. pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
  1388. goto errout;
  1389. }
  1390. obj->efile.ehdr = ehdr = elf64_getehdr(elf);
  1391. if (!obj->efile.ehdr) {
  1392. pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
  1393. err = -LIBBPF_ERRNO__FORMAT;
  1394. goto errout;
  1395. }
  1396. /* Validate ELF object endianness... */
  1397. if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
  1398. ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
  1399. err = -LIBBPF_ERRNO__ENDIAN;
  1400. pr_warn("elf: '%s' has unknown byte order\n", obj->path);
  1401. goto errout;
  1402. }
  1403. /* and save after bpf_object_open() frees ELF data */
  1404. obj->byteorder = ehdr->e_ident[EI_DATA];
  1405. if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
  1406. pr_warn("elf: failed to get section names section index for %s: %s\n",
  1407. obj->path, elf_errmsg(-1));
  1408. err = -LIBBPF_ERRNO__FORMAT;
  1409. goto errout;
  1410. }
  1411. /* ELF is corrupted/truncated, avoid calling elf_strptr. */
  1412. if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
  1413. pr_warn("elf: failed to get section names strings from %s: %s\n",
  1414. obj->path, elf_errmsg(-1));
  1415. err = -LIBBPF_ERRNO__FORMAT;
  1416. goto errout;
  1417. }
  1418. /* Old LLVM set e_machine to EM_NONE */
  1419. if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
  1420. pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
  1421. err = -LIBBPF_ERRNO__FORMAT;
  1422. goto errout;
  1423. }
  1424. return 0;
  1425. errout:
  1426. bpf_object__elf_finish(obj);
  1427. return err;
  1428. }
  1429. static bool is_native_endianness(struct bpf_object *obj)
  1430. {
  1431. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1432. return obj->byteorder == ELFDATA2LSB;
  1433. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  1434. return obj->byteorder == ELFDATA2MSB;
  1435. #else
  1436. # error "Unrecognized __BYTE_ORDER__"
  1437. #endif
  1438. }
  1439. static int
  1440. bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
  1441. {
  1442. if (!data) {
  1443. pr_warn("invalid license section in %s\n", obj->path);
  1444. return -LIBBPF_ERRNO__FORMAT;
  1445. }
  1446. /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
  1447. * go over allowed ELF data section buffer
  1448. */
  1449. libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
  1450. pr_debug("license of %s is %s\n", obj->path, obj->license);
  1451. return 0;
  1452. }
  1453. static int
  1454. bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
  1455. {
  1456. __u32 kver;
  1457. if (!data || size != sizeof(kver)) {
  1458. pr_warn("invalid kver section in %s\n", obj->path);
  1459. return -LIBBPF_ERRNO__FORMAT;
  1460. }
  1461. memcpy(&kver, data, sizeof(kver));
  1462. obj->kern_version = kver;
  1463. pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
  1464. return 0;
  1465. }
  1466. static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
  1467. {
  1468. if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
  1469. type == BPF_MAP_TYPE_HASH_OF_MAPS)
  1470. return true;
  1471. return false;
  1472. }
  1473. static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
  1474. {
  1475. Elf_Data *data;
  1476. Elf_Scn *scn;
  1477. if (!name)
  1478. return -EINVAL;
  1479. scn = elf_sec_by_name(obj, name);
  1480. data = elf_sec_data(obj, scn);
  1481. if (data) {
  1482. *size = data->d_size;
  1483. return 0; /* found it */
  1484. }
  1485. return -ENOENT;
  1486. }
  1487. static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
  1488. {
  1489. Elf_Data *symbols = obj->efile.symbols;
  1490. const char *sname;
  1491. size_t si;
  1492. for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
  1493. Elf64_Sym *sym = elf_sym_by_idx(obj, si);
  1494. if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
  1495. continue;
  1496. if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
  1497. ELF64_ST_BIND(sym->st_info) != STB_WEAK)
  1498. continue;
  1499. sname = elf_sym_str(obj, sym->st_name);
  1500. if (!sname) {
  1501. pr_warn("failed to get sym name string for var %s\n", name);
  1502. return ERR_PTR(-EIO);
  1503. }
  1504. if (strcmp(name, sname) == 0)
  1505. return sym;
  1506. }
  1507. return ERR_PTR(-ENOENT);
  1508. }
  1509. #ifndef MFD_CLOEXEC
  1510. #define MFD_CLOEXEC 0x0001U
  1511. #endif
  1512. #ifndef MFD_NOEXEC_SEAL
  1513. #define MFD_NOEXEC_SEAL 0x0008U
  1514. #endif
  1515. static int create_placeholder_fd(void)
  1516. {
  1517. unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
  1518. const char *name = "libbpf-placeholder-fd";
  1519. int fd;
  1520. fd = ensure_good_fd(sys_memfd_create(name, flags));
  1521. if (fd >= 0)
  1522. return fd;
  1523. else if (errno != EINVAL)
  1524. return -errno;
  1525. /* Possibly running on kernel without MFD_NOEXEC_SEAL */
  1526. fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
  1527. if (fd < 0)
  1528. return -errno;
  1529. return fd;
  1530. }
  1531. static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
  1532. {
  1533. struct bpf_map *map;
  1534. int err;
  1535. err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
  1536. sizeof(*obj->maps), obj->nr_maps + 1);
  1537. if (err)
  1538. return ERR_PTR(err);
  1539. map = &obj->maps[obj->nr_maps++];
  1540. map->obj = obj;
  1541. /* Preallocate map FD without actually creating BPF map just yet.
  1542. * These map FD "placeholders" will be reused later without changing
  1543. * FD value when map is actually created in the kernel.
  1544. *
  1545. * This is useful to be able to perform BPF program relocations
  1546. * without having to create BPF maps before that step. This allows us
  1547. * to finalize and load BTF very late in BPF object's loading phase,
  1548. * right before BPF maps have to be created and BPF programs have to
  1549. * be loaded. By having these map FD placeholders we can perform all
  1550. * the sanitizations, relocations, and any other adjustments before we
  1551. * start creating actual BPF kernel objects (BTF, maps, progs).
  1552. */
  1553. map->fd = create_placeholder_fd();
  1554. if (map->fd < 0)
  1555. return ERR_PTR(map->fd);
  1556. map->inner_map_fd = -1;
  1557. map->autocreate = true;
  1558. return map;
  1559. }
  1560. static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
  1561. {
  1562. const long page_sz = sysconf(_SC_PAGE_SIZE);
  1563. size_t map_sz;
  1564. map_sz = (size_t)roundup(value_sz, 8) * max_entries;
  1565. map_sz = roundup(map_sz, page_sz);
  1566. return map_sz;
  1567. }
  1568. static size_t bpf_map_mmap_sz(const struct bpf_map *map)
  1569. {
  1570. const long page_sz = sysconf(_SC_PAGE_SIZE);
  1571. switch (map->def.type) {
  1572. case BPF_MAP_TYPE_ARRAY:
  1573. return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
  1574. case BPF_MAP_TYPE_ARENA:
  1575. return page_sz * map->def.max_entries;
  1576. default:
  1577. return 0; /* not supported */
  1578. }
  1579. }
  1580. static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
  1581. {
  1582. void *mmaped;
  1583. if (!map->mmaped)
  1584. return -EINVAL;
  1585. if (old_sz == new_sz)
  1586. return 0;
  1587. mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  1588. if (mmaped == MAP_FAILED)
  1589. return -errno;
  1590. memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
  1591. munmap(map->mmaped, old_sz);
  1592. map->mmaped = mmaped;
  1593. return 0;
  1594. }
  1595. static char *internal_map_name(struct bpf_object *obj, const char *real_name)
  1596. {
  1597. char map_name[BPF_OBJ_NAME_LEN], *p;
  1598. int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
  1599. /* This is one of the more confusing parts of libbpf for various
  1600. * reasons, some of which are historical. The original idea for naming
  1601. * internal names was to include as much of BPF object name prefix as
  1602. * possible, so that it can be distinguished from similar internal
  1603. * maps of a different BPF object.
  1604. * As an example, let's say we have bpf_object named 'my_object_name'
  1605. * and internal map corresponding to '.rodata' ELF section. The final
  1606. * map name advertised to user and to the kernel will be
  1607. * 'my_objec.rodata', taking first 8 characters of object name and
  1608. * entire 7 characters of '.rodata'.
  1609. * Somewhat confusingly, if internal map ELF section name is shorter
  1610. * than 7 characters, e.g., '.bss', we still reserve 7 characters
  1611. * for the suffix, even though we only have 4 actual characters, and
  1612. * resulting map will be called 'my_objec.bss', not even using all 15
  1613. * characters allowed by the kernel. Oh well, at least the truncated
  1614. * object name is somewhat consistent in this case. But if the map
  1615. * name is '.kconfig', we'll still have entirety of '.kconfig' added
  1616. * (8 chars) and thus will be left with only first 7 characters of the
  1617. * object name ('my_obje'). Happy guessing, user, that the final map
  1618. * name will be "my_obje.kconfig".
  1619. * Now, with libbpf starting to support arbitrarily named .rodata.*
  1620. * and .data.* data sections, it's possible that ELF section name is
  1621. * longer than allowed 15 chars, so we now need to be careful to take
  1622. * only up to 15 first characters of ELF name, taking no BPF object
  1623. * name characters at all. So '.rodata.abracadabra' will result in
  1624. * '.rodata.abracad' kernel and user-visible name.
  1625. * We need to keep this convoluted logic intact for .data, .bss and
  1626. * .rodata maps, but for new custom .data.custom and .rodata.custom
  1627. * maps we use their ELF names as is, not prepending bpf_object name
  1628. * in front. We still need to truncate them to 15 characters for the
  1629. * kernel. Full name can be recovered for such maps by using DATASEC
  1630. * BTF type associated with such map's value type, though.
  1631. */
  1632. if (sfx_len >= BPF_OBJ_NAME_LEN)
  1633. sfx_len = BPF_OBJ_NAME_LEN - 1;
  1634. /* if there are two or more dots in map name, it's a custom dot map */
  1635. if (strchr(real_name + 1, '.') != NULL)
  1636. pfx_len = 0;
  1637. else
  1638. pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
  1639. snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
  1640. sfx_len, real_name);
  1641. /* sanities map name to characters allowed by kernel */
  1642. for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
  1643. if (!isalnum(*p) && *p != '_' && *p != '.')
  1644. *p = '_';
  1645. return strdup(map_name);
  1646. }
  1647. static int
  1648. map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
  1649. /* Internal BPF map is mmap()'able only if at least one of corresponding
  1650. * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
  1651. * variable and it's not marked as __hidden (which turns it into, effectively,
  1652. * a STATIC variable).
  1653. */
  1654. static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
  1655. {
  1656. const struct btf_type *t, *vt;
  1657. struct btf_var_secinfo *vsi;
  1658. int i, n;
  1659. if (!map->btf_value_type_id)
  1660. return false;
  1661. t = btf__type_by_id(obj->btf, map->btf_value_type_id);
  1662. if (!btf_is_datasec(t))
  1663. return false;
  1664. vsi = btf_var_secinfos(t);
  1665. for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
  1666. vt = btf__type_by_id(obj->btf, vsi->type);
  1667. if (!btf_is_var(vt))
  1668. continue;
  1669. if (btf_var(vt)->linkage != BTF_VAR_STATIC)
  1670. return true;
  1671. }
  1672. return false;
  1673. }
  1674. static int
  1675. bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
  1676. const char *real_name, int sec_idx, void *data, size_t data_sz)
  1677. {
  1678. struct bpf_map_def *def;
  1679. struct bpf_map *map;
  1680. size_t mmap_sz;
  1681. int err;
  1682. map = bpf_object__add_map(obj);
  1683. if (IS_ERR(map))
  1684. return PTR_ERR(map);
  1685. map->libbpf_type = type;
  1686. map->sec_idx = sec_idx;
  1687. map->sec_offset = 0;
  1688. map->real_name = strdup(real_name);
  1689. map->name = internal_map_name(obj, real_name);
  1690. if (!map->real_name || !map->name) {
  1691. zfree(&map->real_name);
  1692. zfree(&map->name);
  1693. return -ENOMEM;
  1694. }
  1695. def = &map->def;
  1696. def->type = BPF_MAP_TYPE_ARRAY;
  1697. def->key_size = sizeof(int);
  1698. def->value_size = data_sz;
  1699. def->max_entries = 1;
  1700. def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
  1701. ? BPF_F_RDONLY_PROG : 0;
  1702. /* failures are fine because of maps like .rodata.str1.1 */
  1703. (void) map_fill_btf_type_info(obj, map);
  1704. if (map_is_mmapable(obj, map))
  1705. def->map_flags |= BPF_F_MMAPABLE;
  1706. pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
  1707. map->name, map->sec_idx, map->sec_offset, def->map_flags);
  1708. mmap_sz = bpf_map_mmap_sz(map);
  1709. map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
  1710. MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  1711. if (map->mmaped == MAP_FAILED) {
  1712. err = -errno;
  1713. map->mmaped = NULL;
  1714. pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
  1715. zfree(&map->real_name);
  1716. zfree(&map->name);
  1717. return err;
  1718. }
  1719. if (data)
  1720. memcpy(map->mmaped, data, data_sz);
  1721. pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
  1722. return 0;
  1723. }
  1724. static int bpf_object__init_global_data_maps(struct bpf_object *obj)
  1725. {
  1726. struct elf_sec_desc *sec_desc;
  1727. const char *sec_name;
  1728. int err = 0, sec_idx;
  1729. /*
  1730. * Populate obj->maps with libbpf internal maps.
  1731. */
  1732. for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
  1733. sec_desc = &obj->efile.secs[sec_idx];
  1734. /* Skip recognized sections with size 0. */
  1735. if (!sec_desc->data || sec_desc->data->d_size == 0)
  1736. continue;
  1737. switch (sec_desc->sec_type) {
  1738. case SEC_DATA:
  1739. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1740. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
  1741. sec_name, sec_idx,
  1742. sec_desc->data->d_buf,
  1743. sec_desc->data->d_size);
  1744. break;
  1745. case SEC_RODATA:
  1746. obj->has_rodata = true;
  1747. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1748. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
  1749. sec_name, sec_idx,
  1750. sec_desc->data->d_buf,
  1751. sec_desc->data->d_size);
  1752. break;
  1753. case SEC_BSS:
  1754. sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
  1755. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
  1756. sec_name, sec_idx,
  1757. NULL,
  1758. sec_desc->data->d_size);
  1759. break;
  1760. default:
  1761. /* skip */
  1762. break;
  1763. }
  1764. if (err)
  1765. return err;
  1766. }
  1767. return 0;
  1768. }
  1769. static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
  1770. const void *name)
  1771. {
  1772. int i;
  1773. for (i = 0; i < obj->nr_extern; i++) {
  1774. if (strcmp(obj->externs[i].name, name) == 0)
  1775. return &obj->externs[i];
  1776. }
  1777. return NULL;
  1778. }
  1779. static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
  1780. const void *name, int len)
  1781. {
  1782. const char *ext_name;
  1783. int i;
  1784. for (i = 0; i < obj->nr_extern; i++) {
  1785. ext_name = obj->externs[i].name;
  1786. if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
  1787. return &obj->externs[i];
  1788. }
  1789. return NULL;
  1790. }
  1791. static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
  1792. char value)
  1793. {
  1794. switch (ext->kcfg.type) {
  1795. case KCFG_BOOL:
  1796. if (value == 'm') {
  1797. pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
  1798. ext->name, value);
  1799. return -EINVAL;
  1800. }
  1801. *(bool *)ext_val = value == 'y' ? true : false;
  1802. break;
  1803. case KCFG_TRISTATE:
  1804. if (value == 'y')
  1805. *(enum libbpf_tristate *)ext_val = TRI_YES;
  1806. else if (value == 'm')
  1807. *(enum libbpf_tristate *)ext_val = TRI_MODULE;
  1808. else /* value == 'n' */
  1809. *(enum libbpf_tristate *)ext_val = TRI_NO;
  1810. break;
  1811. case KCFG_CHAR:
  1812. *(char *)ext_val = value;
  1813. break;
  1814. case KCFG_UNKNOWN:
  1815. case KCFG_INT:
  1816. case KCFG_CHAR_ARR:
  1817. default:
  1818. pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
  1819. ext->name, value);
  1820. return -EINVAL;
  1821. }
  1822. ext->is_set = true;
  1823. return 0;
  1824. }
  1825. static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
  1826. const char *value)
  1827. {
  1828. size_t len;
  1829. if (ext->kcfg.type != KCFG_CHAR_ARR) {
  1830. pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
  1831. ext->name, value);
  1832. return -EINVAL;
  1833. }
  1834. len = strlen(value);
  1835. if (len < 2 || value[len - 1] != '"') {
  1836. pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
  1837. ext->name, value);
  1838. return -EINVAL;
  1839. }
  1840. /* strip quotes */
  1841. len -= 2;
  1842. if (len >= ext->kcfg.sz) {
  1843. pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
  1844. ext->name, value, len, ext->kcfg.sz - 1);
  1845. len = ext->kcfg.sz - 1;
  1846. }
  1847. memcpy(ext_val, value + 1, len);
  1848. ext_val[len] = '\0';
  1849. ext->is_set = true;
  1850. return 0;
  1851. }
  1852. static int parse_u64(const char *value, __u64 *res)
  1853. {
  1854. char *value_end;
  1855. int err;
  1856. errno = 0;
  1857. *res = strtoull(value, &value_end, 0);
  1858. if (errno) {
  1859. err = -errno;
  1860. pr_warn("failed to parse '%s': %s\n", value, errstr(err));
  1861. return err;
  1862. }
  1863. if (*value_end) {
  1864. pr_warn("failed to parse '%s' as integer completely\n", value);
  1865. return -EINVAL;
  1866. }
  1867. return 0;
  1868. }
  1869. static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
  1870. {
  1871. int bit_sz = ext->kcfg.sz * 8;
  1872. if (ext->kcfg.sz == 8)
  1873. return true;
  1874. /* Validate that value stored in u64 fits in integer of `ext->sz`
  1875. * bytes size without any loss of information. If the target integer
  1876. * is signed, we rely on the following limits of integer type of
  1877. * Y bits and subsequent transformation:
  1878. *
  1879. * -2^(Y-1) <= X <= 2^(Y-1) - 1
  1880. * 0 <= X + 2^(Y-1) <= 2^Y - 1
  1881. * 0 <= X + 2^(Y-1) < 2^Y
  1882. *
  1883. * For unsigned target integer, check that all the (64 - Y) bits are
  1884. * zero.
  1885. */
  1886. if (ext->kcfg.is_signed)
  1887. return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
  1888. else
  1889. return (v >> bit_sz) == 0;
  1890. }
  1891. static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
  1892. __u64 value)
  1893. {
  1894. if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
  1895. ext->kcfg.type != KCFG_BOOL) {
  1896. pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
  1897. ext->name, (unsigned long long)value);
  1898. return -EINVAL;
  1899. }
  1900. if (ext->kcfg.type == KCFG_BOOL && value > 1) {
  1901. pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
  1902. ext->name, (unsigned long long)value);
  1903. return -EINVAL;
  1904. }
  1905. if (!is_kcfg_value_in_range(ext, value)) {
  1906. pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
  1907. ext->name, (unsigned long long)value, ext->kcfg.sz);
  1908. return -ERANGE;
  1909. }
  1910. switch (ext->kcfg.sz) {
  1911. case 1:
  1912. *(__u8 *)ext_val = value;
  1913. break;
  1914. case 2:
  1915. *(__u16 *)ext_val = value;
  1916. break;
  1917. case 4:
  1918. *(__u32 *)ext_val = value;
  1919. break;
  1920. case 8:
  1921. *(__u64 *)ext_val = value;
  1922. break;
  1923. default:
  1924. return -EINVAL;
  1925. }
  1926. ext->is_set = true;
  1927. return 0;
  1928. }
  1929. static int bpf_object__process_kconfig_line(struct bpf_object *obj,
  1930. char *buf, void *data)
  1931. {
  1932. struct extern_desc *ext;
  1933. char *sep, *value;
  1934. int len, err = 0;
  1935. void *ext_val;
  1936. __u64 num;
  1937. if (!str_has_pfx(buf, "CONFIG_"))
  1938. return 0;
  1939. sep = strchr(buf, '=');
  1940. if (!sep) {
  1941. pr_warn("failed to parse '%s': no separator\n", buf);
  1942. return -EINVAL;
  1943. }
  1944. /* Trim ending '\n' */
  1945. len = strlen(buf);
  1946. if (buf[len - 1] == '\n')
  1947. buf[len - 1] = '\0';
  1948. /* Split on '=' and ensure that a value is present. */
  1949. *sep = '\0';
  1950. if (!sep[1]) {
  1951. *sep = '=';
  1952. pr_warn("failed to parse '%s': no value\n", buf);
  1953. return -EINVAL;
  1954. }
  1955. ext = find_extern_by_name(obj, buf);
  1956. if (!ext || ext->is_set)
  1957. return 0;
  1958. ext_val = data + ext->kcfg.data_off;
  1959. value = sep + 1;
  1960. switch (*value) {
  1961. case 'y': case 'n': case 'm':
  1962. err = set_kcfg_value_tri(ext, ext_val, *value);
  1963. break;
  1964. case '"':
  1965. err = set_kcfg_value_str(ext, ext_val, value);
  1966. break;
  1967. default:
  1968. /* assume integer */
  1969. err = parse_u64(value, &num);
  1970. if (err) {
  1971. pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
  1972. return err;
  1973. }
  1974. if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
  1975. pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
  1976. return -EINVAL;
  1977. }
  1978. err = set_kcfg_value_num(ext, ext_val, num);
  1979. break;
  1980. }
  1981. if (err)
  1982. return err;
  1983. pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
  1984. return 0;
  1985. }
  1986. static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
  1987. {
  1988. char buf[PATH_MAX];
  1989. struct utsname uts;
  1990. int len, err = 0;
  1991. gzFile file;
  1992. uname(&uts);
  1993. len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
  1994. if (len < 0)
  1995. return -EINVAL;
  1996. else if (len >= PATH_MAX)
  1997. return -ENAMETOOLONG;
  1998. /* gzopen also accepts uncompressed files. */
  1999. file = gzopen(buf, "re");
  2000. if (!file)
  2001. file = gzopen("/proc/config.gz", "re");
  2002. if (!file) {
  2003. pr_warn("failed to open system Kconfig\n");
  2004. return -ENOENT;
  2005. }
  2006. while (gzgets(file, buf, sizeof(buf))) {
  2007. err = bpf_object__process_kconfig_line(obj, buf, data);
  2008. if (err) {
  2009. pr_warn("error parsing system Kconfig line '%s': %s\n",
  2010. buf, errstr(err));
  2011. goto out;
  2012. }
  2013. }
  2014. out:
  2015. gzclose(file);
  2016. return err;
  2017. }
  2018. static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
  2019. const char *config, void *data)
  2020. {
  2021. char buf[PATH_MAX];
  2022. int err = 0;
  2023. FILE *file;
  2024. file = fmemopen((void *)config, strlen(config), "r");
  2025. if (!file) {
  2026. err = -errno;
  2027. pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
  2028. return err;
  2029. }
  2030. while (fgets(buf, sizeof(buf), file)) {
  2031. err = bpf_object__process_kconfig_line(obj, buf, data);
  2032. if (err) {
  2033. pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
  2034. buf, errstr(err));
  2035. break;
  2036. }
  2037. }
  2038. fclose(file);
  2039. return err;
  2040. }
  2041. static int bpf_object__init_kconfig_map(struct bpf_object *obj)
  2042. {
  2043. struct extern_desc *last_ext = NULL, *ext;
  2044. size_t map_sz;
  2045. int i, err;
  2046. for (i = 0; i < obj->nr_extern; i++) {
  2047. ext = &obj->externs[i];
  2048. if (ext->type == EXT_KCFG)
  2049. last_ext = ext;
  2050. }
  2051. if (!last_ext)
  2052. return 0;
  2053. map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
  2054. err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
  2055. ".kconfig", obj->efile.symbols_shndx,
  2056. NULL, map_sz);
  2057. if (err)
  2058. return err;
  2059. obj->kconfig_map_idx = obj->nr_maps - 1;
  2060. return 0;
  2061. }
  2062. const struct btf_type *
  2063. skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
  2064. {
  2065. const struct btf_type *t = btf__type_by_id(btf, id);
  2066. if (res_id)
  2067. *res_id = id;
  2068. while (btf_is_mod(t) || btf_is_typedef(t)) {
  2069. if (res_id)
  2070. *res_id = t->type;
  2071. t = btf__type_by_id(btf, t->type);
  2072. }
  2073. return t;
  2074. }
  2075. static const struct btf_type *
  2076. resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
  2077. {
  2078. const struct btf_type *t;
  2079. t = skip_mods_and_typedefs(btf, id, NULL);
  2080. if (!btf_is_ptr(t))
  2081. return NULL;
  2082. t = skip_mods_and_typedefs(btf, t->type, res_id);
  2083. return btf_is_func_proto(t) ? t : NULL;
  2084. }
  2085. static const char *__btf_kind_str(__u16 kind)
  2086. {
  2087. switch (kind) {
  2088. case BTF_KIND_UNKN: return "void";
  2089. case BTF_KIND_INT: return "int";
  2090. case BTF_KIND_PTR: return "ptr";
  2091. case BTF_KIND_ARRAY: return "array";
  2092. case BTF_KIND_STRUCT: return "struct";
  2093. case BTF_KIND_UNION: return "union";
  2094. case BTF_KIND_ENUM: return "enum";
  2095. case BTF_KIND_FWD: return "fwd";
  2096. case BTF_KIND_TYPEDEF: return "typedef";
  2097. case BTF_KIND_VOLATILE: return "volatile";
  2098. case BTF_KIND_CONST: return "const";
  2099. case BTF_KIND_RESTRICT: return "restrict";
  2100. case BTF_KIND_FUNC: return "func";
  2101. case BTF_KIND_FUNC_PROTO: return "func_proto";
  2102. case BTF_KIND_VAR: return "var";
  2103. case BTF_KIND_DATASEC: return "datasec";
  2104. case BTF_KIND_FLOAT: return "float";
  2105. case BTF_KIND_DECL_TAG: return "decl_tag";
  2106. case BTF_KIND_TYPE_TAG: return "type_tag";
  2107. case BTF_KIND_ENUM64: return "enum64";
  2108. default: return "unknown";
  2109. }
  2110. }
  2111. const char *btf_kind_str(const struct btf_type *t)
  2112. {
  2113. return __btf_kind_str(btf_kind(t));
  2114. }
  2115. /*
  2116. * Fetch integer attribute of BTF map definition. Such attributes are
  2117. * represented using a pointer to an array, in which dimensionality of array
  2118. * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
  2119. * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
  2120. * type definition, while using only sizeof(void *) space in ELF data section.
  2121. */
  2122. static bool get_map_field_int(const char *map_name, const struct btf *btf,
  2123. const struct btf_member *m, __u32 *res)
  2124. {
  2125. const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
  2126. const char *name = btf__name_by_offset(btf, m->name_off);
  2127. const struct btf_array *arr_info;
  2128. const struct btf_type *arr_t;
  2129. if (!btf_is_ptr(t)) {
  2130. pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
  2131. map_name, name, btf_kind_str(t));
  2132. return false;
  2133. }
  2134. arr_t = btf__type_by_id(btf, t->type);
  2135. if (!arr_t) {
  2136. pr_warn("map '%s': attr '%s': type [%u] not found.\n",
  2137. map_name, name, t->type);
  2138. return false;
  2139. }
  2140. if (!btf_is_array(arr_t)) {
  2141. pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
  2142. map_name, name, btf_kind_str(arr_t));
  2143. return false;
  2144. }
  2145. arr_info = btf_array(arr_t);
  2146. *res = arr_info->nelems;
  2147. return true;
  2148. }
  2149. static bool get_map_field_long(const char *map_name, const struct btf *btf,
  2150. const struct btf_member *m, __u64 *res)
  2151. {
  2152. const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
  2153. const char *name = btf__name_by_offset(btf, m->name_off);
  2154. if (btf_is_ptr(t)) {
  2155. __u32 res32;
  2156. bool ret;
  2157. ret = get_map_field_int(map_name, btf, m, &res32);
  2158. if (ret)
  2159. *res = (__u64)res32;
  2160. return ret;
  2161. }
  2162. if (!btf_is_enum(t) && !btf_is_enum64(t)) {
  2163. pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
  2164. map_name, name, btf_kind_str(t));
  2165. return false;
  2166. }
  2167. if (btf_vlen(t) != 1) {
  2168. pr_warn("map '%s': attr '%s': invalid __ulong\n",
  2169. map_name, name);
  2170. return false;
  2171. }
  2172. if (btf_is_enum(t)) {
  2173. const struct btf_enum *e = btf_enum(t);
  2174. *res = e->val;
  2175. } else {
  2176. const struct btf_enum64 *e = btf_enum64(t);
  2177. *res = btf_enum64_value(e);
  2178. }
  2179. return true;
  2180. }
  2181. static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
  2182. {
  2183. int len;
  2184. len = snprintf(buf, buf_sz, "%s/%s", path, name);
  2185. if (len < 0)
  2186. return -EINVAL;
  2187. if (len >= buf_sz)
  2188. return -ENAMETOOLONG;
  2189. return 0;
  2190. }
  2191. static int build_map_pin_path(struct bpf_map *map, const char *path)
  2192. {
  2193. char buf[PATH_MAX];
  2194. int err;
  2195. if (!path)
  2196. path = BPF_FS_DEFAULT_PATH;
  2197. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  2198. if (err)
  2199. return err;
  2200. return bpf_map__set_pin_path(map, buf);
  2201. }
  2202. /* should match definition in bpf_helpers.h */
  2203. enum libbpf_pin_type {
  2204. LIBBPF_PIN_NONE,
  2205. /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
  2206. LIBBPF_PIN_BY_NAME,
  2207. };
  2208. int parse_btf_map_def(const char *map_name, struct btf *btf,
  2209. const struct btf_type *def_t, bool strict,
  2210. struct btf_map_def *map_def, struct btf_map_def *inner_def)
  2211. {
  2212. const struct btf_type *t;
  2213. const struct btf_member *m;
  2214. bool is_inner = inner_def == NULL;
  2215. int vlen, i;
  2216. vlen = btf_vlen(def_t);
  2217. m = btf_members(def_t);
  2218. for (i = 0; i < vlen; i++, m++) {
  2219. const char *name = btf__name_by_offset(btf, m->name_off);
  2220. if (!name) {
  2221. pr_warn("map '%s': invalid field #%d.\n", map_name, i);
  2222. return -EINVAL;
  2223. }
  2224. if (strcmp(name, "type") == 0) {
  2225. if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
  2226. return -EINVAL;
  2227. map_def->parts |= MAP_DEF_MAP_TYPE;
  2228. } else if (strcmp(name, "max_entries") == 0) {
  2229. if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
  2230. return -EINVAL;
  2231. map_def->parts |= MAP_DEF_MAX_ENTRIES;
  2232. } else if (strcmp(name, "map_flags") == 0) {
  2233. if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
  2234. return -EINVAL;
  2235. map_def->parts |= MAP_DEF_MAP_FLAGS;
  2236. } else if (strcmp(name, "numa_node") == 0) {
  2237. if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
  2238. return -EINVAL;
  2239. map_def->parts |= MAP_DEF_NUMA_NODE;
  2240. } else if (strcmp(name, "key_size") == 0) {
  2241. __u32 sz;
  2242. if (!get_map_field_int(map_name, btf, m, &sz))
  2243. return -EINVAL;
  2244. if (map_def->key_size && map_def->key_size != sz) {
  2245. pr_warn("map '%s': conflicting key size %u != %u.\n",
  2246. map_name, map_def->key_size, sz);
  2247. return -EINVAL;
  2248. }
  2249. map_def->key_size = sz;
  2250. map_def->parts |= MAP_DEF_KEY_SIZE;
  2251. } else if (strcmp(name, "key") == 0) {
  2252. __s64 sz;
  2253. t = btf__type_by_id(btf, m->type);
  2254. if (!t) {
  2255. pr_warn("map '%s': key type [%d] not found.\n",
  2256. map_name, m->type);
  2257. return -EINVAL;
  2258. }
  2259. if (!btf_is_ptr(t)) {
  2260. pr_warn("map '%s': key spec is not PTR: %s.\n",
  2261. map_name, btf_kind_str(t));
  2262. return -EINVAL;
  2263. }
  2264. sz = btf__resolve_size(btf, t->type);
  2265. if (sz < 0) {
  2266. pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
  2267. map_name, t->type, (ssize_t)sz);
  2268. return sz;
  2269. }
  2270. if (map_def->key_size && map_def->key_size != sz) {
  2271. pr_warn("map '%s': conflicting key size %u != %zd.\n",
  2272. map_name, map_def->key_size, (ssize_t)sz);
  2273. return -EINVAL;
  2274. }
  2275. map_def->key_size = sz;
  2276. map_def->key_type_id = t->type;
  2277. map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
  2278. } else if (strcmp(name, "value_size") == 0) {
  2279. __u32 sz;
  2280. if (!get_map_field_int(map_name, btf, m, &sz))
  2281. return -EINVAL;
  2282. if (map_def->value_size && map_def->value_size != sz) {
  2283. pr_warn("map '%s': conflicting value size %u != %u.\n",
  2284. map_name, map_def->value_size, sz);
  2285. return -EINVAL;
  2286. }
  2287. map_def->value_size = sz;
  2288. map_def->parts |= MAP_DEF_VALUE_SIZE;
  2289. } else if (strcmp(name, "value") == 0) {
  2290. __s64 sz;
  2291. t = btf__type_by_id(btf, m->type);
  2292. if (!t) {
  2293. pr_warn("map '%s': value type [%d] not found.\n",
  2294. map_name, m->type);
  2295. return -EINVAL;
  2296. }
  2297. if (!btf_is_ptr(t)) {
  2298. pr_warn("map '%s': value spec is not PTR: %s.\n",
  2299. map_name, btf_kind_str(t));
  2300. return -EINVAL;
  2301. }
  2302. sz = btf__resolve_size(btf, t->type);
  2303. if (sz < 0) {
  2304. pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
  2305. map_name, t->type, (ssize_t)sz);
  2306. return sz;
  2307. }
  2308. if (map_def->value_size && map_def->value_size != sz) {
  2309. pr_warn("map '%s': conflicting value size %u != %zd.\n",
  2310. map_name, map_def->value_size, (ssize_t)sz);
  2311. return -EINVAL;
  2312. }
  2313. map_def->value_size = sz;
  2314. map_def->value_type_id = t->type;
  2315. map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
  2316. }
  2317. else if (strcmp(name, "values") == 0) {
  2318. bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
  2319. bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
  2320. const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
  2321. char inner_map_name[128];
  2322. int err;
  2323. if (is_inner) {
  2324. pr_warn("map '%s': multi-level inner maps not supported.\n",
  2325. map_name);
  2326. return -ENOTSUP;
  2327. }
  2328. if (i != vlen - 1) {
  2329. pr_warn("map '%s': '%s' member should be last.\n",
  2330. map_name, name);
  2331. return -EINVAL;
  2332. }
  2333. if (!is_map_in_map && !is_prog_array) {
  2334. pr_warn("map '%s': should be map-in-map or prog-array.\n",
  2335. map_name);
  2336. return -ENOTSUP;
  2337. }
  2338. if (map_def->value_size && map_def->value_size != 4) {
  2339. pr_warn("map '%s': conflicting value size %u != 4.\n",
  2340. map_name, map_def->value_size);
  2341. return -EINVAL;
  2342. }
  2343. map_def->value_size = 4;
  2344. t = btf__type_by_id(btf, m->type);
  2345. if (!t) {
  2346. pr_warn("map '%s': %s type [%d] not found.\n",
  2347. map_name, desc, m->type);
  2348. return -EINVAL;
  2349. }
  2350. if (!btf_is_array(t) || btf_array(t)->nelems) {
  2351. pr_warn("map '%s': %s spec is not a zero-sized array.\n",
  2352. map_name, desc);
  2353. return -EINVAL;
  2354. }
  2355. t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
  2356. if (!btf_is_ptr(t)) {
  2357. pr_warn("map '%s': %s def is of unexpected kind %s.\n",
  2358. map_name, desc, btf_kind_str(t));
  2359. return -EINVAL;
  2360. }
  2361. t = skip_mods_and_typedefs(btf, t->type, NULL);
  2362. if (is_prog_array) {
  2363. if (!btf_is_func_proto(t)) {
  2364. pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
  2365. map_name, btf_kind_str(t));
  2366. return -EINVAL;
  2367. }
  2368. continue;
  2369. }
  2370. if (!btf_is_struct(t)) {
  2371. pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
  2372. map_name, btf_kind_str(t));
  2373. return -EINVAL;
  2374. }
  2375. snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
  2376. err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
  2377. if (err)
  2378. return err;
  2379. map_def->parts |= MAP_DEF_INNER_MAP;
  2380. } else if (strcmp(name, "pinning") == 0) {
  2381. __u32 val;
  2382. if (is_inner) {
  2383. pr_warn("map '%s': inner def can't be pinned.\n", map_name);
  2384. return -EINVAL;
  2385. }
  2386. if (!get_map_field_int(map_name, btf, m, &val))
  2387. return -EINVAL;
  2388. if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
  2389. pr_warn("map '%s': invalid pinning value %u.\n",
  2390. map_name, val);
  2391. return -EINVAL;
  2392. }
  2393. map_def->pinning = val;
  2394. map_def->parts |= MAP_DEF_PINNING;
  2395. } else if (strcmp(name, "map_extra") == 0) {
  2396. __u64 map_extra;
  2397. if (!get_map_field_long(map_name, btf, m, &map_extra))
  2398. return -EINVAL;
  2399. map_def->map_extra = map_extra;
  2400. map_def->parts |= MAP_DEF_MAP_EXTRA;
  2401. } else {
  2402. if (strict) {
  2403. pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
  2404. return -ENOTSUP;
  2405. }
  2406. pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
  2407. }
  2408. }
  2409. if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
  2410. pr_warn("map '%s': map type isn't specified.\n", map_name);
  2411. return -EINVAL;
  2412. }
  2413. return 0;
  2414. }
  2415. static size_t adjust_ringbuf_sz(size_t sz)
  2416. {
  2417. __u32 page_sz = sysconf(_SC_PAGE_SIZE);
  2418. __u32 mul;
  2419. /* if user forgot to set any size, make sure they see error */
  2420. if (sz == 0)
  2421. return 0;
  2422. /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
  2423. * a power-of-2 multiple of kernel's page size. If user diligently
  2424. * satisified these conditions, pass the size through.
  2425. */
  2426. if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
  2427. return sz;
  2428. /* Otherwise find closest (page_sz * power_of_2) product bigger than
  2429. * user-set size to satisfy both user size request and kernel
  2430. * requirements and substitute correct max_entries for map creation.
  2431. */
  2432. for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
  2433. if (mul * page_sz > sz)
  2434. return mul * page_sz;
  2435. }
  2436. /* if it's impossible to satisfy the conditions (i.e., user size is
  2437. * very close to UINT_MAX but is not a power-of-2 multiple of
  2438. * page_size) then just return original size and let kernel reject it
  2439. */
  2440. return sz;
  2441. }
  2442. static bool map_is_ringbuf(const struct bpf_map *map)
  2443. {
  2444. return map->def.type == BPF_MAP_TYPE_RINGBUF ||
  2445. map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
  2446. }
  2447. static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
  2448. {
  2449. map->def.type = def->map_type;
  2450. map->def.key_size = def->key_size;
  2451. map->def.value_size = def->value_size;
  2452. map->def.max_entries = def->max_entries;
  2453. map->def.map_flags = def->map_flags;
  2454. map->map_extra = def->map_extra;
  2455. map->numa_node = def->numa_node;
  2456. map->btf_key_type_id = def->key_type_id;
  2457. map->btf_value_type_id = def->value_type_id;
  2458. /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
  2459. if (map_is_ringbuf(map))
  2460. map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
  2461. if (def->parts & MAP_DEF_MAP_TYPE)
  2462. pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
  2463. if (def->parts & MAP_DEF_KEY_TYPE)
  2464. pr_debug("map '%s': found key [%u], sz = %u.\n",
  2465. map->name, def->key_type_id, def->key_size);
  2466. else if (def->parts & MAP_DEF_KEY_SIZE)
  2467. pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
  2468. if (def->parts & MAP_DEF_VALUE_TYPE)
  2469. pr_debug("map '%s': found value [%u], sz = %u.\n",
  2470. map->name, def->value_type_id, def->value_size);
  2471. else if (def->parts & MAP_DEF_VALUE_SIZE)
  2472. pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
  2473. if (def->parts & MAP_DEF_MAX_ENTRIES)
  2474. pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
  2475. if (def->parts & MAP_DEF_MAP_FLAGS)
  2476. pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
  2477. if (def->parts & MAP_DEF_MAP_EXTRA)
  2478. pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
  2479. (unsigned long long)def->map_extra);
  2480. if (def->parts & MAP_DEF_PINNING)
  2481. pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
  2482. if (def->parts & MAP_DEF_NUMA_NODE)
  2483. pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
  2484. if (def->parts & MAP_DEF_INNER_MAP)
  2485. pr_debug("map '%s': found inner map definition.\n", map->name);
  2486. }
  2487. static const char *btf_var_linkage_str(__u32 linkage)
  2488. {
  2489. switch (linkage) {
  2490. case BTF_VAR_STATIC: return "static";
  2491. case BTF_VAR_GLOBAL_ALLOCATED: return "global";
  2492. case BTF_VAR_GLOBAL_EXTERN: return "extern";
  2493. default: return "unknown";
  2494. }
  2495. }
  2496. static int bpf_object__init_user_btf_map(struct bpf_object *obj,
  2497. const struct btf_type *sec,
  2498. int var_idx, int sec_idx,
  2499. const Elf_Data *data, bool strict,
  2500. const char *pin_root_path)
  2501. {
  2502. struct btf_map_def map_def = {}, inner_def = {};
  2503. const struct btf_type *var, *def;
  2504. const struct btf_var_secinfo *vi;
  2505. const struct btf_var *var_extra;
  2506. const char *map_name;
  2507. struct bpf_map *map;
  2508. int err;
  2509. vi = btf_var_secinfos(sec) + var_idx;
  2510. var = btf__type_by_id(obj->btf, vi->type);
  2511. var_extra = btf_var(var);
  2512. map_name = btf__name_by_offset(obj->btf, var->name_off);
  2513. if (str_is_empty(map_name)) {
  2514. pr_warn("map #%d: empty name.\n", var_idx);
  2515. return -EINVAL;
  2516. }
  2517. if ((__u64)vi->offset + vi->size > data->d_size) {
  2518. pr_warn("map '%s' BTF data is corrupted.\n", map_name);
  2519. return -EINVAL;
  2520. }
  2521. if (!btf_is_var(var)) {
  2522. pr_warn("map '%s': unexpected var kind %s.\n",
  2523. map_name, btf_kind_str(var));
  2524. return -EINVAL;
  2525. }
  2526. if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
  2527. pr_warn("map '%s': unsupported map linkage %s.\n",
  2528. map_name, btf_var_linkage_str(var_extra->linkage));
  2529. return -EOPNOTSUPP;
  2530. }
  2531. def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
  2532. if (!btf_is_struct(def)) {
  2533. pr_warn("map '%s': unexpected def kind %s.\n",
  2534. map_name, btf_kind_str(var));
  2535. return -EINVAL;
  2536. }
  2537. if (def->size > vi->size) {
  2538. pr_warn("map '%s': invalid def size.\n", map_name);
  2539. return -EINVAL;
  2540. }
  2541. map = bpf_object__add_map(obj);
  2542. if (IS_ERR(map))
  2543. return PTR_ERR(map);
  2544. map->name = strdup(map_name);
  2545. if (!map->name) {
  2546. pr_warn("map '%s': failed to alloc map name.\n", map_name);
  2547. return -ENOMEM;
  2548. }
  2549. map->libbpf_type = LIBBPF_MAP_UNSPEC;
  2550. map->def.type = BPF_MAP_TYPE_UNSPEC;
  2551. map->sec_idx = sec_idx;
  2552. map->sec_offset = vi->offset;
  2553. map->btf_var_idx = var_idx;
  2554. pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
  2555. map_name, map->sec_idx, map->sec_offset);
  2556. err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
  2557. if (err)
  2558. return err;
  2559. fill_map_from_def(map, &map_def);
  2560. if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
  2561. err = build_map_pin_path(map, pin_root_path);
  2562. if (err) {
  2563. pr_warn("map '%s': couldn't build pin path.\n", map->name);
  2564. return err;
  2565. }
  2566. }
  2567. if (map_def.parts & MAP_DEF_INNER_MAP) {
  2568. map->inner_map = calloc(1, sizeof(*map->inner_map));
  2569. if (!map->inner_map)
  2570. return -ENOMEM;
  2571. map->inner_map->fd = create_placeholder_fd();
  2572. if (map->inner_map->fd < 0)
  2573. return map->inner_map->fd;
  2574. map->inner_map->sec_idx = sec_idx;
  2575. map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
  2576. if (!map->inner_map->name)
  2577. return -ENOMEM;
  2578. sprintf(map->inner_map->name, "%s.inner", map_name);
  2579. fill_map_from_def(map->inner_map, &inner_def);
  2580. }
  2581. err = map_fill_btf_type_info(obj, map);
  2582. if (err)
  2583. return err;
  2584. return 0;
  2585. }
  2586. static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
  2587. const char *sec_name, int sec_idx,
  2588. void *data, size_t data_sz)
  2589. {
  2590. const long page_sz = sysconf(_SC_PAGE_SIZE);
  2591. const size_t data_alloc_sz = roundup(data_sz, page_sz);
  2592. size_t mmap_sz;
  2593. mmap_sz = bpf_map_mmap_sz(map);
  2594. if (data_alloc_sz > mmap_sz) {
  2595. pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
  2596. sec_name, mmap_sz, data_sz);
  2597. return -E2BIG;
  2598. }
  2599. obj->arena_data = malloc(data_sz);
  2600. if (!obj->arena_data)
  2601. return -ENOMEM;
  2602. memcpy(obj->arena_data, data, data_sz);
  2603. obj->arena_data_sz = data_sz;
  2604. /* make bpf_map__init_value() work for ARENA maps */
  2605. map->mmaped = obj->arena_data;
  2606. return 0;
  2607. }
  2608. static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
  2609. const char *pin_root_path)
  2610. {
  2611. const struct btf_type *sec = NULL;
  2612. int nr_types, i, vlen, err;
  2613. const struct btf_type *t;
  2614. const char *name;
  2615. Elf_Data *data;
  2616. Elf_Scn *scn;
  2617. if (obj->efile.btf_maps_shndx < 0)
  2618. return 0;
  2619. scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
  2620. data = elf_sec_data(obj, scn);
  2621. if (!data) {
  2622. pr_warn("elf: failed to get %s map definitions for %s\n",
  2623. MAPS_ELF_SEC, obj->path);
  2624. return -EINVAL;
  2625. }
  2626. nr_types = btf__type_cnt(obj->btf);
  2627. for (i = 1; i < nr_types; i++) {
  2628. t = btf__type_by_id(obj->btf, i);
  2629. if (!btf_is_datasec(t))
  2630. continue;
  2631. name = btf__name_by_offset(obj->btf, t->name_off);
  2632. if (strcmp(name, MAPS_ELF_SEC) == 0) {
  2633. sec = t;
  2634. obj->efile.btf_maps_sec_btf_id = i;
  2635. break;
  2636. }
  2637. }
  2638. if (!sec) {
  2639. pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
  2640. return -ENOENT;
  2641. }
  2642. vlen = btf_vlen(sec);
  2643. for (i = 0; i < vlen; i++) {
  2644. err = bpf_object__init_user_btf_map(obj, sec, i,
  2645. obj->efile.btf_maps_shndx,
  2646. data, strict,
  2647. pin_root_path);
  2648. if (err)
  2649. return err;
  2650. }
  2651. for (i = 0; i < obj->nr_maps; i++) {
  2652. struct bpf_map *map = &obj->maps[i];
  2653. if (map->def.type != BPF_MAP_TYPE_ARENA)
  2654. continue;
  2655. if (obj->arena_map_idx >= 0) {
  2656. pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
  2657. map->name, obj->maps[obj->arena_map_idx].name);
  2658. return -EINVAL;
  2659. }
  2660. obj->arena_map_idx = i;
  2661. if (obj->efile.arena_data) {
  2662. err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
  2663. obj->efile.arena_data->d_buf,
  2664. obj->efile.arena_data->d_size);
  2665. if (err)
  2666. return err;
  2667. }
  2668. }
  2669. if (obj->efile.arena_data && obj->arena_map_idx < 0) {
  2670. pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
  2671. ARENA_SEC);
  2672. return -ENOENT;
  2673. }
  2674. return 0;
  2675. }
  2676. static int bpf_object__init_maps(struct bpf_object *obj,
  2677. const struct bpf_object_open_opts *opts)
  2678. {
  2679. const char *pin_root_path;
  2680. bool strict;
  2681. int err = 0;
  2682. strict = !OPTS_GET(opts, relaxed_maps, false);
  2683. pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
  2684. err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
  2685. err = err ?: bpf_object__init_global_data_maps(obj);
  2686. err = err ?: bpf_object__init_kconfig_map(obj);
  2687. err = err ?: bpf_object_init_struct_ops(obj);
  2688. return err;
  2689. }
  2690. static bool section_have_execinstr(struct bpf_object *obj, int idx)
  2691. {
  2692. Elf64_Shdr *sh;
  2693. sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
  2694. if (!sh)
  2695. return false;
  2696. return sh->sh_flags & SHF_EXECINSTR;
  2697. }
  2698. static bool starts_with_qmark(const char *s)
  2699. {
  2700. return s && s[0] == '?';
  2701. }
  2702. static bool btf_needs_sanitization(struct bpf_object *obj)
  2703. {
  2704. bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
  2705. bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
  2706. bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
  2707. bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
  2708. bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
  2709. bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
  2710. bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
  2711. bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
  2712. return !has_func || !has_datasec || !has_func_global || !has_float ||
  2713. !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
  2714. }
  2715. static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
  2716. {
  2717. bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
  2718. bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
  2719. bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
  2720. bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
  2721. bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
  2722. bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
  2723. bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
  2724. bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
  2725. int enum64_placeholder_id = 0;
  2726. struct btf_type *t;
  2727. int i, j, vlen;
  2728. for (i = 1; i < btf__type_cnt(btf); i++) {
  2729. t = (struct btf_type *)btf__type_by_id(btf, i);
  2730. if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
  2731. /* replace VAR/DECL_TAG with INT */
  2732. t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
  2733. /*
  2734. * using size = 1 is the safest choice, 4 will be too
  2735. * big and cause kernel BTF validation failure if
  2736. * original variable took less than 4 bytes
  2737. */
  2738. t->size = 1;
  2739. *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
  2740. } else if (!has_datasec && btf_is_datasec(t)) {
  2741. /* replace DATASEC with STRUCT */
  2742. const struct btf_var_secinfo *v = btf_var_secinfos(t);
  2743. struct btf_member *m = btf_members(t);
  2744. struct btf_type *vt;
  2745. char *name;
  2746. name = (char *)btf__name_by_offset(btf, t->name_off);
  2747. while (*name) {
  2748. if (*name == '.' || *name == '?')
  2749. *name = '_';
  2750. name++;
  2751. }
  2752. vlen = btf_vlen(t);
  2753. t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
  2754. for (j = 0; j < vlen; j++, v++, m++) {
  2755. /* order of field assignments is important */
  2756. m->offset = v->offset * 8;
  2757. m->type = v->type;
  2758. /* preserve variable name as member name */
  2759. vt = (void *)btf__type_by_id(btf, v->type);
  2760. m->name_off = vt->name_off;
  2761. }
  2762. } else if (!has_qmark_datasec && btf_is_datasec(t) &&
  2763. starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
  2764. /* replace '?' prefix with '_' for DATASEC names */
  2765. char *name;
  2766. name = (char *)btf__name_by_offset(btf, t->name_off);
  2767. if (name[0] == '?')
  2768. name[0] = '_';
  2769. } else if (!has_func && btf_is_func_proto(t)) {
  2770. /* replace FUNC_PROTO with ENUM */
  2771. vlen = btf_vlen(t);
  2772. t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
  2773. t->size = sizeof(__u32); /* kernel enforced */
  2774. } else if (!has_func && btf_is_func(t)) {
  2775. /* replace FUNC with TYPEDEF */
  2776. t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
  2777. } else if (!has_func_global && btf_is_func(t)) {
  2778. /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
  2779. t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
  2780. } else if (!has_float && btf_is_float(t)) {
  2781. /* replace FLOAT with an equally-sized empty STRUCT;
  2782. * since C compilers do not accept e.g. "float" as a
  2783. * valid struct name, make it anonymous
  2784. */
  2785. t->name_off = 0;
  2786. t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
  2787. } else if (!has_type_tag && btf_is_type_tag(t)) {
  2788. /* replace TYPE_TAG with a CONST */
  2789. t->name_off = 0;
  2790. t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
  2791. } else if (!has_enum64 && btf_is_enum(t)) {
  2792. /* clear the kflag */
  2793. t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
  2794. } else if (!has_enum64 && btf_is_enum64(t)) {
  2795. /* replace ENUM64 with a union */
  2796. struct btf_member *m;
  2797. if (enum64_placeholder_id == 0) {
  2798. enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
  2799. if (enum64_placeholder_id < 0)
  2800. return enum64_placeholder_id;
  2801. t = (struct btf_type *)btf__type_by_id(btf, i);
  2802. }
  2803. m = btf_members(t);
  2804. vlen = btf_vlen(t);
  2805. t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
  2806. for (j = 0; j < vlen; j++, m++) {
  2807. m->type = enum64_placeholder_id;
  2808. m->offset = 0;
  2809. }
  2810. }
  2811. }
  2812. return 0;
  2813. }
  2814. static bool libbpf_needs_btf(const struct bpf_object *obj)
  2815. {
  2816. return obj->efile.btf_maps_shndx >= 0 ||
  2817. obj->efile.has_st_ops ||
  2818. obj->nr_extern > 0;
  2819. }
  2820. static bool kernel_needs_btf(const struct bpf_object *obj)
  2821. {
  2822. return obj->efile.has_st_ops;
  2823. }
  2824. static int bpf_object__init_btf(struct bpf_object *obj,
  2825. Elf_Data *btf_data,
  2826. Elf_Data *btf_ext_data)
  2827. {
  2828. int err = -ENOENT;
  2829. if (btf_data) {
  2830. obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
  2831. err = libbpf_get_error(obj->btf);
  2832. if (err) {
  2833. obj->btf = NULL;
  2834. pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
  2835. goto out;
  2836. }
  2837. /* enforce 8-byte pointers for BPF-targeted BTFs */
  2838. btf__set_pointer_size(obj->btf, 8);
  2839. }
  2840. if (btf_ext_data) {
  2841. struct btf_ext_info *ext_segs[3];
  2842. int seg_num, sec_num;
  2843. if (!obj->btf) {
  2844. pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
  2845. BTF_EXT_ELF_SEC, BTF_ELF_SEC);
  2846. goto out;
  2847. }
  2848. obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
  2849. err = libbpf_get_error(obj->btf_ext);
  2850. if (err) {
  2851. pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
  2852. BTF_EXT_ELF_SEC, errstr(err));
  2853. obj->btf_ext = NULL;
  2854. goto out;
  2855. }
  2856. /* setup .BTF.ext to ELF section mapping */
  2857. ext_segs[0] = &obj->btf_ext->func_info;
  2858. ext_segs[1] = &obj->btf_ext->line_info;
  2859. ext_segs[2] = &obj->btf_ext->core_relo_info;
  2860. for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
  2861. struct btf_ext_info *seg = ext_segs[seg_num];
  2862. const struct btf_ext_info_sec *sec;
  2863. const char *sec_name;
  2864. Elf_Scn *scn;
  2865. if (seg->sec_cnt == 0)
  2866. continue;
  2867. seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
  2868. if (!seg->sec_idxs) {
  2869. err = -ENOMEM;
  2870. goto out;
  2871. }
  2872. sec_num = 0;
  2873. for_each_btf_ext_sec(seg, sec) {
  2874. /* preventively increment index to avoid doing
  2875. * this before every continue below
  2876. */
  2877. sec_num++;
  2878. sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
  2879. if (str_is_empty(sec_name))
  2880. continue;
  2881. scn = elf_sec_by_name(obj, sec_name);
  2882. if (!scn)
  2883. continue;
  2884. seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
  2885. }
  2886. }
  2887. }
  2888. out:
  2889. if (err && libbpf_needs_btf(obj)) {
  2890. pr_warn("BTF is required, but is missing or corrupted.\n");
  2891. return err;
  2892. }
  2893. return 0;
  2894. }
  2895. static int compare_vsi_off(const void *_a, const void *_b)
  2896. {
  2897. const struct btf_var_secinfo *a = _a;
  2898. const struct btf_var_secinfo *b = _b;
  2899. return a->offset - b->offset;
  2900. }
  2901. static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
  2902. struct btf_type *t)
  2903. {
  2904. __u32 size = 0, i, vars = btf_vlen(t);
  2905. const char *sec_name = btf__name_by_offset(btf, t->name_off);
  2906. struct btf_var_secinfo *vsi;
  2907. bool fixup_offsets = false;
  2908. int err;
  2909. if (!sec_name) {
  2910. pr_debug("No name found in string section for DATASEC kind.\n");
  2911. return -ENOENT;
  2912. }
  2913. /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
  2914. * variable offsets set at the previous step. Further, not every
  2915. * extern BTF VAR has corresponding ELF symbol preserved, so we skip
  2916. * all fixups altogether for such sections and go straight to sorting
  2917. * VARs within their DATASEC.
  2918. */
  2919. if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
  2920. goto sort_vars;
  2921. /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
  2922. * fix this up. But BPF static linker already fixes this up and fills
  2923. * all the sizes and offsets during static linking. So this step has
  2924. * to be optional. But the STV_HIDDEN handling is non-optional for any
  2925. * non-extern DATASEC, so the variable fixup loop below handles both
  2926. * functions at the same time, paying the cost of BTF VAR <-> ELF
  2927. * symbol matching just once.
  2928. */
  2929. if (t->size == 0) {
  2930. err = find_elf_sec_sz(obj, sec_name, &size);
  2931. if (err || !size) {
  2932. pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
  2933. sec_name, size, errstr(err));
  2934. return -ENOENT;
  2935. }
  2936. t->size = size;
  2937. fixup_offsets = true;
  2938. }
  2939. for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
  2940. const struct btf_type *t_var;
  2941. struct btf_var *var;
  2942. const char *var_name;
  2943. Elf64_Sym *sym;
  2944. t_var = btf__type_by_id(btf, vsi->type);
  2945. if (!t_var || !btf_is_var(t_var)) {
  2946. pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
  2947. return -EINVAL;
  2948. }
  2949. var = btf_var(t_var);
  2950. if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
  2951. continue;
  2952. var_name = btf__name_by_offset(btf, t_var->name_off);
  2953. if (!var_name) {
  2954. pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
  2955. sec_name, i);
  2956. return -ENOENT;
  2957. }
  2958. sym = find_elf_var_sym(obj, var_name);
  2959. if (IS_ERR(sym)) {
  2960. pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
  2961. sec_name, var_name);
  2962. return -ENOENT;
  2963. }
  2964. if (fixup_offsets)
  2965. vsi->offset = sym->st_value;
  2966. /* if variable is a global/weak symbol, but has restricted
  2967. * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
  2968. * as static. This follows similar logic for functions (BPF
  2969. * subprogs) and influences libbpf's further decisions about
  2970. * whether to make global data BPF array maps as
  2971. * BPF_F_MMAPABLE.
  2972. */
  2973. if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
  2974. || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
  2975. var->linkage = BTF_VAR_STATIC;
  2976. }
  2977. sort_vars:
  2978. qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
  2979. return 0;
  2980. }
  2981. static int bpf_object_fixup_btf(struct bpf_object *obj)
  2982. {
  2983. int i, n, err = 0;
  2984. if (!obj->btf)
  2985. return 0;
  2986. n = btf__type_cnt(obj->btf);
  2987. for (i = 1; i < n; i++) {
  2988. struct btf_type *t = btf_type_by_id(obj->btf, i);
  2989. /* Loader needs to fix up some of the things compiler
  2990. * couldn't get its hands on while emitting BTF. This
  2991. * is section size and global variable offset. We use
  2992. * the info from the ELF itself for this purpose.
  2993. */
  2994. if (btf_is_datasec(t)) {
  2995. err = btf_fixup_datasec(obj, obj->btf, t);
  2996. if (err)
  2997. return err;
  2998. }
  2999. }
  3000. return 0;
  3001. }
  3002. static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
  3003. {
  3004. if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
  3005. prog->type == BPF_PROG_TYPE_LSM)
  3006. return true;
  3007. /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
  3008. * also need vmlinux BTF
  3009. */
  3010. if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
  3011. return true;
  3012. return false;
  3013. }
  3014. static bool map_needs_vmlinux_btf(struct bpf_map *map)
  3015. {
  3016. return bpf_map__is_struct_ops(map);
  3017. }
  3018. static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
  3019. {
  3020. struct bpf_program *prog;
  3021. struct bpf_map *map;
  3022. int i;
  3023. /* CO-RE relocations need kernel BTF, only when btf_custom_path
  3024. * is not specified
  3025. */
  3026. if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
  3027. return true;
  3028. /* Support for typed ksyms needs kernel BTF */
  3029. for (i = 0; i < obj->nr_extern; i++) {
  3030. const struct extern_desc *ext;
  3031. ext = &obj->externs[i];
  3032. if (ext->type == EXT_KSYM && ext->ksym.type_id)
  3033. return true;
  3034. }
  3035. bpf_object__for_each_program(prog, obj) {
  3036. if (!prog->autoload)
  3037. continue;
  3038. if (prog_needs_vmlinux_btf(prog))
  3039. return true;
  3040. }
  3041. bpf_object__for_each_map(map, obj) {
  3042. if (map_needs_vmlinux_btf(map))
  3043. return true;
  3044. }
  3045. return false;
  3046. }
  3047. static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
  3048. {
  3049. int err;
  3050. /* btf_vmlinux could be loaded earlier */
  3051. if (obj->btf_vmlinux || obj->gen_loader)
  3052. return 0;
  3053. if (!force && !obj_needs_vmlinux_btf(obj))
  3054. return 0;
  3055. obj->btf_vmlinux = btf__load_vmlinux_btf();
  3056. err = libbpf_get_error(obj->btf_vmlinux);
  3057. if (err) {
  3058. pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
  3059. obj->btf_vmlinux = NULL;
  3060. return err;
  3061. }
  3062. return 0;
  3063. }
  3064. static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
  3065. {
  3066. struct btf *kern_btf = obj->btf;
  3067. bool btf_mandatory, sanitize;
  3068. int i, err = 0;
  3069. if (!obj->btf)
  3070. return 0;
  3071. if (!kernel_supports(obj, FEAT_BTF)) {
  3072. if (kernel_needs_btf(obj)) {
  3073. err = -EOPNOTSUPP;
  3074. goto report;
  3075. }
  3076. pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
  3077. return 0;
  3078. }
  3079. /* Even though some subprogs are global/weak, user might prefer more
  3080. * permissive BPF verification process that BPF verifier performs for
  3081. * static functions, taking into account more context from the caller
  3082. * functions. In such case, they need to mark such subprogs with
  3083. * __attribute__((visibility("hidden"))) and libbpf will adjust
  3084. * corresponding FUNC BTF type to be marked as static and trigger more
  3085. * involved BPF verification process.
  3086. */
  3087. for (i = 0; i < obj->nr_programs; i++) {
  3088. struct bpf_program *prog = &obj->programs[i];
  3089. struct btf_type *t;
  3090. const char *name;
  3091. int j, n;
  3092. if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
  3093. continue;
  3094. n = btf__type_cnt(obj->btf);
  3095. for (j = 1; j < n; j++) {
  3096. t = btf_type_by_id(obj->btf, j);
  3097. if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
  3098. continue;
  3099. name = btf__str_by_offset(obj->btf, t->name_off);
  3100. if (strcmp(name, prog->name) != 0)
  3101. continue;
  3102. t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
  3103. break;
  3104. }
  3105. }
  3106. sanitize = btf_needs_sanitization(obj);
  3107. if (sanitize) {
  3108. const void *raw_data;
  3109. __u32 sz;
  3110. /* clone BTF to sanitize a copy and leave the original intact */
  3111. raw_data = btf__raw_data(obj->btf, &sz);
  3112. kern_btf = btf__new(raw_data, sz);
  3113. err = libbpf_get_error(kern_btf);
  3114. if (err)
  3115. return err;
  3116. /* enforce 8-byte pointers for BPF-targeted BTFs */
  3117. btf__set_pointer_size(obj->btf, 8);
  3118. err = bpf_object__sanitize_btf(obj, kern_btf);
  3119. if (err)
  3120. return err;
  3121. }
  3122. if (obj->gen_loader) {
  3123. __u32 raw_size = 0;
  3124. const void *raw_data = btf__raw_data(kern_btf, &raw_size);
  3125. if (!raw_data)
  3126. return -ENOMEM;
  3127. bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
  3128. /* Pretend to have valid FD to pass various fd >= 0 checks.
  3129. * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
  3130. */
  3131. btf__set_fd(kern_btf, 0);
  3132. } else {
  3133. /* currently BPF_BTF_LOAD only supports log_level 1 */
  3134. err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
  3135. obj->log_level ? 1 : 0, obj->token_fd);
  3136. }
  3137. if (sanitize) {
  3138. if (!err) {
  3139. /* move fd to libbpf's BTF */
  3140. btf__set_fd(obj->btf, btf__fd(kern_btf));
  3141. btf__set_fd(kern_btf, -1);
  3142. }
  3143. btf__free(kern_btf);
  3144. }
  3145. report:
  3146. if (err) {
  3147. btf_mandatory = kernel_needs_btf(obj);
  3148. if (btf_mandatory) {
  3149. pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
  3150. errstr(err));
  3151. } else {
  3152. pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
  3153. errstr(err));
  3154. err = 0;
  3155. }
  3156. }
  3157. return err;
  3158. }
  3159. static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
  3160. {
  3161. const char *name;
  3162. name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
  3163. if (!name) {
  3164. pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
  3165. off, obj->path, elf_errmsg(-1));
  3166. return NULL;
  3167. }
  3168. return name;
  3169. }
  3170. static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
  3171. {
  3172. const char *name;
  3173. name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
  3174. if (!name) {
  3175. pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
  3176. off, obj->path, elf_errmsg(-1));
  3177. return NULL;
  3178. }
  3179. return name;
  3180. }
  3181. static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
  3182. {
  3183. Elf_Scn *scn;
  3184. scn = elf_getscn(obj->efile.elf, idx);
  3185. if (!scn) {
  3186. pr_warn("elf: failed to get section(%zu) from %s: %s\n",
  3187. idx, obj->path, elf_errmsg(-1));
  3188. return NULL;
  3189. }
  3190. return scn;
  3191. }
  3192. static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
  3193. {
  3194. Elf_Scn *scn = NULL;
  3195. Elf *elf = obj->efile.elf;
  3196. const char *sec_name;
  3197. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  3198. sec_name = elf_sec_name(obj, scn);
  3199. if (!sec_name)
  3200. return NULL;
  3201. if (strcmp(sec_name, name) != 0)
  3202. continue;
  3203. return scn;
  3204. }
  3205. return NULL;
  3206. }
  3207. static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
  3208. {
  3209. Elf64_Shdr *shdr;
  3210. if (!scn)
  3211. return NULL;
  3212. shdr = elf64_getshdr(scn);
  3213. if (!shdr) {
  3214. pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
  3215. elf_ndxscn(scn), obj->path, elf_errmsg(-1));
  3216. return NULL;
  3217. }
  3218. return shdr;
  3219. }
  3220. static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
  3221. {
  3222. const char *name;
  3223. Elf64_Shdr *sh;
  3224. if (!scn)
  3225. return NULL;
  3226. sh = elf_sec_hdr(obj, scn);
  3227. if (!sh)
  3228. return NULL;
  3229. name = elf_sec_str(obj, sh->sh_name);
  3230. if (!name) {
  3231. pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
  3232. elf_ndxscn(scn), obj->path, elf_errmsg(-1));
  3233. return NULL;
  3234. }
  3235. return name;
  3236. }
  3237. static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
  3238. {
  3239. Elf_Data *data;
  3240. if (!scn)
  3241. return NULL;
  3242. data = elf_getdata(scn, 0);
  3243. if (!data) {
  3244. pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
  3245. elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
  3246. obj->path, elf_errmsg(-1));
  3247. return NULL;
  3248. }
  3249. return data;
  3250. }
  3251. static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
  3252. {
  3253. if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
  3254. return NULL;
  3255. return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
  3256. }
  3257. static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
  3258. {
  3259. if (idx >= data->d_size / sizeof(Elf64_Rel))
  3260. return NULL;
  3261. return (Elf64_Rel *)data->d_buf + idx;
  3262. }
  3263. static bool is_sec_name_dwarf(const char *name)
  3264. {
  3265. /* approximation, but the actual list is too long */
  3266. return str_has_pfx(name, ".debug_");
  3267. }
  3268. static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
  3269. {
  3270. /* no special handling of .strtab */
  3271. if (hdr->sh_type == SHT_STRTAB)
  3272. return true;
  3273. /* ignore .llvm_addrsig section as well */
  3274. if (hdr->sh_type == SHT_LLVM_ADDRSIG)
  3275. return true;
  3276. /* no subprograms will lead to an empty .text section, ignore it */
  3277. if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
  3278. strcmp(name, ".text") == 0)
  3279. return true;
  3280. /* DWARF sections */
  3281. if (is_sec_name_dwarf(name))
  3282. return true;
  3283. if (str_has_pfx(name, ".rel")) {
  3284. name += sizeof(".rel") - 1;
  3285. /* DWARF section relocations */
  3286. if (is_sec_name_dwarf(name))
  3287. return true;
  3288. /* .BTF and .BTF.ext don't need relocations */
  3289. if (strcmp(name, BTF_ELF_SEC) == 0 ||
  3290. strcmp(name, BTF_EXT_ELF_SEC) == 0)
  3291. return true;
  3292. }
  3293. return false;
  3294. }
  3295. static int cmp_progs(const void *_a, const void *_b)
  3296. {
  3297. const struct bpf_program *a = _a;
  3298. const struct bpf_program *b = _b;
  3299. if (a->sec_idx != b->sec_idx)
  3300. return a->sec_idx < b->sec_idx ? -1 : 1;
  3301. /* sec_insn_off can't be the same within the section */
  3302. return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
  3303. }
  3304. static int bpf_object__elf_collect(struct bpf_object *obj)
  3305. {
  3306. struct elf_sec_desc *sec_desc;
  3307. Elf *elf = obj->efile.elf;
  3308. Elf_Data *btf_ext_data = NULL;
  3309. Elf_Data *btf_data = NULL;
  3310. int idx = 0, err = 0;
  3311. const char *name;
  3312. Elf_Data *data;
  3313. Elf_Scn *scn;
  3314. Elf64_Shdr *sh;
  3315. /* ELF section indices are 0-based, but sec #0 is special "invalid"
  3316. * section. Since section count retrieved by elf_getshdrnum() does
  3317. * include sec #0, it is already the necessary size of an array to keep
  3318. * all the sections.
  3319. */
  3320. if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
  3321. pr_warn("elf: failed to get the number of sections for %s: %s\n",
  3322. obj->path, elf_errmsg(-1));
  3323. return -LIBBPF_ERRNO__FORMAT;
  3324. }
  3325. obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
  3326. if (!obj->efile.secs)
  3327. return -ENOMEM;
  3328. /* a bunch of ELF parsing functionality depends on processing symbols,
  3329. * so do the first pass and find the symbol table
  3330. */
  3331. scn = NULL;
  3332. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  3333. sh = elf_sec_hdr(obj, scn);
  3334. if (!sh)
  3335. return -LIBBPF_ERRNO__FORMAT;
  3336. if (sh->sh_type == SHT_SYMTAB) {
  3337. if (obj->efile.symbols) {
  3338. pr_warn("elf: multiple symbol tables in %s\n", obj->path);
  3339. return -LIBBPF_ERRNO__FORMAT;
  3340. }
  3341. data = elf_sec_data(obj, scn);
  3342. if (!data)
  3343. return -LIBBPF_ERRNO__FORMAT;
  3344. idx = elf_ndxscn(scn);
  3345. obj->efile.symbols = data;
  3346. obj->efile.symbols_shndx = idx;
  3347. obj->efile.strtabidx = sh->sh_link;
  3348. }
  3349. }
  3350. if (!obj->efile.symbols) {
  3351. pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
  3352. obj->path);
  3353. return -ENOENT;
  3354. }
  3355. scn = NULL;
  3356. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  3357. idx = elf_ndxscn(scn);
  3358. sec_desc = &obj->efile.secs[idx];
  3359. sh = elf_sec_hdr(obj, scn);
  3360. if (!sh)
  3361. return -LIBBPF_ERRNO__FORMAT;
  3362. name = elf_sec_str(obj, sh->sh_name);
  3363. if (!name)
  3364. return -LIBBPF_ERRNO__FORMAT;
  3365. if (ignore_elf_section(sh, name))
  3366. continue;
  3367. data = elf_sec_data(obj, scn);
  3368. if (!data)
  3369. return -LIBBPF_ERRNO__FORMAT;
  3370. pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
  3371. idx, name, (unsigned long)data->d_size,
  3372. (int)sh->sh_link, (unsigned long)sh->sh_flags,
  3373. (int)sh->sh_type);
  3374. if (strcmp(name, "license") == 0) {
  3375. err = bpf_object__init_license(obj, data->d_buf, data->d_size);
  3376. if (err)
  3377. return err;
  3378. } else if (strcmp(name, "version") == 0) {
  3379. err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
  3380. if (err)
  3381. return err;
  3382. } else if (strcmp(name, "maps") == 0) {
  3383. pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
  3384. return -ENOTSUP;
  3385. } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
  3386. obj->efile.btf_maps_shndx = idx;
  3387. } else if (strcmp(name, BTF_ELF_SEC) == 0) {
  3388. if (sh->sh_type != SHT_PROGBITS)
  3389. return -LIBBPF_ERRNO__FORMAT;
  3390. btf_data = data;
  3391. } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
  3392. if (sh->sh_type != SHT_PROGBITS)
  3393. return -LIBBPF_ERRNO__FORMAT;
  3394. btf_ext_data = data;
  3395. } else if (sh->sh_type == SHT_SYMTAB) {
  3396. /* already processed during the first pass above */
  3397. } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
  3398. if (sh->sh_flags & SHF_EXECINSTR) {
  3399. if (strcmp(name, ".text") == 0)
  3400. obj->efile.text_shndx = idx;
  3401. err = bpf_object__add_programs(obj, data, name, idx);
  3402. if (err)
  3403. return err;
  3404. } else if (strcmp(name, DATA_SEC) == 0 ||
  3405. str_has_pfx(name, DATA_SEC ".")) {
  3406. sec_desc->sec_type = SEC_DATA;
  3407. sec_desc->shdr = sh;
  3408. sec_desc->data = data;
  3409. } else if (strcmp(name, RODATA_SEC) == 0 ||
  3410. str_has_pfx(name, RODATA_SEC ".")) {
  3411. sec_desc->sec_type = SEC_RODATA;
  3412. sec_desc->shdr = sh;
  3413. sec_desc->data = data;
  3414. } else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
  3415. strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
  3416. strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
  3417. strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
  3418. sec_desc->sec_type = SEC_ST_OPS;
  3419. sec_desc->shdr = sh;
  3420. sec_desc->data = data;
  3421. obj->efile.has_st_ops = true;
  3422. } else if (strcmp(name, ARENA_SEC) == 0) {
  3423. obj->efile.arena_data = data;
  3424. obj->efile.arena_data_shndx = idx;
  3425. } else if (strcmp(name, JUMPTABLES_SEC) == 0) {
  3426. obj->jumptables_data = malloc(data->d_size);
  3427. if (!obj->jumptables_data)
  3428. return -ENOMEM;
  3429. memcpy(obj->jumptables_data, data->d_buf, data->d_size);
  3430. obj->jumptables_data_sz = data->d_size;
  3431. obj->efile.jumptables_data_shndx = idx;
  3432. } else {
  3433. pr_info("elf: skipping unrecognized data section(%d) %s\n",
  3434. idx, name);
  3435. }
  3436. } else if (sh->sh_type == SHT_REL) {
  3437. int targ_sec_idx = sh->sh_info; /* points to other section */
  3438. if (sh->sh_entsize != sizeof(Elf64_Rel) ||
  3439. targ_sec_idx >= obj->efile.sec_cnt)
  3440. return -LIBBPF_ERRNO__FORMAT;
  3441. /* Only do relo for section with exec instructions */
  3442. if (!section_have_execinstr(obj, targ_sec_idx) &&
  3443. strcmp(name, ".rel" STRUCT_OPS_SEC) &&
  3444. strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
  3445. strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
  3446. strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
  3447. strcmp(name, ".rel" MAPS_ELF_SEC)) {
  3448. pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
  3449. idx, name, targ_sec_idx,
  3450. elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
  3451. continue;
  3452. }
  3453. sec_desc->sec_type = SEC_RELO;
  3454. sec_desc->shdr = sh;
  3455. sec_desc->data = data;
  3456. } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
  3457. str_has_pfx(name, BSS_SEC "."))) {
  3458. sec_desc->sec_type = SEC_BSS;
  3459. sec_desc->shdr = sh;
  3460. sec_desc->data = data;
  3461. } else {
  3462. pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
  3463. (size_t)sh->sh_size);
  3464. }
  3465. }
  3466. if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
  3467. pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
  3468. return -LIBBPF_ERRNO__FORMAT;
  3469. }
  3470. /* change BPF program insns to native endianness for introspection */
  3471. if (!is_native_endianness(obj))
  3472. bpf_object_bswap_progs(obj);
  3473. /* sort BPF programs by section name and in-section instruction offset
  3474. * for faster search
  3475. */
  3476. if (obj->nr_programs)
  3477. qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
  3478. return bpf_object__init_btf(obj, btf_data, btf_ext_data);
  3479. }
  3480. static bool sym_is_extern(const Elf64_Sym *sym)
  3481. {
  3482. int bind = ELF64_ST_BIND(sym->st_info);
  3483. /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
  3484. return sym->st_shndx == SHN_UNDEF &&
  3485. (bind == STB_GLOBAL || bind == STB_WEAK) &&
  3486. ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
  3487. }
  3488. static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
  3489. {
  3490. int bind = ELF64_ST_BIND(sym->st_info);
  3491. int type = ELF64_ST_TYPE(sym->st_info);
  3492. /* in .text section */
  3493. if (sym->st_shndx != text_shndx)
  3494. return false;
  3495. /* local function */
  3496. if (bind == STB_LOCAL && type == STT_SECTION)
  3497. return true;
  3498. /* global function */
  3499. return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
  3500. }
  3501. static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
  3502. {
  3503. const struct btf_type *t;
  3504. const char *tname;
  3505. int i, n;
  3506. if (!btf)
  3507. return -ESRCH;
  3508. n = btf__type_cnt(btf);
  3509. for (i = 1; i < n; i++) {
  3510. t = btf__type_by_id(btf, i);
  3511. if (!btf_is_var(t) && !btf_is_func(t))
  3512. continue;
  3513. tname = btf__name_by_offset(btf, t->name_off);
  3514. if (strcmp(tname, ext_name))
  3515. continue;
  3516. if (btf_is_var(t) &&
  3517. btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
  3518. return -EINVAL;
  3519. if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
  3520. return -EINVAL;
  3521. return i;
  3522. }
  3523. return -ENOENT;
  3524. }
  3525. static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
  3526. const struct btf_var_secinfo *vs;
  3527. const struct btf_type *t;
  3528. int i, j, n;
  3529. if (!btf)
  3530. return -ESRCH;
  3531. n = btf__type_cnt(btf);
  3532. for (i = 1; i < n; i++) {
  3533. t = btf__type_by_id(btf, i);
  3534. if (!btf_is_datasec(t))
  3535. continue;
  3536. vs = btf_var_secinfos(t);
  3537. for (j = 0; j < btf_vlen(t); j++, vs++) {
  3538. if (vs->type == ext_btf_id)
  3539. return i;
  3540. }
  3541. }
  3542. return -ENOENT;
  3543. }
  3544. static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
  3545. bool *is_signed)
  3546. {
  3547. const struct btf_type *t;
  3548. const char *name;
  3549. t = skip_mods_and_typedefs(btf, id, NULL);
  3550. name = btf__name_by_offset(btf, t->name_off);
  3551. if (is_signed)
  3552. *is_signed = false;
  3553. switch (btf_kind(t)) {
  3554. case BTF_KIND_INT: {
  3555. int enc = btf_int_encoding(t);
  3556. if (enc & BTF_INT_BOOL)
  3557. return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
  3558. if (is_signed)
  3559. *is_signed = enc & BTF_INT_SIGNED;
  3560. if (t->size == 1)
  3561. return KCFG_CHAR;
  3562. if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
  3563. return KCFG_UNKNOWN;
  3564. return KCFG_INT;
  3565. }
  3566. case BTF_KIND_ENUM:
  3567. if (t->size != 4)
  3568. return KCFG_UNKNOWN;
  3569. if (strcmp(name, "libbpf_tristate"))
  3570. return KCFG_UNKNOWN;
  3571. return KCFG_TRISTATE;
  3572. case BTF_KIND_ENUM64:
  3573. if (strcmp(name, "libbpf_tristate"))
  3574. return KCFG_UNKNOWN;
  3575. return KCFG_TRISTATE;
  3576. case BTF_KIND_ARRAY:
  3577. if (btf_array(t)->nelems == 0)
  3578. return KCFG_UNKNOWN;
  3579. if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
  3580. return KCFG_UNKNOWN;
  3581. return KCFG_CHAR_ARR;
  3582. default:
  3583. return KCFG_UNKNOWN;
  3584. }
  3585. }
  3586. static int cmp_externs(const void *_a, const void *_b)
  3587. {
  3588. const struct extern_desc *a = _a;
  3589. const struct extern_desc *b = _b;
  3590. if (a->type != b->type)
  3591. return a->type < b->type ? -1 : 1;
  3592. if (a->type == EXT_KCFG) {
  3593. /* descending order by alignment requirements */
  3594. if (a->kcfg.align != b->kcfg.align)
  3595. return a->kcfg.align > b->kcfg.align ? -1 : 1;
  3596. /* ascending order by size, within same alignment class */
  3597. if (a->kcfg.sz != b->kcfg.sz)
  3598. return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
  3599. }
  3600. /* resolve ties by name */
  3601. return strcmp(a->name, b->name);
  3602. }
  3603. static int find_int_btf_id(const struct btf *btf)
  3604. {
  3605. const struct btf_type *t;
  3606. int i, n;
  3607. n = btf__type_cnt(btf);
  3608. for (i = 1; i < n; i++) {
  3609. t = btf__type_by_id(btf, i);
  3610. if (btf_is_int(t) && btf_int_bits(t) == 32)
  3611. return i;
  3612. }
  3613. return 0;
  3614. }
  3615. static int add_dummy_ksym_var(struct btf *btf)
  3616. {
  3617. int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
  3618. const struct btf_var_secinfo *vs;
  3619. const struct btf_type *sec;
  3620. if (!btf)
  3621. return 0;
  3622. sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
  3623. BTF_KIND_DATASEC);
  3624. if (sec_btf_id < 0)
  3625. return 0;
  3626. sec = btf__type_by_id(btf, sec_btf_id);
  3627. vs = btf_var_secinfos(sec);
  3628. for (i = 0; i < btf_vlen(sec); i++, vs++) {
  3629. const struct btf_type *vt;
  3630. vt = btf__type_by_id(btf, vs->type);
  3631. if (btf_is_func(vt))
  3632. break;
  3633. }
  3634. /* No func in ksyms sec. No need to add dummy var. */
  3635. if (i == btf_vlen(sec))
  3636. return 0;
  3637. int_btf_id = find_int_btf_id(btf);
  3638. dummy_var_btf_id = btf__add_var(btf,
  3639. "dummy_ksym",
  3640. BTF_VAR_GLOBAL_ALLOCATED,
  3641. int_btf_id);
  3642. if (dummy_var_btf_id < 0)
  3643. pr_warn("cannot create a dummy_ksym var\n");
  3644. return dummy_var_btf_id;
  3645. }
  3646. static int bpf_object__collect_externs(struct bpf_object *obj)
  3647. {
  3648. struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
  3649. const struct btf_type *t;
  3650. struct extern_desc *ext;
  3651. int i, n, off, dummy_var_btf_id;
  3652. const char *ext_name, *sec_name;
  3653. size_t ext_essent_len;
  3654. Elf_Scn *scn;
  3655. Elf64_Shdr *sh;
  3656. if (!obj->efile.symbols)
  3657. return 0;
  3658. scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
  3659. sh = elf_sec_hdr(obj, scn);
  3660. if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
  3661. return -LIBBPF_ERRNO__FORMAT;
  3662. dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
  3663. if (dummy_var_btf_id < 0)
  3664. return dummy_var_btf_id;
  3665. n = sh->sh_size / sh->sh_entsize;
  3666. pr_debug("looking for externs among %d symbols...\n", n);
  3667. for (i = 0; i < n; i++) {
  3668. Elf64_Sym *sym = elf_sym_by_idx(obj, i);
  3669. if (!sym)
  3670. return -LIBBPF_ERRNO__FORMAT;
  3671. if (!sym_is_extern(sym))
  3672. continue;
  3673. ext_name = elf_sym_str(obj, sym->st_name);
  3674. if (str_is_empty(ext_name))
  3675. continue;
  3676. ext = obj->externs;
  3677. ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
  3678. if (!ext)
  3679. return -ENOMEM;
  3680. obj->externs = ext;
  3681. ext = &ext[obj->nr_extern];
  3682. memset(ext, 0, sizeof(*ext));
  3683. obj->nr_extern++;
  3684. ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
  3685. if (ext->btf_id <= 0) {
  3686. pr_warn("failed to find BTF for extern '%s': %d\n",
  3687. ext_name, ext->btf_id);
  3688. return ext->btf_id;
  3689. }
  3690. t = btf__type_by_id(obj->btf, ext->btf_id);
  3691. ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
  3692. if (!ext->name)
  3693. return -ENOMEM;
  3694. ext->sym_idx = i;
  3695. ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
  3696. ext_essent_len = bpf_core_essential_name_len(ext->name);
  3697. ext->essent_name = NULL;
  3698. if (ext_essent_len != strlen(ext->name)) {
  3699. ext->essent_name = strndup(ext->name, ext_essent_len);
  3700. if (!ext->essent_name)
  3701. return -ENOMEM;
  3702. }
  3703. ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
  3704. if (ext->sec_btf_id <= 0) {
  3705. pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
  3706. ext_name, ext->btf_id, ext->sec_btf_id);
  3707. return ext->sec_btf_id;
  3708. }
  3709. sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
  3710. sec_name = btf__name_by_offset(obj->btf, sec->name_off);
  3711. if (strcmp(sec_name, KCONFIG_SEC) == 0) {
  3712. if (btf_is_func(t)) {
  3713. pr_warn("extern function %s is unsupported under %s section\n",
  3714. ext->name, KCONFIG_SEC);
  3715. return -ENOTSUP;
  3716. }
  3717. kcfg_sec = sec;
  3718. ext->type = EXT_KCFG;
  3719. ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
  3720. if (ext->kcfg.sz <= 0) {
  3721. pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
  3722. ext_name, ext->kcfg.sz);
  3723. return ext->kcfg.sz;
  3724. }
  3725. ext->kcfg.align = btf__align_of(obj->btf, t->type);
  3726. if (ext->kcfg.align <= 0) {
  3727. pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
  3728. ext_name, ext->kcfg.align);
  3729. return -EINVAL;
  3730. }
  3731. ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
  3732. &ext->kcfg.is_signed);
  3733. if (ext->kcfg.type == KCFG_UNKNOWN) {
  3734. pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
  3735. return -ENOTSUP;
  3736. }
  3737. } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
  3738. ksym_sec = sec;
  3739. ext->type = EXT_KSYM;
  3740. skip_mods_and_typedefs(obj->btf, t->type,
  3741. &ext->ksym.type_id);
  3742. } else {
  3743. pr_warn("unrecognized extern section '%s'\n", sec_name);
  3744. return -ENOTSUP;
  3745. }
  3746. }
  3747. pr_debug("collected %d externs total\n", obj->nr_extern);
  3748. if (!obj->nr_extern)
  3749. return 0;
  3750. /* sort externs by type, for kcfg ones also by (align, size, name) */
  3751. qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
  3752. /* for .ksyms section, we need to turn all externs into allocated
  3753. * variables in BTF to pass kernel verification; we do this by
  3754. * pretending that each extern is a 8-byte variable
  3755. */
  3756. if (ksym_sec) {
  3757. /* find existing 4-byte integer type in BTF to use for fake
  3758. * extern variables in DATASEC
  3759. */
  3760. int int_btf_id = find_int_btf_id(obj->btf);
  3761. /* For extern function, a dummy_var added earlier
  3762. * will be used to replace the vs->type and
  3763. * its name string will be used to refill
  3764. * the missing param's name.
  3765. */
  3766. const struct btf_type *dummy_var;
  3767. dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
  3768. for (i = 0; i < obj->nr_extern; i++) {
  3769. ext = &obj->externs[i];
  3770. if (ext->type != EXT_KSYM)
  3771. continue;
  3772. pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
  3773. i, ext->sym_idx, ext->name);
  3774. }
  3775. sec = ksym_sec;
  3776. n = btf_vlen(sec);
  3777. for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
  3778. struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
  3779. struct btf_type *vt;
  3780. vt = (void *)btf__type_by_id(obj->btf, vs->type);
  3781. ext_name = btf__name_by_offset(obj->btf, vt->name_off);
  3782. ext = find_extern_by_name(obj, ext_name);
  3783. if (!ext) {
  3784. pr_warn("failed to find extern definition for BTF %s '%s'\n",
  3785. btf_kind_str(vt), ext_name);
  3786. return -ESRCH;
  3787. }
  3788. if (btf_is_func(vt)) {
  3789. const struct btf_type *func_proto;
  3790. struct btf_param *param;
  3791. int j;
  3792. func_proto = btf__type_by_id(obj->btf,
  3793. vt->type);
  3794. param = btf_params(func_proto);
  3795. /* Reuse the dummy_var string if the
  3796. * func proto does not have param name.
  3797. */
  3798. for (j = 0; j < btf_vlen(func_proto); j++)
  3799. if (param[j].type && !param[j].name_off)
  3800. param[j].name_off =
  3801. dummy_var->name_off;
  3802. vs->type = dummy_var_btf_id;
  3803. vt->info &= ~0xffff;
  3804. vt->info |= BTF_FUNC_GLOBAL;
  3805. } else {
  3806. btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  3807. vt->type = int_btf_id;
  3808. }
  3809. vs->offset = off;
  3810. vs->size = sizeof(int);
  3811. }
  3812. sec->size = off;
  3813. }
  3814. if (kcfg_sec) {
  3815. sec = kcfg_sec;
  3816. /* for kcfg externs calculate their offsets within a .kconfig map */
  3817. off = 0;
  3818. for (i = 0; i < obj->nr_extern; i++) {
  3819. ext = &obj->externs[i];
  3820. if (ext->type != EXT_KCFG)
  3821. continue;
  3822. ext->kcfg.data_off = roundup(off, ext->kcfg.align);
  3823. off = ext->kcfg.data_off + ext->kcfg.sz;
  3824. pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
  3825. i, ext->sym_idx, ext->kcfg.data_off, ext->name);
  3826. }
  3827. sec->size = off;
  3828. n = btf_vlen(sec);
  3829. for (i = 0; i < n; i++) {
  3830. struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
  3831. t = btf__type_by_id(obj->btf, vs->type);
  3832. ext_name = btf__name_by_offset(obj->btf, t->name_off);
  3833. ext = find_extern_by_name(obj, ext_name);
  3834. if (!ext) {
  3835. pr_warn("failed to find extern definition for BTF var '%s'\n",
  3836. ext_name);
  3837. return -ESRCH;
  3838. }
  3839. btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
  3840. vs->offset = ext->kcfg.data_off;
  3841. }
  3842. }
  3843. return 0;
  3844. }
  3845. static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
  3846. {
  3847. return prog->sec_idx == obj->efile.text_shndx;
  3848. }
  3849. struct bpf_program *
  3850. bpf_object__find_program_by_name(const struct bpf_object *obj,
  3851. const char *name)
  3852. {
  3853. struct bpf_program *prog;
  3854. bpf_object__for_each_program(prog, obj) {
  3855. if (prog_is_subprog(obj, prog))
  3856. continue;
  3857. if (!strcmp(prog->name, name))
  3858. return prog;
  3859. }
  3860. return errno = ENOENT, NULL;
  3861. }
  3862. static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
  3863. int shndx)
  3864. {
  3865. switch (obj->efile.secs[shndx].sec_type) {
  3866. case SEC_BSS:
  3867. case SEC_DATA:
  3868. case SEC_RODATA:
  3869. return true;
  3870. default:
  3871. return false;
  3872. }
  3873. }
  3874. static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
  3875. int shndx)
  3876. {
  3877. return shndx == obj->efile.btf_maps_shndx;
  3878. }
  3879. static enum libbpf_map_type
  3880. bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
  3881. {
  3882. if (shndx == obj->efile.symbols_shndx)
  3883. return LIBBPF_MAP_KCONFIG;
  3884. switch (obj->efile.secs[shndx].sec_type) {
  3885. case SEC_BSS:
  3886. return LIBBPF_MAP_BSS;
  3887. case SEC_DATA:
  3888. return LIBBPF_MAP_DATA;
  3889. case SEC_RODATA:
  3890. return LIBBPF_MAP_RODATA;
  3891. default:
  3892. return LIBBPF_MAP_UNSPEC;
  3893. }
  3894. }
  3895. static int bpf_prog_compute_hash(struct bpf_program *prog)
  3896. {
  3897. struct bpf_insn *purged;
  3898. int i, err = 0;
  3899. purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
  3900. if (!purged)
  3901. return -ENOMEM;
  3902. /* If relocations have been done, the map_fd needs to be
  3903. * discarded for the digest calculation.
  3904. */
  3905. for (i = 0; i < prog->insns_cnt; i++) {
  3906. purged[i] = prog->insns[i];
  3907. if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
  3908. (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
  3909. purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
  3910. purged[i].imm = 0;
  3911. i++;
  3912. if (i >= prog->insns_cnt ||
  3913. prog->insns[i].code != 0 ||
  3914. prog->insns[i].dst_reg != 0 ||
  3915. prog->insns[i].src_reg != 0 ||
  3916. prog->insns[i].off != 0) {
  3917. err = -EINVAL;
  3918. goto out;
  3919. }
  3920. purged[i] = prog->insns[i];
  3921. purged[i].imm = 0;
  3922. }
  3923. }
  3924. libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
  3925. prog->hash);
  3926. out:
  3927. free(purged);
  3928. return err;
  3929. }
  3930. static int bpf_program__record_reloc(struct bpf_program *prog,
  3931. struct reloc_desc *reloc_desc,
  3932. __u32 insn_idx, const char *sym_name,
  3933. const Elf64_Sym *sym, const Elf64_Rel *rel)
  3934. {
  3935. struct bpf_insn *insn = &prog->insns[insn_idx];
  3936. size_t map_idx, nr_maps = prog->obj->nr_maps;
  3937. struct bpf_object *obj = prog->obj;
  3938. __u32 shdr_idx = sym->st_shndx;
  3939. enum libbpf_map_type type;
  3940. const char *sym_sec_name;
  3941. struct bpf_map *map;
  3942. if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
  3943. pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
  3944. prog->name, sym_name, insn_idx, insn->code);
  3945. return -LIBBPF_ERRNO__RELOC;
  3946. }
  3947. if (sym_is_extern(sym)) {
  3948. int sym_idx = ELF64_R_SYM(rel->r_info);
  3949. int i, n = obj->nr_extern;
  3950. struct extern_desc *ext;
  3951. for (i = 0; i < n; i++) {
  3952. ext = &obj->externs[i];
  3953. if (ext->sym_idx == sym_idx)
  3954. break;
  3955. }
  3956. if (i >= n) {
  3957. pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
  3958. prog->name, sym_name, sym_idx);
  3959. return -LIBBPF_ERRNO__RELOC;
  3960. }
  3961. pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
  3962. prog->name, i, ext->name, ext->sym_idx, insn_idx);
  3963. if (insn->code == (BPF_JMP | BPF_CALL))
  3964. reloc_desc->type = RELO_EXTERN_CALL;
  3965. else
  3966. reloc_desc->type = RELO_EXTERN_LD64;
  3967. reloc_desc->insn_idx = insn_idx;
  3968. reloc_desc->ext_idx = i;
  3969. return 0;
  3970. }
  3971. /* sub-program call relocation */
  3972. if (is_call_insn(insn)) {
  3973. if (insn->src_reg != BPF_PSEUDO_CALL) {
  3974. pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
  3975. return -LIBBPF_ERRNO__RELOC;
  3976. }
  3977. /* text_shndx can be 0, if no default "main" program exists */
  3978. if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
  3979. sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
  3980. pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
  3981. prog->name, sym_name, sym_sec_name);
  3982. return -LIBBPF_ERRNO__RELOC;
  3983. }
  3984. if (sym->st_value % BPF_INSN_SZ) {
  3985. pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
  3986. prog->name, sym_name, (size_t)sym->st_value);
  3987. return -LIBBPF_ERRNO__RELOC;
  3988. }
  3989. reloc_desc->type = RELO_CALL;
  3990. reloc_desc->insn_idx = insn_idx;
  3991. reloc_desc->sym_off = sym->st_value;
  3992. return 0;
  3993. }
  3994. if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
  3995. pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
  3996. prog->name, sym_name, shdr_idx);
  3997. return -LIBBPF_ERRNO__RELOC;
  3998. }
  3999. /* loading subprog addresses */
  4000. if (sym_is_subprog(sym, obj->efile.text_shndx)) {
  4001. /* global_func: sym->st_value = offset in the section, insn->imm = 0.
  4002. * local_func: sym->st_value = 0, insn->imm = offset in the section.
  4003. */
  4004. if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
  4005. pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
  4006. prog->name, sym_name, (size_t)sym->st_value, insn->imm);
  4007. return -LIBBPF_ERRNO__RELOC;
  4008. }
  4009. reloc_desc->type = RELO_SUBPROG_ADDR;
  4010. reloc_desc->insn_idx = insn_idx;
  4011. reloc_desc->sym_off = sym->st_value;
  4012. return 0;
  4013. }
  4014. type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
  4015. sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
  4016. /* arena data relocation */
  4017. if (shdr_idx == obj->efile.arena_data_shndx) {
  4018. if (obj->arena_map_idx < 0) {
  4019. pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
  4020. prog->name, insn_idx);
  4021. return -LIBBPF_ERRNO__RELOC;
  4022. }
  4023. reloc_desc->type = RELO_DATA;
  4024. reloc_desc->insn_idx = insn_idx;
  4025. reloc_desc->map_idx = obj->arena_map_idx;
  4026. reloc_desc->sym_off = sym->st_value;
  4027. map = &obj->maps[obj->arena_map_idx];
  4028. pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
  4029. prog->name, obj->arena_map_idx, map->name, map->sec_idx,
  4030. map->sec_offset, insn_idx);
  4031. return 0;
  4032. }
  4033. /* jump table data relocation */
  4034. if (shdr_idx == obj->efile.jumptables_data_shndx) {
  4035. reloc_desc->type = RELO_INSN_ARRAY;
  4036. reloc_desc->insn_idx = insn_idx;
  4037. reloc_desc->map_idx = -1;
  4038. reloc_desc->sym_off = sym->st_value;
  4039. reloc_desc->sym_size = sym->st_size;
  4040. return 0;
  4041. }
  4042. /* generic map reference relocation */
  4043. if (type == LIBBPF_MAP_UNSPEC) {
  4044. if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
  4045. pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
  4046. prog->name, sym_name, sym_sec_name);
  4047. return -LIBBPF_ERRNO__RELOC;
  4048. }
  4049. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  4050. map = &obj->maps[map_idx];
  4051. if (map->libbpf_type != type ||
  4052. map->sec_idx != sym->st_shndx ||
  4053. map->sec_offset != sym->st_value)
  4054. continue;
  4055. pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
  4056. prog->name, map_idx, map->name, map->sec_idx,
  4057. map->sec_offset, insn_idx);
  4058. break;
  4059. }
  4060. if (map_idx >= nr_maps) {
  4061. pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
  4062. prog->name, sym_sec_name, (size_t)sym->st_value);
  4063. return -LIBBPF_ERRNO__RELOC;
  4064. }
  4065. reloc_desc->type = RELO_LD64;
  4066. reloc_desc->insn_idx = insn_idx;
  4067. reloc_desc->map_idx = map_idx;
  4068. reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
  4069. return 0;
  4070. }
  4071. /* global data map relocation */
  4072. if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
  4073. pr_warn("prog '%s': bad data relo against section '%s'\n",
  4074. prog->name, sym_sec_name);
  4075. return -LIBBPF_ERRNO__RELOC;
  4076. }
  4077. for (map_idx = 0; map_idx < nr_maps; map_idx++) {
  4078. map = &obj->maps[map_idx];
  4079. if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
  4080. continue;
  4081. pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
  4082. prog->name, map_idx, map->name, map->sec_idx,
  4083. map->sec_offset, insn_idx);
  4084. break;
  4085. }
  4086. if (map_idx >= nr_maps) {
  4087. pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
  4088. prog->name, sym_sec_name);
  4089. return -LIBBPF_ERRNO__RELOC;
  4090. }
  4091. reloc_desc->type = RELO_DATA;
  4092. reloc_desc->insn_idx = insn_idx;
  4093. reloc_desc->map_idx = map_idx;
  4094. reloc_desc->sym_off = sym->st_value;
  4095. return 0;
  4096. }
  4097. static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
  4098. {
  4099. return insn_idx >= prog->sec_insn_off &&
  4100. insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
  4101. }
  4102. static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
  4103. size_t sec_idx, size_t insn_idx)
  4104. {
  4105. int l = 0, r = obj->nr_programs - 1, m;
  4106. struct bpf_program *prog;
  4107. if (!obj->nr_programs)
  4108. return NULL;
  4109. while (l < r) {
  4110. m = l + (r - l + 1) / 2;
  4111. prog = &obj->programs[m];
  4112. if (prog->sec_idx < sec_idx ||
  4113. (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
  4114. l = m;
  4115. else
  4116. r = m - 1;
  4117. }
  4118. /* matching program could be at index l, but it still might be the
  4119. * wrong one, so we need to double check conditions for the last time
  4120. */
  4121. prog = &obj->programs[l];
  4122. if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
  4123. return prog;
  4124. return NULL;
  4125. }
  4126. static int
  4127. bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
  4128. {
  4129. const char *relo_sec_name, *sec_name;
  4130. size_t sec_idx = shdr->sh_info, sym_idx;
  4131. struct bpf_program *prog;
  4132. struct reloc_desc *relos;
  4133. int err, i, nrels;
  4134. const char *sym_name;
  4135. __u32 insn_idx;
  4136. Elf_Scn *scn;
  4137. Elf_Data *scn_data;
  4138. Elf64_Sym *sym;
  4139. Elf64_Rel *rel;
  4140. if (sec_idx >= obj->efile.sec_cnt)
  4141. return -EINVAL;
  4142. scn = elf_sec_by_idx(obj, sec_idx);
  4143. scn_data = elf_sec_data(obj, scn);
  4144. if (!scn_data)
  4145. return -LIBBPF_ERRNO__FORMAT;
  4146. relo_sec_name = elf_sec_str(obj, shdr->sh_name);
  4147. sec_name = elf_sec_name(obj, scn);
  4148. if (!relo_sec_name || !sec_name)
  4149. return -EINVAL;
  4150. pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
  4151. relo_sec_name, sec_idx, sec_name);
  4152. nrels = shdr->sh_size / shdr->sh_entsize;
  4153. for (i = 0; i < nrels; i++) {
  4154. rel = elf_rel_by_idx(data, i);
  4155. if (!rel) {
  4156. pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
  4157. return -LIBBPF_ERRNO__FORMAT;
  4158. }
  4159. sym_idx = ELF64_R_SYM(rel->r_info);
  4160. sym = elf_sym_by_idx(obj, sym_idx);
  4161. if (!sym) {
  4162. pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
  4163. relo_sec_name, sym_idx, i);
  4164. return -LIBBPF_ERRNO__FORMAT;
  4165. }
  4166. if (sym->st_shndx >= obj->efile.sec_cnt) {
  4167. pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
  4168. relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
  4169. return -LIBBPF_ERRNO__FORMAT;
  4170. }
  4171. if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
  4172. pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
  4173. relo_sec_name, (size_t)rel->r_offset, i);
  4174. return -LIBBPF_ERRNO__FORMAT;
  4175. }
  4176. insn_idx = rel->r_offset / BPF_INSN_SZ;
  4177. /* relocations against static functions are recorded as
  4178. * relocations against the section that contains a function;
  4179. * in such case, symbol will be STT_SECTION and sym.st_name
  4180. * will point to empty string (0), so fetch section name
  4181. * instead
  4182. */
  4183. if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
  4184. sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
  4185. else
  4186. sym_name = elf_sym_str(obj, sym->st_name);
  4187. sym_name = sym_name ?: "<?";
  4188. pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
  4189. relo_sec_name, i, insn_idx, sym_name);
  4190. prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
  4191. if (!prog) {
  4192. pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
  4193. relo_sec_name, i, sec_name, insn_idx);
  4194. continue;
  4195. }
  4196. relos = libbpf_reallocarray(prog->reloc_desc,
  4197. prog->nr_reloc + 1, sizeof(*relos));
  4198. if (!relos)
  4199. return -ENOMEM;
  4200. prog->reloc_desc = relos;
  4201. /* adjust insn_idx to local BPF program frame of reference */
  4202. insn_idx -= prog->sec_insn_off;
  4203. err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
  4204. insn_idx, sym_name, sym, rel);
  4205. if (err)
  4206. return err;
  4207. prog->nr_reloc++;
  4208. }
  4209. return 0;
  4210. }
  4211. static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
  4212. {
  4213. int id;
  4214. if (!obj->btf)
  4215. return -ENOENT;
  4216. /* if it's BTF-defined map, we don't need to search for type IDs.
  4217. * For struct_ops map, it does not need btf_key_type_id and
  4218. * btf_value_type_id.
  4219. */
  4220. if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
  4221. return 0;
  4222. /*
  4223. * LLVM annotates global data differently in BTF, that is,
  4224. * only as '.data', '.bss' or '.rodata'.
  4225. */
  4226. if (!bpf_map__is_internal(map))
  4227. return -ENOENT;
  4228. id = btf__find_by_name(obj->btf, map->real_name);
  4229. if (id < 0)
  4230. return id;
  4231. map->btf_key_type_id = 0;
  4232. map->btf_value_type_id = id;
  4233. return 0;
  4234. }
  4235. static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
  4236. {
  4237. char file[PATH_MAX], buff[4096];
  4238. FILE *fp;
  4239. __u32 val;
  4240. int err;
  4241. snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
  4242. memset(info, 0, sizeof(*info));
  4243. fp = fopen(file, "re");
  4244. if (!fp) {
  4245. err = -errno;
  4246. pr_warn("failed to open %s: %s. No procfs support?\n", file,
  4247. errstr(err));
  4248. return err;
  4249. }
  4250. while (fgets(buff, sizeof(buff), fp)) {
  4251. if (sscanf(buff, "map_type:\t%u", &val) == 1)
  4252. info->type = val;
  4253. else if (sscanf(buff, "key_size:\t%u", &val) == 1)
  4254. info->key_size = val;
  4255. else if (sscanf(buff, "value_size:\t%u", &val) == 1)
  4256. info->value_size = val;
  4257. else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
  4258. info->max_entries = val;
  4259. else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
  4260. info->map_flags = val;
  4261. }
  4262. fclose(fp);
  4263. return 0;
  4264. }
  4265. static bool map_is_created(const struct bpf_map *map)
  4266. {
  4267. return map->obj->state >= OBJ_PREPARED || map->reused;
  4268. }
  4269. bool bpf_map__autocreate(const struct bpf_map *map)
  4270. {
  4271. return map->autocreate;
  4272. }
  4273. int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
  4274. {
  4275. if (map_is_created(map))
  4276. return libbpf_err(-EBUSY);
  4277. map->autocreate = autocreate;
  4278. return 0;
  4279. }
  4280. int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
  4281. {
  4282. if (!bpf_map__is_struct_ops(map))
  4283. return libbpf_err(-EINVAL);
  4284. map->autoattach = autoattach;
  4285. return 0;
  4286. }
  4287. bool bpf_map__autoattach(const struct bpf_map *map)
  4288. {
  4289. return map->autoattach;
  4290. }
  4291. int bpf_map__reuse_fd(struct bpf_map *map, int fd)
  4292. {
  4293. struct bpf_map_info info;
  4294. __u32 len = sizeof(info), name_len;
  4295. int new_fd, err;
  4296. char *new_name;
  4297. memset(&info, 0, len);
  4298. err = bpf_map_get_info_by_fd(fd, &info, &len);
  4299. if (err && errno == EINVAL)
  4300. err = bpf_get_map_info_from_fdinfo(fd, &info);
  4301. if (err)
  4302. return libbpf_err(err);
  4303. name_len = strlen(info.name);
  4304. if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
  4305. new_name = strdup(map->name);
  4306. else
  4307. new_name = strdup(info.name);
  4308. if (!new_name)
  4309. return libbpf_err(-errno);
  4310. /*
  4311. * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
  4312. * This is similar to what we do in ensure_good_fd(), but without
  4313. * closing original FD.
  4314. */
  4315. new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
  4316. if (new_fd < 0) {
  4317. err = -errno;
  4318. goto err_free_new_name;
  4319. }
  4320. err = reuse_fd(map->fd, new_fd);
  4321. if (err)
  4322. goto err_free_new_name;
  4323. free(map->name);
  4324. map->name = new_name;
  4325. map->def.type = info.type;
  4326. map->def.key_size = info.key_size;
  4327. map->def.value_size = info.value_size;
  4328. map->def.max_entries = info.max_entries;
  4329. map->def.map_flags = info.map_flags;
  4330. map->btf_key_type_id = info.btf_key_type_id;
  4331. map->btf_value_type_id = info.btf_value_type_id;
  4332. map->reused = true;
  4333. map->map_extra = info.map_extra;
  4334. return 0;
  4335. err_free_new_name:
  4336. free(new_name);
  4337. return libbpf_err(err);
  4338. }
  4339. __u32 bpf_map__max_entries(const struct bpf_map *map)
  4340. {
  4341. return map->def.max_entries;
  4342. }
  4343. struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
  4344. {
  4345. if (!bpf_map_type__is_map_in_map(map->def.type))
  4346. return errno = EINVAL, NULL;
  4347. return map->inner_map;
  4348. }
  4349. int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
  4350. {
  4351. if (map_is_created(map))
  4352. return libbpf_err(-EBUSY);
  4353. map->def.max_entries = max_entries;
  4354. /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
  4355. if (map_is_ringbuf(map))
  4356. map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
  4357. return 0;
  4358. }
  4359. static int bpf_object_prepare_token(struct bpf_object *obj)
  4360. {
  4361. const char *bpffs_path;
  4362. int bpffs_fd = -1, token_fd, err;
  4363. bool mandatory;
  4364. enum libbpf_print_level level;
  4365. /* token is explicitly prevented */
  4366. if (obj->token_path && obj->token_path[0] == '\0') {
  4367. pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
  4368. return 0;
  4369. }
  4370. mandatory = obj->token_path != NULL;
  4371. level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
  4372. bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
  4373. bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
  4374. if (bpffs_fd < 0) {
  4375. err = -errno;
  4376. __pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
  4377. obj->name, errstr(err), bpffs_path,
  4378. mandatory ? "" : ", skipping optional step...");
  4379. return mandatory ? err : 0;
  4380. }
  4381. token_fd = bpf_token_create(bpffs_fd, 0);
  4382. close(bpffs_fd);
  4383. if (token_fd < 0) {
  4384. if (!mandatory && token_fd == -ENOENT) {
  4385. pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
  4386. obj->name, bpffs_path);
  4387. return 0;
  4388. }
  4389. __pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
  4390. obj->name, token_fd, bpffs_path,
  4391. mandatory ? "" : ", skipping optional step...");
  4392. return mandatory ? token_fd : 0;
  4393. }
  4394. obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
  4395. if (!obj->feat_cache) {
  4396. close(token_fd);
  4397. return -ENOMEM;
  4398. }
  4399. obj->token_fd = token_fd;
  4400. obj->feat_cache->token_fd = token_fd;
  4401. return 0;
  4402. }
  4403. static int
  4404. bpf_object__probe_loading(struct bpf_object *obj)
  4405. {
  4406. struct bpf_insn insns[] = {
  4407. BPF_MOV64_IMM(BPF_REG_0, 0),
  4408. BPF_EXIT_INSN(),
  4409. };
  4410. int ret, insn_cnt = ARRAY_SIZE(insns);
  4411. LIBBPF_OPTS(bpf_prog_load_opts, opts,
  4412. .token_fd = obj->token_fd,
  4413. .prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
  4414. );
  4415. if (obj->gen_loader)
  4416. return 0;
  4417. ret = bump_rlimit_memlock();
  4418. if (ret)
  4419. pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
  4420. errstr(ret));
  4421. /* make sure basic loading works */
  4422. ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
  4423. if (ret < 0)
  4424. ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
  4425. if (ret < 0) {
  4426. ret = errno;
  4427. pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
  4428. __func__, errstr(ret));
  4429. return -ret;
  4430. }
  4431. close(ret);
  4432. return 0;
  4433. }
  4434. bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
  4435. {
  4436. if (obj->gen_loader)
  4437. /* To generate loader program assume the latest kernel
  4438. * to avoid doing extra prog_load, map_create syscalls.
  4439. */
  4440. return true;
  4441. if (obj->token_fd)
  4442. return feat_supported(obj->feat_cache, feat_id);
  4443. return feat_supported(NULL, feat_id);
  4444. }
  4445. static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
  4446. {
  4447. struct bpf_map_info map_info;
  4448. __u32 map_info_len = sizeof(map_info);
  4449. int err;
  4450. memset(&map_info, 0, map_info_len);
  4451. err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
  4452. if (err && errno == EINVAL)
  4453. err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
  4454. if (err) {
  4455. pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
  4456. errstr(err));
  4457. return false;
  4458. }
  4459. /*
  4460. * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
  4461. * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
  4462. * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
  4463. * bpf_get_map_info_by_fd() when checking for compatibility with an
  4464. * existing DEVMAP.
  4465. */
  4466. if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
  4467. map_info.map_flags &= ~BPF_F_RDONLY_PROG;
  4468. return (map_info.type == map->def.type &&
  4469. map_info.key_size == map->def.key_size &&
  4470. map_info.value_size == map->def.value_size &&
  4471. map_info.max_entries == map->def.max_entries &&
  4472. map_info.map_flags == map->def.map_flags &&
  4473. map_info.map_extra == map->map_extra);
  4474. }
  4475. static int
  4476. bpf_object__reuse_map(struct bpf_map *map)
  4477. {
  4478. int err, pin_fd;
  4479. pin_fd = bpf_obj_get(map->pin_path);
  4480. if (pin_fd < 0) {
  4481. err = -errno;
  4482. if (err == -ENOENT) {
  4483. pr_debug("found no pinned map to reuse at '%s'\n",
  4484. map->pin_path);
  4485. return 0;
  4486. }
  4487. pr_warn("couldn't retrieve pinned map '%s': %s\n",
  4488. map->pin_path, errstr(err));
  4489. return err;
  4490. }
  4491. if (!map_is_reuse_compat(map, pin_fd)) {
  4492. pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
  4493. map->pin_path);
  4494. close(pin_fd);
  4495. return -EINVAL;
  4496. }
  4497. err = bpf_map__reuse_fd(map, pin_fd);
  4498. close(pin_fd);
  4499. if (err)
  4500. return err;
  4501. map->pinned = true;
  4502. pr_debug("reused pinned map at '%s'\n", map->pin_path);
  4503. return 0;
  4504. }
  4505. static int
  4506. bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
  4507. {
  4508. enum libbpf_map_type map_type = map->libbpf_type;
  4509. int err, zero = 0;
  4510. size_t mmap_sz;
  4511. if (obj->gen_loader) {
  4512. bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
  4513. map->mmaped, map->def.value_size);
  4514. if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
  4515. bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
  4516. return 0;
  4517. }
  4518. err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
  4519. if (err) {
  4520. err = -errno;
  4521. pr_warn("map '%s': failed to set initial contents: %s\n",
  4522. bpf_map__name(map), errstr(err));
  4523. return err;
  4524. }
  4525. /* Freeze .rodata and .kconfig map as read-only from syscall side. */
  4526. if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
  4527. err = bpf_map_freeze(map->fd);
  4528. if (err) {
  4529. err = -errno;
  4530. pr_warn("map '%s': failed to freeze as read-only: %s\n",
  4531. bpf_map__name(map), errstr(err));
  4532. return err;
  4533. }
  4534. }
  4535. /* Remap anonymous mmap()-ed "map initialization image" as
  4536. * a BPF map-backed mmap()-ed memory, but preserving the same
  4537. * memory address. This will cause kernel to change process'
  4538. * page table to point to a different piece of kernel memory,
  4539. * but from userspace point of view memory address (and its
  4540. * contents, being identical at this point) will stay the
  4541. * same. This mapping will be released by bpf_object__close()
  4542. * as per normal clean up procedure.
  4543. */
  4544. mmap_sz = bpf_map_mmap_sz(map);
  4545. if (map->def.map_flags & BPF_F_MMAPABLE) {
  4546. void *mmaped;
  4547. int prot;
  4548. if (map->def.map_flags & BPF_F_RDONLY_PROG)
  4549. prot = PROT_READ;
  4550. else
  4551. prot = PROT_READ | PROT_WRITE;
  4552. mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
  4553. if (mmaped == MAP_FAILED) {
  4554. err = -errno;
  4555. pr_warn("map '%s': failed to re-mmap() contents: %s\n",
  4556. bpf_map__name(map), errstr(err));
  4557. return err;
  4558. }
  4559. map->mmaped = mmaped;
  4560. } else if (map->mmaped) {
  4561. munmap(map->mmaped, mmap_sz);
  4562. map->mmaped = NULL;
  4563. }
  4564. return 0;
  4565. }
  4566. static void bpf_map__destroy(struct bpf_map *map);
  4567. static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
  4568. {
  4569. LIBBPF_OPTS(bpf_map_create_opts, create_attr);
  4570. struct bpf_map_def *def = &map->def;
  4571. const char *map_name = NULL;
  4572. int err = 0, map_fd;
  4573. if (kernel_supports(obj, FEAT_PROG_NAME))
  4574. map_name = map->name;
  4575. create_attr.map_ifindex = map->map_ifindex;
  4576. create_attr.map_flags = def->map_flags;
  4577. create_attr.numa_node = map->numa_node;
  4578. create_attr.map_extra = map->map_extra;
  4579. create_attr.token_fd = obj->token_fd;
  4580. if (obj->token_fd)
  4581. create_attr.map_flags |= BPF_F_TOKEN_FD;
  4582. if (map->excl_prog) {
  4583. err = bpf_prog_compute_hash(map->excl_prog);
  4584. if (err)
  4585. return err;
  4586. create_attr.excl_prog_hash = map->excl_prog->hash;
  4587. create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
  4588. }
  4589. if (bpf_map__is_struct_ops(map)) {
  4590. create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
  4591. if (map->mod_btf_fd >= 0) {
  4592. create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
  4593. create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
  4594. }
  4595. }
  4596. if (obj->btf && btf__fd(obj->btf) >= 0) {
  4597. create_attr.btf_fd = btf__fd(obj->btf);
  4598. create_attr.btf_key_type_id = map->btf_key_type_id;
  4599. create_attr.btf_value_type_id = map->btf_value_type_id;
  4600. }
  4601. if (bpf_map_type__is_map_in_map(def->type)) {
  4602. if (map->inner_map) {
  4603. err = map_set_def_max_entries(map->inner_map);
  4604. if (err)
  4605. return err;
  4606. err = bpf_object__create_map(obj, map->inner_map, true);
  4607. if (err) {
  4608. pr_warn("map '%s': failed to create inner map: %s\n",
  4609. map->name, errstr(err));
  4610. return err;
  4611. }
  4612. map->inner_map_fd = map->inner_map->fd;
  4613. }
  4614. if (map->inner_map_fd >= 0)
  4615. create_attr.inner_map_fd = map->inner_map_fd;
  4616. }
  4617. switch (def->type) {
  4618. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  4619. case BPF_MAP_TYPE_CGROUP_ARRAY:
  4620. case BPF_MAP_TYPE_STACK_TRACE:
  4621. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  4622. case BPF_MAP_TYPE_HASH_OF_MAPS:
  4623. case BPF_MAP_TYPE_DEVMAP:
  4624. case BPF_MAP_TYPE_DEVMAP_HASH:
  4625. case BPF_MAP_TYPE_CPUMAP:
  4626. case BPF_MAP_TYPE_XSKMAP:
  4627. case BPF_MAP_TYPE_SOCKMAP:
  4628. case BPF_MAP_TYPE_SOCKHASH:
  4629. case BPF_MAP_TYPE_QUEUE:
  4630. case BPF_MAP_TYPE_STACK:
  4631. case BPF_MAP_TYPE_ARENA:
  4632. create_attr.btf_fd = 0;
  4633. create_attr.btf_key_type_id = 0;
  4634. create_attr.btf_value_type_id = 0;
  4635. map->btf_key_type_id = 0;
  4636. map->btf_value_type_id = 0;
  4637. break;
  4638. case BPF_MAP_TYPE_STRUCT_OPS:
  4639. create_attr.btf_value_type_id = 0;
  4640. break;
  4641. default:
  4642. break;
  4643. }
  4644. if (obj->gen_loader) {
  4645. bpf_gen__map_create(obj->gen_loader, def->type, map_name,
  4646. def->key_size, def->value_size, def->max_entries,
  4647. &create_attr, is_inner ? -1 : map - obj->maps);
  4648. /* We keep pretenting we have valid FD to pass various fd >= 0
  4649. * checks by just keeping original placeholder FDs in place.
  4650. * See bpf_object__add_map() comment.
  4651. * This placeholder fd will not be used with any syscall and
  4652. * will be reset to -1 eventually.
  4653. */
  4654. map_fd = map->fd;
  4655. } else {
  4656. map_fd = bpf_map_create(def->type, map_name,
  4657. def->key_size, def->value_size,
  4658. def->max_entries, &create_attr);
  4659. }
  4660. if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
  4661. err = -errno;
  4662. pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
  4663. map->name, errstr(err));
  4664. create_attr.btf_fd = 0;
  4665. create_attr.btf_key_type_id = 0;
  4666. create_attr.btf_value_type_id = 0;
  4667. map->btf_key_type_id = 0;
  4668. map->btf_value_type_id = 0;
  4669. map_fd = bpf_map_create(def->type, map_name,
  4670. def->key_size, def->value_size,
  4671. def->max_entries, &create_attr);
  4672. }
  4673. if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
  4674. if (obj->gen_loader)
  4675. map->inner_map->fd = -1;
  4676. bpf_map__destroy(map->inner_map);
  4677. zfree(&map->inner_map);
  4678. }
  4679. if (map_fd < 0)
  4680. return map_fd;
  4681. /* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
  4682. if (map->fd == map_fd)
  4683. return 0;
  4684. /* Keep placeholder FD value but now point it to the BPF map object.
  4685. * This way everything that relied on this map's FD (e.g., relocated
  4686. * ldimm64 instructions) will stay valid and won't need adjustments.
  4687. * map->fd stays valid but now point to what map_fd points to.
  4688. */
  4689. return reuse_fd(map->fd, map_fd);
  4690. }
  4691. static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
  4692. {
  4693. const struct bpf_map *targ_map;
  4694. unsigned int i;
  4695. int fd, err = 0;
  4696. for (i = 0; i < map->init_slots_sz; i++) {
  4697. if (!map->init_slots[i])
  4698. continue;
  4699. targ_map = map->init_slots[i];
  4700. fd = targ_map->fd;
  4701. if (obj->gen_loader) {
  4702. bpf_gen__populate_outer_map(obj->gen_loader,
  4703. map - obj->maps, i,
  4704. targ_map - obj->maps);
  4705. } else {
  4706. err = bpf_map_update_elem(map->fd, &i, &fd, 0);
  4707. }
  4708. if (err) {
  4709. err = -errno;
  4710. pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
  4711. map->name, i, targ_map->name, fd, errstr(err));
  4712. return err;
  4713. }
  4714. pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
  4715. map->name, i, targ_map->name, fd);
  4716. }
  4717. zfree(&map->init_slots);
  4718. map->init_slots_sz = 0;
  4719. return 0;
  4720. }
  4721. static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
  4722. {
  4723. const struct bpf_program *targ_prog;
  4724. unsigned int i;
  4725. int fd, err;
  4726. if (obj->gen_loader)
  4727. return -ENOTSUP;
  4728. for (i = 0; i < map->init_slots_sz; i++) {
  4729. if (!map->init_slots[i])
  4730. continue;
  4731. targ_prog = map->init_slots[i];
  4732. fd = bpf_program__fd(targ_prog);
  4733. err = bpf_map_update_elem(map->fd, &i, &fd, 0);
  4734. if (err) {
  4735. err = -errno;
  4736. pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
  4737. map->name, i, targ_prog->name, fd, errstr(err));
  4738. return err;
  4739. }
  4740. pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
  4741. map->name, i, targ_prog->name, fd);
  4742. }
  4743. zfree(&map->init_slots);
  4744. map->init_slots_sz = 0;
  4745. return 0;
  4746. }
  4747. static int bpf_object_init_prog_arrays(struct bpf_object *obj)
  4748. {
  4749. struct bpf_map *map;
  4750. int i, err;
  4751. for (i = 0; i < obj->nr_maps; i++) {
  4752. map = &obj->maps[i];
  4753. if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
  4754. continue;
  4755. err = init_prog_array_slots(obj, map);
  4756. if (err < 0)
  4757. return err;
  4758. }
  4759. return 0;
  4760. }
  4761. static int map_set_def_max_entries(struct bpf_map *map)
  4762. {
  4763. if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
  4764. int nr_cpus;
  4765. nr_cpus = libbpf_num_possible_cpus();
  4766. if (nr_cpus < 0) {
  4767. pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
  4768. map->name, nr_cpus);
  4769. return nr_cpus;
  4770. }
  4771. pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
  4772. map->def.max_entries = nr_cpus;
  4773. }
  4774. return 0;
  4775. }
  4776. static int
  4777. bpf_object__create_maps(struct bpf_object *obj)
  4778. {
  4779. struct bpf_map *map;
  4780. unsigned int i, j;
  4781. int err;
  4782. bool retried;
  4783. for (i = 0; i < obj->nr_maps; i++) {
  4784. map = &obj->maps[i];
  4785. /* To support old kernels, we skip creating global data maps
  4786. * (.rodata, .data, .kconfig, etc); later on, during program
  4787. * loading, if we detect that at least one of the to-be-loaded
  4788. * programs is referencing any global data map, we'll error
  4789. * out with program name and relocation index logged.
  4790. * This approach allows to accommodate Clang emitting
  4791. * unnecessary .rodata.str1.1 sections for string literals,
  4792. * but also it allows to have CO-RE applications that use
  4793. * global variables in some of BPF programs, but not others.
  4794. * If those global variable-using programs are not loaded at
  4795. * runtime due to bpf_program__set_autoload(prog, false),
  4796. * bpf_object loading will succeed just fine even on old
  4797. * kernels.
  4798. */
  4799. if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
  4800. map->autocreate = false;
  4801. if (!map->autocreate) {
  4802. pr_debug("map '%s': skipped auto-creating...\n", map->name);
  4803. continue;
  4804. }
  4805. err = map_set_def_max_entries(map);
  4806. if (err)
  4807. goto err_out;
  4808. retried = false;
  4809. retry:
  4810. if (map->pin_path) {
  4811. err = bpf_object__reuse_map(map);
  4812. if (err) {
  4813. pr_warn("map '%s': error reusing pinned map\n",
  4814. map->name);
  4815. goto err_out;
  4816. }
  4817. if (retried && map->fd < 0) {
  4818. pr_warn("map '%s': cannot find pinned map\n",
  4819. map->name);
  4820. err = -ENOENT;
  4821. goto err_out;
  4822. }
  4823. }
  4824. if (map->reused) {
  4825. pr_debug("map '%s': skipping creation (preset fd=%d)\n",
  4826. map->name, map->fd);
  4827. } else {
  4828. err = bpf_object__create_map(obj, map, false);
  4829. if (err)
  4830. goto err_out;
  4831. pr_debug("map '%s': created successfully, fd=%d\n",
  4832. map->name, map->fd);
  4833. if (bpf_map__is_internal(map)) {
  4834. err = bpf_object__populate_internal_map(obj, map);
  4835. if (err < 0)
  4836. goto err_out;
  4837. } else if (map->def.type == BPF_MAP_TYPE_ARENA) {
  4838. map->mmaped = mmap((void *)(long)map->map_extra,
  4839. bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
  4840. map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
  4841. map->fd, 0);
  4842. if (map->mmaped == MAP_FAILED) {
  4843. err = -errno;
  4844. map->mmaped = NULL;
  4845. pr_warn("map '%s': failed to mmap arena: %s\n",
  4846. map->name, errstr(err));
  4847. return err;
  4848. }
  4849. if (obj->arena_data) {
  4850. memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
  4851. obj->arena_data_sz);
  4852. zfree(&obj->arena_data);
  4853. }
  4854. }
  4855. if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
  4856. err = init_map_in_map_slots(obj, map);
  4857. if (err < 0)
  4858. goto err_out;
  4859. }
  4860. }
  4861. if (map->pin_path && !map->pinned) {
  4862. err = bpf_map__pin(map, NULL);
  4863. if (err) {
  4864. if (!retried && err == -EEXIST) {
  4865. retried = true;
  4866. goto retry;
  4867. }
  4868. pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
  4869. map->name, map->pin_path, errstr(err));
  4870. goto err_out;
  4871. }
  4872. }
  4873. }
  4874. return 0;
  4875. err_out:
  4876. pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
  4877. pr_perm_msg(err);
  4878. for (j = 0; j < i; j++)
  4879. zclose(obj->maps[j].fd);
  4880. return err;
  4881. }
  4882. static bool bpf_core_is_flavor_sep(const char *s)
  4883. {
  4884. /* check X___Y name pattern, where X and Y are not underscores */
  4885. return s[0] != '_' && /* X */
  4886. s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
  4887. s[4] != '_'; /* Y */
  4888. }
  4889. /* Given 'some_struct_name___with_flavor' return the length of a name prefix
  4890. * before last triple underscore. Struct name part after last triple
  4891. * underscore is ignored by BPF CO-RE relocation during relocation matching.
  4892. */
  4893. size_t bpf_core_essential_name_len(const char *name)
  4894. {
  4895. size_t n = strlen(name);
  4896. int i;
  4897. for (i = n - 5; i >= 0; i--) {
  4898. if (bpf_core_is_flavor_sep(name + i))
  4899. return i + 1;
  4900. }
  4901. return n;
  4902. }
  4903. void bpf_core_free_cands(struct bpf_core_cand_list *cands)
  4904. {
  4905. if (!cands)
  4906. return;
  4907. free(cands->cands);
  4908. free(cands);
  4909. }
  4910. int bpf_core_add_cands(struct bpf_core_cand *local_cand,
  4911. size_t local_essent_len,
  4912. const struct btf *targ_btf,
  4913. const char *targ_btf_name,
  4914. int targ_start_id,
  4915. struct bpf_core_cand_list *cands)
  4916. {
  4917. struct bpf_core_cand *new_cands, *cand;
  4918. const struct btf_type *t, *local_t;
  4919. const char *targ_name, *local_name;
  4920. size_t targ_essent_len;
  4921. int n, i;
  4922. local_t = btf__type_by_id(local_cand->btf, local_cand->id);
  4923. local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
  4924. n = btf__type_cnt(targ_btf);
  4925. for (i = targ_start_id; i < n; i++) {
  4926. t = btf__type_by_id(targ_btf, i);
  4927. if (!btf_kind_core_compat(t, local_t))
  4928. continue;
  4929. targ_name = btf__name_by_offset(targ_btf, t->name_off);
  4930. if (str_is_empty(targ_name))
  4931. continue;
  4932. targ_essent_len = bpf_core_essential_name_len(targ_name);
  4933. if (targ_essent_len != local_essent_len)
  4934. continue;
  4935. if (strncmp(local_name, targ_name, local_essent_len) != 0)
  4936. continue;
  4937. pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
  4938. local_cand->id, btf_kind_str(local_t),
  4939. local_name, i, btf_kind_str(t), targ_name,
  4940. targ_btf_name);
  4941. new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
  4942. sizeof(*cands->cands));
  4943. if (!new_cands)
  4944. return -ENOMEM;
  4945. cand = &new_cands[cands->len];
  4946. cand->btf = targ_btf;
  4947. cand->id = i;
  4948. cands->cands = new_cands;
  4949. cands->len++;
  4950. }
  4951. return 0;
  4952. }
  4953. static int load_module_btfs(struct bpf_object *obj)
  4954. {
  4955. struct bpf_btf_info info;
  4956. struct module_btf *mod_btf;
  4957. struct btf *btf;
  4958. char name[64];
  4959. __u32 id = 0, len;
  4960. int err, fd;
  4961. if (obj->btf_modules_loaded)
  4962. return 0;
  4963. if (obj->gen_loader)
  4964. return 0;
  4965. /* don't do this again, even if we find no module BTFs */
  4966. obj->btf_modules_loaded = true;
  4967. /* kernel too old to support module BTFs */
  4968. if (!kernel_supports(obj, FEAT_MODULE_BTF))
  4969. return 0;
  4970. while (true) {
  4971. err = bpf_btf_get_next_id(id, &id);
  4972. if (err && errno == ENOENT)
  4973. return 0;
  4974. if (err && errno == EPERM) {
  4975. pr_debug("skipping module BTFs loading, missing privileges\n");
  4976. return 0;
  4977. }
  4978. if (err) {
  4979. err = -errno;
  4980. pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
  4981. return err;
  4982. }
  4983. fd = bpf_btf_get_fd_by_id(id);
  4984. if (fd < 0) {
  4985. if (errno == ENOENT)
  4986. continue; /* expected race: BTF was unloaded */
  4987. err = -errno;
  4988. pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
  4989. return err;
  4990. }
  4991. len = sizeof(info);
  4992. memset(&info, 0, sizeof(info));
  4993. info.name = ptr_to_u64(name);
  4994. info.name_len = sizeof(name);
  4995. err = bpf_btf_get_info_by_fd(fd, &info, &len);
  4996. if (err) {
  4997. err = -errno;
  4998. pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
  4999. goto err_out;
  5000. }
  5001. /* ignore non-module BTFs */
  5002. if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
  5003. close(fd);
  5004. continue;
  5005. }
  5006. btf = btf_get_from_fd(fd, obj->btf_vmlinux);
  5007. err = libbpf_get_error(btf);
  5008. if (err) {
  5009. pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
  5010. name, id, errstr(err));
  5011. goto err_out;
  5012. }
  5013. err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
  5014. sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
  5015. if (err)
  5016. goto err_out;
  5017. mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
  5018. mod_btf->btf = btf;
  5019. mod_btf->id = id;
  5020. mod_btf->fd = fd;
  5021. mod_btf->name = strdup(name);
  5022. if (!mod_btf->name) {
  5023. err = -ENOMEM;
  5024. goto err_out;
  5025. }
  5026. continue;
  5027. err_out:
  5028. close(fd);
  5029. return err;
  5030. }
  5031. return 0;
  5032. }
  5033. static struct bpf_core_cand_list *
  5034. bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
  5035. {
  5036. struct bpf_core_cand local_cand = {};
  5037. struct bpf_core_cand_list *cands;
  5038. const struct btf *main_btf;
  5039. const struct btf_type *local_t;
  5040. const char *local_name;
  5041. size_t local_essent_len;
  5042. int err, i;
  5043. local_cand.btf = local_btf;
  5044. local_cand.id = local_type_id;
  5045. local_t = btf__type_by_id(local_btf, local_type_id);
  5046. if (!local_t)
  5047. return ERR_PTR(-EINVAL);
  5048. local_name = btf__name_by_offset(local_btf, local_t->name_off);
  5049. if (str_is_empty(local_name))
  5050. return ERR_PTR(-EINVAL);
  5051. local_essent_len = bpf_core_essential_name_len(local_name);
  5052. cands = calloc(1, sizeof(*cands));
  5053. if (!cands)
  5054. return ERR_PTR(-ENOMEM);
  5055. /* Attempt to find target candidates in vmlinux BTF first */
  5056. main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
  5057. err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
  5058. if (err)
  5059. goto err_out;
  5060. /* if vmlinux BTF has any candidate, don't got for module BTFs */
  5061. if (cands->len)
  5062. return cands;
  5063. /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
  5064. if (obj->btf_vmlinux_override)
  5065. return cands;
  5066. /* now look through module BTFs, trying to still find candidates */
  5067. err = load_module_btfs(obj);
  5068. if (err)
  5069. goto err_out;
  5070. for (i = 0; i < obj->btf_module_cnt; i++) {
  5071. err = bpf_core_add_cands(&local_cand, local_essent_len,
  5072. obj->btf_modules[i].btf,
  5073. obj->btf_modules[i].name,
  5074. btf__type_cnt(obj->btf_vmlinux),
  5075. cands);
  5076. if (err)
  5077. goto err_out;
  5078. }
  5079. return cands;
  5080. err_out:
  5081. bpf_core_free_cands(cands);
  5082. return ERR_PTR(err);
  5083. }
  5084. /* Check local and target types for compatibility. This check is used for
  5085. * type-based CO-RE relocations and follow slightly different rules than
  5086. * field-based relocations. This function assumes that root types were already
  5087. * checked for name match. Beyond that initial root-level name check, names
  5088. * are completely ignored. Compatibility rules are as follows:
  5089. * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
  5090. * kind should match for local and target types (i.e., STRUCT is not
  5091. * compatible with UNION);
  5092. * - for ENUMs, the size is ignored;
  5093. * - for INT, size and signedness are ignored;
  5094. * - for ARRAY, dimensionality is ignored, element types are checked for
  5095. * compatibility recursively;
  5096. * - CONST/VOLATILE/RESTRICT modifiers are ignored;
  5097. * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
  5098. * - FUNC_PROTOs are compatible if they have compatible signature: same
  5099. * number of input args and compatible return and argument types.
  5100. * These rules are not set in stone and probably will be adjusted as we get
  5101. * more experience with using BPF CO-RE relocations.
  5102. */
  5103. int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
  5104. const struct btf *targ_btf, __u32 targ_id)
  5105. {
  5106. return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
  5107. }
  5108. int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
  5109. const struct btf *targ_btf, __u32 targ_id)
  5110. {
  5111. return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
  5112. }
  5113. static size_t bpf_core_hash_fn(const long key, void *ctx)
  5114. {
  5115. return key;
  5116. }
  5117. static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
  5118. {
  5119. return k1 == k2;
  5120. }
  5121. static int record_relo_core(struct bpf_program *prog,
  5122. const struct bpf_core_relo *core_relo, int insn_idx)
  5123. {
  5124. struct reloc_desc *relos, *relo;
  5125. relos = libbpf_reallocarray(prog->reloc_desc,
  5126. prog->nr_reloc + 1, sizeof(*relos));
  5127. if (!relos)
  5128. return -ENOMEM;
  5129. relo = &relos[prog->nr_reloc];
  5130. relo->type = RELO_CORE;
  5131. relo->insn_idx = insn_idx;
  5132. relo->core_relo = core_relo;
  5133. prog->reloc_desc = relos;
  5134. prog->nr_reloc++;
  5135. return 0;
  5136. }
  5137. static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
  5138. {
  5139. struct reloc_desc *relo;
  5140. int i;
  5141. for (i = 0; i < prog->nr_reloc; i++) {
  5142. relo = &prog->reloc_desc[i];
  5143. if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
  5144. continue;
  5145. return relo->core_relo;
  5146. }
  5147. return NULL;
  5148. }
  5149. static int bpf_core_resolve_relo(struct bpf_program *prog,
  5150. const struct bpf_core_relo *relo,
  5151. int relo_idx,
  5152. const struct btf *local_btf,
  5153. struct hashmap *cand_cache,
  5154. struct bpf_core_relo_res *targ_res)
  5155. {
  5156. struct bpf_core_spec specs_scratch[3] = {};
  5157. struct bpf_core_cand_list *cands = NULL;
  5158. const char *prog_name = prog->name;
  5159. const struct btf_type *local_type;
  5160. const char *local_name;
  5161. __u32 local_id = relo->type_id;
  5162. int err;
  5163. local_type = btf__type_by_id(local_btf, local_id);
  5164. if (!local_type)
  5165. return -EINVAL;
  5166. local_name = btf__name_by_offset(local_btf, local_type->name_off);
  5167. if (!local_name)
  5168. return -EINVAL;
  5169. if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
  5170. !hashmap__find(cand_cache, local_id, &cands)) {
  5171. cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
  5172. if (IS_ERR(cands)) {
  5173. pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
  5174. prog_name, relo_idx, local_id, btf_kind_str(local_type),
  5175. local_name, PTR_ERR(cands));
  5176. return PTR_ERR(cands);
  5177. }
  5178. err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
  5179. if (err) {
  5180. bpf_core_free_cands(cands);
  5181. return err;
  5182. }
  5183. }
  5184. return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
  5185. targ_res);
  5186. }
  5187. static int
  5188. bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
  5189. {
  5190. const struct btf_ext_info_sec *sec;
  5191. struct bpf_core_relo_res targ_res;
  5192. const struct bpf_core_relo *rec;
  5193. const struct btf_ext_info *seg;
  5194. struct hashmap_entry *entry;
  5195. struct hashmap *cand_cache = NULL;
  5196. struct bpf_program *prog;
  5197. struct bpf_insn *insn;
  5198. const char *sec_name;
  5199. int i, err = 0, insn_idx, sec_idx, sec_num;
  5200. if (obj->btf_ext->core_relo_info.len == 0)
  5201. return 0;
  5202. if (targ_btf_path) {
  5203. obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
  5204. err = libbpf_get_error(obj->btf_vmlinux_override);
  5205. if (err) {
  5206. pr_warn("failed to parse target BTF: %s\n", errstr(err));
  5207. return err;
  5208. }
  5209. }
  5210. cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
  5211. if (IS_ERR(cand_cache)) {
  5212. err = PTR_ERR(cand_cache);
  5213. goto out;
  5214. }
  5215. seg = &obj->btf_ext->core_relo_info;
  5216. sec_num = 0;
  5217. for_each_btf_ext_sec(seg, sec) {
  5218. sec_idx = seg->sec_idxs[sec_num];
  5219. sec_num++;
  5220. sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
  5221. if (str_is_empty(sec_name)) {
  5222. err = -EINVAL;
  5223. goto out;
  5224. }
  5225. pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
  5226. for_each_btf_ext_rec(seg, sec, i, rec) {
  5227. if (rec->insn_off % BPF_INSN_SZ)
  5228. return -EINVAL;
  5229. insn_idx = rec->insn_off / BPF_INSN_SZ;
  5230. prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
  5231. if (!prog) {
  5232. /* When __weak subprog is "overridden" by another instance
  5233. * of the subprog from a different object file, linker still
  5234. * appends all the .BTF.ext info that used to belong to that
  5235. * eliminated subprogram.
  5236. * This is similar to what x86-64 linker does for relocations.
  5237. * So just ignore such relocations just like we ignore
  5238. * subprog instructions when discovering subprograms.
  5239. */
  5240. pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
  5241. sec_name, i, insn_idx);
  5242. continue;
  5243. }
  5244. /* no need to apply CO-RE relocation if the program is
  5245. * not going to be loaded
  5246. */
  5247. if (!prog->autoload)
  5248. continue;
  5249. /* adjust insn_idx from section frame of reference to the local
  5250. * program's frame of reference; (sub-)program code is not yet
  5251. * relocated, so it's enough to just subtract in-section offset
  5252. */
  5253. insn_idx = insn_idx - prog->sec_insn_off;
  5254. if (insn_idx >= prog->insns_cnt)
  5255. return -EINVAL;
  5256. insn = &prog->insns[insn_idx];
  5257. err = record_relo_core(prog, rec, insn_idx);
  5258. if (err) {
  5259. pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
  5260. prog->name, i, errstr(err));
  5261. goto out;
  5262. }
  5263. if (prog->obj->gen_loader)
  5264. continue;
  5265. err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
  5266. if (err) {
  5267. pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
  5268. prog->name, i, errstr(err));
  5269. goto out;
  5270. }
  5271. err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
  5272. if (err) {
  5273. pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
  5274. prog->name, i, insn_idx, errstr(err));
  5275. goto out;
  5276. }
  5277. }
  5278. }
  5279. out:
  5280. /* obj->btf_vmlinux and module BTFs are freed after object load */
  5281. btf__free(obj->btf_vmlinux_override);
  5282. obj->btf_vmlinux_override = NULL;
  5283. if (!IS_ERR_OR_NULL(cand_cache)) {
  5284. hashmap__for_each_entry(cand_cache, entry, i) {
  5285. bpf_core_free_cands(entry->pvalue);
  5286. }
  5287. hashmap__free(cand_cache);
  5288. }
  5289. return err;
  5290. }
  5291. /* base map load ldimm64 special constant, used also for log fixup logic */
  5292. #define POISON_LDIMM64_MAP_BASE 2001000000
  5293. #define POISON_LDIMM64_MAP_PFX "200100"
  5294. static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
  5295. int insn_idx, struct bpf_insn *insn,
  5296. int map_idx, const struct bpf_map *map)
  5297. {
  5298. int i;
  5299. pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
  5300. prog->name, relo_idx, insn_idx, map_idx, map->name);
  5301. /* we turn single ldimm64 into two identical invalid calls */
  5302. for (i = 0; i < 2; i++) {
  5303. insn->code = BPF_JMP | BPF_CALL;
  5304. insn->dst_reg = 0;
  5305. insn->src_reg = 0;
  5306. insn->off = 0;
  5307. /* if this instruction is reachable (not a dead code),
  5308. * verifier will complain with something like:
  5309. * invalid func unknown#2001000123
  5310. * where lower 123 is map index into obj->maps[] array
  5311. */
  5312. insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
  5313. insn++;
  5314. }
  5315. }
  5316. /* unresolved kfunc call special constant, used also for log fixup logic */
  5317. #define POISON_CALL_KFUNC_BASE 2002000000
  5318. #define POISON_CALL_KFUNC_PFX "2002"
  5319. static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
  5320. int insn_idx, struct bpf_insn *insn,
  5321. int ext_idx, const struct extern_desc *ext)
  5322. {
  5323. pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
  5324. prog->name, relo_idx, insn_idx, ext->name);
  5325. /* we turn kfunc call into invalid helper call with identifiable constant */
  5326. insn->code = BPF_JMP | BPF_CALL;
  5327. insn->dst_reg = 0;
  5328. insn->src_reg = 0;
  5329. insn->off = 0;
  5330. /* if this instruction is reachable (not a dead code),
  5331. * verifier will complain with something like:
  5332. * invalid func unknown#2001000123
  5333. * where lower 123 is extern index into obj->externs[] array
  5334. */
  5335. insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
  5336. }
  5337. static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
  5338. {
  5339. size_t i;
  5340. for (i = 0; i < obj->jumptable_map_cnt; i++) {
  5341. /*
  5342. * This might happen that same offset is used for two different
  5343. * programs (as jump tables can be the same). However, for
  5344. * different programs different maps should be created.
  5345. */
  5346. if (obj->jumptable_maps[i].sym_off == sym_off &&
  5347. obj->jumptable_maps[i].prog == prog)
  5348. return obj->jumptable_maps[i].fd;
  5349. }
  5350. return -ENOENT;
  5351. }
  5352. static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
  5353. {
  5354. size_t cnt = obj->jumptable_map_cnt;
  5355. size_t size = sizeof(obj->jumptable_maps[0]);
  5356. void *tmp;
  5357. tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
  5358. if (!tmp)
  5359. return -ENOMEM;
  5360. obj->jumptable_maps = tmp;
  5361. obj->jumptable_maps[cnt].prog = prog;
  5362. obj->jumptable_maps[cnt].sym_off = sym_off;
  5363. obj->jumptable_maps[cnt].fd = map_fd;
  5364. obj->jumptable_map_cnt++;
  5365. return 0;
  5366. }
  5367. static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
  5368. {
  5369. int i;
  5370. for (i = prog->subprog_cnt - 1; i >= 0; i--) {
  5371. if (insn_idx >= prog->subprogs[i].sub_insn_off)
  5372. return i;
  5373. }
  5374. return -1;
  5375. }
  5376. static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
  5377. {
  5378. const __u32 jt_entry_size = 8;
  5379. unsigned int sym_off = relo->sym_off;
  5380. int jt_size = relo->sym_size;
  5381. __u32 max_entries = jt_size / jt_entry_size;
  5382. __u32 value_size = sizeof(struct bpf_insn_array_value);
  5383. struct bpf_insn_array_value val = {};
  5384. int subprog_idx;
  5385. int map_fd, err;
  5386. __u64 insn_off;
  5387. __u64 *jt;
  5388. __u32 i;
  5389. map_fd = find_jt_map(obj, prog, sym_off);
  5390. if (map_fd >= 0)
  5391. return map_fd;
  5392. if (sym_off % jt_entry_size) {
  5393. pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
  5394. sym_off, jt_entry_size);
  5395. return -EINVAL;
  5396. }
  5397. if (jt_size % jt_entry_size) {
  5398. pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
  5399. jt_size, jt_entry_size);
  5400. return -EINVAL;
  5401. }
  5402. map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
  5403. 4, value_size, max_entries, NULL);
  5404. if (map_fd < 0)
  5405. return map_fd;
  5406. if (!obj->jumptables_data) {
  5407. pr_warn("map '.jumptables': ELF file is missing jump table data\n");
  5408. err = -EINVAL;
  5409. goto err_close;
  5410. }
  5411. if (sym_off + jt_size > obj->jumptables_data_sz) {
  5412. pr_warn("map '.jumptables': jumptables_data size is %zd, trying to access %d\n",
  5413. obj->jumptables_data_sz, sym_off + jt_size);
  5414. err = -EINVAL;
  5415. goto err_close;
  5416. }
  5417. subprog_idx = -1; /* main program */
  5418. if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
  5419. pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
  5420. err = -EINVAL;
  5421. goto err_close;
  5422. }
  5423. if (prog->subprogs)
  5424. subprog_idx = find_subprog_idx(prog, relo->insn_idx);
  5425. jt = (__u64 *)(obj->jumptables_data + sym_off);
  5426. for (i = 0; i < max_entries; i++) {
  5427. /*
  5428. * The offset should be made to be relative to the beginning of
  5429. * the main function, not the subfunction.
  5430. */
  5431. insn_off = jt[i]/sizeof(struct bpf_insn);
  5432. if (subprog_idx >= 0) {
  5433. insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
  5434. insn_off += prog->subprogs[subprog_idx].sub_insn_off;
  5435. } else {
  5436. insn_off -= prog->sec_insn_off;
  5437. }
  5438. /*
  5439. * LLVM-generated jump tables contain u64 records, however
  5440. * should contain values that fit in u32.
  5441. */
  5442. if (insn_off > UINT32_MAX) {
  5443. pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
  5444. (long long)jt[i], sym_off + i * jt_entry_size);
  5445. err = -EINVAL;
  5446. goto err_close;
  5447. }
  5448. val.orig_off = insn_off;
  5449. err = bpf_map_update_elem(map_fd, &i, &val, 0);
  5450. if (err)
  5451. goto err_close;
  5452. }
  5453. err = bpf_map_freeze(map_fd);
  5454. if (err)
  5455. goto err_close;
  5456. err = add_jt_map(obj, prog, sym_off, map_fd);
  5457. if (err)
  5458. goto err_close;
  5459. return map_fd;
  5460. err_close:
  5461. close(map_fd);
  5462. return err;
  5463. }
  5464. /* Relocate data references within program code:
  5465. * - map references;
  5466. * - global variable references;
  5467. * - extern references.
  5468. */
  5469. static int
  5470. bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
  5471. {
  5472. int i;
  5473. for (i = 0; i < prog->nr_reloc; i++) {
  5474. struct reloc_desc *relo = &prog->reloc_desc[i];
  5475. struct bpf_insn *insn = &prog->insns[relo->insn_idx];
  5476. const struct bpf_map *map;
  5477. struct extern_desc *ext;
  5478. switch (relo->type) {
  5479. case RELO_LD64:
  5480. map = &obj->maps[relo->map_idx];
  5481. if (obj->gen_loader) {
  5482. insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
  5483. insn[0].imm = relo->map_idx;
  5484. } else if (map->autocreate) {
  5485. insn[0].src_reg = BPF_PSEUDO_MAP_FD;
  5486. insn[0].imm = map->fd;
  5487. } else {
  5488. poison_map_ldimm64(prog, i, relo->insn_idx, insn,
  5489. relo->map_idx, map);
  5490. }
  5491. break;
  5492. case RELO_DATA:
  5493. map = &obj->maps[relo->map_idx];
  5494. insn[1].imm = insn[0].imm + relo->sym_off;
  5495. if (relo->map_idx == obj->arena_map_idx)
  5496. insn[1].imm += obj->arena_data_off;
  5497. if (obj->gen_loader) {
  5498. insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
  5499. insn[0].imm = relo->map_idx;
  5500. } else if (map->autocreate) {
  5501. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5502. insn[0].imm = map->fd;
  5503. } else {
  5504. poison_map_ldimm64(prog, i, relo->insn_idx, insn,
  5505. relo->map_idx, map);
  5506. }
  5507. break;
  5508. case RELO_EXTERN_LD64:
  5509. ext = &obj->externs[relo->ext_idx];
  5510. if (ext->type == EXT_KCFG) {
  5511. if (obj->gen_loader) {
  5512. insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
  5513. insn[0].imm = obj->kconfig_map_idx;
  5514. } else {
  5515. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5516. insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
  5517. }
  5518. insn[1].imm = ext->kcfg.data_off;
  5519. } else /* EXT_KSYM */ {
  5520. if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
  5521. insn[0].src_reg = BPF_PSEUDO_BTF_ID;
  5522. insn[0].imm = ext->ksym.kernel_btf_id;
  5523. insn[1].imm = ext->ksym.kernel_btf_obj_fd;
  5524. } else { /* typeless ksyms or unresolved typed ksyms */
  5525. insn[0].imm = (__u32)ext->ksym.addr;
  5526. insn[1].imm = ext->ksym.addr >> 32;
  5527. }
  5528. }
  5529. break;
  5530. case RELO_EXTERN_CALL:
  5531. ext = &obj->externs[relo->ext_idx];
  5532. insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
  5533. if (ext->is_set) {
  5534. insn[0].imm = ext->ksym.kernel_btf_id;
  5535. insn[0].off = ext->ksym.btf_fd_idx;
  5536. } else { /* unresolved weak kfunc call */
  5537. poison_kfunc_call(prog, i, relo->insn_idx, insn,
  5538. relo->ext_idx, ext);
  5539. }
  5540. break;
  5541. case RELO_SUBPROG_ADDR:
  5542. if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
  5543. pr_warn("prog '%s': relo #%d: bad insn\n",
  5544. prog->name, i);
  5545. return -EINVAL;
  5546. }
  5547. /* handled already */
  5548. break;
  5549. case RELO_CALL:
  5550. /* handled already */
  5551. break;
  5552. case RELO_CORE:
  5553. /* will be handled by bpf_program_record_relos() */
  5554. break;
  5555. case RELO_INSN_ARRAY: {
  5556. int map_fd;
  5557. map_fd = create_jt_map(obj, prog, relo);
  5558. if (map_fd < 0) {
  5559. pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
  5560. prog->name, i, relo->sym_off);
  5561. return map_fd;
  5562. }
  5563. insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
  5564. insn->imm = map_fd;
  5565. insn->off = 0;
  5566. }
  5567. break;
  5568. default:
  5569. pr_warn("prog '%s': relo #%d: bad relo type %d\n",
  5570. prog->name, i, relo->type);
  5571. return -EINVAL;
  5572. }
  5573. }
  5574. return 0;
  5575. }
  5576. static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
  5577. const struct bpf_program *prog,
  5578. const struct btf_ext_info *ext_info,
  5579. void **prog_info, __u32 *prog_rec_cnt,
  5580. __u32 *prog_rec_sz)
  5581. {
  5582. void *copy_start = NULL, *copy_end = NULL;
  5583. void *rec, *rec_end, *new_prog_info;
  5584. const struct btf_ext_info_sec *sec;
  5585. size_t old_sz, new_sz;
  5586. int i, sec_num, sec_idx, off_adj;
  5587. sec_num = 0;
  5588. for_each_btf_ext_sec(ext_info, sec) {
  5589. sec_idx = ext_info->sec_idxs[sec_num];
  5590. sec_num++;
  5591. if (prog->sec_idx != sec_idx)
  5592. continue;
  5593. for_each_btf_ext_rec(ext_info, sec, i, rec) {
  5594. __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
  5595. if (insn_off < prog->sec_insn_off)
  5596. continue;
  5597. if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
  5598. break;
  5599. if (!copy_start)
  5600. copy_start = rec;
  5601. copy_end = rec + ext_info->rec_size;
  5602. }
  5603. if (!copy_start)
  5604. return -ENOENT;
  5605. /* append func/line info of a given (sub-)program to the main
  5606. * program func/line info
  5607. */
  5608. old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
  5609. new_sz = old_sz + (copy_end - copy_start);
  5610. new_prog_info = realloc(*prog_info, new_sz);
  5611. if (!new_prog_info)
  5612. return -ENOMEM;
  5613. *prog_info = new_prog_info;
  5614. *prog_rec_cnt = new_sz / ext_info->rec_size;
  5615. memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
  5616. /* Kernel instruction offsets are in units of 8-byte
  5617. * instructions, while .BTF.ext instruction offsets generated
  5618. * by Clang are in units of bytes. So convert Clang offsets
  5619. * into kernel offsets and adjust offset according to program
  5620. * relocated position.
  5621. */
  5622. off_adj = prog->sub_insn_off - prog->sec_insn_off;
  5623. rec = new_prog_info + old_sz;
  5624. rec_end = new_prog_info + new_sz;
  5625. for (; rec < rec_end; rec += ext_info->rec_size) {
  5626. __u32 *insn_off = rec;
  5627. *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
  5628. }
  5629. *prog_rec_sz = ext_info->rec_size;
  5630. return 0;
  5631. }
  5632. return -ENOENT;
  5633. }
  5634. static int
  5635. reloc_prog_func_and_line_info(const struct bpf_object *obj,
  5636. struct bpf_program *main_prog,
  5637. const struct bpf_program *prog)
  5638. {
  5639. int err;
  5640. /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
  5641. * support func/line info
  5642. */
  5643. if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
  5644. return 0;
  5645. /* only attempt func info relocation if main program's func_info
  5646. * relocation was successful
  5647. */
  5648. if (main_prog != prog && !main_prog->func_info)
  5649. goto line_info;
  5650. err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
  5651. &main_prog->func_info,
  5652. &main_prog->func_info_cnt,
  5653. &main_prog->func_info_rec_size);
  5654. if (err) {
  5655. if (err != -ENOENT) {
  5656. pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
  5657. prog->name, errstr(err));
  5658. return err;
  5659. }
  5660. if (main_prog->func_info) {
  5661. /*
  5662. * Some info has already been found but has problem
  5663. * in the last btf_ext reloc. Must have to error out.
  5664. */
  5665. pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
  5666. return err;
  5667. }
  5668. /* Have problem loading the very first info. Ignore the rest. */
  5669. pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
  5670. prog->name);
  5671. }
  5672. line_info:
  5673. /* don't relocate line info if main program's relocation failed */
  5674. if (main_prog != prog && !main_prog->line_info)
  5675. return 0;
  5676. err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
  5677. &main_prog->line_info,
  5678. &main_prog->line_info_cnt,
  5679. &main_prog->line_info_rec_size);
  5680. if (err) {
  5681. if (err != -ENOENT) {
  5682. pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
  5683. prog->name, errstr(err));
  5684. return err;
  5685. }
  5686. if (main_prog->line_info) {
  5687. /*
  5688. * Some info has already been found but has problem
  5689. * in the last btf_ext reloc. Must have to error out.
  5690. */
  5691. pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
  5692. return err;
  5693. }
  5694. /* Have problem loading the very first info. Ignore the rest. */
  5695. pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
  5696. prog->name);
  5697. }
  5698. return 0;
  5699. }
  5700. static int cmp_relo_by_insn_idx(const void *key, const void *elem)
  5701. {
  5702. size_t insn_idx = *(const size_t *)key;
  5703. const struct reloc_desc *relo = elem;
  5704. if (insn_idx == relo->insn_idx)
  5705. return 0;
  5706. return insn_idx < relo->insn_idx ? -1 : 1;
  5707. }
  5708. static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
  5709. {
  5710. if (!prog->nr_reloc)
  5711. return NULL;
  5712. return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
  5713. sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
  5714. }
  5715. static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
  5716. {
  5717. int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
  5718. struct reloc_desc *relos;
  5719. int i;
  5720. if (main_prog == subprog)
  5721. return 0;
  5722. relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
  5723. /* if new count is zero, reallocarray can return a valid NULL result;
  5724. * in this case the previous pointer will be freed, so we *have to*
  5725. * reassign old pointer to the new value (even if it's NULL)
  5726. */
  5727. if (!relos && new_cnt)
  5728. return -ENOMEM;
  5729. if (subprog->nr_reloc)
  5730. memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
  5731. sizeof(*relos) * subprog->nr_reloc);
  5732. for (i = main_prog->nr_reloc; i < new_cnt; i++)
  5733. relos[i].insn_idx += subprog->sub_insn_off;
  5734. /* After insn_idx adjustment the 'relos' array is still sorted
  5735. * by insn_idx and doesn't break bsearch.
  5736. */
  5737. main_prog->reloc_desc = relos;
  5738. main_prog->nr_reloc = new_cnt;
  5739. return 0;
  5740. }
  5741. static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
  5742. {
  5743. size_t size = sizeof(main_prog->subprogs[0]);
  5744. int cnt = main_prog->subprog_cnt;
  5745. void *tmp;
  5746. tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
  5747. if (!tmp)
  5748. return -ENOMEM;
  5749. main_prog->subprogs = tmp;
  5750. main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
  5751. main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
  5752. main_prog->subprog_cnt++;
  5753. return 0;
  5754. }
  5755. static int
  5756. bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
  5757. struct bpf_program *subprog)
  5758. {
  5759. struct bpf_insn *insns;
  5760. size_t new_cnt;
  5761. int err;
  5762. subprog->sub_insn_off = main_prog->insns_cnt;
  5763. new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
  5764. insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
  5765. if (!insns) {
  5766. pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
  5767. return -ENOMEM;
  5768. }
  5769. main_prog->insns = insns;
  5770. main_prog->insns_cnt = new_cnt;
  5771. memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
  5772. subprog->insns_cnt * sizeof(*insns));
  5773. pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
  5774. main_prog->name, subprog->insns_cnt, subprog->name);
  5775. /* The subprog insns are now appended. Append its relos too. */
  5776. err = append_subprog_relos(main_prog, subprog);
  5777. if (err)
  5778. return err;
  5779. err = save_subprog_offsets(main_prog, subprog);
  5780. if (err) {
  5781. pr_warn("prog '%s': failed to add subprog offsets: %s\n",
  5782. main_prog->name, errstr(err));
  5783. return err;
  5784. }
  5785. return 0;
  5786. }
  5787. static int
  5788. bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
  5789. struct bpf_program *prog)
  5790. {
  5791. size_t sub_insn_idx, insn_idx;
  5792. struct bpf_program *subprog;
  5793. struct reloc_desc *relo;
  5794. struct bpf_insn *insn;
  5795. int err;
  5796. err = reloc_prog_func_and_line_info(obj, main_prog, prog);
  5797. if (err)
  5798. return err;
  5799. for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
  5800. insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
  5801. if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
  5802. continue;
  5803. relo = find_prog_insn_relo(prog, insn_idx);
  5804. if (relo && relo->type == RELO_EXTERN_CALL)
  5805. /* kfunc relocations will be handled later
  5806. * in bpf_object__relocate_data()
  5807. */
  5808. continue;
  5809. if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
  5810. pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
  5811. prog->name, insn_idx, relo->type);
  5812. return -LIBBPF_ERRNO__RELOC;
  5813. }
  5814. if (relo) {
  5815. /* sub-program instruction index is a combination of
  5816. * an offset of a symbol pointed to by relocation and
  5817. * call instruction's imm field; for global functions,
  5818. * call always has imm = -1, but for static functions
  5819. * relocation is against STT_SECTION and insn->imm
  5820. * points to a start of a static function
  5821. *
  5822. * for subprog addr relocation, the relo->sym_off + insn->imm is
  5823. * the byte offset in the corresponding section.
  5824. */
  5825. if (relo->type == RELO_CALL)
  5826. sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
  5827. else
  5828. sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
  5829. } else if (insn_is_pseudo_func(insn)) {
  5830. /*
  5831. * RELO_SUBPROG_ADDR relo is always emitted even if both
  5832. * functions are in the same section, so it shouldn't reach here.
  5833. */
  5834. pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
  5835. prog->name, insn_idx);
  5836. return -LIBBPF_ERRNO__RELOC;
  5837. } else {
  5838. /* if subprogram call is to a static function within
  5839. * the same ELF section, there won't be any relocation
  5840. * emitted, but it also means there is no additional
  5841. * offset necessary, insns->imm is relative to
  5842. * instruction's original position within the section
  5843. */
  5844. sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
  5845. }
  5846. /* we enforce that sub-programs should be in .text section */
  5847. subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
  5848. if (!subprog) {
  5849. pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
  5850. prog->name);
  5851. return -LIBBPF_ERRNO__RELOC;
  5852. }
  5853. /* if it's the first call instruction calling into this
  5854. * subprogram (meaning this subprog hasn't been processed
  5855. * yet) within the context of current main program:
  5856. * - append it at the end of main program's instructions blog;
  5857. * - process is recursively, while current program is put on hold;
  5858. * - if that subprogram calls some other not yet processes
  5859. * subprogram, same thing will happen recursively until
  5860. * there are no more unprocesses subprograms left to append
  5861. * and relocate.
  5862. */
  5863. if (subprog->sub_insn_off == 0) {
  5864. err = bpf_object__append_subprog_code(obj, main_prog, subprog);
  5865. if (err)
  5866. return err;
  5867. err = bpf_object__reloc_code(obj, main_prog, subprog);
  5868. if (err)
  5869. return err;
  5870. }
  5871. /* main_prog->insns memory could have been re-allocated, so
  5872. * calculate pointer again
  5873. */
  5874. insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
  5875. /* calculate correct instruction position within current main
  5876. * prog; each main prog can have a different set of
  5877. * subprograms appended (potentially in different order as
  5878. * well), so position of any subprog can be different for
  5879. * different main programs
  5880. */
  5881. insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
  5882. pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
  5883. prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
  5884. }
  5885. return 0;
  5886. }
  5887. /*
  5888. * Relocate sub-program calls.
  5889. *
  5890. * Algorithm operates as follows. Each entry-point BPF program (referred to as
  5891. * main prog) is processed separately. For each subprog (non-entry functions,
  5892. * that can be called from either entry progs or other subprogs) gets their
  5893. * sub_insn_off reset to zero. This serves as indicator that this subprogram
  5894. * hasn't been yet appended and relocated within current main prog. Once its
  5895. * relocated, sub_insn_off will point at the position within current main prog
  5896. * where given subprog was appended. This will further be used to relocate all
  5897. * the call instructions jumping into this subprog.
  5898. *
  5899. * We start with main program and process all call instructions. If the call
  5900. * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
  5901. * is zero), subprog instructions are appended at the end of main program's
  5902. * instruction array. Then main program is "put on hold" while we recursively
  5903. * process newly appended subprogram. If that subprogram calls into another
  5904. * subprogram that hasn't been appended, new subprogram is appended again to
  5905. * the *main* prog's instructions (subprog's instructions are always left
  5906. * untouched, as they need to be in unmodified state for subsequent main progs
  5907. * and subprog instructions are always sent only as part of a main prog) and
  5908. * the process continues recursively. Once all the subprogs called from a main
  5909. * prog or any of its subprogs are appended (and relocated), all their
  5910. * positions within finalized instructions array are known, so it's easy to
  5911. * rewrite call instructions with correct relative offsets, corresponding to
  5912. * desired target subprog.
  5913. *
  5914. * Its important to realize that some subprogs might not be called from some
  5915. * main prog and any of its called/used subprogs. Those will keep their
  5916. * subprog->sub_insn_off as zero at all times and won't be appended to current
  5917. * main prog and won't be relocated within the context of current main prog.
  5918. * They might still be used from other main progs later.
  5919. *
  5920. * Visually this process can be shown as below. Suppose we have two main
  5921. * programs mainA and mainB and BPF object contains three subprogs: subA,
  5922. * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
  5923. * subC both call subB:
  5924. *
  5925. * +--------+ +-------+
  5926. * | v v |
  5927. * +--+---+ +--+-+-+ +---+--+
  5928. * | subA | | subB | | subC |
  5929. * +--+---+ +------+ +---+--+
  5930. * ^ ^
  5931. * | |
  5932. * +---+-------+ +------+----+
  5933. * | mainA | | mainB |
  5934. * +-----------+ +-----------+
  5935. *
  5936. * We'll start relocating mainA, will find subA, append it and start
  5937. * processing sub A recursively:
  5938. *
  5939. * +-----------+------+
  5940. * | mainA | subA |
  5941. * +-----------+------+
  5942. *
  5943. * At this point we notice that subB is used from subA, so we append it and
  5944. * relocate (there are no further subcalls from subB):
  5945. *
  5946. * +-----------+------+------+
  5947. * | mainA | subA | subB |
  5948. * +-----------+------+------+
  5949. *
  5950. * At this point, we relocate subA calls, then go one level up and finish with
  5951. * relocatin mainA calls. mainA is done.
  5952. *
  5953. * For mainB process is similar but results in different order. We start with
  5954. * mainB and skip subA and subB, as mainB never calls them (at least
  5955. * directly), but we see subC is needed, so we append and start processing it:
  5956. *
  5957. * +-----------+------+
  5958. * | mainB | subC |
  5959. * +-----------+------+
  5960. * Now we see subC needs subB, so we go back to it, append and relocate it:
  5961. *
  5962. * +-----------+------+------+
  5963. * | mainB | subC | subB |
  5964. * +-----------+------+------+
  5965. *
  5966. * At this point we unwind recursion, relocate calls in subC, then in mainB.
  5967. */
  5968. static int
  5969. bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
  5970. {
  5971. struct bpf_program *subprog;
  5972. int i, err;
  5973. /* mark all subprogs as not relocated (yet) within the context of
  5974. * current main program
  5975. */
  5976. for (i = 0; i < obj->nr_programs; i++) {
  5977. subprog = &obj->programs[i];
  5978. if (!prog_is_subprog(obj, subprog))
  5979. continue;
  5980. subprog->sub_insn_off = 0;
  5981. }
  5982. err = bpf_object__reloc_code(obj, prog, prog);
  5983. if (err)
  5984. return err;
  5985. return 0;
  5986. }
  5987. static void
  5988. bpf_object__free_relocs(struct bpf_object *obj)
  5989. {
  5990. struct bpf_program *prog;
  5991. int i;
  5992. /* free up relocation descriptors */
  5993. for (i = 0; i < obj->nr_programs; i++) {
  5994. prog = &obj->programs[i];
  5995. zfree(&prog->reloc_desc);
  5996. prog->nr_reloc = 0;
  5997. }
  5998. }
  5999. static int cmp_relocs(const void *_a, const void *_b)
  6000. {
  6001. const struct reloc_desc *a = _a;
  6002. const struct reloc_desc *b = _b;
  6003. if (a->insn_idx != b->insn_idx)
  6004. return a->insn_idx < b->insn_idx ? -1 : 1;
  6005. /* no two relocations should have the same insn_idx, but ... */
  6006. if (a->type != b->type)
  6007. return a->type < b->type ? -1 : 1;
  6008. return 0;
  6009. }
  6010. static void bpf_object__sort_relos(struct bpf_object *obj)
  6011. {
  6012. int i;
  6013. for (i = 0; i < obj->nr_programs; i++) {
  6014. struct bpf_program *p = &obj->programs[i];
  6015. if (!p->nr_reloc)
  6016. continue;
  6017. qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
  6018. }
  6019. }
  6020. static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
  6021. {
  6022. const char *str = "exception_callback:";
  6023. size_t pfx_len = strlen(str);
  6024. int i, j, n;
  6025. if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
  6026. return 0;
  6027. n = btf__type_cnt(obj->btf);
  6028. for (i = 1; i < n; i++) {
  6029. const char *name;
  6030. struct btf_type *t;
  6031. t = btf_type_by_id(obj->btf, i);
  6032. if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
  6033. continue;
  6034. name = btf__str_by_offset(obj->btf, t->name_off);
  6035. if (strncmp(name, str, pfx_len) != 0)
  6036. continue;
  6037. t = btf_type_by_id(obj->btf, t->type);
  6038. if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
  6039. pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
  6040. prog->name);
  6041. return -EINVAL;
  6042. }
  6043. if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
  6044. continue;
  6045. /* Multiple callbacks are specified for the same prog,
  6046. * the verifier will eventually return an error for this
  6047. * case, hence simply skip appending a subprog.
  6048. */
  6049. if (prog->exception_cb_idx >= 0) {
  6050. prog->exception_cb_idx = -1;
  6051. break;
  6052. }
  6053. name += pfx_len;
  6054. if (str_is_empty(name)) {
  6055. pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
  6056. prog->name);
  6057. return -EINVAL;
  6058. }
  6059. for (j = 0; j < obj->nr_programs; j++) {
  6060. struct bpf_program *subprog = &obj->programs[j];
  6061. if (!prog_is_subprog(obj, subprog))
  6062. continue;
  6063. if (strcmp(name, subprog->name) != 0)
  6064. continue;
  6065. /* Enforce non-hidden, as from verifier point of
  6066. * view it expects global functions, whereas the
  6067. * mark_btf_static fixes up linkage as static.
  6068. */
  6069. if (!subprog->sym_global || subprog->mark_btf_static) {
  6070. pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
  6071. prog->name, subprog->name);
  6072. return -EINVAL;
  6073. }
  6074. /* Let's see if we already saw a static exception callback with the same name */
  6075. if (prog->exception_cb_idx >= 0) {
  6076. pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
  6077. prog->name, subprog->name);
  6078. return -EINVAL;
  6079. }
  6080. prog->exception_cb_idx = j;
  6081. break;
  6082. }
  6083. if (prog->exception_cb_idx >= 0)
  6084. continue;
  6085. pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
  6086. return -ENOENT;
  6087. }
  6088. return 0;
  6089. }
  6090. static struct {
  6091. enum bpf_prog_type prog_type;
  6092. const char *ctx_name;
  6093. } global_ctx_map[] = {
  6094. { BPF_PROG_TYPE_CGROUP_DEVICE, "bpf_cgroup_dev_ctx" },
  6095. { BPF_PROG_TYPE_CGROUP_SKB, "__sk_buff" },
  6096. { BPF_PROG_TYPE_CGROUP_SOCK, "bpf_sock" },
  6097. { BPF_PROG_TYPE_CGROUP_SOCK_ADDR, "bpf_sock_addr" },
  6098. { BPF_PROG_TYPE_CGROUP_SOCKOPT, "bpf_sockopt" },
  6099. { BPF_PROG_TYPE_CGROUP_SYSCTL, "bpf_sysctl" },
  6100. { BPF_PROG_TYPE_FLOW_DISSECTOR, "__sk_buff" },
  6101. { BPF_PROG_TYPE_KPROBE, "bpf_user_pt_regs_t" },
  6102. { BPF_PROG_TYPE_LWT_IN, "__sk_buff" },
  6103. { BPF_PROG_TYPE_LWT_OUT, "__sk_buff" },
  6104. { BPF_PROG_TYPE_LWT_SEG6LOCAL, "__sk_buff" },
  6105. { BPF_PROG_TYPE_LWT_XMIT, "__sk_buff" },
  6106. { BPF_PROG_TYPE_NETFILTER, "bpf_nf_ctx" },
  6107. { BPF_PROG_TYPE_PERF_EVENT, "bpf_perf_event_data" },
  6108. { BPF_PROG_TYPE_RAW_TRACEPOINT, "bpf_raw_tracepoint_args" },
  6109. { BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
  6110. { BPF_PROG_TYPE_SCHED_ACT, "__sk_buff" },
  6111. { BPF_PROG_TYPE_SCHED_CLS, "__sk_buff" },
  6112. { BPF_PROG_TYPE_SK_LOOKUP, "bpf_sk_lookup" },
  6113. { BPF_PROG_TYPE_SK_MSG, "sk_msg_md" },
  6114. { BPF_PROG_TYPE_SK_REUSEPORT, "sk_reuseport_md" },
  6115. { BPF_PROG_TYPE_SK_SKB, "__sk_buff" },
  6116. { BPF_PROG_TYPE_SOCK_OPS, "bpf_sock_ops" },
  6117. { BPF_PROG_TYPE_SOCKET_FILTER, "__sk_buff" },
  6118. { BPF_PROG_TYPE_XDP, "xdp_md" },
  6119. /* all other program types don't have "named" context structs */
  6120. };
  6121. /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
  6122. * for below __builtin_types_compatible_p() checks;
  6123. * with this approach we don't need any extra arch-specific #ifdef guards
  6124. */
  6125. struct pt_regs;
  6126. struct user_pt_regs;
  6127. struct user_regs_struct;
  6128. static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
  6129. const char *subprog_name, int arg_idx,
  6130. int arg_type_id, const char *ctx_name)
  6131. {
  6132. const struct btf_type *t;
  6133. const char *tname;
  6134. /* check if existing parameter already matches verifier expectations */
  6135. t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
  6136. if (!btf_is_ptr(t))
  6137. goto out_warn;
  6138. /* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
  6139. * and perf_event programs, so check this case early on and forget
  6140. * about it for subsequent checks
  6141. */
  6142. while (btf_is_mod(t))
  6143. t = btf__type_by_id(btf, t->type);
  6144. if (btf_is_typedef(t) &&
  6145. (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
  6146. tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
  6147. if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
  6148. return false; /* canonical type for kprobe/perf_event */
  6149. }
  6150. /* now we can ignore typedefs moving forward */
  6151. t = skip_mods_and_typedefs(btf, t->type, NULL);
  6152. /* if it's `void *`, definitely fix up BTF info */
  6153. if (btf_is_void(t))
  6154. return true;
  6155. /* if it's already proper canonical type, no need to fix up */
  6156. tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
  6157. if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
  6158. return false;
  6159. /* special cases */
  6160. switch (prog->type) {
  6161. case BPF_PROG_TYPE_KPROBE:
  6162. /* `struct pt_regs *` is expected, but we need to fix up */
  6163. if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
  6164. return true;
  6165. break;
  6166. case BPF_PROG_TYPE_PERF_EVENT:
  6167. if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
  6168. btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
  6169. return true;
  6170. if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
  6171. btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
  6172. return true;
  6173. if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
  6174. btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
  6175. return true;
  6176. break;
  6177. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  6178. case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
  6179. /* allow u64* as ctx */
  6180. if (btf_is_int(t) && t->size == 8)
  6181. return true;
  6182. break;
  6183. default:
  6184. break;
  6185. }
  6186. out_warn:
  6187. pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
  6188. prog->name, subprog_name, arg_idx, ctx_name);
  6189. return false;
  6190. }
  6191. static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
  6192. {
  6193. int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
  6194. int i, err, arg_cnt, fn_name_off, linkage;
  6195. struct btf_type *fn_t, *fn_proto_t, *t;
  6196. struct btf_param *p;
  6197. /* caller already validated FUNC -> FUNC_PROTO validity */
  6198. fn_t = btf_type_by_id(btf, orig_fn_id);
  6199. fn_proto_t = btf_type_by_id(btf, fn_t->type);
  6200. /* Note that each btf__add_xxx() operation invalidates
  6201. * all btf_type and string pointers, so we need to be
  6202. * very careful when cloning BTF types. BTF type
  6203. * pointers have to be always refetched. And to avoid
  6204. * problems with invalidated string pointers, we
  6205. * add empty strings initially, then just fix up
  6206. * name_off offsets in place. Offsets are stable for
  6207. * existing strings, so that works out.
  6208. */
  6209. fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
  6210. linkage = btf_func_linkage(fn_t);
  6211. orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
  6212. ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
  6213. arg_cnt = btf_vlen(fn_proto_t);
  6214. /* clone FUNC_PROTO and its params */
  6215. fn_proto_id = btf__add_func_proto(btf, ret_type_id);
  6216. if (fn_proto_id < 0)
  6217. return -EINVAL;
  6218. for (i = 0; i < arg_cnt; i++) {
  6219. int name_off;
  6220. /* copy original parameter data */
  6221. t = btf_type_by_id(btf, orig_proto_id);
  6222. p = &btf_params(t)[i];
  6223. name_off = p->name_off;
  6224. err = btf__add_func_param(btf, "", p->type);
  6225. if (err)
  6226. return err;
  6227. fn_proto_t = btf_type_by_id(btf, fn_proto_id);
  6228. p = &btf_params(fn_proto_t)[i];
  6229. p->name_off = name_off; /* use remembered str offset */
  6230. }
  6231. /* clone FUNC now, btf__add_func() enforces non-empty name, so use
  6232. * entry program's name as a placeholder, which we replace immediately
  6233. * with original name_off
  6234. */
  6235. fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
  6236. if (fn_id < 0)
  6237. return -EINVAL;
  6238. fn_t = btf_type_by_id(btf, fn_id);
  6239. fn_t->name_off = fn_name_off; /* reuse original string */
  6240. return fn_id;
  6241. }
  6242. /* Check if main program or global subprog's function prototype has `arg:ctx`
  6243. * argument tags, and, if necessary, substitute correct type to match what BPF
  6244. * verifier would expect, taking into account specific program type. This
  6245. * allows to support __arg_ctx tag transparently on old kernels that don't yet
  6246. * have a native support for it in the verifier, making user's life much
  6247. * easier.
  6248. */
  6249. static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
  6250. {
  6251. const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
  6252. struct bpf_func_info_min *func_rec;
  6253. struct btf_type *fn_t, *fn_proto_t;
  6254. struct btf *btf = obj->btf;
  6255. const struct btf_type *t;
  6256. struct btf_param *p;
  6257. int ptr_id = 0, struct_id, tag_id, orig_fn_id;
  6258. int i, n, arg_idx, arg_cnt, err, rec_idx;
  6259. int *orig_ids;
  6260. /* no .BTF.ext, no problem */
  6261. if (!obj->btf_ext || !prog->func_info)
  6262. return 0;
  6263. /* don't do any fix ups if kernel natively supports __arg_ctx */
  6264. if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
  6265. return 0;
  6266. /* some BPF program types just don't have named context structs, so
  6267. * this fallback mechanism doesn't work for them
  6268. */
  6269. for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
  6270. if (global_ctx_map[i].prog_type != prog->type)
  6271. continue;
  6272. ctx_name = global_ctx_map[i].ctx_name;
  6273. break;
  6274. }
  6275. if (!ctx_name)
  6276. return 0;
  6277. /* remember original func BTF IDs to detect if we already cloned them */
  6278. orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
  6279. if (!orig_ids)
  6280. return -ENOMEM;
  6281. for (i = 0; i < prog->func_info_cnt; i++) {
  6282. func_rec = prog->func_info + prog->func_info_rec_size * i;
  6283. orig_ids[i] = func_rec->type_id;
  6284. }
  6285. /* go through each DECL_TAG with "arg:ctx" and see if it points to one
  6286. * of our subprogs; if yes and subprog is global and needs adjustment,
  6287. * clone and adjust FUNC -> FUNC_PROTO combo
  6288. */
  6289. for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
  6290. /* only DECL_TAG with "arg:ctx" value are interesting */
  6291. t = btf__type_by_id(btf, i);
  6292. if (!btf_is_decl_tag(t))
  6293. continue;
  6294. if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
  6295. continue;
  6296. /* only global funcs need adjustment, if at all */
  6297. orig_fn_id = t->type;
  6298. fn_t = btf_type_by_id(btf, orig_fn_id);
  6299. if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
  6300. continue;
  6301. /* sanity check FUNC -> FUNC_PROTO chain, just in case */
  6302. fn_proto_t = btf_type_by_id(btf, fn_t->type);
  6303. if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
  6304. continue;
  6305. /* find corresponding func_info record */
  6306. func_rec = NULL;
  6307. for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
  6308. if (orig_ids[rec_idx] == t->type) {
  6309. func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
  6310. break;
  6311. }
  6312. }
  6313. /* current main program doesn't call into this subprog */
  6314. if (!func_rec)
  6315. continue;
  6316. /* some more sanity checking of DECL_TAG */
  6317. arg_cnt = btf_vlen(fn_proto_t);
  6318. arg_idx = btf_decl_tag(t)->component_idx;
  6319. if (arg_idx < 0 || arg_idx >= arg_cnt)
  6320. continue;
  6321. /* check if we should fix up argument type */
  6322. p = &btf_params(fn_proto_t)[arg_idx];
  6323. fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
  6324. if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
  6325. continue;
  6326. /* clone fn/fn_proto, unless we already did it for another arg */
  6327. if (func_rec->type_id == orig_fn_id) {
  6328. int fn_id;
  6329. fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
  6330. if (fn_id < 0) {
  6331. err = fn_id;
  6332. goto err_out;
  6333. }
  6334. /* point func_info record to a cloned FUNC type */
  6335. func_rec->type_id = fn_id;
  6336. }
  6337. /* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
  6338. * we do it just once per main BPF program, as all global
  6339. * funcs share the same program type, so need only PTR ->
  6340. * STRUCT type chain
  6341. */
  6342. if (ptr_id == 0) {
  6343. struct_id = btf__add_struct(btf, ctx_name, 0);
  6344. ptr_id = btf__add_ptr(btf, struct_id);
  6345. if (ptr_id < 0 || struct_id < 0) {
  6346. err = -EINVAL;
  6347. goto err_out;
  6348. }
  6349. }
  6350. /* for completeness, clone DECL_TAG and point it to cloned param */
  6351. tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
  6352. if (tag_id < 0) {
  6353. err = -EINVAL;
  6354. goto err_out;
  6355. }
  6356. /* all the BTF manipulations invalidated pointers, refetch them */
  6357. fn_t = btf_type_by_id(btf, func_rec->type_id);
  6358. fn_proto_t = btf_type_by_id(btf, fn_t->type);
  6359. /* fix up type ID pointed to by param */
  6360. p = &btf_params(fn_proto_t)[arg_idx];
  6361. p->type = ptr_id;
  6362. }
  6363. free(orig_ids);
  6364. return 0;
  6365. err_out:
  6366. free(orig_ids);
  6367. return err;
  6368. }
  6369. static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
  6370. {
  6371. struct bpf_program *prog;
  6372. size_t i, j;
  6373. int err;
  6374. if (obj->btf_ext) {
  6375. err = bpf_object__relocate_core(obj, targ_btf_path);
  6376. if (err) {
  6377. pr_warn("failed to perform CO-RE relocations: %s\n",
  6378. errstr(err));
  6379. return err;
  6380. }
  6381. bpf_object__sort_relos(obj);
  6382. }
  6383. /* place globals at the end of the arena (if supported) */
  6384. if (obj->arena_map_idx >= 0 && kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF)) {
  6385. struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
  6386. obj->arena_data_off = bpf_map_mmap_sz(arena_map) -
  6387. roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
  6388. }
  6389. /* Before relocating calls pre-process relocations and mark
  6390. * few ld_imm64 instructions that points to subprogs.
  6391. * Otherwise bpf_object__reloc_code() later would have to consider
  6392. * all ld_imm64 insns as relocation candidates. That would
  6393. * reduce relocation speed, since amount of find_prog_insn_relo()
  6394. * would increase and most of them will fail to find a relo.
  6395. */
  6396. for (i = 0; i < obj->nr_programs; i++) {
  6397. prog = &obj->programs[i];
  6398. for (j = 0; j < prog->nr_reloc; j++) {
  6399. struct reloc_desc *relo = &prog->reloc_desc[j];
  6400. struct bpf_insn *insn = &prog->insns[relo->insn_idx];
  6401. /* mark the insn, so it's recognized by insn_is_pseudo_func() */
  6402. if (relo->type == RELO_SUBPROG_ADDR)
  6403. insn[0].src_reg = BPF_PSEUDO_FUNC;
  6404. }
  6405. }
  6406. /* relocate subprogram calls and append used subprograms to main
  6407. * programs; each copy of subprogram code needs to be relocated
  6408. * differently for each main program, because its code location might
  6409. * have changed.
  6410. * Append subprog relos to main programs to allow data relos to be
  6411. * processed after text is completely relocated.
  6412. */
  6413. for (i = 0; i < obj->nr_programs; i++) {
  6414. prog = &obj->programs[i];
  6415. /* sub-program's sub-calls are relocated within the context of
  6416. * its main program only
  6417. */
  6418. if (prog_is_subprog(obj, prog))
  6419. continue;
  6420. if (!prog->autoload)
  6421. continue;
  6422. err = bpf_object__relocate_calls(obj, prog);
  6423. if (err) {
  6424. pr_warn("prog '%s': failed to relocate calls: %s\n",
  6425. prog->name, errstr(err));
  6426. return err;
  6427. }
  6428. err = bpf_prog_assign_exc_cb(obj, prog);
  6429. if (err)
  6430. return err;
  6431. /* Now, also append exception callback if it has not been done already. */
  6432. if (prog->exception_cb_idx >= 0) {
  6433. struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
  6434. /* Calling exception callback directly is disallowed, which the
  6435. * verifier will reject later. In case it was processed already,
  6436. * we can skip this step, otherwise for all other valid cases we
  6437. * have to append exception callback now.
  6438. */
  6439. if (subprog->sub_insn_off == 0) {
  6440. err = bpf_object__append_subprog_code(obj, prog, subprog);
  6441. if (err)
  6442. return err;
  6443. err = bpf_object__reloc_code(obj, prog, subprog);
  6444. if (err)
  6445. return err;
  6446. }
  6447. }
  6448. }
  6449. for (i = 0; i < obj->nr_programs; i++) {
  6450. prog = &obj->programs[i];
  6451. if (prog_is_subprog(obj, prog))
  6452. continue;
  6453. if (!prog->autoload)
  6454. continue;
  6455. /* Process data relos for main programs */
  6456. err = bpf_object__relocate_data(obj, prog);
  6457. if (err) {
  6458. pr_warn("prog '%s': failed to relocate data references: %s\n",
  6459. prog->name, errstr(err));
  6460. return err;
  6461. }
  6462. /* Fix up .BTF.ext information, if necessary */
  6463. err = bpf_program_fixup_func_info(obj, prog);
  6464. if (err) {
  6465. pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
  6466. prog->name, errstr(err));
  6467. return err;
  6468. }
  6469. }
  6470. return 0;
  6471. }
  6472. static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
  6473. Elf64_Shdr *shdr, Elf_Data *data);
  6474. static int bpf_object__collect_map_relos(struct bpf_object *obj,
  6475. Elf64_Shdr *shdr, Elf_Data *data)
  6476. {
  6477. const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
  6478. int i, j, nrels, new_sz;
  6479. const struct btf_var_secinfo *vi = NULL;
  6480. const struct btf_type *sec, *var, *def;
  6481. struct bpf_map *map = NULL, *targ_map = NULL;
  6482. struct bpf_program *targ_prog = NULL;
  6483. bool is_prog_array, is_map_in_map;
  6484. const struct btf_member *member;
  6485. const char *name, *mname, *type;
  6486. unsigned int moff;
  6487. Elf64_Sym *sym;
  6488. Elf64_Rel *rel;
  6489. void *tmp;
  6490. if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
  6491. return -EINVAL;
  6492. sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
  6493. if (!sec)
  6494. return -EINVAL;
  6495. nrels = shdr->sh_size / shdr->sh_entsize;
  6496. for (i = 0; i < nrels; i++) {
  6497. rel = elf_rel_by_idx(data, i);
  6498. if (!rel) {
  6499. pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
  6500. return -LIBBPF_ERRNO__FORMAT;
  6501. }
  6502. sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
  6503. if (!sym) {
  6504. pr_warn(".maps relo #%d: symbol %zx not found\n",
  6505. i, (size_t)ELF64_R_SYM(rel->r_info));
  6506. return -LIBBPF_ERRNO__FORMAT;
  6507. }
  6508. name = elf_sym_str(obj, sym->st_name) ?: "<?>";
  6509. pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
  6510. i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
  6511. (size_t)rel->r_offset, sym->st_name, name);
  6512. for (j = 0; j < obj->nr_maps; j++) {
  6513. map = &obj->maps[j];
  6514. if (map->sec_idx != obj->efile.btf_maps_shndx)
  6515. continue;
  6516. vi = btf_var_secinfos(sec) + map->btf_var_idx;
  6517. if (vi->offset <= rel->r_offset &&
  6518. rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
  6519. break;
  6520. }
  6521. if (j == obj->nr_maps) {
  6522. pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
  6523. i, name, (size_t)rel->r_offset);
  6524. return -EINVAL;
  6525. }
  6526. is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
  6527. is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
  6528. type = is_map_in_map ? "map" : "prog";
  6529. if (is_map_in_map) {
  6530. if (sym->st_shndx != obj->efile.btf_maps_shndx) {
  6531. pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
  6532. i, name);
  6533. return -LIBBPF_ERRNO__RELOC;
  6534. }
  6535. if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
  6536. map->def.key_size != sizeof(int)) {
  6537. pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
  6538. i, map->name, sizeof(int));
  6539. return -EINVAL;
  6540. }
  6541. targ_map = bpf_object__find_map_by_name(obj, name);
  6542. if (!targ_map) {
  6543. pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
  6544. i, name);
  6545. return -ESRCH;
  6546. }
  6547. } else if (is_prog_array) {
  6548. targ_prog = bpf_object__find_program_by_name(obj, name);
  6549. if (!targ_prog) {
  6550. pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
  6551. i, name);
  6552. return -ESRCH;
  6553. }
  6554. if (targ_prog->sec_idx != sym->st_shndx ||
  6555. targ_prog->sec_insn_off * 8 != sym->st_value ||
  6556. prog_is_subprog(obj, targ_prog)) {
  6557. pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
  6558. i, name);
  6559. return -LIBBPF_ERRNO__RELOC;
  6560. }
  6561. } else {
  6562. return -EINVAL;
  6563. }
  6564. var = btf__type_by_id(obj->btf, vi->type);
  6565. def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
  6566. if (btf_vlen(def) == 0)
  6567. return -EINVAL;
  6568. member = btf_members(def) + btf_vlen(def) - 1;
  6569. mname = btf__name_by_offset(obj->btf, member->name_off);
  6570. if (strcmp(mname, "values"))
  6571. return -EINVAL;
  6572. moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
  6573. if (rel->r_offset - vi->offset < moff)
  6574. return -EINVAL;
  6575. moff = rel->r_offset - vi->offset - moff;
  6576. /* here we use BPF pointer size, which is always 64 bit, as we
  6577. * are parsing ELF that was built for BPF target
  6578. */
  6579. if (moff % bpf_ptr_sz)
  6580. return -EINVAL;
  6581. moff /= bpf_ptr_sz;
  6582. if (moff >= map->init_slots_sz) {
  6583. new_sz = moff + 1;
  6584. tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
  6585. if (!tmp)
  6586. return -ENOMEM;
  6587. map->init_slots = tmp;
  6588. memset(map->init_slots + map->init_slots_sz, 0,
  6589. (new_sz - map->init_slots_sz) * host_ptr_sz);
  6590. map->init_slots_sz = new_sz;
  6591. }
  6592. map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
  6593. pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
  6594. i, map->name, moff, type, name);
  6595. }
  6596. return 0;
  6597. }
  6598. static int bpf_object__collect_relos(struct bpf_object *obj)
  6599. {
  6600. int i, err;
  6601. for (i = 0; i < obj->efile.sec_cnt; i++) {
  6602. struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
  6603. Elf64_Shdr *shdr;
  6604. Elf_Data *data;
  6605. int idx;
  6606. if (sec_desc->sec_type != SEC_RELO)
  6607. continue;
  6608. shdr = sec_desc->shdr;
  6609. data = sec_desc->data;
  6610. idx = shdr->sh_info;
  6611. if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
  6612. pr_warn("internal error at %d\n", __LINE__);
  6613. return -LIBBPF_ERRNO__INTERNAL;
  6614. }
  6615. if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
  6616. err = bpf_object__collect_st_ops_relos(obj, shdr, data);
  6617. else if (idx == obj->efile.btf_maps_shndx)
  6618. err = bpf_object__collect_map_relos(obj, shdr, data);
  6619. else
  6620. err = bpf_object__collect_prog_relos(obj, shdr, data);
  6621. if (err)
  6622. return err;
  6623. }
  6624. bpf_object__sort_relos(obj);
  6625. return 0;
  6626. }
  6627. static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
  6628. {
  6629. if (BPF_CLASS(insn->code) == BPF_JMP &&
  6630. BPF_OP(insn->code) == BPF_CALL &&
  6631. BPF_SRC(insn->code) == BPF_K &&
  6632. insn->src_reg == 0 &&
  6633. insn->dst_reg == 0) {
  6634. *func_id = insn->imm;
  6635. return true;
  6636. }
  6637. return false;
  6638. }
  6639. static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
  6640. {
  6641. struct bpf_insn *insn = prog->insns;
  6642. enum bpf_func_id func_id;
  6643. int i;
  6644. if (obj->gen_loader)
  6645. return 0;
  6646. for (i = 0; i < prog->insns_cnt; i++, insn++) {
  6647. if (!insn_is_helper_call(insn, &func_id))
  6648. continue;
  6649. /* on kernels that don't yet support
  6650. * bpf_probe_read_{kernel,user}[_str] helpers, fall back
  6651. * to bpf_probe_read() which works well for old kernels
  6652. */
  6653. switch (func_id) {
  6654. case BPF_FUNC_probe_read_kernel:
  6655. case BPF_FUNC_probe_read_user:
  6656. if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
  6657. insn->imm = BPF_FUNC_probe_read;
  6658. break;
  6659. case BPF_FUNC_probe_read_kernel_str:
  6660. case BPF_FUNC_probe_read_user_str:
  6661. if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
  6662. insn->imm = BPF_FUNC_probe_read_str;
  6663. break;
  6664. default:
  6665. break;
  6666. }
  6667. }
  6668. return 0;
  6669. }
  6670. static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
  6671. int *btf_obj_fd, int *btf_type_id);
  6672. /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
  6673. static int libbpf_prepare_prog_load(struct bpf_program *prog,
  6674. struct bpf_prog_load_opts *opts, long cookie)
  6675. {
  6676. enum sec_def_flags def = cookie;
  6677. /* old kernels might not support specifying expected_attach_type */
  6678. if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
  6679. opts->expected_attach_type = 0;
  6680. if (def & SEC_SLEEPABLE)
  6681. opts->prog_flags |= BPF_F_SLEEPABLE;
  6682. if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
  6683. opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
  6684. /* special check for usdt to use uprobe_multi link */
  6685. if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
  6686. /* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
  6687. * in prog, and expected_attach_type we set in kernel is from opts, so we
  6688. * update both.
  6689. */
  6690. prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
  6691. opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
  6692. }
  6693. if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
  6694. int btf_obj_fd = 0, btf_type_id = 0, err;
  6695. const char *attach_name;
  6696. attach_name = strchr(prog->sec_name, '/');
  6697. if (!attach_name) {
  6698. /* if BPF program is annotated with just SEC("fentry")
  6699. * (or similar) without declaratively specifying
  6700. * target, then it is expected that target will be
  6701. * specified with bpf_program__set_attach_target() at
  6702. * runtime before BPF object load step. If not, then
  6703. * there is nothing to load into the kernel as BPF
  6704. * verifier won't be able to validate BPF program
  6705. * correctness anyways.
  6706. */
  6707. pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
  6708. prog->name);
  6709. return -EINVAL;
  6710. }
  6711. attach_name++; /* skip over / */
  6712. err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
  6713. if (err)
  6714. return err;
  6715. /* cache resolved BTF FD and BTF type ID in the prog */
  6716. prog->attach_btf_obj_fd = btf_obj_fd;
  6717. prog->attach_btf_id = btf_type_id;
  6718. /* but by now libbpf common logic is not utilizing
  6719. * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
  6720. * this callback is called after opts were populated by
  6721. * libbpf, so this callback has to update opts explicitly here
  6722. */
  6723. opts->attach_btf_obj_fd = btf_obj_fd;
  6724. opts->attach_btf_id = btf_type_id;
  6725. }
  6726. return 0;
  6727. }
  6728. static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
  6729. static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
  6730. struct bpf_insn *insns, int insns_cnt,
  6731. const char *license, __u32 kern_version, int *prog_fd)
  6732. {
  6733. LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
  6734. const char *prog_name = NULL;
  6735. size_t log_buf_size = 0;
  6736. char *log_buf = NULL, *tmp;
  6737. bool own_log_buf = true;
  6738. __u32 log_level = prog->log_level;
  6739. int ret, err;
  6740. /* Be more helpful by rejecting programs that can't be validated early
  6741. * with more meaningful and actionable error message.
  6742. */
  6743. switch (prog->type) {
  6744. case BPF_PROG_TYPE_UNSPEC:
  6745. /*
  6746. * The program type must be set. Most likely we couldn't find a proper
  6747. * section definition at load time, and thus we didn't infer the type.
  6748. */
  6749. pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
  6750. prog->name, prog->sec_name);
  6751. return -EINVAL;
  6752. case BPF_PROG_TYPE_STRUCT_OPS:
  6753. if (prog->attach_btf_id == 0) {
  6754. pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
  6755. prog->name);
  6756. return -EINVAL;
  6757. }
  6758. break;
  6759. default:
  6760. break;
  6761. }
  6762. if (!insns || !insns_cnt)
  6763. return -EINVAL;
  6764. if (kernel_supports(obj, FEAT_PROG_NAME))
  6765. prog_name = prog->name;
  6766. load_attr.attach_prog_fd = prog->attach_prog_fd;
  6767. load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
  6768. load_attr.attach_btf_id = prog->attach_btf_id;
  6769. load_attr.kern_version = kern_version;
  6770. load_attr.prog_ifindex = prog->prog_ifindex;
  6771. load_attr.expected_attach_type = prog->expected_attach_type;
  6772. /* specify func_info/line_info only if kernel supports them */
  6773. if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
  6774. load_attr.prog_btf_fd = btf__fd(obj->btf);
  6775. load_attr.func_info = prog->func_info;
  6776. load_attr.func_info_rec_size = prog->func_info_rec_size;
  6777. load_attr.func_info_cnt = prog->func_info_cnt;
  6778. load_attr.line_info = prog->line_info;
  6779. load_attr.line_info_rec_size = prog->line_info_rec_size;
  6780. load_attr.line_info_cnt = prog->line_info_cnt;
  6781. }
  6782. load_attr.log_level = log_level;
  6783. load_attr.prog_flags = prog->prog_flags;
  6784. load_attr.fd_array = obj->fd_array;
  6785. load_attr.token_fd = obj->token_fd;
  6786. if (obj->token_fd)
  6787. load_attr.prog_flags |= BPF_F_TOKEN_FD;
  6788. /* adjust load_attr if sec_def provides custom preload callback */
  6789. if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
  6790. err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
  6791. if (err < 0) {
  6792. pr_warn("prog '%s': failed to prepare load attributes: %s\n",
  6793. prog->name, errstr(err));
  6794. return err;
  6795. }
  6796. insns = prog->insns;
  6797. insns_cnt = prog->insns_cnt;
  6798. }
  6799. if (obj->gen_loader) {
  6800. bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
  6801. license, insns, insns_cnt, &load_attr,
  6802. prog - obj->programs);
  6803. *prog_fd = -1;
  6804. return 0;
  6805. }
  6806. retry_load:
  6807. /* if log_level is zero, we don't request logs initially even if
  6808. * custom log_buf is specified; if the program load fails, then we'll
  6809. * bump log_level to 1 and use either custom log_buf or we'll allocate
  6810. * our own and retry the load to get details on what failed
  6811. */
  6812. if (log_level) {
  6813. if (prog->log_buf) {
  6814. log_buf = prog->log_buf;
  6815. log_buf_size = prog->log_size;
  6816. own_log_buf = false;
  6817. } else if (obj->log_buf) {
  6818. log_buf = obj->log_buf;
  6819. log_buf_size = obj->log_size;
  6820. own_log_buf = false;
  6821. } else {
  6822. log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
  6823. tmp = realloc(log_buf, log_buf_size);
  6824. if (!tmp) {
  6825. ret = -ENOMEM;
  6826. goto out;
  6827. }
  6828. log_buf = tmp;
  6829. log_buf[0] = '\0';
  6830. own_log_buf = true;
  6831. }
  6832. }
  6833. load_attr.log_buf = log_buf;
  6834. load_attr.log_size = log_buf_size;
  6835. load_attr.log_level = log_level;
  6836. ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
  6837. if (ret >= 0) {
  6838. if (log_level && own_log_buf) {
  6839. pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
  6840. prog->name, log_buf);
  6841. }
  6842. if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
  6843. struct bpf_map *map;
  6844. int i;
  6845. for (i = 0; i < obj->nr_maps; i++) {
  6846. map = &prog->obj->maps[i];
  6847. if (map->libbpf_type != LIBBPF_MAP_RODATA)
  6848. continue;
  6849. if (bpf_prog_bind_map(ret, map->fd, NULL)) {
  6850. pr_warn("prog '%s': failed to bind map '%s': %s\n",
  6851. prog->name, map->real_name, errstr(errno));
  6852. /* Don't fail hard if can't bind rodata. */
  6853. }
  6854. }
  6855. }
  6856. *prog_fd = ret;
  6857. ret = 0;
  6858. goto out;
  6859. }
  6860. if (log_level == 0) {
  6861. log_level = 1;
  6862. goto retry_load;
  6863. }
  6864. /* On ENOSPC, increase log buffer size and retry, unless custom
  6865. * log_buf is specified.
  6866. * Be careful to not overflow u32, though. Kernel's log buf size limit
  6867. * isn't part of UAPI so it can always be bumped to full 4GB. So don't
  6868. * multiply by 2 unless we are sure we'll fit within 32 bits.
  6869. * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
  6870. */
  6871. if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
  6872. goto retry_load;
  6873. ret = -errno;
  6874. /* post-process verifier log to improve error descriptions */
  6875. fixup_verifier_log(prog, log_buf, log_buf_size);
  6876. pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
  6877. pr_perm_msg(ret);
  6878. if (own_log_buf && log_buf && log_buf[0] != '\0') {
  6879. pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
  6880. prog->name, log_buf);
  6881. }
  6882. out:
  6883. if (own_log_buf)
  6884. free(log_buf);
  6885. return ret;
  6886. }
  6887. static char *find_prev_line(char *buf, char *cur)
  6888. {
  6889. char *p;
  6890. if (cur == buf) /* end of a log buf */
  6891. return NULL;
  6892. p = cur - 1;
  6893. while (p - 1 >= buf && *(p - 1) != '\n')
  6894. p--;
  6895. return p;
  6896. }
  6897. static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
  6898. char *orig, size_t orig_sz, const char *patch)
  6899. {
  6900. /* size of the remaining log content to the right from the to-be-replaced part */
  6901. size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
  6902. size_t patch_sz = strlen(patch);
  6903. if (patch_sz != orig_sz) {
  6904. /* If patch line(s) are longer than original piece of verifier log,
  6905. * shift log contents by (patch_sz - orig_sz) bytes to the right
  6906. * starting from after to-be-replaced part of the log.
  6907. *
  6908. * If patch line(s) are shorter than original piece of verifier log,
  6909. * shift log contents by (orig_sz - patch_sz) bytes to the left
  6910. * starting from after to-be-replaced part of the log
  6911. *
  6912. * We need to be careful about not overflowing available
  6913. * buf_sz capacity. If that's the case, we'll truncate the end
  6914. * of the original log, as necessary.
  6915. */
  6916. if (patch_sz > orig_sz) {
  6917. if (orig + patch_sz >= buf + buf_sz) {
  6918. /* patch is big enough to cover remaining space completely */
  6919. patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
  6920. rem_sz = 0;
  6921. } else if (patch_sz - orig_sz > buf_sz - log_sz) {
  6922. /* patch causes part of remaining log to be truncated */
  6923. rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
  6924. }
  6925. }
  6926. /* shift remaining log to the right by calculated amount */
  6927. memmove(orig + patch_sz, orig + orig_sz, rem_sz);
  6928. }
  6929. memcpy(orig, patch, patch_sz);
  6930. }
  6931. static void fixup_log_failed_core_relo(struct bpf_program *prog,
  6932. char *buf, size_t buf_sz, size_t log_sz,
  6933. char *line1, char *line2, char *line3)
  6934. {
  6935. /* Expected log for failed and not properly guarded CO-RE relocation:
  6936. * line1 -> 123: (85) call unknown#195896080
  6937. * line2 -> invalid func unknown#195896080
  6938. * line3 -> <anything else or end of buffer>
  6939. *
  6940. * "123" is the index of the instruction that was poisoned. We extract
  6941. * instruction index to find corresponding CO-RE relocation and
  6942. * replace this part of the log with more relevant information about
  6943. * failed CO-RE relocation.
  6944. */
  6945. const struct bpf_core_relo *relo;
  6946. struct bpf_core_spec spec;
  6947. char patch[512], spec_buf[256];
  6948. int insn_idx, err, spec_len;
  6949. if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
  6950. return;
  6951. relo = find_relo_core(prog, insn_idx);
  6952. if (!relo)
  6953. return;
  6954. err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
  6955. if (err)
  6956. return;
  6957. spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
  6958. snprintf(patch, sizeof(patch),
  6959. "%d: <invalid CO-RE relocation>\n"
  6960. "failed to resolve CO-RE relocation %s%s\n",
  6961. insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
  6962. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6963. }
  6964. static void fixup_log_missing_map_load(struct bpf_program *prog,
  6965. char *buf, size_t buf_sz, size_t log_sz,
  6966. char *line1, char *line2, char *line3)
  6967. {
  6968. /* Expected log for failed and not properly guarded map reference:
  6969. * line1 -> 123: (85) call unknown#2001000345
  6970. * line2 -> invalid func unknown#2001000345
  6971. * line3 -> <anything else or end of buffer>
  6972. *
  6973. * "123" is the index of the instruction that was poisoned.
  6974. * "345" in "2001000345" is a map index in obj->maps to fetch map name.
  6975. */
  6976. struct bpf_object *obj = prog->obj;
  6977. const struct bpf_map *map;
  6978. int insn_idx, map_idx;
  6979. char patch[128];
  6980. if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
  6981. return;
  6982. map_idx -= POISON_LDIMM64_MAP_BASE;
  6983. if (map_idx < 0 || map_idx >= obj->nr_maps)
  6984. return;
  6985. map = &obj->maps[map_idx];
  6986. snprintf(patch, sizeof(patch),
  6987. "%d: <invalid BPF map reference>\n"
  6988. "BPF map '%s' is referenced but wasn't created\n",
  6989. insn_idx, map->name);
  6990. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  6991. }
  6992. static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
  6993. char *buf, size_t buf_sz, size_t log_sz,
  6994. char *line1, char *line2, char *line3)
  6995. {
  6996. /* Expected log for failed and not properly guarded kfunc call:
  6997. * line1 -> 123: (85) call unknown#2002000345
  6998. * line2 -> invalid func unknown#2002000345
  6999. * line3 -> <anything else or end of buffer>
  7000. *
  7001. * "123" is the index of the instruction that was poisoned.
  7002. * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
  7003. */
  7004. struct bpf_object *obj = prog->obj;
  7005. const struct extern_desc *ext;
  7006. int insn_idx, ext_idx;
  7007. char patch[128];
  7008. if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
  7009. return;
  7010. ext_idx -= POISON_CALL_KFUNC_BASE;
  7011. if (ext_idx < 0 || ext_idx >= obj->nr_extern)
  7012. return;
  7013. ext = &obj->externs[ext_idx];
  7014. snprintf(patch, sizeof(patch),
  7015. "%d: <invalid kfunc call>\n"
  7016. "kfunc '%s' is referenced but wasn't resolved\n",
  7017. insn_idx, ext->name);
  7018. patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
  7019. }
  7020. static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
  7021. {
  7022. /* look for familiar error patterns in last N lines of the log */
  7023. const size_t max_last_line_cnt = 10;
  7024. char *prev_line, *cur_line, *next_line;
  7025. size_t log_sz;
  7026. int i;
  7027. if (!buf)
  7028. return;
  7029. log_sz = strlen(buf) + 1;
  7030. next_line = buf + log_sz - 1;
  7031. for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
  7032. cur_line = find_prev_line(buf, next_line);
  7033. if (!cur_line)
  7034. return;
  7035. if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
  7036. prev_line = find_prev_line(buf, cur_line);
  7037. if (!prev_line)
  7038. continue;
  7039. /* failed CO-RE relocation case */
  7040. fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
  7041. prev_line, cur_line, next_line);
  7042. return;
  7043. } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
  7044. prev_line = find_prev_line(buf, cur_line);
  7045. if (!prev_line)
  7046. continue;
  7047. /* reference to uncreated BPF map */
  7048. fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
  7049. prev_line, cur_line, next_line);
  7050. return;
  7051. } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
  7052. prev_line = find_prev_line(buf, cur_line);
  7053. if (!prev_line)
  7054. continue;
  7055. /* reference to unresolved kfunc */
  7056. fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
  7057. prev_line, cur_line, next_line);
  7058. return;
  7059. }
  7060. }
  7061. }
  7062. static int bpf_program_record_relos(struct bpf_program *prog)
  7063. {
  7064. struct bpf_object *obj = prog->obj;
  7065. int i;
  7066. for (i = 0; i < prog->nr_reloc; i++) {
  7067. struct reloc_desc *relo = &prog->reloc_desc[i];
  7068. struct extern_desc *ext = &obj->externs[relo->ext_idx];
  7069. int kind;
  7070. switch (relo->type) {
  7071. case RELO_EXTERN_LD64:
  7072. if (ext->type != EXT_KSYM)
  7073. continue;
  7074. kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
  7075. BTF_KIND_VAR : BTF_KIND_FUNC;
  7076. bpf_gen__record_extern(obj->gen_loader, ext->name,
  7077. ext->is_weak, !ext->ksym.type_id,
  7078. true, kind, relo->insn_idx);
  7079. break;
  7080. case RELO_EXTERN_CALL:
  7081. bpf_gen__record_extern(obj->gen_loader, ext->name,
  7082. ext->is_weak, false, false, BTF_KIND_FUNC,
  7083. relo->insn_idx);
  7084. break;
  7085. case RELO_CORE: {
  7086. struct bpf_core_relo cr = {
  7087. .insn_off = relo->insn_idx * 8,
  7088. .type_id = relo->core_relo->type_id,
  7089. .access_str_off = relo->core_relo->access_str_off,
  7090. .kind = relo->core_relo->kind,
  7091. };
  7092. bpf_gen__record_relo_core(obj->gen_loader, &cr);
  7093. break;
  7094. }
  7095. default:
  7096. continue;
  7097. }
  7098. }
  7099. return 0;
  7100. }
  7101. static int
  7102. bpf_object__load_progs(struct bpf_object *obj, int log_level)
  7103. {
  7104. struct bpf_program *prog;
  7105. size_t i;
  7106. int err;
  7107. for (i = 0; i < obj->nr_programs; i++) {
  7108. prog = &obj->programs[i];
  7109. if (prog_is_subprog(obj, prog))
  7110. continue;
  7111. if (!prog->autoload) {
  7112. pr_debug("prog '%s': skipped loading\n", prog->name);
  7113. continue;
  7114. }
  7115. prog->log_level |= log_level;
  7116. if (obj->gen_loader)
  7117. bpf_program_record_relos(prog);
  7118. err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
  7119. obj->license, obj->kern_version, &prog->fd);
  7120. if (err) {
  7121. pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
  7122. return err;
  7123. }
  7124. }
  7125. bpf_object__free_relocs(obj);
  7126. return 0;
  7127. }
  7128. static int bpf_object_prepare_progs(struct bpf_object *obj)
  7129. {
  7130. struct bpf_program *prog;
  7131. size_t i;
  7132. int err;
  7133. for (i = 0; i < obj->nr_programs; i++) {
  7134. prog = &obj->programs[i];
  7135. err = bpf_object__sanitize_prog(obj, prog);
  7136. if (err)
  7137. return err;
  7138. }
  7139. return 0;
  7140. }
  7141. static const struct bpf_sec_def *find_sec_def(const char *sec_name);
  7142. static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
  7143. {
  7144. struct bpf_program *prog;
  7145. int err;
  7146. bpf_object__for_each_program(prog, obj) {
  7147. prog->sec_def = find_sec_def(prog->sec_name);
  7148. if (!prog->sec_def) {
  7149. /* couldn't guess, but user might manually specify */
  7150. pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
  7151. prog->name, prog->sec_name);
  7152. continue;
  7153. }
  7154. prog->type = prog->sec_def->prog_type;
  7155. prog->expected_attach_type = prog->sec_def->expected_attach_type;
  7156. /* sec_def can have custom callback which should be called
  7157. * after bpf_program is initialized to adjust its properties
  7158. */
  7159. if (prog->sec_def->prog_setup_fn) {
  7160. err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
  7161. if (err < 0) {
  7162. pr_warn("prog '%s': failed to initialize: %s\n",
  7163. prog->name, errstr(err));
  7164. return err;
  7165. }
  7166. }
  7167. }
  7168. return 0;
  7169. }
  7170. static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
  7171. const char *obj_name,
  7172. const struct bpf_object_open_opts *opts)
  7173. {
  7174. const char *kconfig, *btf_tmp_path, *token_path;
  7175. struct bpf_object *obj;
  7176. int err;
  7177. char *log_buf;
  7178. size_t log_size;
  7179. __u32 log_level;
  7180. if (obj_buf && !obj_name)
  7181. return ERR_PTR(-EINVAL);
  7182. if (elf_version(EV_CURRENT) == EV_NONE) {
  7183. pr_warn("failed to init libelf for %s\n",
  7184. path ? : "(mem buf)");
  7185. return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
  7186. }
  7187. if (!OPTS_VALID(opts, bpf_object_open_opts))
  7188. return ERR_PTR(-EINVAL);
  7189. obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
  7190. if (obj_buf) {
  7191. path = obj_name;
  7192. pr_debug("loading object '%s' from buffer\n", obj_name);
  7193. } else {
  7194. pr_debug("loading object from %s\n", path);
  7195. }
  7196. log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
  7197. log_size = OPTS_GET(opts, kernel_log_size, 0);
  7198. log_level = OPTS_GET(opts, kernel_log_level, 0);
  7199. if (log_size > UINT_MAX)
  7200. return ERR_PTR(-EINVAL);
  7201. if (log_size && !log_buf)
  7202. return ERR_PTR(-EINVAL);
  7203. token_path = OPTS_GET(opts, bpf_token_path, NULL);
  7204. /* if user didn't specify bpf_token_path explicitly, check if
  7205. * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
  7206. * option
  7207. */
  7208. if (!token_path)
  7209. token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
  7210. if (token_path && strlen(token_path) >= PATH_MAX)
  7211. return ERR_PTR(-ENAMETOOLONG);
  7212. obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
  7213. if (IS_ERR(obj))
  7214. return obj;
  7215. obj->log_buf = log_buf;
  7216. obj->log_size = log_size;
  7217. obj->log_level = log_level;
  7218. if (token_path) {
  7219. obj->token_path = strdup(token_path);
  7220. if (!obj->token_path) {
  7221. err = -ENOMEM;
  7222. goto out;
  7223. }
  7224. }
  7225. btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
  7226. if (btf_tmp_path) {
  7227. if (strlen(btf_tmp_path) >= PATH_MAX) {
  7228. err = -ENAMETOOLONG;
  7229. goto out;
  7230. }
  7231. obj->btf_custom_path = strdup(btf_tmp_path);
  7232. if (!obj->btf_custom_path) {
  7233. err = -ENOMEM;
  7234. goto out;
  7235. }
  7236. }
  7237. kconfig = OPTS_GET(opts, kconfig, NULL);
  7238. if (kconfig) {
  7239. obj->kconfig = strdup(kconfig);
  7240. if (!obj->kconfig) {
  7241. err = -ENOMEM;
  7242. goto out;
  7243. }
  7244. }
  7245. err = bpf_object__elf_init(obj);
  7246. err = err ? : bpf_object__elf_collect(obj);
  7247. err = err ? : bpf_object__collect_externs(obj);
  7248. err = err ? : bpf_object_fixup_btf(obj);
  7249. err = err ? : bpf_object__init_maps(obj, opts);
  7250. err = err ? : bpf_object_init_progs(obj, opts);
  7251. err = err ? : bpf_object__collect_relos(obj);
  7252. if (err)
  7253. goto out;
  7254. bpf_object__elf_finish(obj);
  7255. return obj;
  7256. out:
  7257. bpf_object__close(obj);
  7258. return ERR_PTR(err);
  7259. }
  7260. struct bpf_object *
  7261. bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
  7262. {
  7263. if (!path)
  7264. return libbpf_err_ptr(-EINVAL);
  7265. return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
  7266. }
  7267. struct bpf_object *bpf_object__open(const char *path)
  7268. {
  7269. return bpf_object__open_file(path, NULL);
  7270. }
  7271. struct bpf_object *
  7272. bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
  7273. const struct bpf_object_open_opts *opts)
  7274. {
  7275. char tmp_name[64];
  7276. if (!obj_buf || obj_buf_sz == 0)
  7277. return libbpf_err_ptr(-EINVAL);
  7278. /* create a (quite useless) default "name" for this memory buffer object */
  7279. snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
  7280. return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
  7281. }
  7282. static int bpf_object_unload(struct bpf_object *obj)
  7283. {
  7284. size_t i;
  7285. if (!obj)
  7286. return libbpf_err(-EINVAL);
  7287. for (i = 0; i < obj->nr_maps; i++) {
  7288. zclose(obj->maps[i].fd);
  7289. if (obj->maps[i].st_ops)
  7290. zfree(&obj->maps[i].st_ops->kern_vdata);
  7291. }
  7292. for (i = 0; i < obj->nr_programs; i++)
  7293. bpf_program__unload(&obj->programs[i]);
  7294. return 0;
  7295. }
  7296. static int bpf_object__sanitize_maps(struct bpf_object *obj)
  7297. {
  7298. struct bpf_map *m;
  7299. bpf_object__for_each_map(m, obj) {
  7300. if (!bpf_map__is_internal(m))
  7301. continue;
  7302. if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
  7303. m->def.map_flags &= ~BPF_F_MMAPABLE;
  7304. }
  7305. return 0;
  7306. }
  7307. typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
  7308. const char *sym_name, void *ctx);
  7309. static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
  7310. {
  7311. char sym_type, sym_name[500];
  7312. unsigned long long sym_addr;
  7313. int ret, err = 0;
  7314. FILE *f;
  7315. f = fopen("/proc/kallsyms", "re");
  7316. if (!f) {
  7317. err = -errno;
  7318. pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
  7319. return err;
  7320. }
  7321. while (true) {
  7322. ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
  7323. &sym_addr, &sym_type, sym_name);
  7324. if (ret == EOF && feof(f))
  7325. break;
  7326. if (ret != 3) {
  7327. pr_warn("failed to read kallsyms entry: %d\n", ret);
  7328. err = -EINVAL;
  7329. break;
  7330. }
  7331. err = cb(sym_addr, sym_type, sym_name, ctx);
  7332. if (err)
  7333. break;
  7334. }
  7335. fclose(f);
  7336. return err;
  7337. }
  7338. static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
  7339. const char *sym_name, void *ctx)
  7340. {
  7341. struct bpf_object *obj = ctx;
  7342. const struct btf_type *t;
  7343. struct extern_desc *ext;
  7344. const char *res;
  7345. res = strstr(sym_name, ".llvm.");
  7346. if (sym_type == 'd' && res)
  7347. ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
  7348. else
  7349. ext = find_extern_by_name(obj, sym_name);
  7350. if (!ext || ext->type != EXT_KSYM)
  7351. return 0;
  7352. t = btf__type_by_id(obj->btf, ext->btf_id);
  7353. if (!btf_is_var(t))
  7354. return 0;
  7355. if (ext->is_set && ext->ksym.addr != sym_addr) {
  7356. pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
  7357. sym_name, ext->ksym.addr, sym_addr);
  7358. return -EINVAL;
  7359. }
  7360. if (!ext->is_set) {
  7361. ext->is_set = true;
  7362. ext->ksym.addr = sym_addr;
  7363. pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
  7364. }
  7365. return 0;
  7366. }
  7367. static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
  7368. {
  7369. return libbpf_kallsyms_parse(kallsyms_cb, obj);
  7370. }
  7371. static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
  7372. __u16 kind, struct btf **res_btf,
  7373. struct module_btf **res_mod_btf)
  7374. {
  7375. struct module_btf *mod_btf;
  7376. struct btf *btf;
  7377. int i, id, err;
  7378. btf = obj->btf_vmlinux;
  7379. mod_btf = NULL;
  7380. id = btf__find_by_name_kind(btf, ksym_name, kind);
  7381. if (id == -ENOENT) {
  7382. err = load_module_btfs(obj);
  7383. if (err)
  7384. return err;
  7385. for (i = 0; i < obj->btf_module_cnt; i++) {
  7386. /* we assume module_btf's BTF FD is always >0 */
  7387. mod_btf = &obj->btf_modules[i];
  7388. btf = mod_btf->btf;
  7389. id = btf__find_by_name_kind_own(btf, ksym_name, kind);
  7390. if (id != -ENOENT)
  7391. break;
  7392. }
  7393. }
  7394. if (id <= 0)
  7395. return -ESRCH;
  7396. *res_btf = btf;
  7397. *res_mod_btf = mod_btf;
  7398. return id;
  7399. }
  7400. static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
  7401. struct extern_desc *ext)
  7402. {
  7403. const struct btf_type *targ_var, *targ_type;
  7404. __u32 targ_type_id, local_type_id;
  7405. struct module_btf *mod_btf = NULL;
  7406. const char *targ_var_name;
  7407. struct btf *btf = NULL;
  7408. int id, err;
  7409. id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
  7410. if (id < 0) {
  7411. if (id == -ESRCH && ext->is_weak)
  7412. return 0;
  7413. pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
  7414. ext->name);
  7415. return id;
  7416. }
  7417. /* find local type_id */
  7418. local_type_id = ext->ksym.type_id;
  7419. /* find target type_id */
  7420. targ_var = btf__type_by_id(btf, id);
  7421. targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
  7422. targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
  7423. err = bpf_core_types_are_compat(obj->btf, local_type_id,
  7424. btf, targ_type_id);
  7425. if (err <= 0) {
  7426. const struct btf_type *local_type;
  7427. const char *targ_name, *local_name;
  7428. local_type = btf__type_by_id(obj->btf, local_type_id);
  7429. local_name = btf__name_by_offset(obj->btf, local_type->name_off);
  7430. targ_name = btf__name_by_offset(btf, targ_type->name_off);
  7431. pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
  7432. ext->name, local_type_id,
  7433. btf_kind_str(local_type), local_name, targ_type_id,
  7434. btf_kind_str(targ_type), targ_name);
  7435. return -EINVAL;
  7436. }
  7437. ext->is_set = true;
  7438. ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
  7439. ext->ksym.kernel_btf_id = id;
  7440. pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
  7441. ext->name, id, btf_kind_str(targ_var), targ_var_name);
  7442. return 0;
  7443. }
  7444. static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
  7445. struct extern_desc *ext)
  7446. {
  7447. int local_func_proto_id, kfunc_proto_id, kfunc_id;
  7448. struct module_btf *mod_btf = NULL;
  7449. const struct btf_type *kern_func;
  7450. struct btf *kern_btf = NULL;
  7451. int ret;
  7452. local_func_proto_id = ext->ksym.type_id;
  7453. kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
  7454. &mod_btf);
  7455. if (kfunc_id < 0) {
  7456. if (kfunc_id == -ESRCH && ext->is_weak)
  7457. return 0;
  7458. pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
  7459. ext->name);
  7460. return kfunc_id;
  7461. }
  7462. kern_func = btf__type_by_id(kern_btf, kfunc_id);
  7463. kfunc_proto_id = kern_func->type;
  7464. ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
  7465. kern_btf, kfunc_proto_id);
  7466. if (ret <= 0) {
  7467. if (ext->is_weak)
  7468. return 0;
  7469. pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
  7470. ext->name, local_func_proto_id,
  7471. mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
  7472. return -EINVAL;
  7473. }
  7474. /* set index for module BTF fd in fd_array, if unset */
  7475. if (mod_btf && !mod_btf->fd_array_idx) {
  7476. /* insn->off is s16 */
  7477. if (obj->fd_array_cnt == INT16_MAX) {
  7478. pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
  7479. ext->name, mod_btf->fd_array_idx);
  7480. return -E2BIG;
  7481. }
  7482. /* Cannot use index 0 for module BTF fd */
  7483. if (!obj->fd_array_cnt)
  7484. obj->fd_array_cnt = 1;
  7485. ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
  7486. obj->fd_array_cnt + 1);
  7487. if (ret)
  7488. return ret;
  7489. mod_btf->fd_array_idx = obj->fd_array_cnt;
  7490. /* we assume module BTF FD is always >0 */
  7491. obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
  7492. }
  7493. ext->is_set = true;
  7494. ext->ksym.kernel_btf_id = kfunc_id;
  7495. ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
  7496. /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
  7497. * populates FD into ld_imm64 insn when it's used to point to kfunc.
  7498. * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
  7499. * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
  7500. */
  7501. ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
  7502. pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
  7503. ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
  7504. return 0;
  7505. }
  7506. static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
  7507. {
  7508. const struct btf_type *t;
  7509. struct extern_desc *ext;
  7510. int i, err;
  7511. for (i = 0; i < obj->nr_extern; i++) {
  7512. ext = &obj->externs[i];
  7513. if (ext->type != EXT_KSYM || !ext->ksym.type_id)
  7514. continue;
  7515. if (obj->gen_loader) {
  7516. ext->is_set = true;
  7517. ext->ksym.kernel_btf_obj_fd = 0;
  7518. ext->ksym.kernel_btf_id = 0;
  7519. continue;
  7520. }
  7521. t = btf__type_by_id(obj->btf, ext->btf_id);
  7522. if (btf_is_var(t))
  7523. err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
  7524. else
  7525. err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
  7526. if (err)
  7527. return err;
  7528. }
  7529. return 0;
  7530. }
  7531. static int bpf_object__resolve_externs(struct bpf_object *obj,
  7532. const char *extra_kconfig)
  7533. {
  7534. bool need_config = false, need_kallsyms = false;
  7535. bool need_vmlinux_btf = false;
  7536. struct extern_desc *ext;
  7537. void *kcfg_data = NULL;
  7538. int err, i;
  7539. if (obj->nr_extern == 0)
  7540. return 0;
  7541. if (obj->kconfig_map_idx >= 0)
  7542. kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
  7543. for (i = 0; i < obj->nr_extern; i++) {
  7544. ext = &obj->externs[i];
  7545. if (ext->type == EXT_KSYM) {
  7546. if (ext->ksym.type_id)
  7547. need_vmlinux_btf = true;
  7548. else
  7549. need_kallsyms = true;
  7550. continue;
  7551. } else if (ext->type == EXT_KCFG) {
  7552. void *ext_ptr = kcfg_data + ext->kcfg.data_off;
  7553. __u64 value = 0;
  7554. /* Kconfig externs need actual /proc/config.gz */
  7555. if (str_has_pfx(ext->name, "CONFIG_")) {
  7556. need_config = true;
  7557. continue;
  7558. }
  7559. /* Virtual kcfg externs are customly handled by libbpf */
  7560. if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
  7561. value = get_kernel_version();
  7562. if (!value) {
  7563. pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
  7564. return -EINVAL;
  7565. }
  7566. } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
  7567. value = kernel_supports(obj, FEAT_BPF_COOKIE);
  7568. } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
  7569. value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
  7570. } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
  7571. /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
  7572. * __kconfig externs, where LINUX_ ones are virtual and filled out
  7573. * customly by libbpf (their values don't come from Kconfig).
  7574. * If LINUX_xxx variable is not recognized by libbpf, but is marked
  7575. * __weak, it defaults to zero value, just like for CONFIG_xxx
  7576. * externs.
  7577. */
  7578. pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
  7579. return -EINVAL;
  7580. }
  7581. err = set_kcfg_value_num(ext, ext_ptr, value);
  7582. if (err)
  7583. return err;
  7584. pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
  7585. ext->name, (long long)value);
  7586. } else {
  7587. pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
  7588. return -EINVAL;
  7589. }
  7590. }
  7591. if (need_config && extra_kconfig) {
  7592. err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
  7593. if (err)
  7594. return -EINVAL;
  7595. need_config = false;
  7596. for (i = 0; i < obj->nr_extern; i++) {
  7597. ext = &obj->externs[i];
  7598. if (ext->type == EXT_KCFG && !ext->is_set) {
  7599. need_config = true;
  7600. break;
  7601. }
  7602. }
  7603. }
  7604. if (need_config) {
  7605. err = bpf_object__read_kconfig_file(obj, kcfg_data);
  7606. if (err)
  7607. return -EINVAL;
  7608. }
  7609. if (need_kallsyms) {
  7610. err = bpf_object__read_kallsyms_file(obj);
  7611. if (err)
  7612. return -EINVAL;
  7613. }
  7614. if (need_vmlinux_btf) {
  7615. err = bpf_object__resolve_ksyms_btf_id(obj);
  7616. if (err)
  7617. return -EINVAL;
  7618. }
  7619. for (i = 0; i < obj->nr_extern; i++) {
  7620. ext = &obj->externs[i];
  7621. if (!ext->is_set && !ext->is_weak) {
  7622. pr_warn("extern '%s' (strong): not resolved\n", ext->name);
  7623. return -ESRCH;
  7624. } else if (!ext->is_set) {
  7625. pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
  7626. ext->name);
  7627. }
  7628. }
  7629. return 0;
  7630. }
  7631. static void bpf_map_prepare_vdata(const struct bpf_map *map)
  7632. {
  7633. const struct btf_type *type;
  7634. struct bpf_struct_ops *st_ops;
  7635. __u32 i;
  7636. st_ops = map->st_ops;
  7637. type = btf__type_by_id(map->obj->btf, st_ops->type_id);
  7638. for (i = 0; i < btf_vlen(type); i++) {
  7639. struct bpf_program *prog = st_ops->progs[i];
  7640. void *kern_data;
  7641. int prog_fd;
  7642. if (!prog)
  7643. continue;
  7644. prog_fd = bpf_program__fd(prog);
  7645. kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
  7646. *(unsigned long *)kern_data = prog_fd;
  7647. }
  7648. }
  7649. static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
  7650. {
  7651. struct bpf_map *map;
  7652. int i;
  7653. for (i = 0; i < obj->nr_maps; i++) {
  7654. map = &obj->maps[i];
  7655. if (!bpf_map__is_struct_ops(map))
  7656. continue;
  7657. if (!map->autocreate)
  7658. continue;
  7659. bpf_map_prepare_vdata(map);
  7660. }
  7661. return 0;
  7662. }
  7663. static void bpf_object_unpin(struct bpf_object *obj)
  7664. {
  7665. int i;
  7666. /* unpin any maps that were auto-pinned during load */
  7667. for (i = 0; i < obj->nr_maps; i++)
  7668. if (obj->maps[i].pinned && !obj->maps[i].reused)
  7669. bpf_map__unpin(&obj->maps[i], NULL);
  7670. }
  7671. static void bpf_object_post_load_cleanup(struct bpf_object *obj)
  7672. {
  7673. int i;
  7674. /* clean up fd_array */
  7675. zfree(&obj->fd_array);
  7676. /* clean up module BTFs */
  7677. for (i = 0; i < obj->btf_module_cnt; i++) {
  7678. close(obj->btf_modules[i].fd);
  7679. btf__free(obj->btf_modules[i].btf);
  7680. free(obj->btf_modules[i].name);
  7681. }
  7682. obj->btf_module_cnt = 0;
  7683. zfree(&obj->btf_modules);
  7684. /* clean up vmlinux BTF */
  7685. btf__free(obj->btf_vmlinux);
  7686. obj->btf_vmlinux = NULL;
  7687. }
  7688. static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
  7689. {
  7690. int err;
  7691. if (obj->state >= OBJ_PREPARED) {
  7692. pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
  7693. return -EINVAL;
  7694. }
  7695. err = bpf_object_prepare_token(obj);
  7696. err = err ? : bpf_object__probe_loading(obj);
  7697. err = err ? : bpf_object__load_vmlinux_btf(obj, false);
  7698. err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
  7699. err = err ? : bpf_object__sanitize_maps(obj);
  7700. err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
  7701. err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
  7702. err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
  7703. err = err ? : bpf_object__sanitize_and_load_btf(obj);
  7704. err = err ? : bpf_object__create_maps(obj);
  7705. err = err ? : bpf_object_prepare_progs(obj);
  7706. if (err) {
  7707. bpf_object_unpin(obj);
  7708. bpf_object_unload(obj);
  7709. obj->state = OBJ_LOADED;
  7710. return err;
  7711. }
  7712. obj->state = OBJ_PREPARED;
  7713. return 0;
  7714. }
  7715. static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
  7716. {
  7717. int err;
  7718. if (!obj)
  7719. return libbpf_err(-EINVAL);
  7720. if (obj->state >= OBJ_LOADED) {
  7721. pr_warn("object '%s': load can't be attempted twice\n", obj->name);
  7722. return libbpf_err(-EINVAL);
  7723. }
  7724. /* Disallow kernel loading programs of non-native endianness but
  7725. * permit cross-endian creation of "light skeleton".
  7726. */
  7727. if (obj->gen_loader) {
  7728. bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
  7729. } else if (!is_native_endianness(obj)) {
  7730. pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
  7731. return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
  7732. }
  7733. if (obj->state < OBJ_PREPARED) {
  7734. err = bpf_object_prepare(obj, target_btf_path);
  7735. if (err)
  7736. return libbpf_err(err);
  7737. }
  7738. err = bpf_object__load_progs(obj, extra_log_level);
  7739. err = err ? : bpf_object_init_prog_arrays(obj);
  7740. err = err ? : bpf_object_prepare_struct_ops(obj);
  7741. if (obj->gen_loader) {
  7742. /* reset FDs */
  7743. if (obj->btf)
  7744. btf__set_fd(obj->btf, -1);
  7745. if (!err)
  7746. err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
  7747. }
  7748. bpf_object_post_load_cleanup(obj);
  7749. obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
  7750. if (err) {
  7751. bpf_object_unpin(obj);
  7752. bpf_object_unload(obj);
  7753. pr_warn("failed to load object '%s'\n", obj->path);
  7754. return libbpf_err(err);
  7755. }
  7756. return 0;
  7757. }
  7758. int bpf_object__prepare(struct bpf_object *obj)
  7759. {
  7760. return libbpf_err(bpf_object_prepare(obj, NULL));
  7761. }
  7762. int bpf_object__load(struct bpf_object *obj)
  7763. {
  7764. return bpf_object_load(obj, 0, NULL);
  7765. }
  7766. static int make_parent_dir(const char *path)
  7767. {
  7768. char *dname, *dir;
  7769. int err = 0;
  7770. dname = strdup(path);
  7771. if (dname == NULL)
  7772. return -ENOMEM;
  7773. dir = dirname(dname);
  7774. if (mkdir(dir, 0700) && errno != EEXIST)
  7775. err = -errno;
  7776. free(dname);
  7777. if (err) {
  7778. pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
  7779. }
  7780. return err;
  7781. }
  7782. static int check_path(const char *path)
  7783. {
  7784. struct statfs st_fs;
  7785. char *dname, *dir;
  7786. int err = 0;
  7787. if (path == NULL)
  7788. return -EINVAL;
  7789. dname = strdup(path);
  7790. if (dname == NULL)
  7791. return -ENOMEM;
  7792. dir = dirname(dname);
  7793. if (statfs(dir, &st_fs)) {
  7794. pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
  7795. err = -errno;
  7796. }
  7797. free(dname);
  7798. if (!err && st_fs.f_type != BPF_FS_MAGIC) {
  7799. pr_warn("specified path %s is not on BPF FS\n", path);
  7800. err = -EINVAL;
  7801. }
  7802. return err;
  7803. }
  7804. int bpf_program__pin(struct bpf_program *prog, const char *path)
  7805. {
  7806. int err;
  7807. if (prog->fd < 0) {
  7808. pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
  7809. return libbpf_err(-EINVAL);
  7810. }
  7811. err = make_parent_dir(path);
  7812. if (err)
  7813. return libbpf_err(err);
  7814. err = check_path(path);
  7815. if (err)
  7816. return libbpf_err(err);
  7817. if (bpf_obj_pin(prog->fd, path)) {
  7818. err = -errno;
  7819. pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
  7820. return libbpf_err(err);
  7821. }
  7822. pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
  7823. return 0;
  7824. }
  7825. int bpf_program__unpin(struct bpf_program *prog, const char *path)
  7826. {
  7827. int err;
  7828. if (prog->fd < 0) {
  7829. pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
  7830. return libbpf_err(-EINVAL);
  7831. }
  7832. err = check_path(path);
  7833. if (err)
  7834. return libbpf_err(err);
  7835. err = unlink(path);
  7836. if (err)
  7837. return libbpf_err(-errno);
  7838. pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
  7839. return 0;
  7840. }
  7841. int bpf_map__pin(struct bpf_map *map, const char *path)
  7842. {
  7843. int err;
  7844. if (map == NULL) {
  7845. pr_warn("invalid map pointer\n");
  7846. return libbpf_err(-EINVAL);
  7847. }
  7848. if (map->fd < 0) {
  7849. pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
  7850. return libbpf_err(-EINVAL);
  7851. }
  7852. if (map->pin_path) {
  7853. if (path && strcmp(path, map->pin_path)) {
  7854. pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
  7855. bpf_map__name(map), map->pin_path, path);
  7856. return libbpf_err(-EINVAL);
  7857. } else if (map->pinned) {
  7858. pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
  7859. bpf_map__name(map), map->pin_path);
  7860. return 0;
  7861. }
  7862. } else {
  7863. if (!path) {
  7864. pr_warn("missing a path to pin map '%s' at\n",
  7865. bpf_map__name(map));
  7866. return libbpf_err(-EINVAL);
  7867. } else if (map->pinned) {
  7868. pr_warn("map '%s' already pinned\n", bpf_map__name(map));
  7869. return libbpf_err(-EEXIST);
  7870. }
  7871. map->pin_path = strdup(path);
  7872. if (!map->pin_path) {
  7873. err = -errno;
  7874. goto out_err;
  7875. }
  7876. }
  7877. err = make_parent_dir(map->pin_path);
  7878. if (err)
  7879. return libbpf_err(err);
  7880. err = check_path(map->pin_path);
  7881. if (err)
  7882. return libbpf_err(err);
  7883. if (bpf_obj_pin(map->fd, map->pin_path)) {
  7884. err = -errno;
  7885. goto out_err;
  7886. }
  7887. map->pinned = true;
  7888. pr_debug("pinned map '%s'\n", map->pin_path);
  7889. return 0;
  7890. out_err:
  7891. pr_warn("failed to pin map: %s\n", errstr(err));
  7892. return libbpf_err(err);
  7893. }
  7894. int bpf_map__unpin(struct bpf_map *map, const char *path)
  7895. {
  7896. int err;
  7897. if (map == NULL) {
  7898. pr_warn("invalid map pointer\n");
  7899. return libbpf_err(-EINVAL);
  7900. }
  7901. if (map->pin_path) {
  7902. if (path && strcmp(path, map->pin_path)) {
  7903. pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
  7904. bpf_map__name(map), map->pin_path, path);
  7905. return libbpf_err(-EINVAL);
  7906. }
  7907. path = map->pin_path;
  7908. } else if (!path) {
  7909. pr_warn("no path to unpin map '%s' from\n",
  7910. bpf_map__name(map));
  7911. return libbpf_err(-EINVAL);
  7912. }
  7913. err = check_path(path);
  7914. if (err)
  7915. return libbpf_err(err);
  7916. err = unlink(path);
  7917. if (err != 0)
  7918. return libbpf_err(-errno);
  7919. map->pinned = false;
  7920. pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
  7921. return 0;
  7922. }
  7923. int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
  7924. {
  7925. char *new = NULL;
  7926. if (path) {
  7927. new = strdup(path);
  7928. if (!new)
  7929. return libbpf_err(-errno);
  7930. }
  7931. free(map->pin_path);
  7932. map->pin_path = new;
  7933. return 0;
  7934. }
  7935. __alias(bpf_map__pin_path)
  7936. const char *bpf_map__get_pin_path(const struct bpf_map *map);
  7937. const char *bpf_map__pin_path(const struct bpf_map *map)
  7938. {
  7939. return map->pin_path;
  7940. }
  7941. bool bpf_map__is_pinned(const struct bpf_map *map)
  7942. {
  7943. return map->pinned;
  7944. }
  7945. static void sanitize_pin_path(char *s)
  7946. {
  7947. /* bpffs disallows periods in path names */
  7948. while (*s) {
  7949. if (*s == '.')
  7950. *s = '_';
  7951. s++;
  7952. }
  7953. }
  7954. int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
  7955. {
  7956. struct bpf_map *map;
  7957. int err;
  7958. if (!obj)
  7959. return libbpf_err(-ENOENT);
  7960. if (obj->state < OBJ_PREPARED) {
  7961. pr_warn("object not yet loaded; load it first\n");
  7962. return libbpf_err(-ENOENT);
  7963. }
  7964. bpf_object__for_each_map(map, obj) {
  7965. char *pin_path = NULL;
  7966. char buf[PATH_MAX];
  7967. if (!map->autocreate)
  7968. continue;
  7969. if (path) {
  7970. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  7971. if (err)
  7972. goto err_unpin_maps;
  7973. sanitize_pin_path(buf);
  7974. pin_path = buf;
  7975. } else if (!map->pin_path) {
  7976. continue;
  7977. }
  7978. err = bpf_map__pin(map, pin_path);
  7979. if (err)
  7980. goto err_unpin_maps;
  7981. }
  7982. return 0;
  7983. err_unpin_maps:
  7984. while ((map = bpf_object__prev_map(obj, map))) {
  7985. if (!map->pin_path)
  7986. continue;
  7987. bpf_map__unpin(map, NULL);
  7988. }
  7989. return libbpf_err(err);
  7990. }
  7991. int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
  7992. {
  7993. struct bpf_map *map;
  7994. int err;
  7995. if (!obj)
  7996. return libbpf_err(-ENOENT);
  7997. bpf_object__for_each_map(map, obj) {
  7998. char *pin_path = NULL;
  7999. char buf[PATH_MAX];
  8000. if (path) {
  8001. err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
  8002. if (err)
  8003. return libbpf_err(err);
  8004. sanitize_pin_path(buf);
  8005. pin_path = buf;
  8006. } else if (!map->pin_path) {
  8007. continue;
  8008. }
  8009. err = bpf_map__unpin(map, pin_path);
  8010. if (err)
  8011. return libbpf_err(err);
  8012. }
  8013. return 0;
  8014. }
  8015. int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
  8016. {
  8017. struct bpf_program *prog;
  8018. char buf[PATH_MAX];
  8019. int err;
  8020. if (!obj)
  8021. return libbpf_err(-ENOENT);
  8022. if (obj->state < OBJ_LOADED) {
  8023. pr_warn("object not yet loaded; load it first\n");
  8024. return libbpf_err(-ENOENT);
  8025. }
  8026. bpf_object__for_each_program(prog, obj) {
  8027. err = pathname_concat(buf, sizeof(buf), path, prog->name);
  8028. if (err)
  8029. goto err_unpin_programs;
  8030. err = bpf_program__pin(prog, buf);
  8031. if (err)
  8032. goto err_unpin_programs;
  8033. }
  8034. return 0;
  8035. err_unpin_programs:
  8036. while ((prog = bpf_object__prev_program(obj, prog))) {
  8037. if (pathname_concat(buf, sizeof(buf), path, prog->name))
  8038. continue;
  8039. bpf_program__unpin(prog, buf);
  8040. }
  8041. return libbpf_err(err);
  8042. }
  8043. int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
  8044. {
  8045. struct bpf_program *prog;
  8046. int err;
  8047. if (!obj)
  8048. return libbpf_err(-ENOENT);
  8049. bpf_object__for_each_program(prog, obj) {
  8050. char buf[PATH_MAX];
  8051. err = pathname_concat(buf, sizeof(buf), path, prog->name);
  8052. if (err)
  8053. return libbpf_err(err);
  8054. err = bpf_program__unpin(prog, buf);
  8055. if (err)
  8056. return libbpf_err(err);
  8057. }
  8058. return 0;
  8059. }
  8060. int bpf_object__pin(struct bpf_object *obj, const char *path)
  8061. {
  8062. int err;
  8063. err = bpf_object__pin_maps(obj, path);
  8064. if (err)
  8065. return libbpf_err(err);
  8066. err = bpf_object__pin_programs(obj, path);
  8067. if (err) {
  8068. bpf_object__unpin_maps(obj, path);
  8069. return libbpf_err(err);
  8070. }
  8071. return 0;
  8072. }
  8073. int bpf_object__unpin(struct bpf_object *obj, const char *path)
  8074. {
  8075. int err;
  8076. err = bpf_object__unpin_programs(obj, path);
  8077. if (err)
  8078. return libbpf_err(err);
  8079. err = bpf_object__unpin_maps(obj, path);
  8080. if (err)
  8081. return libbpf_err(err);
  8082. return 0;
  8083. }
  8084. static void bpf_map__destroy(struct bpf_map *map)
  8085. {
  8086. if (map->inner_map) {
  8087. bpf_map__destroy(map->inner_map);
  8088. zfree(&map->inner_map);
  8089. }
  8090. zfree(&map->init_slots);
  8091. map->init_slots_sz = 0;
  8092. if (map->mmaped && map->mmaped != map->obj->arena_data)
  8093. munmap(map->mmaped, bpf_map_mmap_sz(map));
  8094. map->mmaped = NULL;
  8095. if (map->st_ops) {
  8096. zfree(&map->st_ops->data);
  8097. zfree(&map->st_ops->progs);
  8098. zfree(&map->st_ops->kern_func_off);
  8099. zfree(&map->st_ops);
  8100. }
  8101. zfree(&map->name);
  8102. zfree(&map->real_name);
  8103. zfree(&map->pin_path);
  8104. if (map->fd >= 0)
  8105. zclose(map->fd);
  8106. }
  8107. void bpf_object__close(struct bpf_object *obj)
  8108. {
  8109. size_t i;
  8110. if (IS_ERR_OR_NULL(obj))
  8111. return;
  8112. /*
  8113. * if user called bpf_object__prepare() without ever getting to
  8114. * bpf_object__load(), we need to clean up stuff that is normally
  8115. * cleaned up at the end of loading step
  8116. */
  8117. bpf_object_post_load_cleanup(obj);
  8118. usdt_manager_free(obj->usdt_man);
  8119. obj->usdt_man = NULL;
  8120. bpf_gen__free(obj->gen_loader);
  8121. bpf_object__elf_finish(obj);
  8122. bpf_object_unload(obj);
  8123. btf__free(obj->btf);
  8124. btf__free(obj->btf_vmlinux);
  8125. btf_ext__free(obj->btf_ext);
  8126. for (i = 0; i < obj->nr_maps; i++)
  8127. bpf_map__destroy(&obj->maps[i]);
  8128. zfree(&obj->btf_custom_path);
  8129. zfree(&obj->kconfig);
  8130. for (i = 0; i < obj->nr_extern; i++) {
  8131. zfree(&obj->externs[i].name);
  8132. zfree(&obj->externs[i].essent_name);
  8133. }
  8134. zfree(&obj->externs);
  8135. obj->nr_extern = 0;
  8136. zfree(&obj->maps);
  8137. obj->nr_maps = 0;
  8138. if (obj->programs && obj->nr_programs) {
  8139. for (i = 0; i < obj->nr_programs; i++)
  8140. bpf_program__exit(&obj->programs[i]);
  8141. }
  8142. zfree(&obj->programs);
  8143. zfree(&obj->feat_cache);
  8144. zfree(&obj->token_path);
  8145. if (obj->token_fd > 0)
  8146. close(obj->token_fd);
  8147. zfree(&obj->arena_data);
  8148. zfree(&obj->jumptables_data);
  8149. obj->jumptables_data_sz = 0;
  8150. for (i = 0; i < obj->jumptable_map_cnt; i++)
  8151. close(obj->jumptable_maps[i].fd);
  8152. zfree(&obj->jumptable_maps);
  8153. free(obj);
  8154. }
  8155. const char *bpf_object__name(const struct bpf_object *obj)
  8156. {
  8157. return obj ? obj->name : libbpf_err_ptr(-EINVAL);
  8158. }
  8159. unsigned int bpf_object__kversion(const struct bpf_object *obj)
  8160. {
  8161. return obj ? obj->kern_version : 0;
  8162. }
  8163. int bpf_object__token_fd(const struct bpf_object *obj)
  8164. {
  8165. return obj->token_fd ?: -1;
  8166. }
  8167. struct btf *bpf_object__btf(const struct bpf_object *obj)
  8168. {
  8169. return obj ? obj->btf : NULL;
  8170. }
  8171. int bpf_object__btf_fd(const struct bpf_object *obj)
  8172. {
  8173. return obj->btf ? btf__fd(obj->btf) : -1;
  8174. }
  8175. int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
  8176. {
  8177. if (obj->state >= OBJ_LOADED)
  8178. return libbpf_err(-EINVAL);
  8179. obj->kern_version = kern_version;
  8180. return 0;
  8181. }
  8182. int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
  8183. {
  8184. struct bpf_gen *gen;
  8185. if (!opts)
  8186. return libbpf_err(-EFAULT);
  8187. if (!OPTS_VALID(opts, gen_loader_opts))
  8188. return libbpf_err(-EINVAL);
  8189. gen = calloc(1, sizeof(*gen));
  8190. if (!gen)
  8191. return libbpf_err(-ENOMEM);
  8192. gen->opts = opts;
  8193. gen->swapped_endian = !is_native_endianness(obj);
  8194. obj->gen_loader = gen;
  8195. return 0;
  8196. }
  8197. static struct bpf_program *
  8198. __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
  8199. bool forward)
  8200. {
  8201. size_t nr_programs = obj->nr_programs;
  8202. ssize_t idx;
  8203. if (!nr_programs)
  8204. return NULL;
  8205. if (!p)
  8206. /* Iter from the beginning */
  8207. return forward ? &obj->programs[0] :
  8208. &obj->programs[nr_programs - 1];
  8209. if (p->obj != obj) {
  8210. pr_warn("error: program handler doesn't match object\n");
  8211. return errno = EINVAL, NULL;
  8212. }
  8213. idx = (p - obj->programs) + (forward ? 1 : -1);
  8214. if (idx >= obj->nr_programs || idx < 0)
  8215. return NULL;
  8216. return &obj->programs[idx];
  8217. }
  8218. struct bpf_program *
  8219. bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
  8220. {
  8221. struct bpf_program *prog = prev;
  8222. do {
  8223. prog = __bpf_program__iter(prog, obj, true);
  8224. } while (prog && prog_is_subprog(obj, prog));
  8225. return prog;
  8226. }
  8227. struct bpf_program *
  8228. bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
  8229. {
  8230. struct bpf_program *prog = next;
  8231. do {
  8232. prog = __bpf_program__iter(prog, obj, false);
  8233. } while (prog && prog_is_subprog(obj, prog));
  8234. return prog;
  8235. }
  8236. void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
  8237. {
  8238. prog->prog_ifindex = ifindex;
  8239. }
  8240. const char *bpf_program__name(const struct bpf_program *prog)
  8241. {
  8242. return prog->name;
  8243. }
  8244. const char *bpf_program__section_name(const struct bpf_program *prog)
  8245. {
  8246. return prog->sec_name;
  8247. }
  8248. bool bpf_program__autoload(const struct bpf_program *prog)
  8249. {
  8250. return prog->autoload;
  8251. }
  8252. int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
  8253. {
  8254. if (prog->obj->state >= OBJ_LOADED)
  8255. return libbpf_err(-EINVAL);
  8256. prog->autoload = autoload;
  8257. return 0;
  8258. }
  8259. bool bpf_program__autoattach(const struct bpf_program *prog)
  8260. {
  8261. return prog->autoattach;
  8262. }
  8263. void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
  8264. {
  8265. prog->autoattach = autoattach;
  8266. }
  8267. const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
  8268. {
  8269. return prog->insns;
  8270. }
  8271. size_t bpf_program__insn_cnt(const struct bpf_program *prog)
  8272. {
  8273. return prog->insns_cnt;
  8274. }
  8275. int bpf_program__set_insns(struct bpf_program *prog,
  8276. struct bpf_insn *new_insns, size_t new_insn_cnt)
  8277. {
  8278. struct bpf_insn *insns;
  8279. if (prog->obj->state >= OBJ_LOADED)
  8280. return libbpf_err(-EBUSY);
  8281. insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
  8282. /* NULL is a valid return from reallocarray if the new count is zero */
  8283. if (!insns && new_insn_cnt) {
  8284. pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
  8285. return libbpf_err(-ENOMEM);
  8286. }
  8287. memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
  8288. prog->insns = insns;
  8289. prog->insns_cnt = new_insn_cnt;
  8290. return 0;
  8291. }
  8292. int bpf_program__fd(const struct bpf_program *prog)
  8293. {
  8294. if (!prog)
  8295. return libbpf_err(-EINVAL);
  8296. if (prog->fd < 0)
  8297. return libbpf_err(-ENOENT);
  8298. return prog->fd;
  8299. }
  8300. __alias(bpf_program__type)
  8301. enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
  8302. enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
  8303. {
  8304. return prog->type;
  8305. }
  8306. static size_t custom_sec_def_cnt;
  8307. static struct bpf_sec_def *custom_sec_defs;
  8308. static struct bpf_sec_def custom_fallback_def;
  8309. static bool has_custom_fallback_def;
  8310. static int last_custom_sec_def_handler_id;
  8311. int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
  8312. {
  8313. if (prog->obj->state >= OBJ_LOADED)
  8314. return libbpf_err(-EBUSY);
  8315. /* if type is not changed, do nothing */
  8316. if (prog->type == type)
  8317. return 0;
  8318. prog->type = type;
  8319. /* If a program type was changed, we need to reset associated SEC()
  8320. * handler, as it will be invalid now. The only exception is a generic
  8321. * fallback handler, which by definition is program type-agnostic and
  8322. * is a catch-all custom handler, optionally set by the application,
  8323. * so should be able to handle any type of BPF program.
  8324. */
  8325. if (prog->sec_def != &custom_fallback_def)
  8326. prog->sec_def = NULL;
  8327. return 0;
  8328. }
  8329. __alias(bpf_program__expected_attach_type)
  8330. enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
  8331. enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
  8332. {
  8333. return prog->expected_attach_type;
  8334. }
  8335. int bpf_program__set_expected_attach_type(struct bpf_program *prog,
  8336. enum bpf_attach_type type)
  8337. {
  8338. if (prog->obj->state >= OBJ_LOADED)
  8339. return libbpf_err(-EBUSY);
  8340. prog->expected_attach_type = type;
  8341. return 0;
  8342. }
  8343. __u32 bpf_program__flags(const struct bpf_program *prog)
  8344. {
  8345. return prog->prog_flags;
  8346. }
  8347. int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
  8348. {
  8349. if (prog->obj->state >= OBJ_LOADED)
  8350. return libbpf_err(-EBUSY);
  8351. prog->prog_flags = flags;
  8352. return 0;
  8353. }
  8354. __u32 bpf_program__log_level(const struct bpf_program *prog)
  8355. {
  8356. return prog->log_level;
  8357. }
  8358. int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
  8359. {
  8360. if (prog->obj->state >= OBJ_LOADED)
  8361. return libbpf_err(-EBUSY);
  8362. prog->log_level = log_level;
  8363. return 0;
  8364. }
  8365. const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
  8366. {
  8367. *log_size = prog->log_size;
  8368. return prog->log_buf;
  8369. }
  8370. int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
  8371. {
  8372. if (log_size && !log_buf)
  8373. return libbpf_err(-EINVAL);
  8374. if (prog->log_size > UINT_MAX)
  8375. return libbpf_err(-EINVAL);
  8376. if (prog->obj->state >= OBJ_LOADED)
  8377. return libbpf_err(-EBUSY);
  8378. prog->log_buf = log_buf;
  8379. prog->log_size = log_size;
  8380. return 0;
  8381. }
  8382. struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
  8383. {
  8384. if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
  8385. return libbpf_err_ptr(-EOPNOTSUPP);
  8386. return prog->func_info;
  8387. }
  8388. __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
  8389. {
  8390. return prog->func_info_cnt;
  8391. }
  8392. struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
  8393. {
  8394. if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
  8395. return libbpf_err_ptr(-EOPNOTSUPP);
  8396. return prog->line_info;
  8397. }
  8398. __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
  8399. {
  8400. return prog->line_info_cnt;
  8401. }
  8402. #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
  8403. .sec = (char *)sec_pfx, \
  8404. .prog_type = BPF_PROG_TYPE_##ptype, \
  8405. .expected_attach_type = atype, \
  8406. .cookie = (long)(flags), \
  8407. .prog_prepare_load_fn = libbpf_prepare_prog_load, \
  8408. __VA_ARGS__ \
  8409. }
  8410. static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8411. static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8412. static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8413. static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8414. static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8415. static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8416. static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8417. static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8418. static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8419. static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8420. static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8421. static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
  8422. static const struct bpf_sec_def section_defs[] = {
  8423. SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE),
  8424. SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
  8425. SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
  8426. SEC_DEF("kprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
  8427. SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
  8428. SEC_DEF("uprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
  8429. SEC_DEF("kretprobe+", KPROBE, 0, SEC_NONE, attach_kprobe),
  8430. SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
  8431. SEC_DEF("uretprobe.s+", KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
  8432. SEC_DEF("kprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
  8433. SEC_DEF("kretprobe.multi+", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
  8434. SEC_DEF("kprobe.session+", KPROBE, BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
  8435. SEC_DEF("uprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
  8436. SEC_DEF("uretprobe.multi+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
  8437. SEC_DEF("uprobe.session+", KPROBE, BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
  8438. SEC_DEF("uprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
  8439. SEC_DEF("uretprobe.multi.s+", KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
  8440. SEC_DEF("uprobe.session.s+", KPROBE, BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
  8441. SEC_DEF("ksyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
  8442. SEC_DEF("kretsyscall+", KPROBE, 0, SEC_NONE, attach_ksyscall),
  8443. SEC_DEF("usdt+", KPROBE, 0, SEC_USDT, attach_usdt),
  8444. SEC_DEF("usdt.s+", KPROBE, 0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
  8445. SEC_DEF("tc/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
  8446. SEC_DEF("tc/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE), /* alias for tcx */
  8447. SEC_DEF("tcx/ingress", SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
  8448. SEC_DEF("tcx/egress", SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
  8449. SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
  8450. SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
  8451. SEC_DEF("action", SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
  8452. SEC_DEF("netkit/primary", SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
  8453. SEC_DEF("netkit/peer", SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
  8454. SEC_DEF("tracepoint+", TRACEPOINT, 0, SEC_NONE, attach_tp),
  8455. SEC_DEF("tp+", TRACEPOINT, 0, SEC_NONE, attach_tp),
  8456. SEC_DEF("raw_tracepoint+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
  8457. SEC_DEF("raw_tp+", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
  8458. SEC_DEF("raw_tracepoint.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
  8459. SEC_DEF("raw_tp.w+", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
  8460. SEC_DEF("tp_btf+", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
  8461. SEC_DEF("fentry+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
  8462. SEC_DEF("fmod_ret+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
  8463. SEC_DEF("fexit+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
  8464. SEC_DEF("fentry.s+", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8465. SEC_DEF("fmod_ret.s+", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8466. SEC_DEF("fexit.s+", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8467. SEC_DEF("fsession+", TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
  8468. SEC_DEF("fsession.s+", TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
  8469. SEC_DEF("freplace+", EXT, 0, SEC_ATTACH_BTF, attach_trace),
  8470. SEC_DEF("lsm+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
  8471. SEC_DEF("lsm.s+", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
  8472. SEC_DEF("lsm_cgroup+", LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
  8473. SEC_DEF("iter+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
  8474. SEC_DEF("iter.s+", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
  8475. SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
  8476. SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
  8477. SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
  8478. SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
  8479. SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
  8480. SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
  8481. SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
  8482. SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE),
  8483. SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE),
  8484. SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE),
  8485. SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE),
  8486. SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE),
  8487. SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
  8488. SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
  8489. SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
  8490. SEC_DEF("sk_skb/verdict", SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
  8491. SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE),
  8492. SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
  8493. SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
  8494. SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
  8495. SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
  8496. SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
  8497. SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE),
  8498. SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
  8499. SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
  8500. SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
  8501. SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
  8502. SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
  8503. SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
  8504. SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
  8505. SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
  8506. SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
  8507. SEC_DEF("cgroup/connect_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
  8508. SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
  8509. SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
  8510. SEC_DEF("cgroup/sendmsg_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
  8511. SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
  8512. SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
  8513. SEC_DEF("cgroup/recvmsg_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
  8514. SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
  8515. SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
  8516. SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
  8517. SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
  8518. SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
  8519. SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
  8520. SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
  8521. SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
  8522. SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
  8523. SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
  8524. SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
  8525. SEC_DEF("struct_ops.s+", STRUCT_OPS, 0, SEC_SLEEPABLE),
  8526. SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
  8527. SEC_DEF("netfilter", NETFILTER, BPF_NETFILTER, SEC_NONE),
  8528. };
  8529. int libbpf_register_prog_handler(const char *sec,
  8530. enum bpf_prog_type prog_type,
  8531. enum bpf_attach_type exp_attach_type,
  8532. const struct libbpf_prog_handler_opts *opts)
  8533. {
  8534. struct bpf_sec_def *sec_def;
  8535. if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
  8536. return libbpf_err(-EINVAL);
  8537. if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
  8538. return libbpf_err(-E2BIG);
  8539. if (sec) {
  8540. sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
  8541. sizeof(*sec_def));
  8542. if (!sec_def)
  8543. return libbpf_err(-ENOMEM);
  8544. custom_sec_defs = sec_def;
  8545. sec_def = &custom_sec_defs[custom_sec_def_cnt];
  8546. } else {
  8547. if (has_custom_fallback_def)
  8548. return libbpf_err(-EBUSY);
  8549. sec_def = &custom_fallback_def;
  8550. }
  8551. sec_def->sec = sec ? strdup(sec) : NULL;
  8552. if (sec && !sec_def->sec)
  8553. return libbpf_err(-ENOMEM);
  8554. sec_def->prog_type = prog_type;
  8555. sec_def->expected_attach_type = exp_attach_type;
  8556. sec_def->cookie = OPTS_GET(opts, cookie, 0);
  8557. sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
  8558. sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
  8559. sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
  8560. sec_def->handler_id = ++last_custom_sec_def_handler_id;
  8561. if (sec)
  8562. custom_sec_def_cnt++;
  8563. else
  8564. has_custom_fallback_def = true;
  8565. return sec_def->handler_id;
  8566. }
  8567. int libbpf_unregister_prog_handler(int handler_id)
  8568. {
  8569. struct bpf_sec_def *sec_defs;
  8570. int i;
  8571. if (handler_id <= 0)
  8572. return libbpf_err(-EINVAL);
  8573. if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
  8574. memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
  8575. has_custom_fallback_def = false;
  8576. return 0;
  8577. }
  8578. for (i = 0; i < custom_sec_def_cnt; i++) {
  8579. if (custom_sec_defs[i].handler_id == handler_id)
  8580. break;
  8581. }
  8582. if (i == custom_sec_def_cnt)
  8583. return libbpf_err(-ENOENT);
  8584. free(custom_sec_defs[i].sec);
  8585. for (i = i + 1; i < custom_sec_def_cnt; i++)
  8586. custom_sec_defs[i - 1] = custom_sec_defs[i];
  8587. custom_sec_def_cnt--;
  8588. /* try to shrink the array, but it's ok if we couldn't */
  8589. sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
  8590. /* if new count is zero, reallocarray can return a valid NULL result;
  8591. * in this case the previous pointer will be freed, so we *have to*
  8592. * reassign old pointer to the new value (even if it's NULL)
  8593. */
  8594. if (sec_defs || custom_sec_def_cnt == 0)
  8595. custom_sec_defs = sec_defs;
  8596. return 0;
  8597. }
  8598. static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
  8599. {
  8600. size_t len = strlen(sec_def->sec);
  8601. /* "type/" always has to have proper SEC("type/extras") form */
  8602. if (sec_def->sec[len - 1] == '/') {
  8603. if (str_has_pfx(sec_name, sec_def->sec))
  8604. return true;
  8605. return false;
  8606. }
  8607. /* "type+" means it can be either exact SEC("type") or
  8608. * well-formed SEC("type/extras") with proper '/' separator
  8609. */
  8610. if (sec_def->sec[len - 1] == '+') {
  8611. len--;
  8612. /* not even a prefix */
  8613. if (strncmp(sec_name, sec_def->sec, len) != 0)
  8614. return false;
  8615. /* exact match or has '/' separator */
  8616. if (sec_name[len] == '\0' || sec_name[len] == '/')
  8617. return true;
  8618. return false;
  8619. }
  8620. return strcmp(sec_name, sec_def->sec) == 0;
  8621. }
  8622. static const struct bpf_sec_def *find_sec_def(const char *sec_name)
  8623. {
  8624. const struct bpf_sec_def *sec_def;
  8625. int i, n;
  8626. n = custom_sec_def_cnt;
  8627. for (i = 0; i < n; i++) {
  8628. sec_def = &custom_sec_defs[i];
  8629. if (sec_def_matches(sec_def, sec_name))
  8630. return sec_def;
  8631. }
  8632. n = ARRAY_SIZE(section_defs);
  8633. for (i = 0; i < n; i++) {
  8634. sec_def = &section_defs[i];
  8635. if (sec_def_matches(sec_def, sec_name))
  8636. return sec_def;
  8637. }
  8638. if (has_custom_fallback_def)
  8639. return &custom_fallback_def;
  8640. return NULL;
  8641. }
  8642. #define MAX_TYPE_NAME_SIZE 32
  8643. static char *libbpf_get_type_names(bool attach_type)
  8644. {
  8645. int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
  8646. char *buf;
  8647. buf = malloc(len);
  8648. if (!buf)
  8649. return NULL;
  8650. buf[0] = '\0';
  8651. /* Forge string buf with all available names */
  8652. for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
  8653. const struct bpf_sec_def *sec_def = &section_defs[i];
  8654. if (attach_type) {
  8655. if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
  8656. continue;
  8657. if (!(sec_def->cookie & SEC_ATTACHABLE))
  8658. continue;
  8659. }
  8660. if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
  8661. free(buf);
  8662. return NULL;
  8663. }
  8664. strcat(buf, " ");
  8665. strcat(buf, section_defs[i].sec);
  8666. }
  8667. return buf;
  8668. }
  8669. int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
  8670. enum bpf_attach_type *expected_attach_type)
  8671. {
  8672. const struct bpf_sec_def *sec_def;
  8673. char *type_names;
  8674. if (!name)
  8675. return libbpf_err(-EINVAL);
  8676. sec_def = find_sec_def(name);
  8677. if (sec_def) {
  8678. *prog_type = sec_def->prog_type;
  8679. *expected_attach_type = sec_def->expected_attach_type;
  8680. return 0;
  8681. }
  8682. pr_debug("failed to guess program type from ELF section '%s'\n", name);
  8683. type_names = libbpf_get_type_names(false);
  8684. if (type_names != NULL) {
  8685. pr_debug("supported section(type) names are:%s\n", type_names);
  8686. free(type_names);
  8687. }
  8688. return libbpf_err(-ESRCH);
  8689. }
  8690. const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
  8691. {
  8692. if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
  8693. return NULL;
  8694. return attach_type_name[t];
  8695. }
  8696. const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
  8697. {
  8698. if (t < 0 || t >= ARRAY_SIZE(link_type_name))
  8699. return NULL;
  8700. return link_type_name[t];
  8701. }
  8702. const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
  8703. {
  8704. if (t < 0 || t >= ARRAY_SIZE(map_type_name))
  8705. return NULL;
  8706. return map_type_name[t];
  8707. }
  8708. const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
  8709. {
  8710. if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
  8711. return NULL;
  8712. return prog_type_name[t];
  8713. }
  8714. static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
  8715. int sec_idx,
  8716. size_t offset)
  8717. {
  8718. struct bpf_map *map;
  8719. size_t i;
  8720. for (i = 0; i < obj->nr_maps; i++) {
  8721. map = &obj->maps[i];
  8722. if (!bpf_map__is_struct_ops(map))
  8723. continue;
  8724. if (map->sec_idx == sec_idx &&
  8725. map->sec_offset <= offset &&
  8726. offset - map->sec_offset < map->def.value_size)
  8727. return map;
  8728. }
  8729. return NULL;
  8730. }
  8731. /* Collect the reloc from ELF, populate the st_ops->progs[], and update
  8732. * st_ops->data for shadow type.
  8733. */
  8734. static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
  8735. Elf64_Shdr *shdr, Elf_Data *data)
  8736. {
  8737. const struct btf_type *type;
  8738. const struct btf_member *member;
  8739. struct bpf_struct_ops *st_ops;
  8740. struct bpf_program *prog;
  8741. unsigned int shdr_idx;
  8742. const struct btf *btf;
  8743. struct bpf_map *map;
  8744. unsigned int moff, insn_idx;
  8745. const char *name;
  8746. __u32 member_idx;
  8747. Elf64_Sym *sym;
  8748. Elf64_Rel *rel;
  8749. int i, nrels;
  8750. btf = obj->btf;
  8751. nrels = shdr->sh_size / shdr->sh_entsize;
  8752. for (i = 0; i < nrels; i++) {
  8753. rel = elf_rel_by_idx(data, i);
  8754. if (!rel) {
  8755. pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
  8756. return -LIBBPF_ERRNO__FORMAT;
  8757. }
  8758. sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
  8759. if (!sym) {
  8760. pr_warn("struct_ops reloc: symbol %zx not found\n",
  8761. (size_t)ELF64_R_SYM(rel->r_info));
  8762. return -LIBBPF_ERRNO__FORMAT;
  8763. }
  8764. name = elf_sym_str(obj, sym->st_name) ?: "<?>";
  8765. map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
  8766. if (!map) {
  8767. pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
  8768. (size_t)rel->r_offset);
  8769. return -EINVAL;
  8770. }
  8771. moff = rel->r_offset - map->sec_offset;
  8772. shdr_idx = sym->st_shndx;
  8773. st_ops = map->st_ops;
  8774. 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",
  8775. map->name,
  8776. (long long)(rel->r_info >> 32),
  8777. (long long)sym->st_value,
  8778. shdr_idx, (size_t)rel->r_offset,
  8779. map->sec_offset, sym->st_name, name);
  8780. if (shdr_idx >= SHN_LORESERVE) {
  8781. pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
  8782. map->name, (size_t)rel->r_offset, shdr_idx);
  8783. return -LIBBPF_ERRNO__RELOC;
  8784. }
  8785. if (sym->st_value % BPF_INSN_SZ) {
  8786. pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
  8787. map->name, (unsigned long long)sym->st_value);
  8788. return -LIBBPF_ERRNO__FORMAT;
  8789. }
  8790. insn_idx = sym->st_value / BPF_INSN_SZ;
  8791. type = btf__type_by_id(btf, st_ops->type_id);
  8792. member = find_member_by_offset(type, moff * 8);
  8793. if (!member) {
  8794. pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
  8795. map->name, moff);
  8796. return -EINVAL;
  8797. }
  8798. member_idx = member - btf_members(type);
  8799. name = btf__name_by_offset(btf, member->name_off);
  8800. if (!resolve_func_ptr(btf, member->type, NULL)) {
  8801. pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
  8802. map->name, name);
  8803. return -EINVAL;
  8804. }
  8805. prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
  8806. if (!prog) {
  8807. pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
  8808. map->name, shdr_idx, name);
  8809. return -EINVAL;
  8810. }
  8811. /* prevent the use of BPF prog with invalid type */
  8812. if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
  8813. pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
  8814. map->name, prog->name);
  8815. return -EINVAL;
  8816. }
  8817. st_ops->progs[member_idx] = prog;
  8818. /* st_ops->data will be exposed to users, being returned by
  8819. * bpf_map__initial_value() as a pointer to the shadow
  8820. * type. All function pointers in the original struct type
  8821. * should be converted to a pointer to struct bpf_program
  8822. * in the shadow type.
  8823. */
  8824. *((struct bpf_program **)(st_ops->data + moff)) = prog;
  8825. }
  8826. return 0;
  8827. }
  8828. #define BTF_TRACE_PREFIX "btf_trace_"
  8829. #define BTF_LSM_PREFIX "bpf_lsm_"
  8830. #define BTF_ITER_PREFIX "bpf_iter_"
  8831. #define BTF_MAX_NAME_SIZE 128
  8832. void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
  8833. const char **prefix, int *kind)
  8834. {
  8835. switch (attach_type) {
  8836. case BPF_TRACE_RAW_TP:
  8837. *prefix = BTF_TRACE_PREFIX;
  8838. *kind = BTF_KIND_TYPEDEF;
  8839. break;
  8840. case BPF_LSM_MAC:
  8841. case BPF_LSM_CGROUP:
  8842. *prefix = BTF_LSM_PREFIX;
  8843. *kind = BTF_KIND_FUNC;
  8844. break;
  8845. case BPF_TRACE_ITER:
  8846. *prefix = BTF_ITER_PREFIX;
  8847. *kind = BTF_KIND_FUNC;
  8848. break;
  8849. default:
  8850. *prefix = "";
  8851. *kind = BTF_KIND_FUNC;
  8852. }
  8853. }
  8854. static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
  8855. const char *name, __u32 kind)
  8856. {
  8857. char btf_type_name[BTF_MAX_NAME_SIZE];
  8858. int ret;
  8859. ret = snprintf(btf_type_name, sizeof(btf_type_name),
  8860. "%s%s", prefix, name);
  8861. /* snprintf returns the number of characters written excluding the
  8862. * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
  8863. * indicates truncation.
  8864. */
  8865. if (ret < 0 || ret >= sizeof(btf_type_name))
  8866. return -ENAMETOOLONG;
  8867. return btf__find_by_name_kind(btf, btf_type_name, kind);
  8868. }
  8869. static inline int find_attach_btf_id(struct btf *btf, const char *name,
  8870. enum bpf_attach_type attach_type)
  8871. {
  8872. const char *prefix;
  8873. int kind;
  8874. btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
  8875. return find_btf_by_prefix_kind(btf, prefix, name, kind);
  8876. }
  8877. int libbpf_find_vmlinux_btf_id(const char *name,
  8878. enum bpf_attach_type attach_type)
  8879. {
  8880. struct btf *btf;
  8881. int err;
  8882. btf = btf__load_vmlinux_btf();
  8883. err = libbpf_get_error(btf);
  8884. if (err) {
  8885. pr_warn("vmlinux BTF is not found\n");
  8886. return libbpf_err(err);
  8887. }
  8888. err = find_attach_btf_id(btf, name, attach_type);
  8889. if (err <= 0)
  8890. pr_warn("%s is not found in vmlinux BTF\n", name);
  8891. btf__free(btf);
  8892. return libbpf_err(err);
  8893. }
  8894. static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
  8895. {
  8896. struct bpf_prog_info info;
  8897. __u32 info_len = sizeof(info);
  8898. struct btf *btf;
  8899. int err;
  8900. memset(&info, 0, info_len);
  8901. err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
  8902. if (err) {
  8903. pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
  8904. attach_prog_fd, errstr(err));
  8905. return err;
  8906. }
  8907. err = -EINVAL;
  8908. if (!info.btf_id) {
  8909. pr_warn("The target program doesn't have BTF\n");
  8910. goto out;
  8911. }
  8912. btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
  8913. err = libbpf_get_error(btf);
  8914. if (err) {
  8915. pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
  8916. goto out;
  8917. }
  8918. err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
  8919. btf__free(btf);
  8920. if (err <= 0) {
  8921. pr_warn("%s is not found in prog's BTF\n", name);
  8922. goto out;
  8923. }
  8924. out:
  8925. return err;
  8926. }
  8927. static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
  8928. enum bpf_attach_type attach_type,
  8929. int *btf_obj_fd, int *btf_type_id)
  8930. {
  8931. int ret, i, mod_len = 0;
  8932. const char *fn_name, *mod_name = NULL;
  8933. fn_name = strchr(attach_name, ':');
  8934. if (fn_name) {
  8935. mod_name = attach_name;
  8936. mod_len = fn_name - mod_name;
  8937. fn_name++;
  8938. }
  8939. if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
  8940. ret = find_attach_btf_id(obj->btf_vmlinux,
  8941. mod_name ? fn_name : attach_name,
  8942. attach_type);
  8943. if (ret > 0) {
  8944. *btf_obj_fd = 0; /* vmlinux BTF */
  8945. *btf_type_id = ret;
  8946. return 0;
  8947. }
  8948. if (ret != -ENOENT)
  8949. return ret;
  8950. }
  8951. ret = load_module_btfs(obj);
  8952. if (ret)
  8953. return ret;
  8954. for (i = 0; i < obj->btf_module_cnt; i++) {
  8955. const struct module_btf *mod = &obj->btf_modules[i];
  8956. if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
  8957. continue;
  8958. ret = find_attach_btf_id(mod->btf,
  8959. mod_name ? fn_name : attach_name,
  8960. attach_type);
  8961. if (ret > 0) {
  8962. *btf_obj_fd = mod->fd;
  8963. *btf_type_id = ret;
  8964. return 0;
  8965. }
  8966. if (ret == -ENOENT)
  8967. continue;
  8968. return ret;
  8969. }
  8970. return -ESRCH;
  8971. }
  8972. static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
  8973. int *btf_obj_fd, int *btf_type_id)
  8974. {
  8975. enum bpf_attach_type attach_type = prog->expected_attach_type;
  8976. __u32 attach_prog_fd = prog->attach_prog_fd;
  8977. int err = 0;
  8978. /* BPF program's BTF ID */
  8979. if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
  8980. if (!attach_prog_fd) {
  8981. pr_warn("prog '%s': attach program FD is not set\n", prog->name);
  8982. return -EINVAL;
  8983. }
  8984. err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
  8985. if (err < 0) {
  8986. pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
  8987. prog->name, attach_prog_fd, attach_name, errstr(err));
  8988. return err;
  8989. }
  8990. *btf_obj_fd = 0;
  8991. *btf_type_id = err;
  8992. return 0;
  8993. }
  8994. /* kernel/module BTF ID */
  8995. if (prog->obj->gen_loader) {
  8996. bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
  8997. *btf_obj_fd = 0;
  8998. *btf_type_id = 1;
  8999. } else {
  9000. err = find_kernel_btf_id(prog->obj, attach_name,
  9001. attach_type, btf_obj_fd,
  9002. btf_type_id);
  9003. }
  9004. if (err) {
  9005. pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
  9006. prog->name, attach_name, errstr(err));
  9007. return err;
  9008. }
  9009. return 0;
  9010. }
  9011. int libbpf_attach_type_by_name(const char *name,
  9012. enum bpf_attach_type *attach_type)
  9013. {
  9014. char *type_names;
  9015. const struct bpf_sec_def *sec_def;
  9016. if (!name)
  9017. return libbpf_err(-EINVAL);
  9018. sec_def = find_sec_def(name);
  9019. if (!sec_def) {
  9020. pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
  9021. type_names = libbpf_get_type_names(true);
  9022. if (type_names != NULL) {
  9023. pr_debug("attachable section(type) names are:%s\n", type_names);
  9024. free(type_names);
  9025. }
  9026. return libbpf_err(-EINVAL);
  9027. }
  9028. if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
  9029. return libbpf_err(-EINVAL);
  9030. if (!(sec_def->cookie & SEC_ATTACHABLE))
  9031. return libbpf_err(-EINVAL);
  9032. *attach_type = sec_def->expected_attach_type;
  9033. return 0;
  9034. }
  9035. int bpf_map__fd(const struct bpf_map *map)
  9036. {
  9037. if (!map)
  9038. return libbpf_err(-EINVAL);
  9039. if (!map_is_created(map))
  9040. return -1;
  9041. return map->fd;
  9042. }
  9043. static bool map_uses_real_name(const struct bpf_map *map)
  9044. {
  9045. /* Since libbpf started to support custom .data.* and .rodata.* maps,
  9046. * their user-visible name differs from kernel-visible name. Users see
  9047. * such map's corresponding ELF section name as a map name.
  9048. * This check distinguishes .data/.rodata from .data.* and .rodata.*
  9049. * maps to know which name has to be returned to the user.
  9050. */
  9051. if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
  9052. return true;
  9053. if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
  9054. return true;
  9055. return false;
  9056. }
  9057. const char *bpf_map__name(const struct bpf_map *map)
  9058. {
  9059. if (!map)
  9060. return NULL;
  9061. if (map_uses_real_name(map))
  9062. return map->real_name;
  9063. return map->name;
  9064. }
  9065. enum bpf_map_type bpf_map__type(const struct bpf_map *map)
  9066. {
  9067. return map->def.type;
  9068. }
  9069. int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
  9070. {
  9071. if (map_is_created(map))
  9072. return libbpf_err(-EBUSY);
  9073. map->def.type = type;
  9074. return 0;
  9075. }
  9076. __u32 bpf_map__map_flags(const struct bpf_map *map)
  9077. {
  9078. return map->def.map_flags;
  9079. }
  9080. int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
  9081. {
  9082. if (map_is_created(map))
  9083. return libbpf_err(-EBUSY);
  9084. map->def.map_flags = flags;
  9085. return 0;
  9086. }
  9087. __u64 bpf_map__map_extra(const struct bpf_map *map)
  9088. {
  9089. return map->map_extra;
  9090. }
  9091. int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
  9092. {
  9093. if (map_is_created(map))
  9094. return libbpf_err(-EBUSY);
  9095. map->map_extra = map_extra;
  9096. return 0;
  9097. }
  9098. __u32 bpf_map__numa_node(const struct bpf_map *map)
  9099. {
  9100. return map->numa_node;
  9101. }
  9102. int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
  9103. {
  9104. if (map_is_created(map))
  9105. return libbpf_err(-EBUSY);
  9106. map->numa_node = numa_node;
  9107. return 0;
  9108. }
  9109. __u32 bpf_map__key_size(const struct bpf_map *map)
  9110. {
  9111. return map->def.key_size;
  9112. }
  9113. int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
  9114. {
  9115. if (map_is_created(map))
  9116. return libbpf_err(-EBUSY);
  9117. map->def.key_size = size;
  9118. return 0;
  9119. }
  9120. __u32 bpf_map__value_size(const struct bpf_map *map)
  9121. {
  9122. return map->def.value_size;
  9123. }
  9124. static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
  9125. {
  9126. struct btf *btf;
  9127. struct btf_type *datasec_type, *var_type;
  9128. struct btf_var_secinfo *var;
  9129. const struct btf_type *array_type;
  9130. const struct btf_array *array;
  9131. int vlen, element_sz, new_array_id;
  9132. __u32 nr_elements;
  9133. /* check btf existence */
  9134. btf = bpf_object__btf(map->obj);
  9135. if (!btf)
  9136. return -ENOENT;
  9137. /* verify map is datasec */
  9138. datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
  9139. if (!btf_is_datasec(datasec_type)) {
  9140. pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
  9141. bpf_map__name(map));
  9142. return -EINVAL;
  9143. }
  9144. /* verify datasec has at least one var */
  9145. vlen = btf_vlen(datasec_type);
  9146. if (vlen == 0) {
  9147. pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
  9148. bpf_map__name(map));
  9149. return -EINVAL;
  9150. }
  9151. /* verify last var in the datasec is an array */
  9152. var = &btf_var_secinfos(datasec_type)[vlen - 1];
  9153. var_type = btf_type_by_id(btf, var->type);
  9154. array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
  9155. if (!btf_is_array(array_type)) {
  9156. pr_warn("map '%s': cannot be resized, last var must be an array\n",
  9157. bpf_map__name(map));
  9158. return -EINVAL;
  9159. }
  9160. /* verify request size aligns with array */
  9161. array = btf_array(array_type);
  9162. element_sz = btf__resolve_size(btf, array->type);
  9163. if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
  9164. pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
  9165. bpf_map__name(map), element_sz, size);
  9166. return -EINVAL;
  9167. }
  9168. /* create a new array based on the existing array, but with new length */
  9169. nr_elements = (size - var->offset) / element_sz;
  9170. new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
  9171. if (new_array_id < 0)
  9172. return new_array_id;
  9173. /* adding a new btf type invalidates existing pointers to btf objects,
  9174. * so refresh pointers before proceeding
  9175. */
  9176. datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
  9177. var = &btf_var_secinfos(datasec_type)[vlen - 1];
  9178. var_type = btf_type_by_id(btf, var->type);
  9179. /* finally update btf info */
  9180. datasec_type->size = size;
  9181. var->size = size - var->offset;
  9182. var_type->type = new_array_id;
  9183. return 0;
  9184. }
  9185. int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
  9186. {
  9187. if (map_is_created(map))
  9188. return libbpf_err(-EBUSY);
  9189. if (map->mmaped) {
  9190. size_t mmap_old_sz, mmap_new_sz;
  9191. int err;
  9192. if (map->def.type != BPF_MAP_TYPE_ARRAY)
  9193. return libbpf_err(-EOPNOTSUPP);
  9194. mmap_old_sz = bpf_map_mmap_sz(map);
  9195. mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
  9196. err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
  9197. if (err) {
  9198. pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
  9199. bpf_map__name(map), errstr(err));
  9200. return libbpf_err(err);
  9201. }
  9202. err = map_btf_datasec_resize(map, size);
  9203. if (err && err != -ENOENT) {
  9204. pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
  9205. bpf_map__name(map), errstr(err));
  9206. map->btf_value_type_id = 0;
  9207. map->btf_key_type_id = 0;
  9208. }
  9209. }
  9210. map->def.value_size = size;
  9211. return 0;
  9212. }
  9213. __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
  9214. {
  9215. return map ? map->btf_key_type_id : 0;
  9216. }
  9217. __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
  9218. {
  9219. return map ? map->btf_value_type_id : 0;
  9220. }
  9221. int bpf_map__set_initial_value(struct bpf_map *map,
  9222. const void *data, size_t size)
  9223. {
  9224. size_t actual_sz;
  9225. if (map_is_created(map))
  9226. return libbpf_err(-EBUSY);
  9227. if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
  9228. return libbpf_err(-EINVAL);
  9229. if (map->def.type == BPF_MAP_TYPE_ARENA)
  9230. actual_sz = map->obj->arena_data_sz;
  9231. else
  9232. actual_sz = map->def.value_size;
  9233. if (size != actual_sz)
  9234. return libbpf_err(-EINVAL);
  9235. memcpy(map->mmaped, data, size);
  9236. return 0;
  9237. }
  9238. void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
  9239. {
  9240. if (bpf_map__is_struct_ops(map)) {
  9241. if (psize)
  9242. *psize = map->def.value_size;
  9243. return map->st_ops->data;
  9244. }
  9245. if (!map->mmaped)
  9246. return NULL;
  9247. if (map->def.type == BPF_MAP_TYPE_ARENA)
  9248. *psize = map->obj->arena_data_sz;
  9249. else
  9250. *psize = map->def.value_size;
  9251. return map->mmaped;
  9252. }
  9253. bool bpf_map__is_internal(const struct bpf_map *map)
  9254. {
  9255. return map->libbpf_type != LIBBPF_MAP_UNSPEC;
  9256. }
  9257. __u32 bpf_map__ifindex(const struct bpf_map *map)
  9258. {
  9259. return map->map_ifindex;
  9260. }
  9261. int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
  9262. {
  9263. if (map_is_created(map))
  9264. return libbpf_err(-EBUSY);
  9265. map->map_ifindex = ifindex;
  9266. return 0;
  9267. }
  9268. int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
  9269. {
  9270. if (!bpf_map_type__is_map_in_map(map->def.type)) {
  9271. pr_warn("error: unsupported map type\n");
  9272. return libbpf_err(-EINVAL);
  9273. }
  9274. if (map->inner_map_fd != -1) {
  9275. pr_warn("error: inner_map_fd already specified\n");
  9276. return libbpf_err(-EINVAL);
  9277. }
  9278. if (map->inner_map) {
  9279. bpf_map__destroy(map->inner_map);
  9280. zfree(&map->inner_map);
  9281. }
  9282. map->inner_map_fd = fd;
  9283. return 0;
  9284. }
  9285. int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
  9286. {
  9287. if (map_is_created(map)) {
  9288. pr_warn("exclusive programs must be set before map creation\n");
  9289. return libbpf_err(-EINVAL);
  9290. }
  9291. if (map->obj != prog->obj) {
  9292. pr_warn("excl_prog and map must be from the same bpf object\n");
  9293. return libbpf_err(-EINVAL);
  9294. }
  9295. map->excl_prog = prog;
  9296. return 0;
  9297. }
  9298. struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
  9299. {
  9300. return map->excl_prog;
  9301. }
  9302. static struct bpf_map *
  9303. __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
  9304. {
  9305. ssize_t idx;
  9306. struct bpf_map *s, *e;
  9307. if (!obj || !obj->maps)
  9308. return errno = EINVAL, NULL;
  9309. s = obj->maps;
  9310. e = obj->maps + obj->nr_maps;
  9311. if ((m < s) || (m >= e)) {
  9312. pr_warn("error in %s: map handler doesn't belong to object\n",
  9313. __func__);
  9314. return errno = EINVAL, NULL;
  9315. }
  9316. idx = (m - obj->maps) + i;
  9317. if (idx >= obj->nr_maps || idx < 0)
  9318. return NULL;
  9319. return &obj->maps[idx];
  9320. }
  9321. struct bpf_map *
  9322. bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
  9323. {
  9324. if (prev == NULL && obj != NULL)
  9325. return obj->maps;
  9326. return __bpf_map__iter(prev, obj, 1);
  9327. }
  9328. struct bpf_map *
  9329. bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
  9330. {
  9331. if (next == NULL && obj != NULL) {
  9332. if (!obj->nr_maps)
  9333. return NULL;
  9334. return obj->maps + obj->nr_maps - 1;
  9335. }
  9336. return __bpf_map__iter(next, obj, -1);
  9337. }
  9338. struct bpf_map *
  9339. bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
  9340. {
  9341. struct bpf_map *pos;
  9342. bpf_object__for_each_map(pos, obj) {
  9343. /* if it's a special internal map name (which always starts
  9344. * with dot) then check if that special name matches the
  9345. * real map name (ELF section name)
  9346. */
  9347. if (name[0] == '.') {
  9348. if (pos->real_name && strcmp(pos->real_name, name) == 0)
  9349. return pos;
  9350. continue;
  9351. }
  9352. /* otherwise map name has to be an exact match */
  9353. if (map_uses_real_name(pos)) {
  9354. if (strcmp(pos->real_name, name) == 0)
  9355. return pos;
  9356. continue;
  9357. }
  9358. if (strcmp(pos->name, name) == 0)
  9359. return pos;
  9360. }
  9361. return errno = ENOENT, NULL;
  9362. }
  9363. int
  9364. bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
  9365. {
  9366. return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
  9367. }
  9368. static int validate_map_op(const struct bpf_map *map, size_t key_sz,
  9369. size_t value_sz, bool check_value_sz, __u64 flags)
  9370. {
  9371. if (!map_is_created(map)) /* map is not yet created */
  9372. return -ENOENT;
  9373. if (map->def.key_size != key_sz) {
  9374. pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
  9375. map->name, key_sz, map->def.key_size);
  9376. return -EINVAL;
  9377. }
  9378. if (map->fd < 0) {
  9379. pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
  9380. return -EINVAL;
  9381. }
  9382. if (!check_value_sz)
  9383. return 0;
  9384. switch (map->def.type) {
  9385. case BPF_MAP_TYPE_PERCPU_ARRAY:
  9386. case BPF_MAP_TYPE_PERCPU_HASH:
  9387. case BPF_MAP_TYPE_LRU_PERCPU_HASH:
  9388. case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
  9389. int num_cpu = libbpf_num_possible_cpus();
  9390. size_t elem_sz = roundup(map->def.value_size, 8);
  9391. if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
  9392. if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
  9393. pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
  9394. map->name);
  9395. return -EINVAL;
  9396. }
  9397. if (map->def.value_size != value_sz) {
  9398. pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
  9399. map->name, value_sz, map->def.value_size);
  9400. return -EINVAL;
  9401. }
  9402. break;
  9403. }
  9404. if (value_sz != num_cpu * elem_sz) {
  9405. pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
  9406. map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
  9407. return -EINVAL;
  9408. }
  9409. break;
  9410. }
  9411. default:
  9412. if (map->def.value_size != value_sz) {
  9413. pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
  9414. map->name, value_sz, map->def.value_size);
  9415. return -EINVAL;
  9416. }
  9417. break;
  9418. }
  9419. return 0;
  9420. }
  9421. int bpf_map__lookup_elem(const struct bpf_map *map,
  9422. const void *key, size_t key_sz,
  9423. void *value, size_t value_sz, __u64 flags)
  9424. {
  9425. int err;
  9426. err = validate_map_op(map, key_sz, value_sz, true, flags);
  9427. if (err)
  9428. return libbpf_err(err);
  9429. return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
  9430. }
  9431. int bpf_map__update_elem(const struct bpf_map *map,
  9432. const void *key, size_t key_sz,
  9433. const void *value, size_t value_sz, __u64 flags)
  9434. {
  9435. int err;
  9436. err = validate_map_op(map, key_sz, value_sz, true, flags);
  9437. if (err)
  9438. return libbpf_err(err);
  9439. return bpf_map_update_elem(map->fd, key, value, flags);
  9440. }
  9441. int bpf_map__delete_elem(const struct bpf_map *map,
  9442. const void *key, size_t key_sz, __u64 flags)
  9443. {
  9444. int err;
  9445. err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
  9446. if (err)
  9447. return libbpf_err(err);
  9448. return bpf_map_delete_elem_flags(map->fd, key, flags);
  9449. }
  9450. int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
  9451. const void *key, size_t key_sz,
  9452. void *value, size_t value_sz, __u64 flags)
  9453. {
  9454. int err;
  9455. err = validate_map_op(map, key_sz, value_sz, true, flags);
  9456. if (err)
  9457. return libbpf_err(err);
  9458. return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
  9459. }
  9460. int bpf_map__get_next_key(const struct bpf_map *map,
  9461. const void *cur_key, void *next_key, size_t key_sz)
  9462. {
  9463. int err;
  9464. err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
  9465. if (err)
  9466. return libbpf_err(err);
  9467. return bpf_map_get_next_key(map->fd, cur_key, next_key);
  9468. }
  9469. long libbpf_get_error(const void *ptr)
  9470. {
  9471. if (!IS_ERR_OR_NULL(ptr))
  9472. return 0;
  9473. if (IS_ERR(ptr))
  9474. errno = -PTR_ERR(ptr);
  9475. /* If ptr == NULL, then errno should be already set by the failing
  9476. * API, because libbpf never returns NULL on success and it now always
  9477. * sets errno on error. So no extra errno handling for ptr == NULL
  9478. * case.
  9479. */
  9480. return -errno;
  9481. }
  9482. /* Replace link's underlying BPF program with the new one */
  9483. int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
  9484. {
  9485. int ret;
  9486. int prog_fd = bpf_program__fd(prog);
  9487. if (prog_fd < 0) {
  9488. pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
  9489. prog->name);
  9490. return libbpf_err(-EINVAL);
  9491. }
  9492. ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
  9493. return libbpf_err_errno(ret);
  9494. }
  9495. /* Release "ownership" of underlying BPF resource (typically, BPF program
  9496. * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
  9497. * link, when destructed through bpf_link__destroy() call won't attempt to
  9498. * detach/unregisted that BPF resource. This is useful in situations where,
  9499. * say, attached BPF program has to outlive userspace program that attached it
  9500. * in the system. Depending on type of BPF program, though, there might be
  9501. * additional steps (like pinning BPF program in BPF FS) necessary to ensure
  9502. * exit of userspace program doesn't trigger automatic detachment and clean up
  9503. * inside the kernel.
  9504. */
  9505. void bpf_link__disconnect(struct bpf_link *link)
  9506. {
  9507. link->disconnected = true;
  9508. }
  9509. int bpf_link__destroy(struct bpf_link *link)
  9510. {
  9511. int err = 0;
  9512. if (IS_ERR_OR_NULL(link))
  9513. return 0;
  9514. if (!link->disconnected && link->detach)
  9515. err = link->detach(link);
  9516. if (link->pin_path)
  9517. free(link->pin_path);
  9518. if (link->dealloc)
  9519. link->dealloc(link);
  9520. else
  9521. free(link);
  9522. return libbpf_err(err);
  9523. }
  9524. int bpf_link__fd(const struct bpf_link *link)
  9525. {
  9526. return link->fd;
  9527. }
  9528. const char *bpf_link__pin_path(const struct bpf_link *link)
  9529. {
  9530. return link->pin_path;
  9531. }
  9532. static int bpf_link__detach_fd(struct bpf_link *link)
  9533. {
  9534. return libbpf_err_errno(close(link->fd));
  9535. }
  9536. struct bpf_link *bpf_link__open(const char *path)
  9537. {
  9538. struct bpf_link *link;
  9539. int fd;
  9540. fd = bpf_obj_get(path);
  9541. if (fd < 0) {
  9542. fd = -errno;
  9543. pr_warn("failed to open link at %s: %d\n", path, fd);
  9544. return libbpf_err_ptr(fd);
  9545. }
  9546. link = calloc(1, sizeof(*link));
  9547. if (!link) {
  9548. close(fd);
  9549. return libbpf_err_ptr(-ENOMEM);
  9550. }
  9551. link->detach = &bpf_link__detach_fd;
  9552. link->fd = fd;
  9553. link->pin_path = strdup(path);
  9554. if (!link->pin_path) {
  9555. bpf_link__destroy(link);
  9556. return libbpf_err_ptr(-ENOMEM);
  9557. }
  9558. return link;
  9559. }
  9560. int bpf_link__detach(struct bpf_link *link)
  9561. {
  9562. return bpf_link_detach(link->fd) ? -errno : 0;
  9563. }
  9564. int bpf_link__pin(struct bpf_link *link, const char *path)
  9565. {
  9566. int err;
  9567. if (link->pin_path)
  9568. return libbpf_err(-EBUSY);
  9569. err = make_parent_dir(path);
  9570. if (err)
  9571. return libbpf_err(err);
  9572. err = check_path(path);
  9573. if (err)
  9574. return libbpf_err(err);
  9575. link->pin_path = strdup(path);
  9576. if (!link->pin_path)
  9577. return libbpf_err(-ENOMEM);
  9578. if (bpf_obj_pin(link->fd, link->pin_path)) {
  9579. err = -errno;
  9580. zfree(&link->pin_path);
  9581. return libbpf_err(err);
  9582. }
  9583. pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
  9584. return 0;
  9585. }
  9586. int bpf_link__unpin(struct bpf_link *link)
  9587. {
  9588. int err;
  9589. if (!link->pin_path)
  9590. return libbpf_err(-EINVAL);
  9591. err = unlink(link->pin_path);
  9592. if (err != 0)
  9593. return -errno;
  9594. pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
  9595. zfree(&link->pin_path);
  9596. return 0;
  9597. }
  9598. struct bpf_link_perf {
  9599. struct bpf_link link;
  9600. int perf_event_fd;
  9601. /* legacy kprobe support: keep track of probe identifier and type */
  9602. char *legacy_probe_name;
  9603. bool legacy_is_kprobe;
  9604. bool legacy_is_retprobe;
  9605. };
  9606. static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
  9607. static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
  9608. static int bpf_link_perf_detach(struct bpf_link *link)
  9609. {
  9610. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  9611. int err = 0;
  9612. if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
  9613. err = -errno;
  9614. if (perf_link->perf_event_fd != link->fd)
  9615. close(perf_link->perf_event_fd);
  9616. close(link->fd);
  9617. /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
  9618. if (perf_link->legacy_probe_name) {
  9619. if (perf_link->legacy_is_kprobe) {
  9620. err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
  9621. perf_link->legacy_is_retprobe);
  9622. } else {
  9623. err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
  9624. perf_link->legacy_is_retprobe);
  9625. }
  9626. }
  9627. return err;
  9628. }
  9629. static void bpf_link_perf_dealloc(struct bpf_link *link)
  9630. {
  9631. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  9632. free(perf_link->legacy_probe_name);
  9633. free(perf_link);
  9634. }
  9635. struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
  9636. const struct bpf_perf_event_opts *opts)
  9637. {
  9638. struct bpf_link_perf *link;
  9639. int prog_fd, link_fd = -1, err;
  9640. bool force_ioctl_attach;
  9641. if (!OPTS_VALID(opts, bpf_perf_event_opts))
  9642. return libbpf_err_ptr(-EINVAL);
  9643. if (pfd < 0) {
  9644. pr_warn("prog '%s': invalid perf event FD %d\n",
  9645. prog->name, pfd);
  9646. return libbpf_err_ptr(-EINVAL);
  9647. }
  9648. prog_fd = bpf_program__fd(prog);
  9649. if (prog_fd < 0) {
  9650. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  9651. prog->name);
  9652. return libbpf_err_ptr(-EINVAL);
  9653. }
  9654. link = calloc(1, sizeof(*link));
  9655. if (!link)
  9656. return libbpf_err_ptr(-ENOMEM);
  9657. link->link.detach = &bpf_link_perf_detach;
  9658. link->link.dealloc = &bpf_link_perf_dealloc;
  9659. link->perf_event_fd = pfd;
  9660. force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
  9661. if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
  9662. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
  9663. .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
  9664. link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
  9665. if (link_fd < 0) {
  9666. err = -errno;
  9667. pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
  9668. prog->name, pfd, errstr(err));
  9669. goto err_out;
  9670. }
  9671. link->link.fd = link_fd;
  9672. } else {
  9673. if (OPTS_GET(opts, bpf_cookie, 0)) {
  9674. pr_warn("prog '%s': user context value is not supported\n", prog->name);
  9675. err = -EOPNOTSUPP;
  9676. goto err_out;
  9677. }
  9678. if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
  9679. err = -errno;
  9680. pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
  9681. prog->name, pfd, errstr(err));
  9682. if (err == -EPROTO)
  9683. pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
  9684. prog->name, pfd);
  9685. goto err_out;
  9686. }
  9687. link->link.fd = pfd;
  9688. }
  9689. if (!OPTS_GET(opts, dont_enable, false)) {
  9690. if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
  9691. err = -errno;
  9692. pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
  9693. prog->name, pfd, errstr(err));
  9694. goto err_out;
  9695. }
  9696. }
  9697. return &link->link;
  9698. err_out:
  9699. if (link_fd >= 0)
  9700. close(link_fd);
  9701. free(link);
  9702. return libbpf_err_ptr(err);
  9703. }
  9704. struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
  9705. {
  9706. return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
  9707. }
  9708. /*
  9709. * this function is expected to parse integer in the range of [0, 2^31-1] from
  9710. * given file using scanf format string fmt. If actual parsed value is
  9711. * negative, the result might be indistinguishable from error
  9712. */
  9713. static int parse_uint_from_file(const char *file, const char *fmt)
  9714. {
  9715. int err, ret;
  9716. FILE *f;
  9717. f = fopen(file, "re");
  9718. if (!f) {
  9719. err = -errno;
  9720. pr_debug("failed to open '%s': %s\n", file, errstr(err));
  9721. return err;
  9722. }
  9723. err = fscanf(f, fmt, &ret);
  9724. if (err != 1) {
  9725. err = err == EOF ? -EIO : -errno;
  9726. pr_debug("failed to parse '%s': %s\n", file, errstr(err));
  9727. fclose(f);
  9728. return err;
  9729. }
  9730. fclose(f);
  9731. return ret;
  9732. }
  9733. static int determine_kprobe_perf_type(void)
  9734. {
  9735. const char *file = "/sys/bus/event_source/devices/kprobe/type";
  9736. return parse_uint_from_file(file, "%d\n");
  9737. }
  9738. static int determine_uprobe_perf_type(void)
  9739. {
  9740. const char *file = "/sys/bus/event_source/devices/uprobe/type";
  9741. return parse_uint_from_file(file, "%d\n");
  9742. }
  9743. static int determine_kprobe_retprobe_bit(void)
  9744. {
  9745. const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
  9746. return parse_uint_from_file(file, "config:%d\n");
  9747. }
  9748. static int determine_uprobe_retprobe_bit(void)
  9749. {
  9750. const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
  9751. return parse_uint_from_file(file, "config:%d\n");
  9752. }
  9753. #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
  9754. #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
  9755. static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
  9756. uint64_t offset, int pid, size_t ref_ctr_off)
  9757. {
  9758. const size_t attr_sz = sizeof(struct perf_event_attr);
  9759. struct perf_event_attr attr;
  9760. int type, pfd;
  9761. if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
  9762. return -EINVAL;
  9763. memset(&attr, 0, attr_sz);
  9764. type = uprobe ? determine_uprobe_perf_type()
  9765. : determine_kprobe_perf_type();
  9766. if (type < 0) {
  9767. pr_warn("failed to determine %s perf type: %s\n",
  9768. uprobe ? "uprobe" : "kprobe",
  9769. errstr(type));
  9770. return type;
  9771. }
  9772. if (retprobe) {
  9773. int bit = uprobe ? determine_uprobe_retprobe_bit()
  9774. : determine_kprobe_retprobe_bit();
  9775. if (bit < 0) {
  9776. pr_warn("failed to determine %s retprobe bit: %s\n",
  9777. uprobe ? "uprobe" : "kprobe",
  9778. errstr(bit));
  9779. return bit;
  9780. }
  9781. attr.config |= 1 << bit;
  9782. }
  9783. attr.size = attr_sz;
  9784. attr.type = type;
  9785. attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
  9786. attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
  9787. attr.config2 = offset; /* kprobe_addr or probe_offset */
  9788. /* pid filter is meaningful only for uprobes */
  9789. pfd = syscall(__NR_perf_event_open, &attr,
  9790. pid < 0 ? -1 : pid /* pid */,
  9791. pid == -1 ? 0 : -1 /* cpu */,
  9792. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  9793. return pfd >= 0 ? pfd : -errno;
  9794. }
  9795. static int append_to_file(const char *file, const char *fmt, ...)
  9796. {
  9797. int fd, n, err = 0;
  9798. va_list ap;
  9799. char buf[1024];
  9800. va_start(ap, fmt);
  9801. n = vsnprintf(buf, sizeof(buf), fmt, ap);
  9802. va_end(ap);
  9803. if (n < 0 || n >= sizeof(buf))
  9804. return -EINVAL;
  9805. fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
  9806. if (fd < 0)
  9807. return -errno;
  9808. if (write(fd, buf, n) < 0)
  9809. err = -errno;
  9810. close(fd);
  9811. return err;
  9812. }
  9813. #define DEBUGFS "/sys/kernel/debug/tracing"
  9814. #define TRACEFS "/sys/kernel/tracing"
  9815. static bool use_debugfs(void)
  9816. {
  9817. static int has_debugfs = -1;
  9818. if (has_debugfs < 0)
  9819. has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
  9820. return has_debugfs == 1;
  9821. }
  9822. static const char *tracefs_path(void)
  9823. {
  9824. return use_debugfs() ? DEBUGFS : TRACEFS;
  9825. }
  9826. static const char *tracefs_kprobe_events(void)
  9827. {
  9828. return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
  9829. }
  9830. static const char *tracefs_uprobe_events(void)
  9831. {
  9832. return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
  9833. }
  9834. static const char *tracefs_available_filter_functions(void)
  9835. {
  9836. return use_debugfs() ? DEBUGFS"/available_filter_functions"
  9837. : TRACEFS"/available_filter_functions";
  9838. }
  9839. static const char *tracefs_available_filter_functions_addrs(void)
  9840. {
  9841. return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
  9842. : TRACEFS"/available_filter_functions_addrs";
  9843. }
  9844. static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
  9845. const char *name, size_t offset)
  9846. {
  9847. static int index = 0;
  9848. int i;
  9849. snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
  9850. __sync_fetch_and_add(&index, 1), name, offset);
  9851. /* sanitize name in the probe name */
  9852. for (i = 0; buf[i]; i++) {
  9853. if (!isalnum(buf[i]))
  9854. buf[i] = '_';
  9855. }
  9856. }
  9857. static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
  9858. const char *kfunc_name, size_t offset)
  9859. {
  9860. return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
  9861. retprobe ? 'r' : 'p',
  9862. retprobe ? "kretprobes" : "kprobes",
  9863. probe_name, kfunc_name, offset);
  9864. }
  9865. static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
  9866. {
  9867. return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
  9868. retprobe ? "kretprobes" : "kprobes", probe_name);
  9869. }
  9870. static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
  9871. {
  9872. char file[256];
  9873. snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  9874. tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
  9875. return parse_uint_from_file(file, "%d\n");
  9876. }
  9877. static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
  9878. const char *kfunc_name, size_t offset, int pid)
  9879. {
  9880. const size_t attr_sz = sizeof(struct perf_event_attr);
  9881. struct perf_event_attr attr;
  9882. int type, pfd, err;
  9883. err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
  9884. if (err < 0) {
  9885. pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
  9886. kfunc_name, offset,
  9887. errstr(err));
  9888. return err;
  9889. }
  9890. type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
  9891. if (type < 0) {
  9892. err = type;
  9893. pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
  9894. kfunc_name, offset,
  9895. errstr(err));
  9896. goto err_clean_legacy;
  9897. }
  9898. memset(&attr, 0, attr_sz);
  9899. attr.size = attr_sz;
  9900. attr.config = type;
  9901. attr.type = PERF_TYPE_TRACEPOINT;
  9902. pfd = syscall(__NR_perf_event_open, &attr,
  9903. pid < 0 ? -1 : pid, /* pid */
  9904. pid == -1 ? 0 : -1, /* cpu */
  9905. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  9906. if (pfd < 0) {
  9907. err = -errno;
  9908. pr_warn("legacy kprobe perf_event_open() failed: %s\n",
  9909. errstr(err));
  9910. goto err_clean_legacy;
  9911. }
  9912. return pfd;
  9913. err_clean_legacy:
  9914. /* Clear the newly added legacy kprobe_event */
  9915. remove_kprobe_event_legacy(probe_name, retprobe);
  9916. return err;
  9917. }
  9918. static const char *arch_specific_syscall_pfx(void)
  9919. {
  9920. #if defined(__x86_64__)
  9921. return "x64";
  9922. #elif defined(__i386__)
  9923. return "ia32";
  9924. #elif defined(__s390x__)
  9925. return "s390x";
  9926. #elif defined(__arm__)
  9927. return "arm";
  9928. #elif defined(__aarch64__)
  9929. return "arm64";
  9930. #elif defined(__mips__)
  9931. return "mips";
  9932. #elif defined(__riscv)
  9933. return "riscv";
  9934. #elif defined(__powerpc__)
  9935. return "powerpc";
  9936. #elif defined(__powerpc64__)
  9937. return "powerpc64";
  9938. #else
  9939. return NULL;
  9940. #endif
  9941. }
  9942. int probe_kern_syscall_wrapper(int token_fd)
  9943. {
  9944. char syscall_name[64];
  9945. const char *ksys_pfx;
  9946. ksys_pfx = arch_specific_syscall_pfx();
  9947. if (!ksys_pfx)
  9948. return 0;
  9949. snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
  9950. if (determine_kprobe_perf_type() >= 0) {
  9951. int pfd;
  9952. pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
  9953. if (pfd >= 0)
  9954. close(pfd);
  9955. return pfd >= 0 ? 1 : 0;
  9956. } else { /* legacy mode */
  9957. char probe_name[MAX_EVENT_NAME_LEN];
  9958. gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
  9959. if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
  9960. return 0;
  9961. (void)remove_kprobe_event_legacy(probe_name, false);
  9962. return 1;
  9963. }
  9964. }
  9965. struct bpf_link *
  9966. bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
  9967. const char *func_name,
  9968. const struct bpf_kprobe_opts *opts)
  9969. {
  9970. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  9971. enum probe_attach_mode attach_mode;
  9972. char *legacy_probe = NULL;
  9973. struct bpf_link *link;
  9974. size_t offset;
  9975. bool retprobe, legacy;
  9976. int pfd, err;
  9977. if (!OPTS_VALID(opts, bpf_kprobe_opts))
  9978. return libbpf_err_ptr(-EINVAL);
  9979. attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
  9980. retprobe = OPTS_GET(opts, retprobe, false);
  9981. offset = OPTS_GET(opts, offset, 0);
  9982. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  9983. legacy = determine_kprobe_perf_type() < 0;
  9984. switch (attach_mode) {
  9985. case PROBE_ATTACH_MODE_LEGACY:
  9986. legacy = true;
  9987. pe_opts.force_ioctl_attach = true;
  9988. break;
  9989. case PROBE_ATTACH_MODE_PERF:
  9990. if (legacy)
  9991. return libbpf_err_ptr(-ENOTSUP);
  9992. pe_opts.force_ioctl_attach = true;
  9993. break;
  9994. case PROBE_ATTACH_MODE_LINK:
  9995. if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
  9996. return libbpf_err_ptr(-ENOTSUP);
  9997. break;
  9998. case PROBE_ATTACH_MODE_DEFAULT:
  9999. break;
  10000. default:
  10001. return libbpf_err_ptr(-EINVAL);
  10002. }
  10003. if (!legacy) {
  10004. pfd = perf_event_open_probe(false /* uprobe */, retprobe,
  10005. func_name, offset,
  10006. -1 /* pid */, 0 /* ref_ctr_off */);
  10007. } else {
  10008. char probe_name[MAX_EVENT_NAME_LEN];
  10009. gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
  10010. func_name, offset);
  10011. legacy_probe = strdup(probe_name);
  10012. if (!legacy_probe)
  10013. return libbpf_err_ptr(-ENOMEM);
  10014. pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
  10015. offset, -1 /* pid */);
  10016. }
  10017. if (pfd < 0) {
  10018. err = -errno;
  10019. pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
  10020. prog->name, retprobe ? "kretprobe" : "kprobe",
  10021. func_name, offset,
  10022. errstr(err));
  10023. goto err_out;
  10024. }
  10025. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  10026. err = libbpf_get_error(link);
  10027. if (err) {
  10028. close(pfd);
  10029. pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
  10030. prog->name, retprobe ? "kretprobe" : "kprobe",
  10031. func_name, offset,
  10032. errstr(err));
  10033. goto err_clean_legacy;
  10034. }
  10035. if (legacy) {
  10036. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  10037. perf_link->legacy_probe_name = legacy_probe;
  10038. perf_link->legacy_is_kprobe = true;
  10039. perf_link->legacy_is_retprobe = retprobe;
  10040. }
  10041. return link;
  10042. err_clean_legacy:
  10043. if (legacy)
  10044. remove_kprobe_event_legacy(legacy_probe, retprobe);
  10045. err_out:
  10046. free(legacy_probe);
  10047. return libbpf_err_ptr(err);
  10048. }
  10049. struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
  10050. bool retprobe,
  10051. const char *func_name)
  10052. {
  10053. DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
  10054. .retprobe = retprobe,
  10055. );
  10056. return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
  10057. }
  10058. struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
  10059. const char *syscall_name,
  10060. const struct bpf_ksyscall_opts *opts)
  10061. {
  10062. LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
  10063. char func_name[128];
  10064. if (!OPTS_VALID(opts, bpf_ksyscall_opts))
  10065. return libbpf_err_ptr(-EINVAL);
  10066. if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
  10067. /* arch_specific_syscall_pfx() should never return NULL here
  10068. * because it is guarded by kernel_supports(). However, since
  10069. * compiler does not know that we have an explicit conditional
  10070. * as well.
  10071. */
  10072. snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
  10073. arch_specific_syscall_pfx() ? : "", syscall_name);
  10074. } else {
  10075. snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
  10076. }
  10077. kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
  10078. kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  10079. return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
  10080. }
  10081. /* Adapted from perf/util/string.c */
  10082. bool glob_match(const char *str, const char *pat)
  10083. {
  10084. while (*str && *pat && *pat != '*') {
  10085. if (*pat == '?') { /* Matches any single character */
  10086. str++;
  10087. pat++;
  10088. continue;
  10089. }
  10090. if (*str != *pat)
  10091. return false;
  10092. str++;
  10093. pat++;
  10094. }
  10095. /* Check wild card */
  10096. if (*pat == '*') {
  10097. while (*pat == '*')
  10098. pat++;
  10099. if (!*pat) /* Tail wild card matches all */
  10100. return true;
  10101. while (*str)
  10102. if (glob_match(str++, pat))
  10103. return true;
  10104. }
  10105. return !*str && !*pat;
  10106. }
  10107. struct kprobe_multi_resolve {
  10108. const char *pattern;
  10109. unsigned long *addrs;
  10110. size_t cap;
  10111. size_t cnt;
  10112. };
  10113. struct avail_kallsyms_data {
  10114. char **syms;
  10115. size_t cnt;
  10116. struct kprobe_multi_resolve *res;
  10117. };
  10118. static int avail_func_cmp(const void *a, const void *b)
  10119. {
  10120. return strcmp(*(const char **)a, *(const char **)b);
  10121. }
  10122. static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
  10123. const char *sym_name, void *ctx)
  10124. {
  10125. struct avail_kallsyms_data *data = ctx;
  10126. struct kprobe_multi_resolve *res = data->res;
  10127. int err;
  10128. if (!glob_match(sym_name, res->pattern))
  10129. return 0;
  10130. if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
  10131. /* Some versions of kernel strip out .llvm.<hash> suffix from
  10132. * function names reported in available_filter_functions, but
  10133. * don't do so for kallsyms. While this is clearly a kernel
  10134. * bug (fixed by [0]) we try to accommodate that in libbpf to
  10135. * make multi-kprobe usability a bit better: if no match is
  10136. * found, we will strip .llvm. suffix and try one more time.
  10137. *
  10138. * [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
  10139. */
  10140. char sym_trim[256], *psym_trim = sym_trim;
  10141. const char *sym_sfx;
  10142. if (!(sym_sfx = strstr(sym_name, ".llvm.")))
  10143. return 0;
  10144. /* psym_trim vs sym_trim dance is done to avoid pointer vs array
  10145. * coercion differences and get proper `const char **` pointer
  10146. * which avail_func_cmp() expects
  10147. */
  10148. snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
  10149. if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
  10150. return 0;
  10151. }
  10152. err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
  10153. if (err)
  10154. return err;
  10155. res->addrs[res->cnt++] = (unsigned long)sym_addr;
  10156. return 0;
  10157. }
  10158. static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
  10159. {
  10160. const char *available_functions_file = tracefs_available_filter_functions();
  10161. struct avail_kallsyms_data data;
  10162. char sym_name[500];
  10163. FILE *f;
  10164. int err = 0, ret, i;
  10165. char **syms = NULL;
  10166. size_t cap = 0, cnt = 0;
  10167. f = fopen(available_functions_file, "re");
  10168. if (!f) {
  10169. err = -errno;
  10170. pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
  10171. return err;
  10172. }
  10173. while (true) {
  10174. char *name;
  10175. ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
  10176. if (ret == EOF && feof(f))
  10177. break;
  10178. if (ret != 1) {
  10179. pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
  10180. err = -EINVAL;
  10181. goto cleanup;
  10182. }
  10183. if (!glob_match(sym_name, res->pattern))
  10184. continue;
  10185. err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
  10186. if (err)
  10187. goto cleanup;
  10188. name = strdup(sym_name);
  10189. if (!name) {
  10190. err = -errno;
  10191. goto cleanup;
  10192. }
  10193. syms[cnt++] = name;
  10194. }
  10195. /* no entries found, bail out */
  10196. if (cnt == 0) {
  10197. err = -ENOENT;
  10198. goto cleanup;
  10199. }
  10200. /* sort available functions */
  10201. qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
  10202. data.syms = syms;
  10203. data.res = res;
  10204. data.cnt = cnt;
  10205. libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
  10206. if (res->cnt == 0)
  10207. err = -ENOENT;
  10208. cleanup:
  10209. for (i = 0; i < cnt; i++)
  10210. free((char *)syms[i]);
  10211. free(syms);
  10212. fclose(f);
  10213. return err;
  10214. }
  10215. static bool has_available_filter_functions_addrs(void)
  10216. {
  10217. return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
  10218. }
  10219. static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
  10220. {
  10221. const char *available_path = tracefs_available_filter_functions_addrs();
  10222. char sym_name[500];
  10223. FILE *f;
  10224. int ret, err = 0;
  10225. unsigned long long sym_addr;
  10226. f = fopen(available_path, "re");
  10227. if (!f) {
  10228. err = -errno;
  10229. pr_warn("failed to open %s: %s\n", available_path, errstr(err));
  10230. return err;
  10231. }
  10232. while (true) {
  10233. ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
  10234. if (ret == EOF && feof(f))
  10235. break;
  10236. if (ret != 2) {
  10237. pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
  10238. ret);
  10239. err = -EINVAL;
  10240. goto cleanup;
  10241. }
  10242. if (!glob_match(sym_name, res->pattern))
  10243. continue;
  10244. err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
  10245. sizeof(*res->addrs), res->cnt + 1);
  10246. if (err)
  10247. goto cleanup;
  10248. res->addrs[res->cnt++] = (unsigned long)sym_addr;
  10249. }
  10250. if (res->cnt == 0)
  10251. err = -ENOENT;
  10252. cleanup:
  10253. fclose(f);
  10254. return err;
  10255. }
  10256. struct bpf_link *
  10257. bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
  10258. const char *pattern,
  10259. const struct bpf_kprobe_multi_opts *opts)
  10260. {
  10261. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  10262. struct kprobe_multi_resolve res = {
  10263. .pattern = pattern,
  10264. };
  10265. enum bpf_attach_type attach_type;
  10266. struct bpf_link *link = NULL;
  10267. const unsigned long *addrs;
  10268. int err, link_fd, prog_fd;
  10269. bool retprobe, session, unique_match;
  10270. const __u64 *cookies;
  10271. const char **syms;
  10272. size_t cnt;
  10273. if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
  10274. return libbpf_err_ptr(-EINVAL);
  10275. prog_fd = bpf_program__fd(prog);
  10276. if (prog_fd < 0) {
  10277. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  10278. prog->name);
  10279. return libbpf_err_ptr(-EINVAL);
  10280. }
  10281. syms = OPTS_GET(opts, syms, false);
  10282. addrs = OPTS_GET(opts, addrs, false);
  10283. cnt = OPTS_GET(opts, cnt, false);
  10284. cookies = OPTS_GET(opts, cookies, false);
  10285. unique_match = OPTS_GET(opts, unique_match, false);
  10286. if (!pattern && !addrs && !syms)
  10287. return libbpf_err_ptr(-EINVAL);
  10288. if (pattern && (addrs || syms || cookies || cnt))
  10289. return libbpf_err_ptr(-EINVAL);
  10290. if (!pattern && !cnt)
  10291. return libbpf_err_ptr(-EINVAL);
  10292. if (!pattern && unique_match)
  10293. return libbpf_err_ptr(-EINVAL);
  10294. if (addrs && syms)
  10295. return libbpf_err_ptr(-EINVAL);
  10296. if (pattern) {
  10297. if (has_available_filter_functions_addrs())
  10298. err = libbpf_available_kprobes_parse(&res);
  10299. else
  10300. err = libbpf_available_kallsyms_parse(&res);
  10301. if (err)
  10302. goto error;
  10303. if (unique_match && res.cnt != 1) {
  10304. pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
  10305. prog->name, pattern, res.cnt);
  10306. err = -EINVAL;
  10307. goto error;
  10308. }
  10309. addrs = res.addrs;
  10310. cnt = res.cnt;
  10311. }
  10312. retprobe = OPTS_GET(opts, retprobe, false);
  10313. session = OPTS_GET(opts, session, false);
  10314. if (retprobe && session)
  10315. return libbpf_err_ptr(-EINVAL);
  10316. attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
  10317. lopts.kprobe_multi.syms = syms;
  10318. lopts.kprobe_multi.addrs = addrs;
  10319. lopts.kprobe_multi.cookies = cookies;
  10320. lopts.kprobe_multi.cnt = cnt;
  10321. lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
  10322. link = calloc(1, sizeof(*link));
  10323. if (!link) {
  10324. err = -ENOMEM;
  10325. goto error;
  10326. }
  10327. link->detach = &bpf_link__detach_fd;
  10328. link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
  10329. if (link_fd < 0) {
  10330. err = -errno;
  10331. pr_warn("prog '%s': failed to attach: %s\n",
  10332. prog->name, errstr(err));
  10333. goto error;
  10334. }
  10335. link->fd = link_fd;
  10336. free(res.addrs);
  10337. return link;
  10338. error:
  10339. free(link);
  10340. free(res.addrs);
  10341. return libbpf_err_ptr(err);
  10342. }
  10343. static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10344. {
  10345. DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
  10346. unsigned long offset = 0;
  10347. const char *func_name;
  10348. char *func;
  10349. int n;
  10350. *link = NULL;
  10351. /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
  10352. if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
  10353. return 0;
  10354. opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
  10355. if (opts.retprobe)
  10356. func_name = prog->sec_name + sizeof("kretprobe/") - 1;
  10357. else
  10358. func_name = prog->sec_name + sizeof("kprobe/") - 1;
  10359. n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
  10360. if (n < 1) {
  10361. pr_warn("kprobe name is invalid: %s\n", func_name);
  10362. return -EINVAL;
  10363. }
  10364. if (opts.retprobe && offset != 0) {
  10365. free(func);
  10366. pr_warn("kretprobes do not support offset specification\n");
  10367. return -EINVAL;
  10368. }
  10369. opts.offset = offset;
  10370. *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
  10371. free(func);
  10372. return libbpf_get_error(*link);
  10373. }
  10374. static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10375. {
  10376. LIBBPF_OPTS(bpf_ksyscall_opts, opts);
  10377. const char *syscall_name;
  10378. *link = NULL;
  10379. /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
  10380. if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
  10381. return 0;
  10382. opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
  10383. if (opts.retprobe)
  10384. syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
  10385. else
  10386. syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
  10387. *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
  10388. return *link ? 0 : -errno;
  10389. }
  10390. static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10391. {
  10392. LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
  10393. const char *spec;
  10394. char *pattern;
  10395. int n;
  10396. *link = NULL;
  10397. /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
  10398. if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
  10399. strcmp(prog->sec_name, "kretprobe.multi") == 0)
  10400. return 0;
  10401. opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
  10402. if (opts.retprobe)
  10403. spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
  10404. else
  10405. spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
  10406. n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
  10407. if (n < 1) {
  10408. pr_warn("kprobe multi pattern is invalid: %s\n", spec);
  10409. return -EINVAL;
  10410. }
  10411. *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
  10412. free(pattern);
  10413. return libbpf_get_error(*link);
  10414. }
  10415. static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
  10416. struct bpf_link **link)
  10417. {
  10418. LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
  10419. const char *spec;
  10420. char *pattern;
  10421. int n;
  10422. *link = NULL;
  10423. /* no auto-attach for SEC("kprobe.session") */
  10424. if (strcmp(prog->sec_name, "kprobe.session") == 0)
  10425. return 0;
  10426. spec = prog->sec_name + sizeof("kprobe.session/") - 1;
  10427. n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
  10428. if (n < 1) {
  10429. pr_warn("kprobe session pattern is invalid: %s\n", spec);
  10430. return -EINVAL;
  10431. }
  10432. *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
  10433. free(pattern);
  10434. return *link ? 0 : -errno;
  10435. }
  10436. static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10437. {
  10438. char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
  10439. LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
  10440. int n, ret = -EINVAL;
  10441. *link = NULL;
  10442. n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
  10443. &probe_type, &binary_path, &func_name);
  10444. switch (n) {
  10445. case 1:
  10446. /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
  10447. ret = 0;
  10448. break;
  10449. case 3:
  10450. opts.session = str_has_pfx(probe_type, "uprobe.session");
  10451. opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
  10452. *link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
  10453. ret = libbpf_get_error(*link);
  10454. break;
  10455. default:
  10456. pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
  10457. prog->sec_name);
  10458. break;
  10459. }
  10460. free(probe_type);
  10461. free(binary_path);
  10462. free(func_name);
  10463. return ret;
  10464. }
  10465. static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
  10466. const char *binary_path, size_t offset)
  10467. {
  10468. return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
  10469. retprobe ? 'r' : 'p',
  10470. retprobe ? "uretprobes" : "uprobes",
  10471. probe_name, binary_path, offset);
  10472. }
  10473. static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
  10474. {
  10475. return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
  10476. retprobe ? "uretprobes" : "uprobes", probe_name);
  10477. }
  10478. static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
  10479. {
  10480. char file[512];
  10481. snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  10482. tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
  10483. return parse_uint_from_file(file, "%d\n");
  10484. }
  10485. static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
  10486. const char *binary_path, size_t offset, int pid)
  10487. {
  10488. const size_t attr_sz = sizeof(struct perf_event_attr);
  10489. struct perf_event_attr attr;
  10490. int type, pfd, err;
  10491. err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
  10492. if (err < 0) {
  10493. pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
  10494. binary_path, (size_t)offset, errstr(err));
  10495. return err;
  10496. }
  10497. type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
  10498. if (type < 0) {
  10499. err = type;
  10500. pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
  10501. binary_path, offset, errstr(err));
  10502. goto err_clean_legacy;
  10503. }
  10504. memset(&attr, 0, attr_sz);
  10505. attr.size = attr_sz;
  10506. attr.config = type;
  10507. attr.type = PERF_TYPE_TRACEPOINT;
  10508. pfd = syscall(__NR_perf_event_open, &attr,
  10509. pid < 0 ? -1 : pid, /* pid */
  10510. pid == -1 ? 0 : -1, /* cpu */
  10511. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  10512. if (pfd < 0) {
  10513. err = -errno;
  10514. pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
  10515. goto err_clean_legacy;
  10516. }
  10517. return pfd;
  10518. err_clean_legacy:
  10519. /* Clear the newly added legacy uprobe_event */
  10520. remove_uprobe_event_legacy(probe_name, retprobe);
  10521. return err;
  10522. }
  10523. /* Find offset of function name in archive specified by path. Currently
  10524. * supported are .zip files that do not compress their contents, as used on
  10525. * Android in the form of APKs, for example. "file_name" is the name of the ELF
  10526. * file inside the archive. "func_name" matches symbol name or name@@LIB for
  10527. * library functions.
  10528. *
  10529. * An overview of the APK format specifically provided here:
  10530. * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
  10531. */
  10532. static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
  10533. const char *func_name)
  10534. {
  10535. struct zip_archive *archive;
  10536. struct zip_entry entry;
  10537. long ret;
  10538. Elf *elf;
  10539. archive = zip_archive_open(archive_path);
  10540. if (IS_ERR(archive)) {
  10541. ret = PTR_ERR(archive);
  10542. pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
  10543. return ret;
  10544. }
  10545. ret = zip_archive_find_entry(archive, file_name, &entry);
  10546. if (ret) {
  10547. pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
  10548. archive_path, ret);
  10549. goto out;
  10550. }
  10551. pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
  10552. (unsigned long)entry.data_offset);
  10553. if (entry.compression) {
  10554. pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
  10555. archive_path);
  10556. ret = -LIBBPF_ERRNO__FORMAT;
  10557. goto out;
  10558. }
  10559. elf = elf_memory((void *)entry.data, entry.data_length);
  10560. if (!elf) {
  10561. pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
  10562. elf_errmsg(-1));
  10563. ret = -LIBBPF_ERRNO__LIBELF;
  10564. goto out;
  10565. }
  10566. ret = elf_find_func_offset(elf, file_name, func_name);
  10567. if (ret > 0) {
  10568. pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
  10569. func_name, file_name, archive_path, entry.data_offset, ret,
  10570. ret + entry.data_offset);
  10571. ret += entry.data_offset;
  10572. }
  10573. elf_end(elf);
  10574. out:
  10575. zip_archive_close(archive);
  10576. return ret;
  10577. }
  10578. static const char *arch_specific_lib_paths(void)
  10579. {
  10580. /*
  10581. * Based on https://packages.debian.org/sid/libc6.
  10582. *
  10583. * Assume that the traced program is built for the same architecture
  10584. * as libbpf, which should cover the vast majority of cases.
  10585. */
  10586. #if defined(__x86_64__)
  10587. return "/lib/x86_64-linux-gnu";
  10588. #elif defined(__i386__)
  10589. return "/lib/i386-linux-gnu";
  10590. #elif defined(__s390x__)
  10591. return "/lib/s390x-linux-gnu";
  10592. #elif defined(__arm__) && defined(__SOFTFP__)
  10593. return "/lib/arm-linux-gnueabi";
  10594. #elif defined(__arm__) && !defined(__SOFTFP__)
  10595. return "/lib/arm-linux-gnueabihf";
  10596. #elif defined(__aarch64__)
  10597. return "/lib/aarch64-linux-gnu";
  10598. #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
  10599. return "/lib/mips64el-linux-gnuabi64";
  10600. #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
  10601. return "/lib/mipsel-linux-gnu";
  10602. #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  10603. return "/lib/powerpc64le-linux-gnu";
  10604. #elif defined(__sparc__) && defined(__arch64__)
  10605. return "/lib/sparc64-linux-gnu";
  10606. #elif defined(__riscv) && __riscv_xlen == 64
  10607. return "/lib/riscv64-linux-gnu";
  10608. #else
  10609. return NULL;
  10610. #endif
  10611. }
  10612. /* Get full path to program/shared library. */
  10613. static int resolve_full_path(const char *file, char *result, size_t result_sz)
  10614. {
  10615. const char *search_paths[3] = {};
  10616. int i, perm;
  10617. if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
  10618. search_paths[0] = getenv("LD_LIBRARY_PATH");
  10619. search_paths[1] = "/usr/lib64:/usr/lib";
  10620. search_paths[2] = arch_specific_lib_paths();
  10621. perm = R_OK;
  10622. } else {
  10623. search_paths[0] = getenv("PATH");
  10624. search_paths[1] = "/usr/bin:/usr/sbin";
  10625. perm = R_OK | X_OK;
  10626. }
  10627. for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
  10628. const char *s;
  10629. if (!search_paths[i])
  10630. continue;
  10631. for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
  10632. const char *next_path;
  10633. int seg_len;
  10634. if (s[0] == ':')
  10635. s++;
  10636. next_path = strchr(s, ':');
  10637. seg_len = next_path ? next_path - s : strlen(s);
  10638. if (!seg_len)
  10639. continue;
  10640. snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
  10641. /* ensure it has required permissions */
  10642. if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
  10643. continue;
  10644. pr_debug("resolved '%s' to '%s'\n", file, result);
  10645. return 0;
  10646. }
  10647. }
  10648. return -ENOENT;
  10649. }
  10650. struct bpf_link *
  10651. bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
  10652. pid_t pid,
  10653. const char *path,
  10654. const char *func_pattern,
  10655. const struct bpf_uprobe_multi_opts *opts)
  10656. {
  10657. const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
  10658. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  10659. unsigned long *resolved_offsets = NULL;
  10660. enum bpf_attach_type attach_type;
  10661. int err = 0, link_fd, prog_fd;
  10662. struct bpf_link *link = NULL;
  10663. char full_path[PATH_MAX];
  10664. bool retprobe, session;
  10665. const __u64 *cookies;
  10666. const char **syms;
  10667. size_t cnt;
  10668. if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
  10669. return libbpf_err_ptr(-EINVAL);
  10670. prog_fd = bpf_program__fd(prog);
  10671. if (prog_fd < 0) {
  10672. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  10673. prog->name);
  10674. return libbpf_err_ptr(-EINVAL);
  10675. }
  10676. syms = OPTS_GET(opts, syms, NULL);
  10677. offsets = OPTS_GET(opts, offsets, NULL);
  10678. ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
  10679. cookies = OPTS_GET(opts, cookies, NULL);
  10680. cnt = OPTS_GET(opts, cnt, 0);
  10681. retprobe = OPTS_GET(opts, retprobe, false);
  10682. session = OPTS_GET(opts, session, false);
  10683. /*
  10684. * User can specify 2 mutually exclusive set of inputs:
  10685. *
  10686. * 1) use only path/func_pattern/pid arguments
  10687. *
  10688. * 2) use path/pid with allowed combinations of:
  10689. * syms/offsets/ref_ctr_offsets/cookies/cnt
  10690. *
  10691. * - syms and offsets are mutually exclusive
  10692. * - ref_ctr_offsets and cookies are optional
  10693. *
  10694. * Any other usage results in error.
  10695. */
  10696. if (!path)
  10697. return libbpf_err_ptr(-EINVAL);
  10698. if (!func_pattern && cnt == 0)
  10699. return libbpf_err_ptr(-EINVAL);
  10700. if (func_pattern) {
  10701. if (syms || offsets || ref_ctr_offsets || cookies || cnt)
  10702. return libbpf_err_ptr(-EINVAL);
  10703. } else {
  10704. if (!!syms == !!offsets)
  10705. return libbpf_err_ptr(-EINVAL);
  10706. }
  10707. if (retprobe && session)
  10708. return libbpf_err_ptr(-EINVAL);
  10709. if (func_pattern) {
  10710. if (!strchr(path, '/')) {
  10711. err = resolve_full_path(path, full_path, sizeof(full_path));
  10712. if (err) {
  10713. pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
  10714. prog->name, path, errstr(err));
  10715. return libbpf_err_ptr(err);
  10716. }
  10717. path = full_path;
  10718. }
  10719. err = elf_resolve_pattern_offsets(path, func_pattern,
  10720. &resolved_offsets, &cnt);
  10721. if (err < 0)
  10722. return libbpf_err_ptr(err);
  10723. offsets = resolved_offsets;
  10724. } else if (syms) {
  10725. err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
  10726. if (err < 0)
  10727. return libbpf_err_ptr(err);
  10728. offsets = resolved_offsets;
  10729. }
  10730. attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
  10731. lopts.uprobe_multi.path = path;
  10732. lopts.uprobe_multi.offsets = offsets;
  10733. lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
  10734. lopts.uprobe_multi.cookies = cookies;
  10735. lopts.uprobe_multi.cnt = cnt;
  10736. lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
  10737. if (pid == 0)
  10738. pid = getpid();
  10739. if (pid > 0)
  10740. lopts.uprobe_multi.pid = pid;
  10741. link = calloc(1, sizeof(*link));
  10742. if (!link) {
  10743. err = -ENOMEM;
  10744. goto error;
  10745. }
  10746. link->detach = &bpf_link__detach_fd;
  10747. link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
  10748. if (link_fd < 0) {
  10749. err = -errno;
  10750. pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
  10751. prog->name, errstr(err));
  10752. goto error;
  10753. }
  10754. link->fd = link_fd;
  10755. free(resolved_offsets);
  10756. return link;
  10757. error:
  10758. free(resolved_offsets);
  10759. free(link);
  10760. return libbpf_err_ptr(err);
  10761. }
  10762. LIBBPF_API struct bpf_link *
  10763. bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
  10764. const char *binary_path, size_t func_offset,
  10765. const struct bpf_uprobe_opts *opts)
  10766. {
  10767. const char *archive_path = NULL, *archive_sep = NULL;
  10768. char *legacy_probe = NULL;
  10769. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  10770. enum probe_attach_mode attach_mode;
  10771. char full_path[PATH_MAX];
  10772. struct bpf_link *link;
  10773. size_t ref_ctr_off;
  10774. int pfd, err;
  10775. bool retprobe, legacy;
  10776. const char *func_name;
  10777. if (!OPTS_VALID(opts, bpf_uprobe_opts))
  10778. return libbpf_err_ptr(-EINVAL);
  10779. attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
  10780. retprobe = OPTS_GET(opts, retprobe, false);
  10781. ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
  10782. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  10783. if (!binary_path)
  10784. return libbpf_err_ptr(-EINVAL);
  10785. /* Check if "binary_path" refers to an archive. */
  10786. archive_sep = strstr(binary_path, "!/");
  10787. if (archive_sep) {
  10788. full_path[0] = '\0';
  10789. libbpf_strlcpy(full_path, binary_path,
  10790. min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
  10791. archive_path = full_path;
  10792. binary_path = archive_sep + 2;
  10793. } else if (!strchr(binary_path, '/')) {
  10794. err = resolve_full_path(binary_path, full_path, sizeof(full_path));
  10795. if (err) {
  10796. pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
  10797. prog->name, binary_path, errstr(err));
  10798. return libbpf_err_ptr(err);
  10799. }
  10800. binary_path = full_path;
  10801. }
  10802. func_name = OPTS_GET(opts, func_name, NULL);
  10803. if (func_name) {
  10804. long sym_off;
  10805. if (archive_path) {
  10806. sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
  10807. func_name);
  10808. binary_path = archive_path;
  10809. } else {
  10810. sym_off = elf_find_func_offset_from_file(binary_path, func_name);
  10811. }
  10812. if (sym_off < 0)
  10813. return libbpf_err_ptr(sym_off);
  10814. func_offset += sym_off;
  10815. }
  10816. legacy = determine_uprobe_perf_type() < 0;
  10817. switch (attach_mode) {
  10818. case PROBE_ATTACH_MODE_LEGACY:
  10819. legacy = true;
  10820. pe_opts.force_ioctl_attach = true;
  10821. break;
  10822. case PROBE_ATTACH_MODE_PERF:
  10823. if (legacy)
  10824. return libbpf_err_ptr(-ENOTSUP);
  10825. pe_opts.force_ioctl_attach = true;
  10826. break;
  10827. case PROBE_ATTACH_MODE_LINK:
  10828. if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
  10829. return libbpf_err_ptr(-ENOTSUP);
  10830. break;
  10831. case PROBE_ATTACH_MODE_DEFAULT:
  10832. break;
  10833. default:
  10834. return libbpf_err_ptr(-EINVAL);
  10835. }
  10836. if (!legacy) {
  10837. pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
  10838. func_offset, pid, ref_ctr_off);
  10839. } else {
  10840. char probe_name[MAX_EVENT_NAME_LEN];
  10841. if (ref_ctr_off)
  10842. return libbpf_err_ptr(-EINVAL);
  10843. gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
  10844. strrchr(binary_path, '/') ? : binary_path,
  10845. func_offset);
  10846. legacy_probe = strdup(probe_name);
  10847. if (!legacy_probe)
  10848. return libbpf_err_ptr(-ENOMEM);
  10849. pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
  10850. binary_path, func_offset, pid);
  10851. }
  10852. if (pfd < 0) {
  10853. err = -errno;
  10854. pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
  10855. prog->name, retprobe ? "uretprobe" : "uprobe",
  10856. binary_path, func_offset,
  10857. errstr(err));
  10858. goto err_out;
  10859. }
  10860. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  10861. err = libbpf_get_error(link);
  10862. if (err) {
  10863. close(pfd);
  10864. pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
  10865. prog->name, retprobe ? "uretprobe" : "uprobe",
  10866. binary_path, func_offset,
  10867. errstr(err));
  10868. goto err_clean_legacy;
  10869. }
  10870. if (legacy) {
  10871. struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
  10872. perf_link->legacy_probe_name = legacy_probe;
  10873. perf_link->legacy_is_kprobe = false;
  10874. perf_link->legacy_is_retprobe = retprobe;
  10875. }
  10876. return link;
  10877. err_clean_legacy:
  10878. if (legacy)
  10879. remove_uprobe_event_legacy(legacy_probe, retprobe);
  10880. err_out:
  10881. free(legacy_probe);
  10882. return libbpf_err_ptr(err);
  10883. }
  10884. /* Format of u[ret]probe section definition supporting auto-attach:
  10885. * u[ret]probe/binary:function[+offset]
  10886. *
  10887. * binary can be an absolute/relative path or a filename; the latter is resolved to a
  10888. * full binary path via bpf_program__attach_uprobe_opts.
  10889. *
  10890. * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
  10891. * specified (and auto-attach is not possible) or the above format is specified for
  10892. * auto-attach.
  10893. */
  10894. static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  10895. {
  10896. DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
  10897. char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
  10898. int n, c, ret = -EINVAL;
  10899. long offset = 0;
  10900. *link = NULL;
  10901. n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
  10902. &probe_type, &binary_path, &func_name);
  10903. switch (n) {
  10904. case 1:
  10905. /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
  10906. ret = 0;
  10907. break;
  10908. case 2:
  10909. pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
  10910. prog->name, prog->sec_name);
  10911. break;
  10912. case 3:
  10913. /* check if user specifies `+offset`, if yes, this should be
  10914. * the last part of the string, make sure sscanf read to EOL
  10915. */
  10916. func_off = strrchr(func_name, '+');
  10917. if (func_off) {
  10918. n = sscanf(func_off, "+%li%n", &offset, &c);
  10919. if (n == 1 && *(func_off + c) == '\0')
  10920. func_off[0] = '\0';
  10921. else
  10922. offset = 0;
  10923. }
  10924. opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
  10925. strcmp(probe_type, "uretprobe.s") == 0;
  10926. if (opts.retprobe && offset != 0) {
  10927. pr_warn("prog '%s': uretprobes do not support offset specification\n",
  10928. prog->name);
  10929. break;
  10930. }
  10931. opts.func_name = func_name;
  10932. *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
  10933. ret = libbpf_get_error(*link);
  10934. break;
  10935. default:
  10936. pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
  10937. prog->sec_name);
  10938. break;
  10939. }
  10940. free(probe_type);
  10941. free(binary_path);
  10942. free(func_name);
  10943. return ret;
  10944. }
  10945. struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
  10946. bool retprobe, pid_t pid,
  10947. const char *binary_path,
  10948. size_t func_offset)
  10949. {
  10950. DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
  10951. return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
  10952. }
  10953. struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
  10954. pid_t pid, const char *binary_path,
  10955. const char *usdt_provider, const char *usdt_name,
  10956. const struct bpf_usdt_opts *opts)
  10957. {
  10958. char resolved_path[512];
  10959. struct bpf_object *obj = prog->obj;
  10960. struct bpf_link *link;
  10961. __u64 usdt_cookie;
  10962. int err;
  10963. if (!OPTS_VALID(opts, bpf_uprobe_opts))
  10964. return libbpf_err_ptr(-EINVAL);
  10965. if (bpf_program__fd(prog) < 0) {
  10966. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  10967. prog->name);
  10968. return libbpf_err_ptr(-EINVAL);
  10969. }
  10970. if (!binary_path)
  10971. return libbpf_err_ptr(-EINVAL);
  10972. if (!strchr(binary_path, '/')) {
  10973. err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
  10974. if (err) {
  10975. pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
  10976. prog->name, binary_path, errstr(err));
  10977. return libbpf_err_ptr(err);
  10978. }
  10979. binary_path = resolved_path;
  10980. }
  10981. /* USDT manager is instantiated lazily on first USDT attach. It will
  10982. * be destroyed together with BPF object in bpf_object__close().
  10983. */
  10984. if (IS_ERR(obj->usdt_man))
  10985. return libbpf_ptr(obj->usdt_man);
  10986. if (!obj->usdt_man) {
  10987. obj->usdt_man = usdt_manager_new(obj);
  10988. if (IS_ERR(obj->usdt_man))
  10989. return libbpf_ptr(obj->usdt_man);
  10990. }
  10991. usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
  10992. link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
  10993. usdt_provider, usdt_name, usdt_cookie);
  10994. err = libbpf_get_error(link);
  10995. if (err)
  10996. return libbpf_err_ptr(err);
  10997. return link;
  10998. }
  10999. static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11000. {
  11001. char *path = NULL, *provider = NULL, *name = NULL;
  11002. const char *sec_name;
  11003. int n, err;
  11004. sec_name = bpf_program__section_name(prog);
  11005. if (strcmp(sec_name, "usdt") == 0) {
  11006. /* no auto-attach for just SEC("usdt") */
  11007. *link = NULL;
  11008. return 0;
  11009. }
  11010. n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
  11011. if (n != 3) {
  11012. pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
  11013. sec_name);
  11014. err = -EINVAL;
  11015. } else {
  11016. *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
  11017. provider, name, NULL);
  11018. err = libbpf_get_error(*link);
  11019. }
  11020. free(path);
  11021. free(provider);
  11022. free(name);
  11023. return err;
  11024. }
  11025. static int determine_tracepoint_id(const char *tp_category,
  11026. const char *tp_name)
  11027. {
  11028. char file[PATH_MAX];
  11029. int ret;
  11030. ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
  11031. tracefs_path(), tp_category, tp_name);
  11032. if (ret < 0)
  11033. return -errno;
  11034. if (ret >= sizeof(file)) {
  11035. pr_debug("tracepoint %s/%s path is too long\n",
  11036. tp_category, tp_name);
  11037. return -E2BIG;
  11038. }
  11039. return parse_uint_from_file(file, "%d\n");
  11040. }
  11041. static int perf_event_open_tracepoint(const char *tp_category,
  11042. const char *tp_name)
  11043. {
  11044. const size_t attr_sz = sizeof(struct perf_event_attr);
  11045. struct perf_event_attr attr;
  11046. int tp_id, pfd, err;
  11047. tp_id = determine_tracepoint_id(tp_category, tp_name);
  11048. if (tp_id < 0) {
  11049. pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
  11050. tp_category, tp_name,
  11051. errstr(tp_id));
  11052. return tp_id;
  11053. }
  11054. memset(&attr, 0, attr_sz);
  11055. attr.type = PERF_TYPE_TRACEPOINT;
  11056. attr.size = attr_sz;
  11057. attr.config = tp_id;
  11058. pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
  11059. -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
  11060. if (pfd < 0) {
  11061. err = -errno;
  11062. pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
  11063. tp_category, tp_name,
  11064. errstr(err));
  11065. return err;
  11066. }
  11067. return pfd;
  11068. }
  11069. struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
  11070. const char *tp_category,
  11071. const char *tp_name,
  11072. const struct bpf_tracepoint_opts *opts)
  11073. {
  11074. DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
  11075. struct bpf_link *link;
  11076. int pfd, err;
  11077. if (!OPTS_VALID(opts, bpf_tracepoint_opts))
  11078. return libbpf_err_ptr(-EINVAL);
  11079. pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
  11080. pfd = perf_event_open_tracepoint(tp_category, tp_name);
  11081. if (pfd < 0) {
  11082. pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
  11083. prog->name, tp_category, tp_name,
  11084. errstr(pfd));
  11085. return libbpf_err_ptr(pfd);
  11086. }
  11087. link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
  11088. err = libbpf_get_error(link);
  11089. if (err) {
  11090. close(pfd);
  11091. pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
  11092. prog->name, tp_category, tp_name,
  11093. errstr(err));
  11094. return libbpf_err_ptr(err);
  11095. }
  11096. return link;
  11097. }
  11098. struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
  11099. const char *tp_category,
  11100. const char *tp_name)
  11101. {
  11102. return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
  11103. }
  11104. static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11105. {
  11106. char *sec_name, *tp_cat, *tp_name;
  11107. *link = NULL;
  11108. /* no auto-attach for SEC("tp") or SEC("tracepoint") */
  11109. if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
  11110. return 0;
  11111. sec_name = strdup(prog->sec_name);
  11112. if (!sec_name)
  11113. return -ENOMEM;
  11114. /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
  11115. if (str_has_pfx(prog->sec_name, "tp/"))
  11116. tp_cat = sec_name + sizeof("tp/") - 1;
  11117. else
  11118. tp_cat = sec_name + sizeof("tracepoint/") - 1;
  11119. tp_name = strchr(tp_cat, '/');
  11120. if (!tp_name) {
  11121. free(sec_name);
  11122. return -EINVAL;
  11123. }
  11124. *tp_name = '\0';
  11125. tp_name++;
  11126. *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
  11127. free(sec_name);
  11128. return libbpf_get_error(*link);
  11129. }
  11130. struct bpf_link *
  11131. bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
  11132. const char *tp_name,
  11133. struct bpf_raw_tracepoint_opts *opts)
  11134. {
  11135. LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
  11136. struct bpf_link *link;
  11137. int prog_fd, pfd;
  11138. if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
  11139. return libbpf_err_ptr(-EINVAL);
  11140. prog_fd = bpf_program__fd(prog);
  11141. if (prog_fd < 0) {
  11142. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11143. return libbpf_err_ptr(-EINVAL);
  11144. }
  11145. link = calloc(1, sizeof(*link));
  11146. if (!link)
  11147. return libbpf_err_ptr(-ENOMEM);
  11148. link->detach = &bpf_link__detach_fd;
  11149. raw_opts.tp_name = tp_name;
  11150. raw_opts.cookie = OPTS_GET(opts, cookie, 0);
  11151. pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
  11152. if (pfd < 0) {
  11153. pfd = -errno;
  11154. free(link);
  11155. pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
  11156. prog->name, tp_name, errstr(pfd));
  11157. return libbpf_err_ptr(pfd);
  11158. }
  11159. link->fd = pfd;
  11160. return link;
  11161. }
  11162. struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
  11163. const char *tp_name)
  11164. {
  11165. return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
  11166. }
  11167. static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11168. {
  11169. static const char *const prefixes[] = {
  11170. "raw_tp",
  11171. "raw_tracepoint",
  11172. "raw_tp.w",
  11173. "raw_tracepoint.w",
  11174. };
  11175. size_t i;
  11176. const char *tp_name = NULL;
  11177. *link = NULL;
  11178. for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
  11179. size_t pfx_len;
  11180. if (!str_has_pfx(prog->sec_name, prefixes[i]))
  11181. continue;
  11182. pfx_len = strlen(prefixes[i]);
  11183. /* no auto-attach case of, e.g., SEC("raw_tp") */
  11184. if (prog->sec_name[pfx_len] == '\0')
  11185. return 0;
  11186. if (prog->sec_name[pfx_len] != '/')
  11187. continue;
  11188. tp_name = prog->sec_name + pfx_len + 1;
  11189. break;
  11190. }
  11191. if (!tp_name) {
  11192. pr_warn("prog '%s': invalid section name '%s'\n",
  11193. prog->name, prog->sec_name);
  11194. return -EINVAL;
  11195. }
  11196. *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
  11197. return libbpf_get_error(*link);
  11198. }
  11199. /* Common logic for all BPF program types that attach to a btf_id */
  11200. static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
  11201. const struct bpf_trace_opts *opts)
  11202. {
  11203. LIBBPF_OPTS(bpf_link_create_opts, link_opts);
  11204. struct bpf_link *link;
  11205. int prog_fd, pfd;
  11206. if (!OPTS_VALID(opts, bpf_trace_opts))
  11207. return libbpf_err_ptr(-EINVAL);
  11208. prog_fd = bpf_program__fd(prog);
  11209. if (prog_fd < 0) {
  11210. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11211. return libbpf_err_ptr(-EINVAL);
  11212. }
  11213. link = calloc(1, sizeof(*link));
  11214. if (!link)
  11215. return libbpf_err_ptr(-ENOMEM);
  11216. link->detach = &bpf_link__detach_fd;
  11217. /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
  11218. link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
  11219. pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
  11220. if (pfd < 0) {
  11221. pfd = -errno;
  11222. free(link);
  11223. pr_warn("prog '%s': failed to attach: %s\n",
  11224. prog->name, errstr(pfd));
  11225. return libbpf_err_ptr(pfd);
  11226. }
  11227. link->fd = pfd;
  11228. return link;
  11229. }
  11230. struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
  11231. {
  11232. return bpf_program__attach_btf_id(prog, NULL);
  11233. }
  11234. struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
  11235. const struct bpf_trace_opts *opts)
  11236. {
  11237. return bpf_program__attach_btf_id(prog, opts);
  11238. }
  11239. struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
  11240. {
  11241. return bpf_program__attach_btf_id(prog, NULL);
  11242. }
  11243. static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11244. {
  11245. *link = bpf_program__attach_trace(prog);
  11246. return libbpf_get_error(*link);
  11247. }
  11248. static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11249. {
  11250. *link = bpf_program__attach_lsm(prog);
  11251. return libbpf_get_error(*link);
  11252. }
  11253. static struct bpf_link *
  11254. bpf_program_attach_fd(const struct bpf_program *prog,
  11255. int target_fd, const char *target_name,
  11256. const struct bpf_link_create_opts *opts)
  11257. {
  11258. enum bpf_attach_type attach_type;
  11259. struct bpf_link *link;
  11260. int prog_fd, link_fd;
  11261. prog_fd = bpf_program__fd(prog);
  11262. if (prog_fd < 0) {
  11263. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11264. return libbpf_err_ptr(-EINVAL);
  11265. }
  11266. link = calloc(1, sizeof(*link));
  11267. if (!link)
  11268. return libbpf_err_ptr(-ENOMEM);
  11269. link->detach = &bpf_link__detach_fd;
  11270. attach_type = bpf_program__expected_attach_type(prog);
  11271. link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
  11272. if (link_fd < 0) {
  11273. link_fd = -errno;
  11274. free(link);
  11275. pr_warn("prog '%s': failed to attach to %s: %s\n",
  11276. prog->name, target_name,
  11277. errstr(link_fd));
  11278. return libbpf_err_ptr(link_fd);
  11279. }
  11280. link->fd = link_fd;
  11281. return link;
  11282. }
  11283. struct bpf_link *
  11284. bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
  11285. {
  11286. return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
  11287. }
  11288. struct bpf_link *
  11289. bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
  11290. {
  11291. return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
  11292. }
  11293. struct bpf_link *
  11294. bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
  11295. {
  11296. return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
  11297. }
  11298. struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
  11299. {
  11300. /* target_fd/target_ifindex use the same field in LINK_CREATE */
  11301. return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
  11302. }
  11303. struct bpf_link *
  11304. bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
  11305. const struct bpf_cgroup_opts *opts)
  11306. {
  11307. LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  11308. __u32 relative_id;
  11309. int relative_fd;
  11310. if (!OPTS_VALID(opts, bpf_cgroup_opts))
  11311. return libbpf_err_ptr(-EINVAL);
  11312. relative_id = OPTS_GET(opts, relative_id, 0);
  11313. relative_fd = OPTS_GET(opts, relative_fd, 0);
  11314. if (relative_fd && relative_id) {
  11315. pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
  11316. prog->name);
  11317. return libbpf_err_ptr(-EINVAL);
  11318. }
  11319. link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
  11320. link_create_opts.cgroup.relative_fd = relative_fd;
  11321. link_create_opts.cgroup.relative_id = relative_id;
  11322. link_create_opts.flags = OPTS_GET(opts, flags, 0);
  11323. return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
  11324. }
  11325. struct bpf_link *
  11326. bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
  11327. const struct bpf_tcx_opts *opts)
  11328. {
  11329. LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  11330. __u32 relative_id;
  11331. int relative_fd;
  11332. if (!OPTS_VALID(opts, bpf_tcx_opts))
  11333. return libbpf_err_ptr(-EINVAL);
  11334. relative_id = OPTS_GET(opts, relative_id, 0);
  11335. relative_fd = OPTS_GET(opts, relative_fd, 0);
  11336. /* validate we don't have unexpected combinations of non-zero fields */
  11337. if (!ifindex) {
  11338. pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
  11339. prog->name);
  11340. return libbpf_err_ptr(-EINVAL);
  11341. }
  11342. if (relative_fd && relative_id) {
  11343. pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
  11344. prog->name);
  11345. return libbpf_err_ptr(-EINVAL);
  11346. }
  11347. link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
  11348. link_create_opts.tcx.relative_fd = relative_fd;
  11349. link_create_opts.tcx.relative_id = relative_id;
  11350. link_create_opts.flags = OPTS_GET(opts, flags, 0);
  11351. /* target_fd/target_ifindex use the same field in LINK_CREATE */
  11352. return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
  11353. }
  11354. struct bpf_link *
  11355. bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
  11356. const struct bpf_netkit_opts *opts)
  11357. {
  11358. LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  11359. __u32 relative_id;
  11360. int relative_fd;
  11361. if (!OPTS_VALID(opts, bpf_netkit_opts))
  11362. return libbpf_err_ptr(-EINVAL);
  11363. relative_id = OPTS_GET(opts, relative_id, 0);
  11364. relative_fd = OPTS_GET(opts, relative_fd, 0);
  11365. /* validate we don't have unexpected combinations of non-zero fields */
  11366. if (!ifindex) {
  11367. pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
  11368. prog->name);
  11369. return libbpf_err_ptr(-EINVAL);
  11370. }
  11371. if (relative_fd && relative_id) {
  11372. pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
  11373. prog->name);
  11374. return libbpf_err_ptr(-EINVAL);
  11375. }
  11376. link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
  11377. link_create_opts.netkit.relative_fd = relative_fd;
  11378. link_create_opts.netkit.relative_id = relative_id;
  11379. link_create_opts.flags = OPTS_GET(opts, flags, 0);
  11380. return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
  11381. }
  11382. struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
  11383. int target_fd,
  11384. const char *attach_func_name)
  11385. {
  11386. int btf_id;
  11387. if (!!target_fd != !!attach_func_name) {
  11388. pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
  11389. prog->name);
  11390. return libbpf_err_ptr(-EINVAL);
  11391. }
  11392. if (prog->type != BPF_PROG_TYPE_EXT) {
  11393. pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
  11394. prog->name);
  11395. return libbpf_err_ptr(-EINVAL);
  11396. }
  11397. if (target_fd) {
  11398. LIBBPF_OPTS(bpf_link_create_opts, target_opts);
  11399. btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
  11400. if (btf_id < 0)
  11401. return libbpf_err_ptr(btf_id);
  11402. target_opts.target_btf_id = btf_id;
  11403. return bpf_program_attach_fd(prog, target_fd, "freplace",
  11404. &target_opts);
  11405. } else {
  11406. /* no target, so use raw_tracepoint_open for compatibility
  11407. * with old kernels
  11408. */
  11409. return bpf_program__attach_trace(prog);
  11410. }
  11411. }
  11412. struct bpf_link *
  11413. bpf_program__attach_iter(const struct bpf_program *prog,
  11414. const struct bpf_iter_attach_opts *opts)
  11415. {
  11416. DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
  11417. struct bpf_link *link;
  11418. int prog_fd, link_fd;
  11419. __u32 target_fd = 0;
  11420. if (!OPTS_VALID(opts, bpf_iter_attach_opts))
  11421. return libbpf_err_ptr(-EINVAL);
  11422. link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
  11423. link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
  11424. prog_fd = bpf_program__fd(prog);
  11425. if (prog_fd < 0) {
  11426. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11427. return libbpf_err_ptr(-EINVAL);
  11428. }
  11429. link = calloc(1, sizeof(*link));
  11430. if (!link)
  11431. return libbpf_err_ptr(-ENOMEM);
  11432. link->detach = &bpf_link__detach_fd;
  11433. link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
  11434. &link_create_opts);
  11435. if (link_fd < 0) {
  11436. link_fd = -errno;
  11437. free(link);
  11438. pr_warn("prog '%s': failed to attach to iterator: %s\n",
  11439. prog->name, errstr(link_fd));
  11440. return libbpf_err_ptr(link_fd);
  11441. }
  11442. link->fd = link_fd;
  11443. return link;
  11444. }
  11445. static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
  11446. {
  11447. *link = bpf_program__attach_iter(prog, NULL);
  11448. return libbpf_get_error(*link);
  11449. }
  11450. struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
  11451. const struct bpf_netfilter_opts *opts)
  11452. {
  11453. LIBBPF_OPTS(bpf_link_create_opts, lopts);
  11454. struct bpf_link *link;
  11455. int prog_fd, link_fd;
  11456. if (!OPTS_VALID(opts, bpf_netfilter_opts))
  11457. return libbpf_err_ptr(-EINVAL);
  11458. prog_fd = bpf_program__fd(prog);
  11459. if (prog_fd < 0) {
  11460. pr_warn("prog '%s': can't attach before loaded\n", prog->name);
  11461. return libbpf_err_ptr(-EINVAL);
  11462. }
  11463. link = calloc(1, sizeof(*link));
  11464. if (!link)
  11465. return libbpf_err_ptr(-ENOMEM);
  11466. link->detach = &bpf_link__detach_fd;
  11467. lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
  11468. lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
  11469. lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
  11470. lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
  11471. link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
  11472. if (link_fd < 0) {
  11473. link_fd = -errno;
  11474. free(link);
  11475. pr_warn("prog '%s': failed to attach to netfilter: %s\n",
  11476. prog->name, errstr(link_fd));
  11477. return libbpf_err_ptr(link_fd);
  11478. }
  11479. link->fd = link_fd;
  11480. return link;
  11481. }
  11482. struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
  11483. {
  11484. struct bpf_link *link = NULL;
  11485. int err;
  11486. if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
  11487. return libbpf_err_ptr(-EOPNOTSUPP);
  11488. if (bpf_program__fd(prog) < 0) {
  11489. pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
  11490. prog->name);
  11491. return libbpf_err_ptr(-EINVAL);
  11492. }
  11493. err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
  11494. if (err)
  11495. return libbpf_err_ptr(err);
  11496. /* When calling bpf_program__attach() explicitly, auto-attach support
  11497. * is expected to work, so NULL returned link is considered an error.
  11498. * This is different for skeleton's attach, see comment in
  11499. * bpf_object__attach_skeleton().
  11500. */
  11501. if (!link)
  11502. return libbpf_err_ptr(-EOPNOTSUPP);
  11503. return link;
  11504. }
  11505. struct bpf_link_struct_ops {
  11506. struct bpf_link link;
  11507. int map_fd;
  11508. };
  11509. static int bpf_link__detach_struct_ops(struct bpf_link *link)
  11510. {
  11511. struct bpf_link_struct_ops *st_link;
  11512. __u32 zero = 0;
  11513. st_link = container_of(link, struct bpf_link_struct_ops, link);
  11514. if (st_link->map_fd < 0)
  11515. /* w/o a real link */
  11516. return bpf_map_delete_elem(link->fd, &zero);
  11517. return close(link->fd);
  11518. }
  11519. struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
  11520. {
  11521. struct bpf_link_struct_ops *link;
  11522. __u32 zero = 0;
  11523. int err, fd;
  11524. if (!bpf_map__is_struct_ops(map)) {
  11525. pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
  11526. return libbpf_err_ptr(-EINVAL);
  11527. }
  11528. if (map->fd < 0) {
  11529. pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
  11530. return libbpf_err_ptr(-EINVAL);
  11531. }
  11532. link = calloc(1, sizeof(*link));
  11533. if (!link)
  11534. return libbpf_err_ptr(-EINVAL);
  11535. /* kern_vdata should be prepared during the loading phase. */
  11536. err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
  11537. /* It can be EBUSY if the map has been used to create or
  11538. * update a link before. We don't allow updating the value of
  11539. * a struct_ops once it is set. That ensures that the value
  11540. * never changed. So, it is safe to skip EBUSY.
  11541. */
  11542. if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
  11543. free(link);
  11544. return libbpf_err_ptr(err);
  11545. }
  11546. link->link.detach = bpf_link__detach_struct_ops;
  11547. if (!(map->def.map_flags & BPF_F_LINK)) {
  11548. /* w/o a real link */
  11549. link->link.fd = map->fd;
  11550. link->map_fd = -1;
  11551. return &link->link;
  11552. }
  11553. fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
  11554. if (fd < 0) {
  11555. free(link);
  11556. return libbpf_err_ptr(fd);
  11557. }
  11558. link->link.fd = fd;
  11559. link->map_fd = map->fd;
  11560. return &link->link;
  11561. }
  11562. /*
  11563. * Swap the back struct_ops of a link with a new struct_ops map.
  11564. */
  11565. int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
  11566. {
  11567. struct bpf_link_struct_ops *st_ops_link;
  11568. __u32 zero = 0;
  11569. int err;
  11570. if (!bpf_map__is_struct_ops(map))
  11571. return libbpf_err(-EINVAL);
  11572. if (map->fd < 0) {
  11573. pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
  11574. return libbpf_err(-EINVAL);
  11575. }
  11576. st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
  11577. /* Ensure the type of a link is correct */
  11578. if (st_ops_link->map_fd < 0)
  11579. return libbpf_err(-EINVAL);
  11580. err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
  11581. /* It can be EBUSY if the map has been used to create or
  11582. * update a link before. We don't allow updating the value of
  11583. * a struct_ops once it is set. That ensures that the value
  11584. * never changed. So, it is safe to skip EBUSY.
  11585. */
  11586. if (err && err != -EBUSY)
  11587. return err;
  11588. err = bpf_link_update(link->fd, map->fd, NULL);
  11589. if (err < 0)
  11590. return err;
  11591. st_ops_link->map_fd = map->fd;
  11592. return 0;
  11593. }
  11594. typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
  11595. void *private_data);
  11596. static enum bpf_perf_event_ret
  11597. perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
  11598. void **copy_mem, size_t *copy_size,
  11599. bpf_perf_event_print_t fn, void *private_data)
  11600. {
  11601. struct perf_event_mmap_page *header = mmap_mem;
  11602. __u64 data_head = ring_buffer_read_head(header);
  11603. __u64 data_tail = header->data_tail;
  11604. void *base = ((__u8 *)header) + page_size;
  11605. int ret = LIBBPF_PERF_EVENT_CONT;
  11606. struct perf_event_header *ehdr;
  11607. size_t ehdr_size;
  11608. while (data_head != data_tail) {
  11609. ehdr = base + (data_tail & (mmap_size - 1));
  11610. ehdr_size = ehdr->size;
  11611. if (((void *)ehdr) + ehdr_size > base + mmap_size) {
  11612. void *copy_start = ehdr;
  11613. size_t len_first = base + mmap_size - copy_start;
  11614. size_t len_secnd = ehdr_size - len_first;
  11615. if (*copy_size < ehdr_size) {
  11616. free(*copy_mem);
  11617. *copy_mem = malloc(ehdr_size);
  11618. if (!*copy_mem) {
  11619. *copy_size = 0;
  11620. ret = LIBBPF_PERF_EVENT_ERROR;
  11621. break;
  11622. }
  11623. *copy_size = ehdr_size;
  11624. }
  11625. memcpy(*copy_mem, copy_start, len_first);
  11626. memcpy(*copy_mem + len_first, base, len_secnd);
  11627. ehdr = *copy_mem;
  11628. }
  11629. ret = fn(ehdr, private_data);
  11630. data_tail += ehdr_size;
  11631. if (ret != LIBBPF_PERF_EVENT_CONT)
  11632. break;
  11633. }
  11634. ring_buffer_write_tail(header, data_tail);
  11635. return libbpf_err(ret);
  11636. }
  11637. struct perf_buffer;
  11638. struct perf_buffer_params {
  11639. struct perf_event_attr *attr;
  11640. /* if event_cb is specified, it takes precendence */
  11641. perf_buffer_event_fn event_cb;
  11642. /* sample_cb and lost_cb are higher-level common-case callbacks */
  11643. perf_buffer_sample_fn sample_cb;
  11644. perf_buffer_lost_fn lost_cb;
  11645. void *ctx;
  11646. int cpu_cnt;
  11647. int *cpus;
  11648. int *map_keys;
  11649. };
  11650. struct perf_cpu_buf {
  11651. struct perf_buffer *pb;
  11652. void *base; /* mmap()'ed memory */
  11653. void *buf; /* for reconstructing segmented data */
  11654. size_t buf_size;
  11655. int fd;
  11656. int cpu;
  11657. int map_key;
  11658. };
  11659. struct perf_buffer {
  11660. perf_buffer_event_fn event_cb;
  11661. perf_buffer_sample_fn sample_cb;
  11662. perf_buffer_lost_fn lost_cb;
  11663. void *ctx; /* passed into callbacks */
  11664. size_t page_size;
  11665. size_t mmap_size;
  11666. struct perf_cpu_buf **cpu_bufs;
  11667. struct epoll_event *events;
  11668. int cpu_cnt; /* number of allocated CPU buffers */
  11669. int epoll_fd; /* perf event FD */
  11670. int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
  11671. };
  11672. static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
  11673. struct perf_cpu_buf *cpu_buf)
  11674. {
  11675. if (!cpu_buf)
  11676. return;
  11677. if (cpu_buf->base &&
  11678. munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
  11679. pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
  11680. if (cpu_buf->fd >= 0) {
  11681. ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
  11682. close(cpu_buf->fd);
  11683. }
  11684. free(cpu_buf->buf);
  11685. free(cpu_buf);
  11686. }
  11687. void perf_buffer__free(struct perf_buffer *pb)
  11688. {
  11689. int i;
  11690. if (IS_ERR_OR_NULL(pb))
  11691. return;
  11692. if (pb->cpu_bufs) {
  11693. for (i = 0; i < pb->cpu_cnt; i++) {
  11694. struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
  11695. if (!cpu_buf)
  11696. continue;
  11697. bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
  11698. perf_buffer__free_cpu_buf(pb, cpu_buf);
  11699. }
  11700. free(pb->cpu_bufs);
  11701. }
  11702. if (pb->epoll_fd >= 0)
  11703. close(pb->epoll_fd);
  11704. free(pb->events);
  11705. free(pb);
  11706. }
  11707. static struct perf_cpu_buf *
  11708. perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
  11709. int cpu, int map_key)
  11710. {
  11711. struct perf_cpu_buf *cpu_buf;
  11712. int err;
  11713. cpu_buf = calloc(1, sizeof(*cpu_buf));
  11714. if (!cpu_buf)
  11715. return ERR_PTR(-ENOMEM);
  11716. cpu_buf->pb = pb;
  11717. cpu_buf->cpu = cpu;
  11718. cpu_buf->map_key = map_key;
  11719. cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
  11720. -1, PERF_FLAG_FD_CLOEXEC);
  11721. if (cpu_buf->fd < 0) {
  11722. err = -errno;
  11723. pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
  11724. cpu, errstr(err));
  11725. goto error;
  11726. }
  11727. cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
  11728. PROT_READ | PROT_WRITE, MAP_SHARED,
  11729. cpu_buf->fd, 0);
  11730. if (cpu_buf->base == MAP_FAILED) {
  11731. cpu_buf->base = NULL;
  11732. err = -errno;
  11733. pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
  11734. cpu, errstr(err));
  11735. goto error;
  11736. }
  11737. if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
  11738. err = -errno;
  11739. pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
  11740. cpu, errstr(err));
  11741. goto error;
  11742. }
  11743. return cpu_buf;
  11744. error:
  11745. perf_buffer__free_cpu_buf(pb, cpu_buf);
  11746. return (struct perf_cpu_buf *)ERR_PTR(err);
  11747. }
  11748. static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
  11749. struct perf_buffer_params *p);
  11750. struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
  11751. perf_buffer_sample_fn sample_cb,
  11752. perf_buffer_lost_fn lost_cb,
  11753. void *ctx,
  11754. const struct perf_buffer_opts *opts)
  11755. {
  11756. const size_t attr_sz = sizeof(struct perf_event_attr);
  11757. struct perf_buffer_params p = {};
  11758. struct perf_event_attr attr;
  11759. __u32 sample_period;
  11760. if (!OPTS_VALID(opts, perf_buffer_opts))
  11761. return libbpf_err_ptr(-EINVAL);
  11762. sample_period = OPTS_GET(opts, sample_period, 1);
  11763. if (!sample_period)
  11764. sample_period = 1;
  11765. memset(&attr, 0, attr_sz);
  11766. attr.size = attr_sz;
  11767. attr.config = PERF_COUNT_SW_BPF_OUTPUT;
  11768. attr.type = PERF_TYPE_SOFTWARE;
  11769. attr.sample_type = PERF_SAMPLE_RAW;
  11770. attr.wakeup_events = sample_period;
  11771. p.attr = &attr;
  11772. p.sample_cb = sample_cb;
  11773. p.lost_cb = lost_cb;
  11774. p.ctx = ctx;
  11775. return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
  11776. }
  11777. struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
  11778. struct perf_event_attr *attr,
  11779. perf_buffer_event_fn event_cb, void *ctx,
  11780. const struct perf_buffer_raw_opts *opts)
  11781. {
  11782. struct perf_buffer_params p = {};
  11783. if (!attr)
  11784. return libbpf_err_ptr(-EINVAL);
  11785. if (!OPTS_VALID(opts, perf_buffer_raw_opts))
  11786. return libbpf_err_ptr(-EINVAL);
  11787. p.attr = attr;
  11788. p.event_cb = event_cb;
  11789. p.ctx = ctx;
  11790. p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
  11791. p.cpus = OPTS_GET(opts, cpus, NULL);
  11792. p.map_keys = OPTS_GET(opts, map_keys, NULL);
  11793. return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
  11794. }
  11795. static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
  11796. struct perf_buffer_params *p)
  11797. {
  11798. const char *online_cpus_file = "/sys/devices/system/cpu/online";
  11799. struct bpf_map_info map;
  11800. struct perf_buffer *pb;
  11801. bool *online = NULL;
  11802. __u32 map_info_len;
  11803. int err, i, j, n;
  11804. if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
  11805. pr_warn("page count should be power of two, but is %zu\n",
  11806. page_cnt);
  11807. return ERR_PTR(-EINVAL);
  11808. }
  11809. /* best-effort sanity checks */
  11810. memset(&map, 0, sizeof(map));
  11811. map_info_len = sizeof(map);
  11812. err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
  11813. if (err) {
  11814. err = -errno;
  11815. /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
  11816. * -EBADFD, -EFAULT, or -E2BIG on real error
  11817. */
  11818. if (err != -EINVAL) {
  11819. pr_warn("failed to get map info for map FD %d: %s\n",
  11820. map_fd, errstr(err));
  11821. return ERR_PTR(err);
  11822. }
  11823. pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
  11824. map_fd);
  11825. } else {
  11826. if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
  11827. pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
  11828. map.name);
  11829. return ERR_PTR(-EINVAL);
  11830. }
  11831. }
  11832. pb = calloc(1, sizeof(*pb));
  11833. if (!pb)
  11834. return ERR_PTR(-ENOMEM);
  11835. pb->event_cb = p->event_cb;
  11836. pb->sample_cb = p->sample_cb;
  11837. pb->lost_cb = p->lost_cb;
  11838. pb->ctx = p->ctx;
  11839. pb->page_size = getpagesize();
  11840. pb->mmap_size = pb->page_size * page_cnt;
  11841. pb->map_fd = map_fd;
  11842. pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
  11843. if (pb->epoll_fd < 0) {
  11844. err = -errno;
  11845. pr_warn("failed to create epoll instance: %s\n",
  11846. errstr(err));
  11847. goto error;
  11848. }
  11849. if (p->cpu_cnt > 0) {
  11850. pb->cpu_cnt = p->cpu_cnt;
  11851. } else {
  11852. pb->cpu_cnt = libbpf_num_possible_cpus();
  11853. if (pb->cpu_cnt < 0) {
  11854. err = pb->cpu_cnt;
  11855. goto error;
  11856. }
  11857. if (map.max_entries && map.max_entries < pb->cpu_cnt)
  11858. pb->cpu_cnt = map.max_entries;
  11859. }
  11860. pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
  11861. if (!pb->events) {
  11862. err = -ENOMEM;
  11863. pr_warn("failed to allocate events: out of memory\n");
  11864. goto error;
  11865. }
  11866. pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
  11867. if (!pb->cpu_bufs) {
  11868. err = -ENOMEM;
  11869. pr_warn("failed to allocate buffers: out of memory\n");
  11870. goto error;
  11871. }
  11872. err = parse_cpu_mask_file(online_cpus_file, &online, &n);
  11873. if (err) {
  11874. pr_warn("failed to get online CPU mask: %s\n", errstr(err));
  11875. goto error;
  11876. }
  11877. for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
  11878. struct perf_cpu_buf *cpu_buf;
  11879. int cpu, map_key;
  11880. cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
  11881. map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
  11882. /* in case user didn't explicitly requested particular CPUs to
  11883. * be attached to, skip offline/not present CPUs
  11884. */
  11885. if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
  11886. continue;
  11887. cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
  11888. if (IS_ERR(cpu_buf)) {
  11889. err = PTR_ERR(cpu_buf);
  11890. goto error;
  11891. }
  11892. pb->cpu_bufs[j] = cpu_buf;
  11893. err = bpf_map_update_elem(pb->map_fd, &map_key,
  11894. &cpu_buf->fd, 0);
  11895. if (err) {
  11896. err = -errno;
  11897. pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
  11898. cpu, map_key, cpu_buf->fd,
  11899. errstr(err));
  11900. goto error;
  11901. }
  11902. pb->events[j].events = EPOLLIN;
  11903. pb->events[j].data.ptr = cpu_buf;
  11904. if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
  11905. &pb->events[j]) < 0) {
  11906. err = -errno;
  11907. pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
  11908. cpu, cpu_buf->fd,
  11909. errstr(err));
  11910. goto error;
  11911. }
  11912. j++;
  11913. }
  11914. pb->cpu_cnt = j;
  11915. free(online);
  11916. return pb;
  11917. error:
  11918. free(online);
  11919. if (pb)
  11920. perf_buffer__free(pb);
  11921. return ERR_PTR(err);
  11922. }
  11923. struct perf_sample_raw {
  11924. struct perf_event_header header;
  11925. uint32_t size;
  11926. char data[];
  11927. };
  11928. struct perf_sample_lost {
  11929. struct perf_event_header header;
  11930. uint64_t id;
  11931. uint64_t lost;
  11932. uint64_t sample_id;
  11933. };
  11934. static enum bpf_perf_event_ret
  11935. perf_buffer__process_record(struct perf_event_header *e, void *ctx)
  11936. {
  11937. struct perf_cpu_buf *cpu_buf = ctx;
  11938. struct perf_buffer *pb = cpu_buf->pb;
  11939. void *data = e;
  11940. /* user wants full control over parsing perf event */
  11941. if (pb->event_cb)
  11942. return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
  11943. switch (e->type) {
  11944. case PERF_RECORD_SAMPLE: {
  11945. struct perf_sample_raw *s = data;
  11946. if (pb->sample_cb)
  11947. pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
  11948. break;
  11949. }
  11950. case PERF_RECORD_LOST: {
  11951. struct perf_sample_lost *s = data;
  11952. if (pb->lost_cb)
  11953. pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
  11954. break;
  11955. }
  11956. default:
  11957. pr_warn("unknown perf sample type %d\n", e->type);
  11958. return LIBBPF_PERF_EVENT_ERROR;
  11959. }
  11960. return LIBBPF_PERF_EVENT_CONT;
  11961. }
  11962. static int perf_buffer__process_records(struct perf_buffer *pb,
  11963. struct perf_cpu_buf *cpu_buf)
  11964. {
  11965. enum bpf_perf_event_ret ret;
  11966. ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
  11967. pb->page_size, &cpu_buf->buf,
  11968. &cpu_buf->buf_size,
  11969. perf_buffer__process_record, cpu_buf);
  11970. if (ret != LIBBPF_PERF_EVENT_CONT)
  11971. return ret;
  11972. return 0;
  11973. }
  11974. int perf_buffer__epoll_fd(const struct perf_buffer *pb)
  11975. {
  11976. return pb->epoll_fd;
  11977. }
  11978. int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
  11979. {
  11980. int i, cnt, err;
  11981. cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
  11982. if (cnt < 0)
  11983. return -errno;
  11984. for (i = 0; i < cnt; i++) {
  11985. struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
  11986. err = perf_buffer__process_records(pb, cpu_buf);
  11987. if (err) {
  11988. pr_warn("error while processing records: %s\n", errstr(err));
  11989. return libbpf_err(err);
  11990. }
  11991. }
  11992. return cnt;
  11993. }
  11994. /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
  11995. * manager.
  11996. */
  11997. size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
  11998. {
  11999. return pb->cpu_cnt;
  12000. }
  12001. /*
  12002. * Return perf_event FD of a ring buffer in *buf_idx* slot of
  12003. * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
  12004. * select()/poll()/epoll() Linux syscalls.
  12005. */
  12006. int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
  12007. {
  12008. struct perf_cpu_buf *cpu_buf;
  12009. if (buf_idx >= pb->cpu_cnt)
  12010. return libbpf_err(-EINVAL);
  12011. cpu_buf = pb->cpu_bufs[buf_idx];
  12012. if (!cpu_buf)
  12013. return libbpf_err(-ENOENT);
  12014. return cpu_buf->fd;
  12015. }
  12016. int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
  12017. {
  12018. struct perf_cpu_buf *cpu_buf;
  12019. if (buf_idx >= pb->cpu_cnt)
  12020. return libbpf_err(-EINVAL);
  12021. cpu_buf = pb->cpu_bufs[buf_idx];
  12022. if (!cpu_buf)
  12023. return libbpf_err(-ENOENT);
  12024. *buf = cpu_buf->base;
  12025. *buf_size = pb->mmap_size;
  12026. return 0;
  12027. }
  12028. /*
  12029. * Consume data from perf ring buffer corresponding to slot *buf_idx* in
  12030. * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
  12031. * consume, do nothing and return success.
  12032. * Returns:
  12033. * - 0 on success;
  12034. * - <0 on failure.
  12035. */
  12036. int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
  12037. {
  12038. struct perf_cpu_buf *cpu_buf;
  12039. if (buf_idx >= pb->cpu_cnt)
  12040. return libbpf_err(-EINVAL);
  12041. cpu_buf = pb->cpu_bufs[buf_idx];
  12042. if (!cpu_buf)
  12043. return libbpf_err(-ENOENT);
  12044. return perf_buffer__process_records(pb, cpu_buf);
  12045. }
  12046. int perf_buffer__consume(struct perf_buffer *pb)
  12047. {
  12048. int i, err;
  12049. for (i = 0; i < pb->cpu_cnt; i++) {
  12050. struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
  12051. if (!cpu_buf)
  12052. continue;
  12053. err = perf_buffer__process_records(pb, cpu_buf);
  12054. if (err) {
  12055. pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
  12056. i, errstr(err));
  12057. return libbpf_err(err);
  12058. }
  12059. }
  12060. return 0;
  12061. }
  12062. int bpf_program__set_attach_target(struct bpf_program *prog,
  12063. int attach_prog_fd,
  12064. const char *attach_func_name)
  12065. {
  12066. int btf_obj_fd = 0, btf_id = 0, err;
  12067. if (!prog || attach_prog_fd < 0)
  12068. return libbpf_err(-EINVAL);
  12069. if (prog->obj->state >= OBJ_LOADED)
  12070. return libbpf_err(-EINVAL);
  12071. if (attach_prog_fd && !attach_func_name) {
  12072. /* Store attach_prog_fd. The BTF ID will be resolved later during
  12073. * the normal object/program load phase.
  12074. */
  12075. prog->attach_prog_fd = attach_prog_fd;
  12076. return 0;
  12077. }
  12078. if (attach_prog_fd) {
  12079. btf_id = libbpf_find_prog_btf_id(attach_func_name,
  12080. attach_prog_fd, prog->obj->token_fd);
  12081. if (btf_id < 0)
  12082. return libbpf_err(btf_id);
  12083. } else {
  12084. if (!attach_func_name)
  12085. return libbpf_err(-EINVAL);
  12086. /* load btf_vmlinux, if not yet */
  12087. err = bpf_object__load_vmlinux_btf(prog->obj, true);
  12088. if (err)
  12089. return libbpf_err(err);
  12090. err = find_kernel_btf_id(prog->obj, attach_func_name,
  12091. prog->expected_attach_type,
  12092. &btf_obj_fd, &btf_id);
  12093. if (err)
  12094. return libbpf_err(err);
  12095. }
  12096. prog->attach_btf_id = btf_id;
  12097. prog->attach_btf_obj_fd = btf_obj_fd;
  12098. prog->attach_prog_fd = attach_prog_fd;
  12099. return 0;
  12100. }
  12101. int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
  12102. struct bpf_prog_assoc_struct_ops_opts *opts)
  12103. {
  12104. int prog_fd, map_fd;
  12105. prog_fd = bpf_program__fd(prog);
  12106. if (prog_fd < 0) {
  12107. pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
  12108. prog->name);
  12109. return libbpf_err(-EINVAL);
  12110. }
  12111. if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
  12112. pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
  12113. return libbpf_err(-EINVAL);
  12114. }
  12115. map_fd = bpf_map__fd(map);
  12116. if (map_fd < 0) {
  12117. pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
  12118. return libbpf_err(-EINVAL);
  12119. }
  12120. if (!bpf_map__is_struct_ops(map)) {
  12121. pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
  12122. return libbpf_err(-EINVAL);
  12123. }
  12124. return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
  12125. }
  12126. int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
  12127. {
  12128. int err = 0, n, len, start, end = -1;
  12129. bool *tmp;
  12130. *mask = NULL;
  12131. *mask_sz = 0;
  12132. /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
  12133. while (*s) {
  12134. if (*s == ',' || *s == '\n') {
  12135. s++;
  12136. continue;
  12137. }
  12138. n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
  12139. if (n <= 0 || n > 2) {
  12140. pr_warn("Failed to get CPU range %s: %d\n", s, n);
  12141. err = -EINVAL;
  12142. goto cleanup;
  12143. } else if (n == 1) {
  12144. end = start;
  12145. }
  12146. if (start < 0 || start > end) {
  12147. pr_warn("Invalid CPU range [%d,%d] in %s\n",
  12148. start, end, s);
  12149. err = -EINVAL;
  12150. goto cleanup;
  12151. }
  12152. tmp = realloc(*mask, end + 1);
  12153. if (!tmp) {
  12154. err = -ENOMEM;
  12155. goto cleanup;
  12156. }
  12157. *mask = tmp;
  12158. memset(tmp + *mask_sz, 0, start - *mask_sz);
  12159. memset(tmp + start, 1, end - start + 1);
  12160. *mask_sz = end + 1;
  12161. s += len;
  12162. }
  12163. if (!*mask_sz) {
  12164. pr_warn("Empty CPU range\n");
  12165. return -EINVAL;
  12166. }
  12167. return 0;
  12168. cleanup:
  12169. free(*mask);
  12170. *mask = NULL;
  12171. return err;
  12172. }
  12173. int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
  12174. {
  12175. int fd, err = 0, len;
  12176. char buf[128];
  12177. fd = open(fcpu, O_RDONLY | O_CLOEXEC);
  12178. if (fd < 0) {
  12179. err = -errno;
  12180. pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
  12181. return err;
  12182. }
  12183. len = read(fd, buf, sizeof(buf));
  12184. close(fd);
  12185. if (len <= 0) {
  12186. err = len ? -errno : -EINVAL;
  12187. pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
  12188. return err;
  12189. }
  12190. if (len >= sizeof(buf)) {
  12191. pr_warn("CPU mask is too big in file %s\n", fcpu);
  12192. return -E2BIG;
  12193. }
  12194. buf[len] = '\0';
  12195. return parse_cpu_mask_str(buf, mask, mask_sz);
  12196. }
  12197. int libbpf_num_possible_cpus(void)
  12198. {
  12199. static const char *fcpu = "/sys/devices/system/cpu/possible";
  12200. static int cpus;
  12201. int err, n, i, tmp_cpus;
  12202. bool *mask;
  12203. tmp_cpus = READ_ONCE(cpus);
  12204. if (tmp_cpus > 0)
  12205. return tmp_cpus;
  12206. err = parse_cpu_mask_file(fcpu, &mask, &n);
  12207. if (err)
  12208. return libbpf_err(err);
  12209. tmp_cpus = 0;
  12210. for (i = 0; i < n; i++) {
  12211. if (mask[i])
  12212. tmp_cpus++;
  12213. }
  12214. free(mask);
  12215. WRITE_ONCE(cpus, tmp_cpus);
  12216. return tmp_cpus;
  12217. }
  12218. static int populate_skeleton_maps(const struct bpf_object *obj,
  12219. struct bpf_map_skeleton *maps,
  12220. size_t map_cnt, size_t map_skel_sz)
  12221. {
  12222. int i;
  12223. for (i = 0; i < map_cnt; i++) {
  12224. struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
  12225. struct bpf_map **map = map_skel->map;
  12226. const char *name = map_skel->name;
  12227. void **mmaped = map_skel->mmaped;
  12228. *map = bpf_object__find_map_by_name(obj, name);
  12229. if (!*map) {
  12230. pr_warn("failed to find skeleton map '%s'\n", name);
  12231. return -ESRCH;
  12232. }
  12233. /* externs shouldn't be pre-setup from user code */
  12234. if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
  12235. *mmaped = (*map)->mmaped;
  12236. }
  12237. return 0;
  12238. }
  12239. static int populate_skeleton_progs(const struct bpf_object *obj,
  12240. struct bpf_prog_skeleton *progs,
  12241. size_t prog_cnt, size_t prog_skel_sz)
  12242. {
  12243. int i;
  12244. for (i = 0; i < prog_cnt; i++) {
  12245. struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
  12246. struct bpf_program **prog = prog_skel->prog;
  12247. const char *name = prog_skel->name;
  12248. *prog = bpf_object__find_program_by_name(obj, name);
  12249. if (!*prog) {
  12250. pr_warn("failed to find skeleton program '%s'\n", name);
  12251. return -ESRCH;
  12252. }
  12253. }
  12254. return 0;
  12255. }
  12256. int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
  12257. const struct bpf_object_open_opts *opts)
  12258. {
  12259. struct bpf_object *obj;
  12260. int err;
  12261. obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
  12262. if (IS_ERR(obj)) {
  12263. err = PTR_ERR(obj);
  12264. pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
  12265. s->name, errstr(err));
  12266. return libbpf_err(err);
  12267. }
  12268. *s->obj = obj;
  12269. err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
  12270. if (err) {
  12271. pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
  12272. return libbpf_err(err);
  12273. }
  12274. err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
  12275. if (err) {
  12276. pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
  12277. return libbpf_err(err);
  12278. }
  12279. return 0;
  12280. }
  12281. int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
  12282. {
  12283. int err, len, var_idx, i;
  12284. const char *var_name;
  12285. const struct bpf_map *map;
  12286. struct btf *btf;
  12287. __u32 map_type_id;
  12288. const struct btf_type *map_type, *var_type;
  12289. const struct bpf_var_skeleton *var_skel;
  12290. struct btf_var_secinfo *var;
  12291. if (!s->obj)
  12292. return libbpf_err(-EINVAL);
  12293. btf = bpf_object__btf(s->obj);
  12294. if (!btf) {
  12295. pr_warn("subskeletons require BTF at runtime (object %s)\n",
  12296. bpf_object__name(s->obj));
  12297. return libbpf_err(-errno);
  12298. }
  12299. err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
  12300. if (err) {
  12301. pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
  12302. return libbpf_err(err);
  12303. }
  12304. err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
  12305. if (err) {
  12306. pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
  12307. return libbpf_err(err);
  12308. }
  12309. for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
  12310. var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
  12311. map = *var_skel->map;
  12312. map_type_id = bpf_map__btf_value_type_id(map);
  12313. map_type = btf__type_by_id(btf, map_type_id);
  12314. if (!btf_is_datasec(map_type)) {
  12315. pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
  12316. bpf_map__name(map),
  12317. __btf_kind_str(btf_kind(map_type)));
  12318. return libbpf_err(-EINVAL);
  12319. }
  12320. len = btf_vlen(map_type);
  12321. var = btf_var_secinfos(map_type);
  12322. for (i = 0; i < len; i++, var++) {
  12323. var_type = btf__type_by_id(btf, var->type);
  12324. var_name = btf__name_by_offset(btf, var_type->name_off);
  12325. if (strcmp(var_name, var_skel->name) == 0) {
  12326. *var_skel->addr = map->mmaped + var->offset;
  12327. break;
  12328. }
  12329. }
  12330. }
  12331. return 0;
  12332. }
  12333. void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
  12334. {
  12335. if (!s)
  12336. return;
  12337. free(s->maps);
  12338. free(s->progs);
  12339. free(s->vars);
  12340. free(s);
  12341. }
  12342. int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
  12343. {
  12344. int i, err;
  12345. err = bpf_object__load(*s->obj);
  12346. if (err) {
  12347. pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
  12348. return libbpf_err(err);
  12349. }
  12350. for (i = 0; i < s->map_cnt; i++) {
  12351. struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
  12352. struct bpf_map *map = *map_skel->map;
  12353. if (!map_skel->mmaped)
  12354. continue;
  12355. if (map->def.type == BPF_MAP_TYPE_ARENA)
  12356. *map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
  12357. else
  12358. *map_skel->mmaped = map->mmaped;
  12359. }
  12360. return 0;
  12361. }
  12362. int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
  12363. {
  12364. int i, err;
  12365. for (i = 0; i < s->prog_cnt; i++) {
  12366. struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
  12367. struct bpf_program *prog = *prog_skel->prog;
  12368. struct bpf_link **link = prog_skel->link;
  12369. if (!prog->autoload || !prog->autoattach)
  12370. continue;
  12371. /* auto-attaching not supported for this program */
  12372. if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
  12373. continue;
  12374. /* if user already set the link manually, don't attempt auto-attach */
  12375. if (*link)
  12376. continue;
  12377. err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
  12378. if (err) {
  12379. pr_warn("prog '%s': failed to auto-attach: %s\n",
  12380. bpf_program__name(prog), errstr(err));
  12381. return libbpf_err(err);
  12382. }
  12383. /* It's possible that for some SEC() definitions auto-attach
  12384. * is supported in some cases (e.g., if definition completely
  12385. * specifies target information), but is not in other cases.
  12386. * SEC("uprobe") is one such case. If user specified target
  12387. * binary and function name, such BPF program can be
  12388. * auto-attached. But if not, it shouldn't trigger skeleton's
  12389. * attach to fail. It should just be skipped.
  12390. * attach_fn signals such case with returning 0 (no error) and
  12391. * setting link to NULL.
  12392. */
  12393. }
  12394. for (i = 0; i < s->map_cnt; i++) {
  12395. struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
  12396. struct bpf_map *map = *map_skel->map;
  12397. struct bpf_link **link;
  12398. if (!map->autocreate || !map->autoattach)
  12399. continue;
  12400. /* only struct_ops maps can be attached */
  12401. if (!bpf_map__is_struct_ops(map))
  12402. continue;
  12403. /* skeleton is created with earlier version of bpftool, notify user */
  12404. if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
  12405. pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
  12406. bpf_map__name(map));
  12407. continue;
  12408. }
  12409. link = map_skel->link;
  12410. if (!link) {
  12411. pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
  12412. bpf_map__name(map));
  12413. continue;
  12414. }
  12415. if (*link)
  12416. continue;
  12417. *link = bpf_map__attach_struct_ops(map);
  12418. if (!*link) {
  12419. err = -errno;
  12420. pr_warn("map '%s': failed to auto-attach: %s\n",
  12421. bpf_map__name(map), errstr(err));
  12422. return libbpf_err(err);
  12423. }
  12424. }
  12425. return 0;
  12426. }
  12427. void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
  12428. {
  12429. int i;
  12430. for (i = 0; i < s->prog_cnt; i++) {
  12431. struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
  12432. struct bpf_link **link = prog_skel->link;
  12433. bpf_link__destroy(*link);
  12434. *link = NULL;
  12435. }
  12436. if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
  12437. return;
  12438. for (i = 0; i < s->map_cnt; i++) {
  12439. struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
  12440. struct bpf_link **link = map_skel->link;
  12441. if (link) {
  12442. bpf_link__destroy(*link);
  12443. *link = NULL;
  12444. }
  12445. }
  12446. }
  12447. void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
  12448. {
  12449. if (!s)
  12450. return;
  12451. bpf_object__detach_skeleton(s);
  12452. if (s->obj)
  12453. bpf_object__close(*s->obj);
  12454. free(s->maps);
  12455. free(s->progs);
  12456. free(s);
  12457. }