verifier.c 682 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  3. * Copyright (c) 2016 Facebook
  4. * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
  5. */
  6. #include <uapi/linux/btf.h>
  7. #include <linux/bpf-cgroup.h>
  8. #include <linux/kernel.h>
  9. #include <linux/types.h>
  10. #include <linux/slab.h>
  11. #include <linux/bpf.h>
  12. #include <linux/btf.h>
  13. #include <linux/bpf_verifier.h>
  14. #include <linux/filter.h>
  15. #include <net/netlink.h>
  16. #include <linux/file.h>
  17. #include <linux/vmalloc.h>
  18. #include <linux/stringify.h>
  19. #include <linux/bsearch.h>
  20. #include <linux/sort.h>
  21. #include <linux/perf_event.h>
  22. #include <linux/ctype.h>
  23. #include <linux/error-injection.h>
  24. #include <linux/bpf_lsm.h>
  25. #include <linux/btf_ids.h>
  26. #include <linux/poison.h>
  27. #include <linux/module.h>
  28. #include <linux/cpumask.h>
  29. #include <linux/bpf_mem_alloc.h>
  30. #include <net/xdp.h>
  31. #include <linux/trace_events.h>
  32. #include <linux/kallsyms.h>
  33. #include "disasm.h"
  34. static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
  35. #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
  36. [_id] = & _name ## _verifier_ops,
  37. #define BPF_MAP_TYPE(_id, _ops)
  38. #define BPF_LINK_TYPE(_id, _name)
  39. #include <linux/bpf_types.h>
  40. #undef BPF_PROG_TYPE
  41. #undef BPF_MAP_TYPE
  42. #undef BPF_LINK_TYPE
  43. };
  44. struct bpf_mem_alloc bpf_global_percpu_ma;
  45. static bool bpf_global_percpu_ma_set;
  46. /* bpf_check() is a static code analyzer that walks eBPF program
  47. * instruction by instruction and updates register/stack state.
  48. * All paths of conditional branches are analyzed until 'bpf_exit' insn.
  49. *
  50. * The first pass is depth-first-search to check that the program is a DAG.
  51. * It rejects the following programs:
  52. * - larger than BPF_MAXINSNS insns
  53. * - if loop is present (detected via back-edge)
  54. * - unreachable insns exist (shouldn't be a forest. program = one function)
  55. * - out of bounds or malformed jumps
  56. * The second pass is all possible path descent from the 1st insn.
  57. * Since it's analyzing all paths through the program, the length of the
  58. * analysis is limited to 64k insn, which may be hit even if total number of
  59. * insn is less then 4K, but there are too many branches that change stack/regs.
  60. * Number of 'branches to be analyzed' is limited to 1k
  61. *
  62. * On entry to each instruction, each register has a type, and the instruction
  63. * changes the types of the registers depending on instruction semantics.
  64. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
  65. * copied to R1.
  66. *
  67. * All registers are 64-bit.
  68. * R0 - return register
  69. * R1-R5 argument passing registers
  70. * R6-R9 callee saved registers
  71. * R10 - frame pointer read-only
  72. *
  73. * At the start of BPF program the register R1 contains a pointer to bpf_context
  74. * and has type PTR_TO_CTX.
  75. *
  76. * Verifier tracks arithmetic operations on pointers in case:
  77. * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
  78. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
  79. * 1st insn copies R10 (which has FRAME_PTR) type into R1
  80. * and 2nd arithmetic instruction is pattern matched to recognize
  81. * that it wants to construct a pointer to some element within stack.
  82. * So after 2nd insn, the register R1 has type PTR_TO_STACK
  83. * (and -20 constant is saved for further stack bounds checking).
  84. * Meaning that this reg is a pointer to stack plus known immediate constant.
  85. *
  86. * Most of the time the registers have SCALAR_VALUE type, which
  87. * means the register has some value, but it's not a valid pointer.
  88. * (like pointer plus pointer becomes SCALAR_VALUE type)
  89. *
  90. * When verifier sees load or store instructions the type of base register
  91. * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
  92. * four pointer types recognized by check_mem_access() function.
  93. *
  94. * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
  95. * and the range of [ptr, ptr + map's value_size) is accessible.
  96. *
  97. * registers used to pass values to function calls are checked against
  98. * function argument constraints.
  99. *
  100. * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
  101. * It means that the register type passed to this function must be
  102. * PTR_TO_STACK and it will be used inside the function as
  103. * 'pointer to map element key'
  104. *
  105. * For example the argument constraints for bpf_map_lookup_elem():
  106. * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  107. * .arg1_type = ARG_CONST_MAP_PTR,
  108. * .arg2_type = ARG_PTR_TO_MAP_KEY,
  109. *
  110. * ret_type says that this function returns 'pointer to map elem value or null'
  111. * function expects 1st argument to be a const pointer to 'struct bpf_map' and
  112. * 2nd argument should be a pointer to stack, which will be used inside
  113. * the helper function as a pointer to map element key.
  114. *
  115. * On the kernel side the helper function looks like:
  116. * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
  117. * {
  118. * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
  119. * void *key = (void *) (unsigned long) r2;
  120. * void *value;
  121. *
  122. * here kernel can access 'key' and 'map' pointers safely, knowing that
  123. * [key, key + map->key_size) bytes are valid and were initialized on
  124. * the stack of eBPF program.
  125. * }
  126. *
  127. * Corresponding eBPF program may look like:
  128. * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
  129. * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
  130. * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
  131. * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
  132. * here verifier looks at prototype of map_lookup_elem() and sees:
  133. * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
  134. * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
  135. *
  136. * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
  137. * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
  138. * and were initialized prior to this call.
  139. * If it's ok, then verifier allows this BPF_CALL insn and looks at
  140. * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
  141. * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
  142. * returns either pointer to map value or NULL.
  143. *
  144. * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
  145. * insn, the register holding that pointer in the true branch changes state to
  146. * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
  147. * branch. See check_cond_jmp_op().
  148. *
  149. * After the call R0 is set to return type of the function and registers R1-R5
  150. * are set to NOT_INIT to indicate that they are no longer readable.
  151. *
  152. * The following reference types represent a potential reference to a kernel
  153. * resource which, after first being allocated, must be checked and freed by
  154. * the BPF program:
  155. * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
  156. *
  157. * When the verifier sees a helper call return a reference type, it allocates a
  158. * pointer id for the reference and stores it in the current function state.
  159. * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
  160. * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
  161. * passes through a NULL-check conditional. For the branch wherein the state is
  162. * changed to CONST_IMM, the verifier releases the reference.
  163. *
  164. * For each helper function that allocates a reference, such as
  165. * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
  166. * bpf_sk_release(). When a reference type passes into the release function,
  167. * the verifier also releases the reference. If any unchecked or unreleased
  168. * reference remains at the end of the program, the verifier rejects it.
  169. */
  170. /* verifier_state + insn_idx are pushed to stack when branch is encountered */
  171. struct bpf_verifier_stack_elem {
  172. /* verifier state is 'st'
  173. * before processing instruction 'insn_idx'
  174. * and after processing instruction 'prev_insn_idx'
  175. */
  176. struct bpf_verifier_state st;
  177. int insn_idx;
  178. int prev_insn_idx;
  179. struct bpf_verifier_stack_elem *next;
  180. /* length of verifier log at the time this state was pushed on stack */
  181. u32 log_pos;
  182. };
  183. #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
  184. #define BPF_COMPLEXITY_LIMIT_STATES 64
  185. #define BPF_MAP_KEY_POISON (1ULL << 63)
  186. #define BPF_MAP_KEY_SEEN (1ULL << 62)
  187. #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512
  188. static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
  189. static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
  190. static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
  191. static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
  192. static int ref_set_non_owning(struct bpf_verifier_env *env,
  193. struct bpf_reg_state *reg);
  194. static void specialize_kfunc(struct bpf_verifier_env *env,
  195. u32 func_id, u16 offset, unsigned long *addr);
  196. static bool is_trusted_reg(const struct bpf_reg_state *reg);
  197. static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
  198. {
  199. return aux->map_ptr_state.poison;
  200. }
  201. static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
  202. {
  203. return aux->map_ptr_state.unpriv;
  204. }
  205. static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
  206. struct bpf_map *map,
  207. bool unpriv, bool poison)
  208. {
  209. unpriv |= bpf_map_ptr_unpriv(aux);
  210. aux->map_ptr_state.unpriv = unpriv;
  211. aux->map_ptr_state.poison = poison;
  212. aux->map_ptr_state.map_ptr = map;
  213. }
  214. static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
  215. {
  216. return aux->map_key_state & BPF_MAP_KEY_POISON;
  217. }
  218. static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
  219. {
  220. return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
  221. }
  222. static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
  223. {
  224. return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
  225. }
  226. static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
  227. {
  228. bool poisoned = bpf_map_key_poisoned(aux);
  229. aux->map_key_state = state | BPF_MAP_KEY_SEEN |
  230. (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
  231. }
  232. static bool bpf_helper_call(const struct bpf_insn *insn)
  233. {
  234. return insn->code == (BPF_JMP | BPF_CALL) &&
  235. insn->src_reg == 0;
  236. }
  237. static bool bpf_pseudo_call(const struct bpf_insn *insn)
  238. {
  239. return insn->code == (BPF_JMP | BPF_CALL) &&
  240. insn->src_reg == BPF_PSEUDO_CALL;
  241. }
  242. static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
  243. {
  244. return insn->code == (BPF_JMP | BPF_CALL) &&
  245. insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
  246. }
  247. struct bpf_call_arg_meta {
  248. struct bpf_map *map_ptr;
  249. bool raw_mode;
  250. bool pkt_access;
  251. u8 release_regno;
  252. int regno;
  253. int access_size;
  254. int mem_size;
  255. u64 msize_max_value;
  256. int ref_obj_id;
  257. int dynptr_id;
  258. int map_uid;
  259. int func_id;
  260. struct btf *btf;
  261. u32 btf_id;
  262. struct btf *ret_btf;
  263. u32 ret_btf_id;
  264. u32 subprogno;
  265. struct btf_field *kptr_field;
  266. };
  267. struct bpf_kfunc_call_arg_meta {
  268. /* In parameters */
  269. struct btf *btf;
  270. u32 func_id;
  271. u32 kfunc_flags;
  272. const struct btf_type *func_proto;
  273. const char *func_name;
  274. /* Out parameters */
  275. u32 ref_obj_id;
  276. u8 release_regno;
  277. bool r0_rdonly;
  278. u32 ret_btf_id;
  279. u64 r0_size;
  280. u32 subprogno;
  281. struct {
  282. u64 value;
  283. bool found;
  284. } arg_constant;
  285. /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
  286. * generally to pass info about user-defined local kptr types to later
  287. * verification logic
  288. * bpf_obj_drop/bpf_percpu_obj_drop
  289. * Record the local kptr type to be drop'd
  290. * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
  291. * Record the local kptr type to be refcount_incr'd and use
  292. * arg_owning_ref to determine whether refcount_acquire should be
  293. * fallible
  294. */
  295. struct btf *arg_btf;
  296. u32 arg_btf_id;
  297. bool arg_owning_ref;
  298. struct {
  299. struct btf_field *field;
  300. } arg_list_head;
  301. struct {
  302. struct btf_field *field;
  303. } arg_rbtree_root;
  304. struct {
  305. enum bpf_dynptr_type type;
  306. u32 id;
  307. u32 ref_obj_id;
  308. } initialized_dynptr;
  309. struct {
  310. u8 spi;
  311. u8 frameno;
  312. } iter;
  313. struct {
  314. struct bpf_map *ptr;
  315. int uid;
  316. } map;
  317. u64 mem_size;
  318. };
  319. struct btf *btf_vmlinux;
  320. static const char *btf_type_name(const struct btf *btf, u32 id)
  321. {
  322. return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
  323. }
  324. static DEFINE_MUTEX(bpf_verifier_lock);
  325. static DEFINE_MUTEX(bpf_percpu_ma_lock);
  326. __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
  327. {
  328. struct bpf_verifier_env *env = private_data;
  329. va_list args;
  330. if (!bpf_verifier_log_needed(&env->log))
  331. return;
  332. va_start(args, fmt);
  333. bpf_verifier_vlog(&env->log, fmt, args);
  334. va_end(args);
  335. }
  336. static void verbose_invalid_scalar(struct bpf_verifier_env *env,
  337. struct bpf_reg_state *reg,
  338. struct bpf_retval_range range, const char *ctx,
  339. const char *reg_name)
  340. {
  341. bool unknown = true;
  342. verbose(env, "%s the register %s has", ctx, reg_name);
  343. if (reg->smin_value > S64_MIN) {
  344. verbose(env, " smin=%lld", reg->smin_value);
  345. unknown = false;
  346. }
  347. if (reg->smax_value < S64_MAX) {
  348. verbose(env, " smax=%lld", reg->smax_value);
  349. unknown = false;
  350. }
  351. if (unknown)
  352. verbose(env, " unknown scalar value");
  353. verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
  354. }
  355. static bool reg_not_null(const struct bpf_reg_state *reg)
  356. {
  357. enum bpf_reg_type type;
  358. type = reg->type;
  359. if (type_may_be_null(type))
  360. return false;
  361. type = base_type(type);
  362. return type == PTR_TO_SOCKET ||
  363. type == PTR_TO_TCP_SOCK ||
  364. type == PTR_TO_MAP_VALUE ||
  365. type == PTR_TO_MAP_KEY ||
  366. type == PTR_TO_SOCK_COMMON ||
  367. (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
  368. type == PTR_TO_MEM ||
  369. type == CONST_PTR_TO_MAP;
  370. }
  371. static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
  372. {
  373. struct btf_record *rec = NULL;
  374. struct btf_struct_meta *meta;
  375. if (reg->type == PTR_TO_MAP_VALUE) {
  376. rec = reg->map_ptr->record;
  377. } else if (type_is_ptr_alloc_obj(reg->type)) {
  378. meta = btf_find_struct_meta(reg->btf, reg->btf_id);
  379. if (meta)
  380. rec = meta->record;
  381. }
  382. return rec;
  383. }
  384. static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
  385. {
  386. struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
  387. return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
  388. }
  389. static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
  390. {
  391. struct bpf_func_info *info;
  392. if (!env->prog->aux->func_info)
  393. return "";
  394. info = &env->prog->aux->func_info[subprog];
  395. return btf_type_name(env->prog->aux->btf, info->type_id);
  396. }
  397. static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
  398. {
  399. struct bpf_subprog_info *info = subprog_info(env, subprog);
  400. info->is_cb = true;
  401. info->is_async_cb = true;
  402. info->is_exception_cb = true;
  403. }
  404. static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
  405. {
  406. return subprog_info(env, subprog)->is_exception_cb;
  407. }
  408. static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
  409. {
  410. return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
  411. }
  412. static bool type_is_rdonly_mem(u32 type)
  413. {
  414. return type & MEM_RDONLY;
  415. }
  416. static bool is_acquire_function(enum bpf_func_id func_id,
  417. const struct bpf_map *map)
  418. {
  419. enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
  420. if (func_id == BPF_FUNC_sk_lookup_tcp ||
  421. func_id == BPF_FUNC_sk_lookup_udp ||
  422. func_id == BPF_FUNC_skc_lookup_tcp ||
  423. func_id == BPF_FUNC_ringbuf_reserve ||
  424. func_id == BPF_FUNC_kptr_xchg)
  425. return true;
  426. if (func_id == BPF_FUNC_map_lookup_elem &&
  427. (map_type == BPF_MAP_TYPE_SOCKMAP ||
  428. map_type == BPF_MAP_TYPE_SOCKHASH))
  429. return true;
  430. return false;
  431. }
  432. static bool is_ptr_cast_function(enum bpf_func_id func_id)
  433. {
  434. return func_id == BPF_FUNC_tcp_sock ||
  435. func_id == BPF_FUNC_sk_fullsock ||
  436. func_id == BPF_FUNC_skc_to_tcp_sock ||
  437. func_id == BPF_FUNC_skc_to_tcp6_sock ||
  438. func_id == BPF_FUNC_skc_to_udp6_sock ||
  439. func_id == BPF_FUNC_skc_to_mptcp_sock ||
  440. func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
  441. func_id == BPF_FUNC_skc_to_tcp_request_sock;
  442. }
  443. static bool is_dynptr_ref_function(enum bpf_func_id func_id)
  444. {
  445. return func_id == BPF_FUNC_dynptr_data;
  446. }
  447. static bool is_sync_callback_calling_kfunc(u32 btf_id);
  448. static bool is_async_callback_calling_kfunc(u32 btf_id);
  449. static bool is_callback_calling_kfunc(u32 btf_id);
  450. static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
  451. static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
  452. static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
  453. {
  454. return func_id == BPF_FUNC_for_each_map_elem ||
  455. func_id == BPF_FUNC_find_vma ||
  456. func_id == BPF_FUNC_loop ||
  457. func_id == BPF_FUNC_user_ringbuf_drain;
  458. }
  459. static bool is_async_callback_calling_function(enum bpf_func_id func_id)
  460. {
  461. return func_id == BPF_FUNC_timer_set_callback;
  462. }
  463. static bool is_callback_calling_function(enum bpf_func_id func_id)
  464. {
  465. return is_sync_callback_calling_function(func_id) ||
  466. is_async_callback_calling_function(func_id);
  467. }
  468. static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
  469. {
  470. return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
  471. (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
  472. }
  473. static bool is_async_callback_calling_insn(struct bpf_insn *insn)
  474. {
  475. return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
  476. (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
  477. }
  478. static bool is_may_goto_insn(struct bpf_insn *insn)
  479. {
  480. return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
  481. }
  482. static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
  483. {
  484. return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
  485. }
  486. static bool is_storage_get_function(enum bpf_func_id func_id)
  487. {
  488. return func_id == BPF_FUNC_sk_storage_get ||
  489. func_id == BPF_FUNC_inode_storage_get ||
  490. func_id == BPF_FUNC_task_storage_get ||
  491. func_id == BPF_FUNC_cgrp_storage_get;
  492. }
  493. static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
  494. const struct bpf_map *map)
  495. {
  496. int ref_obj_uses = 0;
  497. if (is_ptr_cast_function(func_id))
  498. ref_obj_uses++;
  499. if (is_acquire_function(func_id, map))
  500. ref_obj_uses++;
  501. if (is_dynptr_ref_function(func_id))
  502. ref_obj_uses++;
  503. return ref_obj_uses > 1;
  504. }
  505. static bool is_cmpxchg_insn(const struct bpf_insn *insn)
  506. {
  507. return BPF_CLASS(insn->code) == BPF_STX &&
  508. BPF_MODE(insn->code) == BPF_ATOMIC &&
  509. insn->imm == BPF_CMPXCHG;
  510. }
  511. static int __get_spi(s32 off)
  512. {
  513. return (-off - 1) / BPF_REG_SIZE;
  514. }
  515. static struct bpf_func_state *func(struct bpf_verifier_env *env,
  516. const struct bpf_reg_state *reg)
  517. {
  518. struct bpf_verifier_state *cur = env->cur_state;
  519. return cur->frame[reg->frameno];
  520. }
  521. static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
  522. {
  523. int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
  524. /* We need to check that slots between [spi - nr_slots + 1, spi] are
  525. * within [0, allocated_stack).
  526. *
  527. * Please note that the spi grows downwards. For example, a dynptr
  528. * takes the size of two stack slots; the first slot will be at
  529. * spi and the second slot will be at spi - 1.
  530. */
  531. return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
  532. }
  533. static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  534. const char *obj_kind, int nr_slots)
  535. {
  536. int off, spi;
  537. if (!tnum_is_const(reg->var_off)) {
  538. verbose(env, "%s has to be at a constant offset\n", obj_kind);
  539. return -EINVAL;
  540. }
  541. off = reg->off + reg->var_off.value;
  542. if (off % BPF_REG_SIZE) {
  543. verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
  544. return -EINVAL;
  545. }
  546. spi = __get_spi(off);
  547. if (spi + 1 < nr_slots) {
  548. verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
  549. return -EINVAL;
  550. }
  551. if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
  552. return -ERANGE;
  553. return spi;
  554. }
  555. static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  556. {
  557. return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
  558. }
  559. static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
  560. {
  561. return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
  562. }
  563. static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
  564. {
  565. switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
  566. case DYNPTR_TYPE_LOCAL:
  567. return BPF_DYNPTR_TYPE_LOCAL;
  568. case DYNPTR_TYPE_RINGBUF:
  569. return BPF_DYNPTR_TYPE_RINGBUF;
  570. case DYNPTR_TYPE_SKB:
  571. return BPF_DYNPTR_TYPE_SKB;
  572. case DYNPTR_TYPE_XDP:
  573. return BPF_DYNPTR_TYPE_XDP;
  574. default:
  575. return BPF_DYNPTR_TYPE_INVALID;
  576. }
  577. }
  578. static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
  579. {
  580. switch (type) {
  581. case BPF_DYNPTR_TYPE_LOCAL:
  582. return DYNPTR_TYPE_LOCAL;
  583. case BPF_DYNPTR_TYPE_RINGBUF:
  584. return DYNPTR_TYPE_RINGBUF;
  585. case BPF_DYNPTR_TYPE_SKB:
  586. return DYNPTR_TYPE_SKB;
  587. case BPF_DYNPTR_TYPE_XDP:
  588. return DYNPTR_TYPE_XDP;
  589. default:
  590. return 0;
  591. }
  592. }
  593. static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
  594. {
  595. return type == BPF_DYNPTR_TYPE_RINGBUF;
  596. }
  597. static void __mark_dynptr_reg(struct bpf_reg_state *reg,
  598. enum bpf_dynptr_type type,
  599. bool first_slot, int dynptr_id);
  600. static void __mark_reg_not_init(const struct bpf_verifier_env *env,
  601. struct bpf_reg_state *reg);
  602. static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
  603. struct bpf_reg_state *sreg1,
  604. struct bpf_reg_state *sreg2,
  605. enum bpf_dynptr_type type)
  606. {
  607. int id = ++env->id_gen;
  608. __mark_dynptr_reg(sreg1, type, true, id);
  609. __mark_dynptr_reg(sreg2, type, false, id);
  610. }
  611. static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
  612. struct bpf_reg_state *reg,
  613. enum bpf_dynptr_type type)
  614. {
  615. __mark_dynptr_reg(reg, type, true, ++env->id_gen);
  616. }
  617. static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
  618. struct bpf_func_state *state, int spi);
  619. static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  620. enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
  621. {
  622. struct bpf_func_state *state = func(env, reg);
  623. enum bpf_dynptr_type type;
  624. int spi, i, err;
  625. spi = dynptr_get_spi(env, reg);
  626. if (spi < 0)
  627. return spi;
  628. /* We cannot assume both spi and spi - 1 belong to the same dynptr,
  629. * hence we need to call destroy_if_dynptr_stack_slot twice for both,
  630. * to ensure that for the following example:
  631. * [d1][d1][d2][d2]
  632. * spi 3 2 1 0
  633. * So marking spi = 2 should lead to destruction of both d1 and d2. In
  634. * case they do belong to same dynptr, second call won't see slot_type
  635. * as STACK_DYNPTR and will simply skip destruction.
  636. */
  637. err = destroy_if_dynptr_stack_slot(env, state, spi);
  638. if (err)
  639. return err;
  640. err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
  641. if (err)
  642. return err;
  643. for (i = 0; i < BPF_REG_SIZE; i++) {
  644. state->stack[spi].slot_type[i] = STACK_DYNPTR;
  645. state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
  646. }
  647. type = arg_to_dynptr_type(arg_type);
  648. if (type == BPF_DYNPTR_TYPE_INVALID)
  649. return -EINVAL;
  650. mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
  651. &state->stack[spi - 1].spilled_ptr, type);
  652. if (dynptr_type_refcounted(type)) {
  653. /* The id is used to track proper releasing */
  654. int id;
  655. if (clone_ref_obj_id)
  656. id = clone_ref_obj_id;
  657. else
  658. id = acquire_reference_state(env, insn_idx);
  659. if (id < 0)
  660. return id;
  661. state->stack[spi].spilled_ptr.ref_obj_id = id;
  662. state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
  663. }
  664. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  665. state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
  666. return 0;
  667. }
  668. static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
  669. {
  670. int i;
  671. for (i = 0; i < BPF_REG_SIZE; i++) {
  672. state->stack[spi].slot_type[i] = STACK_INVALID;
  673. state->stack[spi - 1].slot_type[i] = STACK_INVALID;
  674. }
  675. __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
  676. __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
  677. /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
  678. *
  679. * While we don't allow reading STACK_INVALID, it is still possible to
  680. * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
  681. * helpers or insns can do partial read of that part without failing,
  682. * but check_stack_range_initialized, check_stack_read_var_off, and
  683. * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
  684. * the slot conservatively. Hence we need to prevent those liveness
  685. * marking walks.
  686. *
  687. * This was not a problem before because STACK_INVALID is only set by
  688. * default (where the default reg state has its reg->parent as NULL), or
  689. * in clean_live_states after REG_LIVE_DONE (at which point
  690. * mark_reg_read won't walk reg->parent chain), but not randomly during
  691. * verifier state exploration (like we did above). Hence, for our case
  692. * parentage chain will still be live (i.e. reg->parent may be
  693. * non-NULL), while earlier reg->parent was NULL, so we need
  694. * REG_LIVE_WRITTEN to screen off read marker propagation when it is
  695. * done later on reads or by mark_dynptr_read as well to unnecessary
  696. * mark registers in verifier state.
  697. */
  698. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  699. state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
  700. }
  701. static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  702. {
  703. struct bpf_func_state *state = func(env, reg);
  704. int spi, ref_obj_id, i;
  705. spi = dynptr_get_spi(env, reg);
  706. if (spi < 0)
  707. return spi;
  708. if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
  709. invalidate_dynptr(env, state, spi);
  710. return 0;
  711. }
  712. ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
  713. /* If the dynptr has a ref_obj_id, then we need to invalidate
  714. * two things:
  715. *
  716. * 1) Any dynptrs with a matching ref_obj_id (clones)
  717. * 2) Any slices derived from this dynptr.
  718. */
  719. /* Invalidate any slices associated with this dynptr */
  720. WARN_ON_ONCE(release_reference(env, ref_obj_id));
  721. /* Invalidate any dynptr clones */
  722. for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  723. if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
  724. continue;
  725. /* it should always be the case that if the ref obj id
  726. * matches then the stack slot also belongs to a
  727. * dynptr
  728. */
  729. if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
  730. verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
  731. return -EFAULT;
  732. }
  733. if (state->stack[i].spilled_ptr.dynptr.first_slot)
  734. invalidate_dynptr(env, state, i);
  735. }
  736. return 0;
  737. }
  738. static void __mark_reg_unknown(const struct bpf_verifier_env *env,
  739. struct bpf_reg_state *reg);
  740. static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  741. {
  742. if (!env->allow_ptr_leaks)
  743. __mark_reg_not_init(env, reg);
  744. else
  745. __mark_reg_unknown(env, reg);
  746. }
  747. static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
  748. struct bpf_func_state *state, int spi)
  749. {
  750. struct bpf_func_state *fstate;
  751. struct bpf_reg_state *dreg;
  752. int i, dynptr_id;
  753. /* We always ensure that STACK_DYNPTR is never set partially,
  754. * hence just checking for slot_type[0] is enough. This is
  755. * different for STACK_SPILL, where it may be only set for
  756. * 1 byte, so code has to use is_spilled_reg.
  757. */
  758. if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
  759. return 0;
  760. /* Reposition spi to first slot */
  761. if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
  762. spi = spi + 1;
  763. if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
  764. verbose(env, "cannot overwrite referenced dynptr\n");
  765. return -EINVAL;
  766. }
  767. mark_stack_slot_scratched(env, spi);
  768. mark_stack_slot_scratched(env, spi - 1);
  769. /* Writing partially to one dynptr stack slot destroys both. */
  770. for (i = 0; i < BPF_REG_SIZE; i++) {
  771. state->stack[spi].slot_type[i] = STACK_INVALID;
  772. state->stack[spi - 1].slot_type[i] = STACK_INVALID;
  773. }
  774. dynptr_id = state->stack[spi].spilled_ptr.id;
  775. /* Invalidate any slices associated with this dynptr */
  776. bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
  777. /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
  778. if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
  779. continue;
  780. if (dreg->dynptr_id == dynptr_id)
  781. mark_reg_invalid(env, dreg);
  782. }));
  783. /* Do not release reference state, we are destroying dynptr on stack,
  784. * not using some helper to release it. Just reset register.
  785. */
  786. __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
  787. __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
  788. /* Same reason as unmark_stack_slots_dynptr above */
  789. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  790. state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
  791. return 0;
  792. }
  793. static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  794. {
  795. int spi;
  796. if (reg->type == CONST_PTR_TO_DYNPTR)
  797. return false;
  798. spi = dynptr_get_spi(env, reg);
  799. /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
  800. * error because this just means the stack state hasn't been updated yet.
  801. * We will do check_mem_access to check and update stack bounds later.
  802. */
  803. if (spi < 0 && spi != -ERANGE)
  804. return false;
  805. /* We don't need to check if the stack slots are marked by previous
  806. * dynptr initializations because we allow overwriting existing unreferenced
  807. * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
  808. * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
  809. * touching are completely destructed before we reinitialize them for a new
  810. * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
  811. * instead of delaying it until the end where the user will get "Unreleased
  812. * reference" error.
  813. */
  814. return true;
  815. }
  816. static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  817. {
  818. struct bpf_func_state *state = func(env, reg);
  819. int i, spi;
  820. /* This already represents first slot of initialized bpf_dynptr.
  821. *
  822. * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
  823. * check_func_arg_reg_off's logic, so we don't need to check its
  824. * offset and alignment.
  825. */
  826. if (reg->type == CONST_PTR_TO_DYNPTR)
  827. return true;
  828. spi = dynptr_get_spi(env, reg);
  829. if (spi < 0)
  830. return false;
  831. if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
  832. return false;
  833. for (i = 0; i < BPF_REG_SIZE; i++) {
  834. if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
  835. state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
  836. return false;
  837. }
  838. return true;
  839. }
  840. static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  841. enum bpf_arg_type arg_type)
  842. {
  843. struct bpf_func_state *state = func(env, reg);
  844. enum bpf_dynptr_type dynptr_type;
  845. int spi;
  846. /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
  847. if (arg_type == ARG_PTR_TO_DYNPTR)
  848. return true;
  849. dynptr_type = arg_to_dynptr_type(arg_type);
  850. if (reg->type == CONST_PTR_TO_DYNPTR) {
  851. return reg->dynptr.type == dynptr_type;
  852. } else {
  853. spi = dynptr_get_spi(env, reg);
  854. if (spi < 0)
  855. return false;
  856. return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
  857. }
  858. }
  859. static void __mark_reg_known_zero(struct bpf_reg_state *reg);
  860. static bool in_rcu_cs(struct bpf_verifier_env *env);
  861. static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
  862. static int mark_stack_slots_iter(struct bpf_verifier_env *env,
  863. struct bpf_kfunc_call_arg_meta *meta,
  864. struct bpf_reg_state *reg, int insn_idx,
  865. struct btf *btf, u32 btf_id, int nr_slots)
  866. {
  867. struct bpf_func_state *state = func(env, reg);
  868. int spi, i, j, id;
  869. spi = iter_get_spi(env, reg, nr_slots);
  870. if (spi < 0)
  871. return spi;
  872. id = acquire_reference_state(env, insn_idx);
  873. if (id < 0)
  874. return id;
  875. for (i = 0; i < nr_slots; i++) {
  876. struct bpf_stack_state *slot = &state->stack[spi - i];
  877. struct bpf_reg_state *st = &slot->spilled_ptr;
  878. __mark_reg_known_zero(st);
  879. st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
  880. if (is_kfunc_rcu_protected(meta)) {
  881. if (in_rcu_cs(env))
  882. st->type |= MEM_RCU;
  883. else
  884. st->type |= PTR_UNTRUSTED;
  885. }
  886. st->live |= REG_LIVE_WRITTEN;
  887. st->ref_obj_id = i == 0 ? id : 0;
  888. st->iter.btf = btf;
  889. st->iter.btf_id = btf_id;
  890. st->iter.state = BPF_ITER_STATE_ACTIVE;
  891. st->iter.depth = 0;
  892. for (j = 0; j < BPF_REG_SIZE; j++)
  893. slot->slot_type[j] = STACK_ITER;
  894. mark_stack_slot_scratched(env, spi - i);
  895. }
  896. return 0;
  897. }
  898. static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
  899. struct bpf_reg_state *reg, int nr_slots)
  900. {
  901. struct bpf_func_state *state = func(env, reg);
  902. int spi, i, j;
  903. spi = iter_get_spi(env, reg, nr_slots);
  904. if (spi < 0)
  905. return spi;
  906. for (i = 0; i < nr_slots; i++) {
  907. struct bpf_stack_state *slot = &state->stack[spi - i];
  908. struct bpf_reg_state *st = &slot->spilled_ptr;
  909. if (i == 0)
  910. WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
  911. __mark_reg_not_init(env, st);
  912. /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
  913. st->live |= REG_LIVE_WRITTEN;
  914. for (j = 0; j < BPF_REG_SIZE; j++)
  915. slot->slot_type[j] = STACK_INVALID;
  916. mark_stack_slot_scratched(env, spi - i);
  917. }
  918. return 0;
  919. }
  920. static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
  921. struct bpf_reg_state *reg, int nr_slots)
  922. {
  923. struct bpf_func_state *state = func(env, reg);
  924. int spi, i, j;
  925. /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
  926. * will do check_mem_access to check and update stack bounds later, so
  927. * return true for that case.
  928. */
  929. spi = iter_get_spi(env, reg, nr_slots);
  930. if (spi == -ERANGE)
  931. return true;
  932. if (spi < 0)
  933. return false;
  934. for (i = 0; i < nr_slots; i++) {
  935. struct bpf_stack_state *slot = &state->stack[spi - i];
  936. for (j = 0; j < BPF_REG_SIZE; j++)
  937. if (slot->slot_type[j] == STACK_ITER)
  938. return false;
  939. }
  940. return true;
  941. }
  942. static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  943. struct btf *btf, u32 btf_id, int nr_slots)
  944. {
  945. struct bpf_func_state *state = func(env, reg);
  946. int spi, i, j;
  947. spi = iter_get_spi(env, reg, nr_slots);
  948. if (spi < 0)
  949. return -EINVAL;
  950. for (i = 0; i < nr_slots; i++) {
  951. struct bpf_stack_state *slot = &state->stack[spi - i];
  952. struct bpf_reg_state *st = &slot->spilled_ptr;
  953. if (st->type & PTR_UNTRUSTED)
  954. return -EPROTO;
  955. /* only main (first) slot has ref_obj_id set */
  956. if (i == 0 && !st->ref_obj_id)
  957. return -EINVAL;
  958. if (i != 0 && st->ref_obj_id)
  959. return -EINVAL;
  960. if (st->iter.btf != btf || st->iter.btf_id != btf_id)
  961. return -EINVAL;
  962. for (j = 0; j < BPF_REG_SIZE; j++)
  963. if (slot->slot_type[j] != STACK_ITER)
  964. return -EINVAL;
  965. }
  966. return 0;
  967. }
  968. /* Check if given stack slot is "special":
  969. * - spilled register state (STACK_SPILL);
  970. * - dynptr state (STACK_DYNPTR);
  971. * - iter state (STACK_ITER).
  972. */
  973. static bool is_stack_slot_special(const struct bpf_stack_state *stack)
  974. {
  975. enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
  976. switch (type) {
  977. case STACK_SPILL:
  978. case STACK_DYNPTR:
  979. case STACK_ITER:
  980. return true;
  981. case STACK_INVALID:
  982. case STACK_MISC:
  983. case STACK_ZERO:
  984. return false;
  985. default:
  986. WARN_ONCE(1, "unknown stack slot type %d\n", type);
  987. return true;
  988. }
  989. }
  990. /* The reg state of a pointer or a bounded scalar was saved when
  991. * it was spilled to the stack.
  992. */
  993. static bool is_spilled_reg(const struct bpf_stack_state *stack)
  994. {
  995. return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
  996. }
  997. static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
  998. {
  999. return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
  1000. stack->spilled_ptr.type == SCALAR_VALUE;
  1001. }
  1002. static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
  1003. {
  1004. return stack->slot_type[0] == STACK_SPILL &&
  1005. stack->spilled_ptr.type == SCALAR_VALUE;
  1006. }
  1007. /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
  1008. * case they are equivalent, or it's STACK_ZERO, in which case we preserve
  1009. * more precise STACK_ZERO.
  1010. * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
  1011. * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
  1012. * unnecessary as both are considered equivalent when loading data and pruning,
  1013. * in case of unprivileged mode it will be incorrect to allow reads of invalid
  1014. * slots.
  1015. */
  1016. static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
  1017. {
  1018. if (*stype == STACK_ZERO)
  1019. return;
  1020. if (*stype == STACK_INVALID)
  1021. return;
  1022. *stype = STACK_MISC;
  1023. }
  1024. static void scrub_spilled_slot(u8 *stype)
  1025. {
  1026. if (*stype != STACK_INVALID)
  1027. *stype = STACK_MISC;
  1028. }
  1029. /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
  1030. * small to hold src. This is different from krealloc since we don't want to preserve
  1031. * the contents of dst.
  1032. *
  1033. * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
  1034. * not be allocated.
  1035. */
  1036. static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
  1037. {
  1038. size_t alloc_bytes;
  1039. void *orig = dst;
  1040. size_t bytes;
  1041. if (ZERO_OR_NULL_PTR(src))
  1042. goto out;
  1043. if (unlikely(check_mul_overflow(n, size, &bytes)))
  1044. return NULL;
  1045. alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
  1046. dst = krealloc(orig, alloc_bytes, flags);
  1047. if (!dst) {
  1048. kfree(orig);
  1049. return NULL;
  1050. }
  1051. memcpy(dst, src, bytes);
  1052. out:
  1053. return dst ? dst : ZERO_SIZE_PTR;
  1054. }
  1055. /* resize an array from old_n items to new_n items. the array is reallocated if it's too
  1056. * small to hold new_n items. new items are zeroed out if the array grows.
  1057. *
  1058. * Contrary to krealloc_array, does not free arr if new_n is zero.
  1059. */
  1060. static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
  1061. {
  1062. size_t alloc_size;
  1063. void *new_arr;
  1064. if (!new_n || old_n == new_n)
  1065. goto out;
  1066. alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
  1067. new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
  1068. if (!new_arr) {
  1069. kfree(arr);
  1070. return NULL;
  1071. }
  1072. arr = new_arr;
  1073. if (new_n > old_n)
  1074. memset(arr + old_n * size, 0, (new_n - old_n) * size);
  1075. out:
  1076. return arr ? arr : ZERO_SIZE_PTR;
  1077. }
  1078. static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
  1079. {
  1080. dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
  1081. sizeof(struct bpf_reference_state), GFP_KERNEL);
  1082. if (!dst->refs)
  1083. return -ENOMEM;
  1084. dst->acquired_refs = src->acquired_refs;
  1085. return 0;
  1086. }
  1087. static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
  1088. {
  1089. size_t n = src->allocated_stack / BPF_REG_SIZE;
  1090. dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
  1091. GFP_KERNEL);
  1092. if (!dst->stack)
  1093. return -ENOMEM;
  1094. dst->allocated_stack = src->allocated_stack;
  1095. return 0;
  1096. }
  1097. static int resize_reference_state(struct bpf_func_state *state, size_t n)
  1098. {
  1099. state->refs = realloc_array(state->refs, state->acquired_refs, n,
  1100. sizeof(struct bpf_reference_state));
  1101. if (!state->refs)
  1102. return -ENOMEM;
  1103. state->acquired_refs = n;
  1104. return 0;
  1105. }
  1106. /* Possibly update state->allocated_stack to be at least size bytes. Also
  1107. * possibly update the function's high-water mark in its bpf_subprog_info.
  1108. */
  1109. static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
  1110. {
  1111. size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
  1112. /* The stack size is always a multiple of BPF_REG_SIZE. */
  1113. size = round_up(size, BPF_REG_SIZE);
  1114. n = size / BPF_REG_SIZE;
  1115. if (old_n >= n)
  1116. return 0;
  1117. state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
  1118. if (!state->stack)
  1119. return -ENOMEM;
  1120. state->allocated_stack = size;
  1121. /* update known max for given subprogram */
  1122. if (env->subprog_info[state->subprogno].stack_depth < size)
  1123. env->subprog_info[state->subprogno].stack_depth = size;
  1124. return 0;
  1125. }
  1126. /* Acquire a pointer id from the env and update the state->refs to include
  1127. * this new pointer reference.
  1128. * On success, returns a valid pointer id to associate with the register
  1129. * On failure, returns a negative errno.
  1130. */
  1131. static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
  1132. {
  1133. struct bpf_func_state *state = cur_func(env);
  1134. int new_ofs = state->acquired_refs;
  1135. int id, err;
  1136. err = resize_reference_state(state, state->acquired_refs + 1);
  1137. if (err)
  1138. return err;
  1139. id = ++env->id_gen;
  1140. state->refs[new_ofs].id = id;
  1141. state->refs[new_ofs].insn_idx = insn_idx;
  1142. state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
  1143. return id;
  1144. }
  1145. /* release function corresponding to acquire_reference_state(). Idempotent. */
  1146. static int release_reference_state(struct bpf_func_state *state, int ptr_id)
  1147. {
  1148. int i, last_idx;
  1149. last_idx = state->acquired_refs - 1;
  1150. for (i = 0; i < state->acquired_refs; i++) {
  1151. if (state->refs[i].id == ptr_id) {
  1152. /* Cannot release caller references in callbacks */
  1153. if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
  1154. return -EINVAL;
  1155. if (last_idx && i != last_idx)
  1156. memcpy(&state->refs[i], &state->refs[last_idx],
  1157. sizeof(*state->refs));
  1158. memset(&state->refs[last_idx], 0, sizeof(*state->refs));
  1159. state->acquired_refs--;
  1160. return 0;
  1161. }
  1162. }
  1163. return -EINVAL;
  1164. }
  1165. static void free_func_state(struct bpf_func_state *state)
  1166. {
  1167. if (!state)
  1168. return;
  1169. kfree(state->refs);
  1170. kfree(state->stack);
  1171. kfree(state);
  1172. }
  1173. static void free_verifier_state(struct bpf_verifier_state *state,
  1174. bool free_self)
  1175. {
  1176. int i;
  1177. for (i = 0; i <= state->curframe; i++) {
  1178. free_func_state(state->frame[i]);
  1179. state->frame[i] = NULL;
  1180. }
  1181. if (free_self)
  1182. kfree(state);
  1183. }
  1184. /* copy verifier state from src to dst growing dst stack space
  1185. * when necessary to accommodate larger src stack
  1186. */
  1187. static int copy_func_state(struct bpf_func_state *dst,
  1188. const struct bpf_func_state *src)
  1189. {
  1190. int err;
  1191. memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
  1192. err = copy_reference_state(dst, src);
  1193. if (err)
  1194. return err;
  1195. return copy_stack_state(dst, src);
  1196. }
  1197. static int copy_verifier_state(struct bpf_verifier_state *dst_state,
  1198. const struct bpf_verifier_state *src)
  1199. {
  1200. struct bpf_func_state *dst;
  1201. int i, err;
  1202. /* if dst has more stack frames then src frame, free them, this is also
  1203. * necessary in case of exceptional exits using bpf_throw.
  1204. */
  1205. for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
  1206. free_func_state(dst_state->frame[i]);
  1207. dst_state->frame[i] = NULL;
  1208. }
  1209. dst_state->speculative = src->speculative;
  1210. dst_state->active_rcu_lock = src->active_rcu_lock;
  1211. dst_state->active_preempt_lock = src->active_preempt_lock;
  1212. dst_state->in_sleepable = src->in_sleepable;
  1213. dst_state->curframe = src->curframe;
  1214. dst_state->active_lock.ptr = src->active_lock.ptr;
  1215. dst_state->active_lock.id = src->active_lock.id;
  1216. dst_state->branches = src->branches;
  1217. dst_state->parent = src->parent;
  1218. dst_state->first_insn_idx = src->first_insn_idx;
  1219. dst_state->last_insn_idx = src->last_insn_idx;
  1220. dst_state->insn_hist_start = src->insn_hist_start;
  1221. dst_state->insn_hist_end = src->insn_hist_end;
  1222. dst_state->dfs_depth = src->dfs_depth;
  1223. dst_state->callback_unroll_depth = src->callback_unroll_depth;
  1224. dst_state->used_as_loop_entry = src->used_as_loop_entry;
  1225. dst_state->may_goto_depth = src->may_goto_depth;
  1226. dst_state->loop_entry = src->loop_entry;
  1227. for (i = 0; i <= src->curframe; i++) {
  1228. dst = dst_state->frame[i];
  1229. if (!dst) {
  1230. dst = kzalloc(sizeof(*dst), GFP_KERNEL);
  1231. if (!dst)
  1232. return -ENOMEM;
  1233. dst_state->frame[i] = dst;
  1234. }
  1235. err = copy_func_state(dst, src->frame[i]);
  1236. if (err)
  1237. return err;
  1238. }
  1239. return 0;
  1240. }
  1241. static u32 state_htab_size(struct bpf_verifier_env *env)
  1242. {
  1243. return env->prog->len;
  1244. }
  1245. static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
  1246. {
  1247. struct bpf_verifier_state *cur = env->cur_state;
  1248. struct bpf_func_state *state = cur->frame[cur->curframe];
  1249. return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
  1250. }
  1251. static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
  1252. {
  1253. int fr;
  1254. if (a->curframe != b->curframe)
  1255. return false;
  1256. for (fr = a->curframe; fr >= 0; fr--)
  1257. if (a->frame[fr]->callsite != b->frame[fr]->callsite)
  1258. return false;
  1259. return true;
  1260. }
  1261. /* Open coded iterators allow back-edges in the state graph in order to
  1262. * check unbounded loops that iterators.
  1263. *
  1264. * In is_state_visited() it is necessary to know if explored states are
  1265. * part of some loops in order to decide whether non-exact states
  1266. * comparison could be used:
  1267. * - non-exact states comparison establishes sub-state relation and uses
  1268. * read and precision marks to do so, these marks are propagated from
  1269. * children states and thus are not guaranteed to be final in a loop;
  1270. * - exact states comparison just checks if current and explored states
  1271. * are identical (and thus form a back-edge).
  1272. *
  1273. * Paper "A New Algorithm for Identifying Loops in Decompilation"
  1274. * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
  1275. * algorithm for loop structure detection and gives an overview of
  1276. * relevant terminology. It also has helpful illustrations.
  1277. *
  1278. * [1] https://api.semanticscholar.org/CorpusID:15784067
  1279. *
  1280. * We use a similar algorithm but because loop nested structure is
  1281. * irrelevant for verifier ours is significantly simpler and resembles
  1282. * strongly connected components algorithm from Sedgewick's textbook.
  1283. *
  1284. * Define topmost loop entry as a first node of the loop traversed in a
  1285. * depth first search starting from initial state. The goal of the loop
  1286. * tracking algorithm is to associate topmost loop entries with states
  1287. * derived from these entries.
  1288. *
  1289. * For each step in the DFS states traversal algorithm needs to identify
  1290. * the following situations:
  1291. *
  1292. * initial initial initial
  1293. * | | |
  1294. * V V V
  1295. * ... ... .---------> hdr
  1296. * | | | |
  1297. * V V | V
  1298. * cur .-> succ | .------...
  1299. * | | | | | |
  1300. * V | V | V V
  1301. * succ '-- cur | ... ...
  1302. * | | |
  1303. * | V V
  1304. * | succ <- cur
  1305. * | |
  1306. * | V
  1307. * | ...
  1308. * | |
  1309. * '----'
  1310. *
  1311. * (A) successor state of cur (B) successor state of cur or it's entry
  1312. * not yet traversed are in current DFS path, thus cur and succ
  1313. * are members of the same outermost loop
  1314. *
  1315. * initial initial
  1316. * | |
  1317. * V V
  1318. * ... ...
  1319. * | |
  1320. * V V
  1321. * .------... .------...
  1322. * | | | |
  1323. * V V V V
  1324. * .-> hdr ... ... ...
  1325. * | | | | |
  1326. * | V V V V
  1327. * | succ <- cur succ <- cur
  1328. * | | |
  1329. * | V V
  1330. * | ... ...
  1331. * | | |
  1332. * '----' exit
  1333. *
  1334. * (C) successor state of cur is a part of some loop but this loop
  1335. * does not include cur or successor state is not in a loop at all.
  1336. *
  1337. * Algorithm could be described as the following python code:
  1338. *
  1339. * traversed = set() # Set of traversed nodes
  1340. * entries = {} # Mapping from node to loop entry
  1341. * depths = {} # Depth level assigned to graph node
  1342. * path = set() # Current DFS path
  1343. *
  1344. * # Find outermost loop entry known for n
  1345. * def get_loop_entry(n):
  1346. * h = entries.get(n, None)
  1347. * while h in entries and entries[h] != h:
  1348. * h = entries[h]
  1349. * return h
  1350. *
  1351. * # Update n's loop entry if h's outermost entry comes
  1352. * # before n's outermost entry in current DFS path.
  1353. * def update_loop_entry(n, h):
  1354. * n1 = get_loop_entry(n) or n
  1355. * h1 = get_loop_entry(h) or h
  1356. * if h1 in path and depths[h1] <= depths[n1]:
  1357. * entries[n] = h1
  1358. *
  1359. * def dfs(n, depth):
  1360. * traversed.add(n)
  1361. * path.add(n)
  1362. * depths[n] = depth
  1363. * for succ in G.successors(n):
  1364. * if succ not in traversed:
  1365. * # Case A: explore succ and update cur's loop entry
  1366. * # only if succ's entry is in current DFS path.
  1367. * dfs(succ, depth + 1)
  1368. * h = get_loop_entry(succ)
  1369. * update_loop_entry(n, h)
  1370. * else:
  1371. * # Case B or C depending on `h1 in path` check in update_loop_entry().
  1372. * update_loop_entry(n, succ)
  1373. * path.remove(n)
  1374. *
  1375. * To adapt this algorithm for use with verifier:
  1376. * - use st->branch == 0 as a signal that DFS of succ had been finished
  1377. * and cur's loop entry has to be updated (case A), handle this in
  1378. * update_branch_counts();
  1379. * - use st->branch > 0 as a signal that st is in the current DFS path;
  1380. * - handle cases B and C in is_state_visited();
  1381. * - update topmost loop entry for intermediate states in get_loop_entry().
  1382. */
  1383. static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
  1384. {
  1385. struct bpf_verifier_state *topmost = st->loop_entry, *old;
  1386. while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
  1387. topmost = topmost->loop_entry;
  1388. /* Update loop entries for intermediate states to avoid this
  1389. * traversal in future get_loop_entry() calls.
  1390. */
  1391. while (st && st->loop_entry != topmost) {
  1392. old = st->loop_entry;
  1393. st->loop_entry = topmost;
  1394. st = old;
  1395. }
  1396. return topmost;
  1397. }
  1398. static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
  1399. {
  1400. struct bpf_verifier_state *cur1, *hdr1;
  1401. cur1 = get_loop_entry(cur) ?: cur;
  1402. hdr1 = get_loop_entry(hdr) ?: hdr;
  1403. /* The head1->branches check decides between cases B and C in
  1404. * comment for get_loop_entry(). If hdr1->branches == 0 then
  1405. * head's topmost loop entry is not in current DFS path,
  1406. * hence 'cur' and 'hdr' are not in the same loop and there is
  1407. * no need to update cur->loop_entry.
  1408. */
  1409. if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
  1410. cur->loop_entry = hdr;
  1411. hdr->used_as_loop_entry = true;
  1412. }
  1413. }
  1414. static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
  1415. {
  1416. while (st) {
  1417. u32 br = --st->branches;
  1418. /* br == 0 signals that DFS exploration for 'st' is finished,
  1419. * thus it is necessary to update parent's loop entry if it
  1420. * turned out that st is a part of some loop.
  1421. * This is a part of 'case A' in get_loop_entry() comment.
  1422. */
  1423. if (br == 0 && st->parent && st->loop_entry)
  1424. update_loop_entry(st->parent, st->loop_entry);
  1425. /* WARN_ON(br > 1) technically makes sense here,
  1426. * but see comment in push_stack(), hence:
  1427. */
  1428. WARN_ONCE((int)br < 0,
  1429. "BUG update_branch_counts:branches_to_explore=%d\n",
  1430. br);
  1431. if (br)
  1432. break;
  1433. st = st->parent;
  1434. }
  1435. }
  1436. static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
  1437. int *insn_idx, bool pop_log)
  1438. {
  1439. struct bpf_verifier_state *cur = env->cur_state;
  1440. struct bpf_verifier_stack_elem *elem, *head = env->head;
  1441. int err;
  1442. if (env->head == NULL)
  1443. return -ENOENT;
  1444. if (cur) {
  1445. err = copy_verifier_state(cur, &head->st);
  1446. if (err)
  1447. return err;
  1448. }
  1449. if (pop_log)
  1450. bpf_vlog_reset(&env->log, head->log_pos);
  1451. if (insn_idx)
  1452. *insn_idx = head->insn_idx;
  1453. if (prev_insn_idx)
  1454. *prev_insn_idx = head->prev_insn_idx;
  1455. elem = head->next;
  1456. free_verifier_state(&head->st, false);
  1457. kfree(head);
  1458. env->head = elem;
  1459. env->stack_size--;
  1460. return 0;
  1461. }
  1462. static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
  1463. int insn_idx, int prev_insn_idx,
  1464. bool speculative)
  1465. {
  1466. struct bpf_verifier_state *cur = env->cur_state;
  1467. struct bpf_verifier_stack_elem *elem;
  1468. int err;
  1469. elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  1470. if (!elem)
  1471. goto err;
  1472. elem->insn_idx = insn_idx;
  1473. elem->prev_insn_idx = prev_insn_idx;
  1474. elem->next = env->head;
  1475. elem->log_pos = env->log.end_pos;
  1476. env->head = elem;
  1477. env->stack_size++;
  1478. err = copy_verifier_state(&elem->st, cur);
  1479. if (err)
  1480. goto err;
  1481. elem->st.speculative |= speculative;
  1482. if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
  1483. verbose(env, "The sequence of %d jumps is too complex.\n",
  1484. env->stack_size);
  1485. goto err;
  1486. }
  1487. if (elem->st.parent) {
  1488. ++elem->st.parent->branches;
  1489. /* WARN_ON(branches > 2) technically makes sense here,
  1490. * but
  1491. * 1. speculative states will bump 'branches' for non-branch
  1492. * instructions
  1493. * 2. is_state_visited() heuristics may decide not to create
  1494. * a new state for a sequence of branches and all such current
  1495. * and cloned states will be pointing to a single parent state
  1496. * which might have large 'branches' count.
  1497. */
  1498. }
  1499. return &elem->st;
  1500. err:
  1501. free_verifier_state(env->cur_state, true);
  1502. env->cur_state = NULL;
  1503. /* pop all elements and return */
  1504. while (!pop_stack(env, NULL, NULL, false));
  1505. return NULL;
  1506. }
  1507. #define CALLER_SAVED_REGS 6
  1508. static const int caller_saved[CALLER_SAVED_REGS] = {
  1509. BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
  1510. };
  1511. /* This helper doesn't clear reg->id */
  1512. static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  1513. {
  1514. reg->var_off = tnum_const(imm);
  1515. reg->smin_value = (s64)imm;
  1516. reg->smax_value = (s64)imm;
  1517. reg->umin_value = imm;
  1518. reg->umax_value = imm;
  1519. reg->s32_min_value = (s32)imm;
  1520. reg->s32_max_value = (s32)imm;
  1521. reg->u32_min_value = (u32)imm;
  1522. reg->u32_max_value = (u32)imm;
  1523. }
  1524. /* Mark the unknown part of a register (variable offset or scalar value) as
  1525. * known to have the value @imm.
  1526. */
  1527. static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
  1528. {
  1529. /* Clear off and union(map_ptr, range) */
  1530. memset(((u8 *)reg) + sizeof(reg->type), 0,
  1531. offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
  1532. reg->id = 0;
  1533. reg->ref_obj_id = 0;
  1534. ___mark_reg_known(reg, imm);
  1535. }
  1536. static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
  1537. {
  1538. reg->var_off = tnum_const_subreg(reg->var_off, imm);
  1539. reg->s32_min_value = (s32)imm;
  1540. reg->s32_max_value = (s32)imm;
  1541. reg->u32_min_value = (u32)imm;
  1542. reg->u32_max_value = (u32)imm;
  1543. }
  1544. /* Mark the 'variable offset' part of a register as zero. This should be
  1545. * used only on registers holding a pointer type.
  1546. */
  1547. static void __mark_reg_known_zero(struct bpf_reg_state *reg)
  1548. {
  1549. __mark_reg_known(reg, 0);
  1550. }
  1551. static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  1552. {
  1553. __mark_reg_known(reg, 0);
  1554. reg->type = SCALAR_VALUE;
  1555. /* all scalars are assumed imprecise initially (unless unprivileged,
  1556. * in which case everything is forced to be precise)
  1557. */
  1558. reg->precise = !env->bpf_capable;
  1559. }
  1560. static void mark_reg_known_zero(struct bpf_verifier_env *env,
  1561. struct bpf_reg_state *regs, u32 regno)
  1562. {
  1563. if (WARN_ON(regno >= MAX_BPF_REG)) {
  1564. verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
  1565. /* Something bad happened, let's kill all regs */
  1566. for (regno = 0; regno < MAX_BPF_REG; regno++)
  1567. __mark_reg_not_init(env, regs + regno);
  1568. return;
  1569. }
  1570. __mark_reg_known_zero(regs + regno);
  1571. }
  1572. static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
  1573. bool first_slot, int dynptr_id)
  1574. {
  1575. /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
  1576. * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
  1577. * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
  1578. */
  1579. __mark_reg_known_zero(reg);
  1580. reg->type = CONST_PTR_TO_DYNPTR;
  1581. /* Give each dynptr a unique id to uniquely associate slices to it. */
  1582. reg->id = dynptr_id;
  1583. reg->dynptr.type = type;
  1584. reg->dynptr.first_slot = first_slot;
  1585. }
  1586. static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
  1587. {
  1588. if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
  1589. const struct bpf_map *map = reg->map_ptr;
  1590. if (map->inner_map_meta) {
  1591. reg->type = CONST_PTR_TO_MAP;
  1592. reg->map_ptr = map->inner_map_meta;
  1593. /* transfer reg's id which is unique for every map_lookup_elem
  1594. * as UID of the inner map.
  1595. */
  1596. if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
  1597. reg->map_uid = reg->id;
  1598. if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
  1599. reg->map_uid = reg->id;
  1600. } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
  1601. reg->type = PTR_TO_XDP_SOCK;
  1602. } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
  1603. map->map_type == BPF_MAP_TYPE_SOCKHASH) {
  1604. reg->type = PTR_TO_SOCKET;
  1605. } else {
  1606. reg->type = PTR_TO_MAP_VALUE;
  1607. }
  1608. return;
  1609. }
  1610. reg->type &= ~PTR_MAYBE_NULL;
  1611. }
  1612. static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
  1613. struct btf_field_graph_root *ds_head)
  1614. {
  1615. __mark_reg_known_zero(&regs[regno]);
  1616. regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
  1617. regs[regno].btf = ds_head->btf;
  1618. regs[regno].btf_id = ds_head->value_btf_id;
  1619. regs[regno].off = ds_head->node_offset;
  1620. }
  1621. static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
  1622. {
  1623. return type_is_pkt_pointer(reg->type);
  1624. }
  1625. static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
  1626. {
  1627. return reg_is_pkt_pointer(reg) ||
  1628. reg->type == PTR_TO_PACKET_END;
  1629. }
  1630. static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
  1631. {
  1632. return base_type(reg->type) == PTR_TO_MEM &&
  1633. (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
  1634. }
  1635. /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
  1636. static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
  1637. enum bpf_reg_type which)
  1638. {
  1639. /* The register can already have a range from prior markings.
  1640. * This is fine as long as it hasn't been advanced from its
  1641. * origin.
  1642. */
  1643. return reg->type == which &&
  1644. reg->id == 0 &&
  1645. reg->off == 0 &&
  1646. tnum_equals_const(reg->var_off, 0);
  1647. }
  1648. /* Reset the min/max bounds of a register */
  1649. static void __mark_reg_unbounded(struct bpf_reg_state *reg)
  1650. {
  1651. reg->smin_value = S64_MIN;
  1652. reg->smax_value = S64_MAX;
  1653. reg->umin_value = 0;
  1654. reg->umax_value = U64_MAX;
  1655. reg->s32_min_value = S32_MIN;
  1656. reg->s32_max_value = S32_MAX;
  1657. reg->u32_min_value = 0;
  1658. reg->u32_max_value = U32_MAX;
  1659. }
  1660. static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
  1661. {
  1662. reg->smin_value = S64_MIN;
  1663. reg->smax_value = S64_MAX;
  1664. reg->umin_value = 0;
  1665. reg->umax_value = U64_MAX;
  1666. }
  1667. static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
  1668. {
  1669. reg->s32_min_value = S32_MIN;
  1670. reg->s32_max_value = S32_MAX;
  1671. reg->u32_min_value = 0;
  1672. reg->u32_max_value = U32_MAX;
  1673. }
  1674. static void __update_reg32_bounds(struct bpf_reg_state *reg)
  1675. {
  1676. struct tnum var32_off = tnum_subreg(reg->var_off);
  1677. /* min signed is max(sign bit) | min(other bits) */
  1678. reg->s32_min_value = max_t(s32, reg->s32_min_value,
  1679. var32_off.value | (var32_off.mask & S32_MIN));
  1680. /* max signed is min(sign bit) | max(other bits) */
  1681. reg->s32_max_value = min_t(s32, reg->s32_max_value,
  1682. var32_off.value | (var32_off.mask & S32_MAX));
  1683. reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
  1684. reg->u32_max_value = min(reg->u32_max_value,
  1685. (u32)(var32_off.value | var32_off.mask));
  1686. }
  1687. static void __update_reg64_bounds(struct bpf_reg_state *reg)
  1688. {
  1689. /* min signed is max(sign bit) | min(other bits) */
  1690. reg->smin_value = max_t(s64, reg->smin_value,
  1691. reg->var_off.value | (reg->var_off.mask & S64_MIN));
  1692. /* max signed is min(sign bit) | max(other bits) */
  1693. reg->smax_value = min_t(s64, reg->smax_value,
  1694. reg->var_off.value | (reg->var_off.mask & S64_MAX));
  1695. reg->umin_value = max(reg->umin_value, reg->var_off.value);
  1696. reg->umax_value = min(reg->umax_value,
  1697. reg->var_off.value | reg->var_off.mask);
  1698. }
  1699. static void __update_reg_bounds(struct bpf_reg_state *reg)
  1700. {
  1701. __update_reg32_bounds(reg);
  1702. __update_reg64_bounds(reg);
  1703. }
  1704. /* Uses signed min/max values to inform unsigned, and vice-versa */
  1705. static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
  1706. {
  1707. /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
  1708. * bits to improve our u32/s32 boundaries.
  1709. *
  1710. * E.g., the case where we have upper 32 bits as zero ([10, 20] in
  1711. * u64) is pretty trivial, it's obvious that in u32 we'll also have
  1712. * [10, 20] range. But this property holds for any 64-bit range as
  1713. * long as upper 32 bits in that entire range of values stay the same.
  1714. *
  1715. * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
  1716. * in decimal) has the same upper 32 bits throughout all the values in
  1717. * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
  1718. * range.
  1719. *
  1720. * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
  1721. * following the rules outlined below about u64/s64 correspondence
  1722. * (which equally applies to u32 vs s32 correspondence). In general it
  1723. * depends on actual hexadecimal values of 32-bit range. They can form
  1724. * only valid u32, or only valid s32 ranges in some cases.
  1725. *
  1726. * So we use all these insights to derive bounds for subregisters here.
  1727. */
  1728. if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
  1729. /* u64 to u32 casting preserves validity of low 32 bits as
  1730. * a range, if upper 32 bits are the same
  1731. */
  1732. reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
  1733. reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
  1734. if ((s32)reg->umin_value <= (s32)reg->umax_value) {
  1735. reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
  1736. reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
  1737. }
  1738. }
  1739. if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
  1740. /* low 32 bits should form a proper u32 range */
  1741. if ((u32)reg->smin_value <= (u32)reg->smax_value) {
  1742. reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
  1743. reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
  1744. }
  1745. /* low 32 bits should form a proper s32 range */
  1746. if ((s32)reg->smin_value <= (s32)reg->smax_value) {
  1747. reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
  1748. reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
  1749. }
  1750. }
  1751. /* Special case where upper bits form a small sequence of two
  1752. * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
  1753. * 0x00000000 is also valid), while lower bits form a proper s32 range
  1754. * going from negative numbers to positive numbers. E.g., let's say we
  1755. * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
  1756. * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
  1757. * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
  1758. * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
  1759. * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
  1760. * upper 32 bits. As a random example, s64 range
  1761. * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
  1762. * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
  1763. */
  1764. if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
  1765. (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
  1766. reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
  1767. reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
  1768. }
  1769. if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
  1770. (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
  1771. reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
  1772. reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
  1773. }
  1774. /* if u32 range forms a valid s32 range (due to matching sign bit),
  1775. * try to learn from that
  1776. */
  1777. if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
  1778. reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
  1779. reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
  1780. }
  1781. /* If we cannot cross the sign boundary, then signed and unsigned bounds
  1782. * are the same, so combine. This works even in the negative case, e.g.
  1783. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
  1784. */
  1785. if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
  1786. reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
  1787. reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
  1788. }
  1789. }
  1790. static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
  1791. {
  1792. /* If u64 range forms a valid s64 range (due to matching sign bit),
  1793. * try to learn from that. Let's do a bit of ASCII art to see when
  1794. * this is happening. Let's take u64 range first:
  1795. *
  1796. * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
  1797. * |-------------------------------|--------------------------------|
  1798. *
  1799. * Valid u64 range is formed when umin and umax are anywhere in the
  1800. * range [0, U64_MAX], and umin <= umax. u64 case is simple and
  1801. * straightforward. Let's see how s64 range maps onto the same range
  1802. * of values, annotated below the line for comparison:
  1803. *
  1804. * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
  1805. * |-------------------------------|--------------------------------|
  1806. * 0 S64_MAX S64_MIN -1
  1807. *
  1808. * So s64 values basically start in the middle and they are logically
  1809. * contiguous to the right of it, wrapping around from -1 to 0, and
  1810. * then finishing as S64_MAX (0x7fffffffffffffff) right before
  1811. * S64_MIN. We can try drawing the continuity of u64 vs s64 values
  1812. * more visually as mapped to sign-agnostic range of hex values.
  1813. *
  1814. * u64 start u64 end
  1815. * _______________________________________________________________
  1816. * / \
  1817. * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
  1818. * |-------------------------------|--------------------------------|
  1819. * 0 S64_MAX S64_MIN -1
  1820. * / \
  1821. * >------------------------------ ------------------------------->
  1822. * s64 continues... s64 end s64 start s64 "midpoint"
  1823. *
  1824. * What this means is that, in general, we can't always derive
  1825. * something new about u64 from any random s64 range, and vice versa.
  1826. *
  1827. * But we can do that in two particular cases. One is when entire
  1828. * u64/s64 range is *entirely* contained within left half of the above
  1829. * diagram or when it is *entirely* contained in the right half. I.e.:
  1830. *
  1831. * |-------------------------------|--------------------------------|
  1832. * ^ ^ ^ ^
  1833. * A B C D
  1834. *
  1835. * [A, B] and [C, D] are contained entirely in their respective halves
  1836. * and form valid contiguous ranges as both u64 and s64 values. [A, B]
  1837. * will be non-negative both as u64 and s64 (and in fact it will be
  1838. * identical ranges no matter the signedness). [C, D] treated as s64
  1839. * will be a range of negative values, while in u64 it will be
  1840. * non-negative range of values larger than 0x8000000000000000.
  1841. *
  1842. * Now, any other range here can't be represented in both u64 and s64
  1843. * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
  1844. * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
  1845. * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
  1846. * for example. Similarly, valid s64 range [D, A] (going from negative
  1847. * to positive values), would be two separate [D, U64_MAX] and [0, A]
  1848. * ranges as u64. Currently reg_state can't represent two segments per
  1849. * numeric domain, so in such situations we can only derive maximal
  1850. * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
  1851. *
  1852. * So we use these facts to derive umin/umax from smin/smax and vice
  1853. * versa only if they stay within the same "half". This is equivalent
  1854. * to checking sign bit: lower half will have sign bit as zero, upper
  1855. * half have sign bit 1. Below in code we simplify this by just
  1856. * casting umin/umax as smin/smax and checking if they form valid
  1857. * range, and vice versa. Those are equivalent checks.
  1858. */
  1859. if ((s64)reg->umin_value <= (s64)reg->umax_value) {
  1860. reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
  1861. reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
  1862. }
  1863. /* If we cannot cross the sign boundary, then signed and unsigned bounds
  1864. * are the same, so combine. This works even in the negative case, e.g.
  1865. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
  1866. */
  1867. if ((u64)reg->smin_value <= (u64)reg->smax_value) {
  1868. reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
  1869. reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
  1870. }
  1871. }
  1872. static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
  1873. {
  1874. /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
  1875. * values on both sides of 64-bit range in hope to have tighter range.
  1876. * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
  1877. * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
  1878. * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
  1879. * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
  1880. * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
  1881. * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
  1882. * We just need to make sure that derived bounds we are intersecting
  1883. * with are well-formed ranges in respective s64 or u64 domain, just
  1884. * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
  1885. */
  1886. __u64 new_umin, new_umax;
  1887. __s64 new_smin, new_smax;
  1888. /* u32 -> u64 tightening, it's always well-formed */
  1889. new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
  1890. new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
  1891. reg->umin_value = max_t(u64, reg->umin_value, new_umin);
  1892. reg->umax_value = min_t(u64, reg->umax_value, new_umax);
  1893. /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
  1894. new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
  1895. new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
  1896. reg->smin_value = max_t(s64, reg->smin_value, new_smin);
  1897. reg->smax_value = min_t(s64, reg->smax_value, new_smax);
  1898. /* if s32 can be treated as valid u32 range, we can use it as well */
  1899. if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
  1900. /* s32 -> u64 tightening */
  1901. new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
  1902. new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
  1903. reg->umin_value = max_t(u64, reg->umin_value, new_umin);
  1904. reg->umax_value = min_t(u64, reg->umax_value, new_umax);
  1905. /* s32 -> s64 tightening */
  1906. new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
  1907. new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
  1908. reg->smin_value = max_t(s64, reg->smin_value, new_smin);
  1909. reg->smax_value = min_t(s64, reg->smax_value, new_smax);
  1910. }
  1911. /* Here we would like to handle a special case after sign extending load,
  1912. * when upper bits for a 64-bit range are all 1s or all 0s.
  1913. *
  1914. * Upper bits are all 1s when register is in a range:
  1915. * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
  1916. * Upper bits are all 0s when register is in a range:
  1917. * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
  1918. * Together this forms are continuous range:
  1919. * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
  1920. *
  1921. * Now, suppose that register range is in fact tighter:
  1922. * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
  1923. * Also suppose that it's 32-bit range is positive,
  1924. * meaning that lower 32-bits of the full 64-bit register
  1925. * are in the range:
  1926. * [0x0000_0000, 0x7fff_ffff] (W)
  1927. *
  1928. * If this happens, then any value in a range:
  1929. * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
  1930. * is smaller than a lowest bound of the range (R):
  1931. * 0xffff_ffff_8000_0000
  1932. * which means that upper bits of the full 64-bit register
  1933. * can't be all 1s, when lower bits are in range (W).
  1934. *
  1935. * Note that:
  1936. * - 0xffff_ffff_8000_0000 == (s64)S32_MIN
  1937. * - 0x0000_0000_7fff_ffff == (s64)S32_MAX
  1938. * These relations are used in the conditions below.
  1939. */
  1940. if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
  1941. reg->smin_value = reg->s32_min_value;
  1942. reg->smax_value = reg->s32_max_value;
  1943. reg->umin_value = reg->s32_min_value;
  1944. reg->umax_value = reg->s32_max_value;
  1945. reg->var_off = tnum_intersect(reg->var_off,
  1946. tnum_range(reg->smin_value, reg->smax_value));
  1947. }
  1948. }
  1949. static void __reg_deduce_bounds(struct bpf_reg_state *reg)
  1950. {
  1951. __reg32_deduce_bounds(reg);
  1952. __reg64_deduce_bounds(reg);
  1953. __reg_deduce_mixed_bounds(reg);
  1954. }
  1955. /* Attempts to improve var_off based on unsigned min/max information */
  1956. static void __reg_bound_offset(struct bpf_reg_state *reg)
  1957. {
  1958. struct tnum var64_off = tnum_intersect(reg->var_off,
  1959. tnum_range(reg->umin_value,
  1960. reg->umax_value));
  1961. struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
  1962. tnum_range(reg->u32_min_value,
  1963. reg->u32_max_value));
  1964. reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
  1965. }
  1966. static void reg_bounds_sync(struct bpf_reg_state *reg)
  1967. {
  1968. /* We might have learned new bounds from the var_off. */
  1969. __update_reg_bounds(reg);
  1970. /* We might have learned something about the sign bit. */
  1971. __reg_deduce_bounds(reg);
  1972. __reg_deduce_bounds(reg);
  1973. /* We might have learned some bits from the bounds. */
  1974. __reg_bound_offset(reg);
  1975. /* Intersecting with the old var_off might have improved our bounds
  1976. * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
  1977. * then new var_off is (0; 0x7f...fc) which improves our umax.
  1978. */
  1979. __update_reg_bounds(reg);
  1980. }
  1981. static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
  1982. struct bpf_reg_state *reg, const char *ctx)
  1983. {
  1984. const char *msg;
  1985. if (reg->umin_value > reg->umax_value ||
  1986. reg->smin_value > reg->smax_value ||
  1987. reg->u32_min_value > reg->u32_max_value ||
  1988. reg->s32_min_value > reg->s32_max_value) {
  1989. msg = "range bounds violation";
  1990. goto out;
  1991. }
  1992. if (tnum_is_const(reg->var_off)) {
  1993. u64 uval = reg->var_off.value;
  1994. s64 sval = (s64)uval;
  1995. if (reg->umin_value != uval || reg->umax_value != uval ||
  1996. reg->smin_value != sval || reg->smax_value != sval) {
  1997. msg = "const tnum out of sync with range bounds";
  1998. goto out;
  1999. }
  2000. }
  2001. if (tnum_subreg_is_const(reg->var_off)) {
  2002. u32 uval32 = tnum_subreg(reg->var_off).value;
  2003. s32 sval32 = (s32)uval32;
  2004. if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
  2005. reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
  2006. msg = "const subreg tnum out of sync with range bounds";
  2007. goto out;
  2008. }
  2009. }
  2010. return 0;
  2011. out:
  2012. verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
  2013. "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
  2014. ctx, msg, reg->umin_value, reg->umax_value,
  2015. reg->smin_value, reg->smax_value,
  2016. reg->u32_min_value, reg->u32_max_value,
  2017. reg->s32_min_value, reg->s32_max_value,
  2018. reg->var_off.value, reg->var_off.mask);
  2019. if (env->test_reg_invariants)
  2020. return -EFAULT;
  2021. __mark_reg_unbounded(reg);
  2022. return 0;
  2023. }
  2024. static bool __reg32_bound_s64(s32 a)
  2025. {
  2026. return a >= 0 && a <= S32_MAX;
  2027. }
  2028. static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
  2029. {
  2030. reg->umin_value = reg->u32_min_value;
  2031. reg->umax_value = reg->u32_max_value;
  2032. /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
  2033. * be positive otherwise set to worse case bounds and refine later
  2034. * from tnum.
  2035. */
  2036. if (__reg32_bound_s64(reg->s32_min_value) &&
  2037. __reg32_bound_s64(reg->s32_max_value)) {
  2038. reg->smin_value = reg->s32_min_value;
  2039. reg->smax_value = reg->s32_max_value;
  2040. } else {
  2041. reg->smin_value = 0;
  2042. reg->smax_value = U32_MAX;
  2043. }
  2044. }
  2045. /* Mark a register as having a completely unknown (scalar) value. */
  2046. static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
  2047. {
  2048. /*
  2049. * Clear type, off, and union(map_ptr, range) and
  2050. * padding between 'type' and union
  2051. */
  2052. memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
  2053. reg->type = SCALAR_VALUE;
  2054. reg->id = 0;
  2055. reg->ref_obj_id = 0;
  2056. reg->var_off = tnum_unknown;
  2057. reg->frameno = 0;
  2058. reg->precise = false;
  2059. __mark_reg_unbounded(reg);
  2060. }
  2061. /* Mark a register as having a completely unknown (scalar) value,
  2062. * initialize .precise as true when not bpf capable.
  2063. */
  2064. static void __mark_reg_unknown(const struct bpf_verifier_env *env,
  2065. struct bpf_reg_state *reg)
  2066. {
  2067. __mark_reg_unknown_imprecise(reg);
  2068. reg->precise = !env->bpf_capable;
  2069. }
  2070. static void mark_reg_unknown(struct bpf_verifier_env *env,
  2071. struct bpf_reg_state *regs, u32 regno)
  2072. {
  2073. if (WARN_ON(regno >= MAX_BPF_REG)) {
  2074. verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
  2075. /* Something bad happened, let's kill all regs except FP */
  2076. for (regno = 0; regno < BPF_REG_FP; regno++)
  2077. __mark_reg_not_init(env, regs + regno);
  2078. return;
  2079. }
  2080. __mark_reg_unknown(env, regs + regno);
  2081. }
  2082. static int __mark_reg_s32_range(struct bpf_verifier_env *env,
  2083. struct bpf_reg_state *regs,
  2084. u32 regno,
  2085. s32 s32_min,
  2086. s32 s32_max)
  2087. {
  2088. struct bpf_reg_state *reg = regs + regno;
  2089. reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
  2090. reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
  2091. reg->smin_value = max_t(s64, reg->smin_value, s32_min);
  2092. reg->smax_value = min_t(s64, reg->smax_value, s32_max);
  2093. reg_bounds_sync(reg);
  2094. return reg_bounds_sanity_check(env, reg, "s32_range");
  2095. }
  2096. static void __mark_reg_not_init(const struct bpf_verifier_env *env,
  2097. struct bpf_reg_state *reg)
  2098. {
  2099. __mark_reg_unknown(env, reg);
  2100. reg->type = NOT_INIT;
  2101. }
  2102. static void mark_reg_not_init(struct bpf_verifier_env *env,
  2103. struct bpf_reg_state *regs, u32 regno)
  2104. {
  2105. if (WARN_ON(regno >= MAX_BPF_REG)) {
  2106. verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
  2107. /* Something bad happened, let's kill all regs except FP */
  2108. for (regno = 0; regno < BPF_REG_FP; regno++)
  2109. __mark_reg_not_init(env, regs + regno);
  2110. return;
  2111. }
  2112. __mark_reg_not_init(env, regs + regno);
  2113. }
  2114. static void mark_btf_ld_reg(struct bpf_verifier_env *env,
  2115. struct bpf_reg_state *regs, u32 regno,
  2116. enum bpf_reg_type reg_type,
  2117. struct btf *btf, u32 btf_id,
  2118. enum bpf_type_flag flag)
  2119. {
  2120. if (reg_type == SCALAR_VALUE) {
  2121. mark_reg_unknown(env, regs, regno);
  2122. return;
  2123. }
  2124. mark_reg_known_zero(env, regs, regno);
  2125. regs[regno].type = PTR_TO_BTF_ID | flag;
  2126. regs[regno].btf = btf;
  2127. regs[regno].btf_id = btf_id;
  2128. if (type_may_be_null(flag))
  2129. regs[regno].id = ++env->id_gen;
  2130. }
  2131. #define DEF_NOT_SUBREG (0)
  2132. static void init_reg_state(struct bpf_verifier_env *env,
  2133. struct bpf_func_state *state)
  2134. {
  2135. struct bpf_reg_state *regs = state->regs;
  2136. int i;
  2137. for (i = 0; i < MAX_BPF_REG; i++) {
  2138. mark_reg_not_init(env, regs, i);
  2139. regs[i].live = REG_LIVE_NONE;
  2140. regs[i].parent = NULL;
  2141. regs[i].subreg_def = DEF_NOT_SUBREG;
  2142. }
  2143. /* frame pointer */
  2144. regs[BPF_REG_FP].type = PTR_TO_STACK;
  2145. mark_reg_known_zero(env, regs, BPF_REG_FP);
  2146. regs[BPF_REG_FP].frameno = state->frameno;
  2147. }
  2148. static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
  2149. {
  2150. return (struct bpf_retval_range){ minval, maxval };
  2151. }
  2152. #define BPF_MAIN_FUNC (-1)
  2153. static void init_func_state(struct bpf_verifier_env *env,
  2154. struct bpf_func_state *state,
  2155. int callsite, int frameno, int subprogno)
  2156. {
  2157. state->callsite = callsite;
  2158. state->frameno = frameno;
  2159. state->subprogno = subprogno;
  2160. state->callback_ret_range = retval_range(0, 0);
  2161. init_reg_state(env, state);
  2162. mark_verifier_state_scratched(env);
  2163. }
  2164. /* Similar to push_stack(), but for async callbacks */
  2165. static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
  2166. int insn_idx, int prev_insn_idx,
  2167. int subprog, bool is_sleepable)
  2168. {
  2169. struct bpf_verifier_stack_elem *elem;
  2170. struct bpf_func_state *frame;
  2171. elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
  2172. if (!elem)
  2173. goto err;
  2174. elem->insn_idx = insn_idx;
  2175. elem->prev_insn_idx = prev_insn_idx;
  2176. elem->next = env->head;
  2177. elem->log_pos = env->log.end_pos;
  2178. env->head = elem;
  2179. env->stack_size++;
  2180. if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
  2181. verbose(env,
  2182. "The sequence of %d jumps is too complex for async cb.\n",
  2183. env->stack_size);
  2184. goto err;
  2185. }
  2186. /* Unlike push_stack() do not copy_verifier_state().
  2187. * The caller state doesn't matter.
  2188. * This is async callback. It starts in a fresh stack.
  2189. * Initialize it similar to do_check_common().
  2190. * But we do need to make sure to not clobber insn_hist, so we keep
  2191. * chaining insn_hist_start/insn_hist_end indices as for a normal
  2192. * child state.
  2193. */
  2194. elem->st.branches = 1;
  2195. elem->st.in_sleepable = is_sleepable;
  2196. elem->st.insn_hist_start = env->cur_state->insn_hist_end;
  2197. elem->st.insn_hist_end = elem->st.insn_hist_start;
  2198. frame = kzalloc(sizeof(*frame), GFP_KERNEL);
  2199. if (!frame)
  2200. goto err;
  2201. init_func_state(env, frame,
  2202. BPF_MAIN_FUNC /* callsite */,
  2203. 0 /* frameno within this callchain */,
  2204. subprog /* subprog number within this prog */);
  2205. elem->st.frame[0] = frame;
  2206. return &elem->st;
  2207. err:
  2208. free_verifier_state(env->cur_state, true);
  2209. env->cur_state = NULL;
  2210. /* pop all elements and return */
  2211. while (!pop_stack(env, NULL, NULL, false));
  2212. return NULL;
  2213. }
  2214. enum reg_arg_type {
  2215. SRC_OP, /* register is used as source operand */
  2216. DST_OP, /* register is used as destination operand */
  2217. DST_OP_NO_MARK /* same as above, check only, don't mark */
  2218. };
  2219. static int cmp_subprogs(const void *a, const void *b)
  2220. {
  2221. return ((struct bpf_subprog_info *)a)->start -
  2222. ((struct bpf_subprog_info *)b)->start;
  2223. }
  2224. /* Find subprogram that contains instruction at 'off' */
  2225. static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
  2226. {
  2227. struct bpf_subprog_info *vals = env->subprog_info;
  2228. int l, r, m;
  2229. if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
  2230. return NULL;
  2231. l = 0;
  2232. r = env->subprog_cnt - 1;
  2233. while (l < r) {
  2234. m = l + (r - l + 1) / 2;
  2235. if (vals[m].start <= off)
  2236. l = m;
  2237. else
  2238. r = m - 1;
  2239. }
  2240. return &vals[l];
  2241. }
  2242. /* Find subprogram that starts exactly at 'off' */
  2243. static int find_subprog(struct bpf_verifier_env *env, int off)
  2244. {
  2245. struct bpf_subprog_info *p;
  2246. p = find_containing_subprog(env, off);
  2247. if (!p || p->start != off)
  2248. return -ENOENT;
  2249. return p - env->subprog_info;
  2250. }
  2251. static int add_subprog(struct bpf_verifier_env *env, int off)
  2252. {
  2253. int insn_cnt = env->prog->len;
  2254. int ret;
  2255. if (off >= insn_cnt || off < 0) {
  2256. verbose(env, "call to invalid destination\n");
  2257. return -EINVAL;
  2258. }
  2259. ret = find_subprog(env, off);
  2260. if (ret >= 0)
  2261. return ret;
  2262. if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
  2263. verbose(env, "too many subprograms\n");
  2264. return -E2BIG;
  2265. }
  2266. /* determine subprog starts. The end is one before the next starts */
  2267. env->subprog_info[env->subprog_cnt++].start = off;
  2268. sort(env->subprog_info, env->subprog_cnt,
  2269. sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
  2270. return env->subprog_cnt - 1;
  2271. }
  2272. static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
  2273. {
  2274. struct bpf_prog_aux *aux = env->prog->aux;
  2275. struct btf *btf = aux->btf;
  2276. const struct btf_type *t;
  2277. u32 main_btf_id, id;
  2278. const char *name;
  2279. int ret, i;
  2280. /* Non-zero func_info_cnt implies valid btf */
  2281. if (!aux->func_info_cnt)
  2282. return 0;
  2283. main_btf_id = aux->func_info[0].type_id;
  2284. t = btf_type_by_id(btf, main_btf_id);
  2285. if (!t) {
  2286. verbose(env, "invalid btf id for main subprog in func_info\n");
  2287. return -EINVAL;
  2288. }
  2289. name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
  2290. if (IS_ERR(name)) {
  2291. ret = PTR_ERR(name);
  2292. /* If there is no tag present, there is no exception callback */
  2293. if (ret == -ENOENT)
  2294. ret = 0;
  2295. else if (ret == -EEXIST)
  2296. verbose(env, "multiple exception callback tags for main subprog\n");
  2297. return ret;
  2298. }
  2299. ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
  2300. if (ret < 0) {
  2301. verbose(env, "exception callback '%s' could not be found in BTF\n", name);
  2302. return ret;
  2303. }
  2304. id = ret;
  2305. t = btf_type_by_id(btf, id);
  2306. if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
  2307. verbose(env, "exception callback '%s' must have global linkage\n", name);
  2308. return -EINVAL;
  2309. }
  2310. ret = 0;
  2311. for (i = 0; i < aux->func_info_cnt; i++) {
  2312. if (aux->func_info[i].type_id != id)
  2313. continue;
  2314. ret = aux->func_info[i].insn_off;
  2315. /* Further func_info and subprog checks will also happen
  2316. * later, so assume this is the right insn_off for now.
  2317. */
  2318. if (!ret) {
  2319. verbose(env, "invalid exception callback insn_off in func_info: 0\n");
  2320. ret = -EINVAL;
  2321. }
  2322. }
  2323. if (!ret) {
  2324. verbose(env, "exception callback type id not found in func_info\n");
  2325. ret = -EINVAL;
  2326. }
  2327. return ret;
  2328. }
  2329. #define MAX_KFUNC_DESCS 256
  2330. #define MAX_KFUNC_BTFS 256
  2331. struct bpf_kfunc_desc {
  2332. struct btf_func_model func_model;
  2333. u32 func_id;
  2334. s32 imm;
  2335. u16 offset;
  2336. unsigned long addr;
  2337. };
  2338. struct bpf_kfunc_btf {
  2339. struct btf *btf;
  2340. struct module *module;
  2341. u16 offset;
  2342. };
  2343. struct bpf_kfunc_desc_tab {
  2344. /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
  2345. * verification. JITs do lookups by bpf_insn, where func_id may not be
  2346. * available, therefore at the end of verification do_misc_fixups()
  2347. * sorts this by imm and offset.
  2348. */
  2349. struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
  2350. u32 nr_descs;
  2351. };
  2352. struct bpf_kfunc_btf_tab {
  2353. struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
  2354. u32 nr_descs;
  2355. };
  2356. static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
  2357. {
  2358. const struct bpf_kfunc_desc *d0 = a;
  2359. const struct bpf_kfunc_desc *d1 = b;
  2360. /* func_id is not greater than BTF_MAX_TYPE */
  2361. return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
  2362. }
  2363. static int kfunc_btf_cmp_by_off(const void *a, const void *b)
  2364. {
  2365. const struct bpf_kfunc_btf *d0 = a;
  2366. const struct bpf_kfunc_btf *d1 = b;
  2367. return d0->offset - d1->offset;
  2368. }
  2369. static const struct bpf_kfunc_desc *
  2370. find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
  2371. {
  2372. struct bpf_kfunc_desc desc = {
  2373. .func_id = func_id,
  2374. .offset = offset,
  2375. };
  2376. struct bpf_kfunc_desc_tab *tab;
  2377. tab = prog->aux->kfunc_tab;
  2378. return bsearch(&desc, tab->descs, tab->nr_descs,
  2379. sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
  2380. }
  2381. int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
  2382. u16 btf_fd_idx, u8 **func_addr)
  2383. {
  2384. const struct bpf_kfunc_desc *desc;
  2385. desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
  2386. if (!desc)
  2387. return -EFAULT;
  2388. *func_addr = (u8 *)desc->addr;
  2389. return 0;
  2390. }
  2391. static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
  2392. s16 offset)
  2393. {
  2394. struct bpf_kfunc_btf kf_btf = { .offset = offset };
  2395. struct bpf_kfunc_btf_tab *tab;
  2396. struct bpf_kfunc_btf *b;
  2397. struct module *mod;
  2398. struct btf *btf;
  2399. int btf_fd;
  2400. tab = env->prog->aux->kfunc_btf_tab;
  2401. b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
  2402. sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
  2403. if (!b) {
  2404. if (tab->nr_descs == MAX_KFUNC_BTFS) {
  2405. verbose(env, "too many different module BTFs\n");
  2406. return ERR_PTR(-E2BIG);
  2407. }
  2408. if (bpfptr_is_null(env->fd_array)) {
  2409. verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
  2410. return ERR_PTR(-EPROTO);
  2411. }
  2412. if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
  2413. offset * sizeof(btf_fd),
  2414. sizeof(btf_fd)))
  2415. return ERR_PTR(-EFAULT);
  2416. btf = btf_get_by_fd(btf_fd);
  2417. if (IS_ERR(btf)) {
  2418. verbose(env, "invalid module BTF fd specified\n");
  2419. return btf;
  2420. }
  2421. if (!btf_is_module(btf)) {
  2422. verbose(env, "BTF fd for kfunc is not a module BTF\n");
  2423. btf_put(btf);
  2424. return ERR_PTR(-EINVAL);
  2425. }
  2426. mod = btf_try_get_module(btf);
  2427. if (!mod) {
  2428. btf_put(btf);
  2429. return ERR_PTR(-ENXIO);
  2430. }
  2431. b = &tab->descs[tab->nr_descs++];
  2432. b->btf = btf;
  2433. b->module = mod;
  2434. b->offset = offset;
  2435. /* sort() reorders entries by value, so b may no longer point
  2436. * to the right entry after this
  2437. */
  2438. sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
  2439. kfunc_btf_cmp_by_off, NULL);
  2440. } else {
  2441. btf = b->btf;
  2442. }
  2443. return btf;
  2444. }
  2445. void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
  2446. {
  2447. if (!tab)
  2448. return;
  2449. while (tab->nr_descs--) {
  2450. module_put(tab->descs[tab->nr_descs].module);
  2451. btf_put(tab->descs[tab->nr_descs].btf);
  2452. }
  2453. kfree(tab);
  2454. }
  2455. static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
  2456. {
  2457. if (offset) {
  2458. if (offset < 0) {
  2459. /* In the future, this can be allowed to increase limit
  2460. * of fd index into fd_array, interpreted as u16.
  2461. */
  2462. verbose(env, "negative offset disallowed for kernel module function call\n");
  2463. return ERR_PTR(-EINVAL);
  2464. }
  2465. return __find_kfunc_desc_btf(env, offset);
  2466. }
  2467. return btf_vmlinux ?: ERR_PTR(-ENOENT);
  2468. }
  2469. static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
  2470. {
  2471. const struct btf_type *func, *func_proto;
  2472. struct bpf_kfunc_btf_tab *btf_tab;
  2473. struct bpf_kfunc_desc_tab *tab;
  2474. struct bpf_prog_aux *prog_aux;
  2475. struct bpf_kfunc_desc *desc;
  2476. const char *func_name;
  2477. struct btf *desc_btf;
  2478. unsigned long call_imm;
  2479. unsigned long addr;
  2480. int err;
  2481. prog_aux = env->prog->aux;
  2482. tab = prog_aux->kfunc_tab;
  2483. btf_tab = prog_aux->kfunc_btf_tab;
  2484. if (!tab) {
  2485. if (!btf_vmlinux) {
  2486. verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
  2487. return -ENOTSUPP;
  2488. }
  2489. if (!env->prog->jit_requested) {
  2490. verbose(env, "JIT is required for calling kernel function\n");
  2491. return -ENOTSUPP;
  2492. }
  2493. if (!bpf_jit_supports_kfunc_call()) {
  2494. verbose(env, "JIT does not support calling kernel function\n");
  2495. return -ENOTSUPP;
  2496. }
  2497. if (!env->prog->gpl_compatible) {
  2498. verbose(env, "cannot call kernel function from non-GPL compatible program\n");
  2499. return -EINVAL;
  2500. }
  2501. tab = kzalloc(sizeof(*tab), GFP_KERNEL);
  2502. if (!tab)
  2503. return -ENOMEM;
  2504. prog_aux->kfunc_tab = tab;
  2505. }
  2506. /* func_id == 0 is always invalid, but instead of returning an error, be
  2507. * conservative and wait until the code elimination pass before returning
  2508. * error, so that invalid calls that get pruned out can be in BPF programs
  2509. * loaded from userspace. It is also required that offset be untouched
  2510. * for such calls.
  2511. */
  2512. if (!func_id && !offset)
  2513. return 0;
  2514. if (!btf_tab && offset) {
  2515. btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
  2516. if (!btf_tab)
  2517. return -ENOMEM;
  2518. prog_aux->kfunc_btf_tab = btf_tab;
  2519. }
  2520. desc_btf = find_kfunc_desc_btf(env, offset);
  2521. if (IS_ERR(desc_btf)) {
  2522. verbose(env, "failed to find BTF for kernel function\n");
  2523. return PTR_ERR(desc_btf);
  2524. }
  2525. if (find_kfunc_desc(env->prog, func_id, offset))
  2526. return 0;
  2527. if (tab->nr_descs == MAX_KFUNC_DESCS) {
  2528. verbose(env, "too many different kernel function calls\n");
  2529. return -E2BIG;
  2530. }
  2531. func = btf_type_by_id(desc_btf, func_id);
  2532. if (!func || !btf_type_is_func(func)) {
  2533. verbose(env, "kernel btf_id %u is not a function\n",
  2534. func_id);
  2535. return -EINVAL;
  2536. }
  2537. func_proto = btf_type_by_id(desc_btf, func->type);
  2538. if (!func_proto || !btf_type_is_func_proto(func_proto)) {
  2539. verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
  2540. func_id);
  2541. return -EINVAL;
  2542. }
  2543. func_name = btf_name_by_offset(desc_btf, func->name_off);
  2544. addr = kallsyms_lookup_name(func_name);
  2545. if (!addr) {
  2546. verbose(env, "cannot find address for kernel function %s\n",
  2547. func_name);
  2548. return -EINVAL;
  2549. }
  2550. specialize_kfunc(env, func_id, offset, &addr);
  2551. if (bpf_jit_supports_far_kfunc_call()) {
  2552. call_imm = func_id;
  2553. } else {
  2554. call_imm = BPF_CALL_IMM(addr);
  2555. /* Check whether the relative offset overflows desc->imm */
  2556. if ((unsigned long)(s32)call_imm != call_imm) {
  2557. verbose(env, "address of kernel function %s is out of range\n",
  2558. func_name);
  2559. return -EINVAL;
  2560. }
  2561. }
  2562. if (bpf_dev_bound_kfunc_id(func_id)) {
  2563. err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
  2564. if (err)
  2565. return err;
  2566. }
  2567. desc = &tab->descs[tab->nr_descs++];
  2568. desc->func_id = func_id;
  2569. desc->imm = call_imm;
  2570. desc->offset = offset;
  2571. desc->addr = addr;
  2572. err = btf_distill_func_proto(&env->log, desc_btf,
  2573. func_proto, func_name,
  2574. &desc->func_model);
  2575. if (!err)
  2576. sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
  2577. kfunc_desc_cmp_by_id_off, NULL);
  2578. return err;
  2579. }
  2580. static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
  2581. {
  2582. const struct bpf_kfunc_desc *d0 = a;
  2583. const struct bpf_kfunc_desc *d1 = b;
  2584. if (d0->imm != d1->imm)
  2585. return d0->imm < d1->imm ? -1 : 1;
  2586. if (d0->offset != d1->offset)
  2587. return d0->offset < d1->offset ? -1 : 1;
  2588. return 0;
  2589. }
  2590. static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
  2591. {
  2592. struct bpf_kfunc_desc_tab *tab;
  2593. tab = prog->aux->kfunc_tab;
  2594. if (!tab)
  2595. return;
  2596. sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
  2597. kfunc_desc_cmp_by_imm_off, NULL);
  2598. }
  2599. bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
  2600. {
  2601. return !!prog->aux->kfunc_tab;
  2602. }
  2603. const struct btf_func_model *
  2604. bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
  2605. const struct bpf_insn *insn)
  2606. {
  2607. const struct bpf_kfunc_desc desc = {
  2608. .imm = insn->imm,
  2609. .offset = insn->off,
  2610. };
  2611. const struct bpf_kfunc_desc *res;
  2612. struct bpf_kfunc_desc_tab *tab;
  2613. tab = prog->aux->kfunc_tab;
  2614. res = bsearch(&desc, tab->descs, tab->nr_descs,
  2615. sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
  2616. return res ? &res->func_model : NULL;
  2617. }
  2618. static int add_kfunc_in_insns(struct bpf_verifier_env *env,
  2619. struct bpf_insn *insn, int cnt)
  2620. {
  2621. int i, ret;
  2622. for (i = 0; i < cnt; i++, insn++) {
  2623. if (bpf_pseudo_kfunc_call(insn)) {
  2624. ret = add_kfunc_call(env, insn->imm, insn->off);
  2625. if (ret < 0)
  2626. return ret;
  2627. }
  2628. }
  2629. return 0;
  2630. }
  2631. static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
  2632. {
  2633. struct bpf_subprog_info *subprog = env->subprog_info;
  2634. int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
  2635. struct bpf_insn *insn = env->prog->insnsi;
  2636. /* Add entry function. */
  2637. ret = add_subprog(env, 0);
  2638. if (ret)
  2639. return ret;
  2640. for (i = 0; i < insn_cnt; i++, insn++) {
  2641. if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
  2642. !bpf_pseudo_kfunc_call(insn))
  2643. continue;
  2644. if (!env->bpf_capable) {
  2645. verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
  2646. return -EPERM;
  2647. }
  2648. if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
  2649. ret = add_subprog(env, i + insn->imm + 1);
  2650. else
  2651. ret = add_kfunc_call(env, insn->imm, insn->off);
  2652. if (ret < 0)
  2653. return ret;
  2654. }
  2655. ret = bpf_find_exception_callback_insn_off(env);
  2656. if (ret < 0)
  2657. return ret;
  2658. ex_cb_insn = ret;
  2659. /* If ex_cb_insn > 0, this means that the main program has a subprog
  2660. * marked using BTF decl tag to serve as the exception callback.
  2661. */
  2662. if (ex_cb_insn) {
  2663. ret = add_subprog(env, ex_cb_insn);
  2664. if (ret < 0)
  2665. return ret;
  2666. for (i = 1; i < env->subprog_cnt; i++) {
  2667. if (env->subprog_info[i].start != ex_cb_insn)
  2668. continue;
  2669. env->exception_callback_subprog = i;
  2670. mark_subprog_exc_cb(env, i);
  2671. break;
  2672. }
  2673. }
  2674. /* Add a fake 'exit' subprog which could simplify subprog iteration
  2675. * logic. 'subprog_cnt' should not be increased.
  2676. */
  2677. subprog[env->subprog_cnt].start = insn_cnt;
  2678. if (env->log.level & BPF_LOG_LEVEL2)
  2679. for (i = 0; i < env->subprog_cnt; i++)
  2680. verbose(env, "func#%d @%d\n", i, subprog[i].start);
  2681. return 0;
  2682. }
  2683. static int check_subprogs(struct bpf_verifier_env *env)
  2684. {
  2685. int i, subprog_start, subprog_end, off, cur_subprog = 0;
  2686. struct bpf_subprog_info *subprog = env->subprog_info;
  2687. struct bpf_insn *insn = env->prog->insnsi;
  2688. int insn_cnt = env->prog->len;
  2689. /* now check that all jumps are within the same subprog */
  2690. subprog_start = subprog[cur_subprog].start;
  2691. subprog_end = subprog[cur_subprog + 1].start;
  2692. for (i = 0; i < insn_cnt; i++) {
  2693. u8 code = insn[i].code;
  2694. if (code == (BPF_JMP | BPF_CALL) &&
  2695. insn[i].src_reg == 0 &&
  2696. insn[i].imm == BPF_FUNC_tail_call) {
  2697. subprog[cur_subprog].has_tail_call = true;
  2698. subprog[cur_subprog].tail_call_reachable = true;
  2699. }
  2700. if (BPF_CLASS(code) == BPF_LD &&
  2701. (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
  2702. subprog[cur_subprog].has_ld_abs = true;
  2703. if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
  2704. goto next;
  2705. if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
  2706. goto next;
  2707. if (code == (BPF_JMP32 | BPF_JA))
  2708. off = i + insn[i].imm + 1;
  2709. else
  2710. off = i + insn[i].off + 1;
  2711. if (off < subprog_start || off >= subprog_end) {
  2712. verbose(env, "jump out of range from insn %d to %d\n", i, off);
  2713. return -EINVAL;
  2714. }
  2715. next:
  2716. if (i == subprog_end - 1) {
  2717. /* to avoid fall-through from one subprog into another
  2718. * the last insn of the subprog should be either exit
  2719. * or unconditional jump back or bpf_throw call
  2720. */
  2721. if (code != (BPF_JMP | BPF_EXIT) &&
  2722. code != (BPF_JMP32 | BPF_JA) &&
  2723. code != (BPF_JMP | BPF_JA)) {
  2724. verbose(env, "last insn is not an exit or jmp\n");
  2725. return -EINVAL;
  2726. }
  2727. subprog_start = subprog_end;
  2728. cur_subprog++;
  2729. if (cur_subprog < env->subprog_cnt)
  2730. subprog_end = subprog[cur_subprog + 1].start;
  2731. }
  2732. }
  2733. return 0;
  2734. }
  2735. /* Parentage chain of this register (or stack slot) should take care of all
  2736. * issues like callee-saved registers, stack slot allocation time, etc.
  2737. */
  2738. static int mark_reg_read(struct bpf_verifier_env *env,
  2739. const struct bpf_reg_state *state,
  2740. struct bpf_reg_state *parent, u8 flag)
  2741. {
  2742. bool writes = parent == state->parent; /* Observe write marks */
  2743. int cnt = 0;
  2744. while (parent) {
  2745. /* if read wasn't screened by an earlier write ... */
  2746. if (writes && state->live & REG_LIVE_WRITTEN)
  2747. break;
  2748. if (parent->live & REG_LIVE_DONE) {
  2749. verbose(env, "verifier BUG type %s var_off %lld off %d\n",
  2750. reg_type_str(env, parent->type),
  2751. parent->var_off.value, parent->off);
  2752. return -EFAULT;
  2753. }
  2754. /* The first condition is more likely to be true than the
  2755. * second, checked it first.
  2756. */
  2757. if ((parent->live & REG_LIVE_READ) == flag ||
  2758. parent->live & REG_LIVE_READ64)
  2759. /* The parentage chain never changes and
  2760. * this parent was already marked as LIVE_READ.
  2761. * There is no need to keep walking the chain again and
  2762. * keep re-marking all parents as LIVE_READ.
  2763. * This case happens when the same register is read
  2764. * multiple times without writes into it in-between.
  2765. * Also, if parent has the stronger REG_LIVE_READ64 set,
  2766. * then no need to set the weak REG_LIVE_READ32.
  2767. */
  2768. break;
  2769. /* ... then we depend on parent's value */
  2770. parent->live |= flag;
  2771. /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
  2772. if (flag == REG_LIVE_READ64)
  2773. parent->live &= ~REG_LIVE_READ32;
  2774. state = parent;
  2775. parent = state->parent;
  2776. writes = true;
  2777. cnt++;
  2778. }
  2779. if (env->longest_mark_read_walk < cnt)
  2780. env->longest_mark_read_walk = cnt;
  2781. return 0;
  2782. }
  2783. static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  2784. {
  2785. struct bpf_func_state *state = func(env, reg);
  2786. int spi, ret;
  2787. /* For CONST_PTR_TO_DYNPTR, it must have already been done by
  2788. * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
  2789. * check_kfunc_call.
  2790. */
  2791. if (reg->type == CONST_PTR_TO_DYNPTR)
  2792. return 0;
  2793. spi = dynptr_get_spi(env, reg);
  2794. if (spi < 0)
  2795. return spi;
  2796. /* Caller ensures dynptr is valid and initialized, which means spi is in
  2797. * bounds and spi is the first dynptr slot. Simply mark stack slot as
  2798. * read.
  2799. */
  2800. ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
  2801. state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
  2802. if (ret)
  2803. return ret;
  2804. return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
  2805. state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
  2806. }
  2807. static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  2808. int spi, int nr_slots)
  2809. {
  2810. struct bpf_func_state *state = func(env, reg);
  2811. int err, i;
  2812. for (i = 0; i < nr_slots; i++) {
  2813. struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
  2814. err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
  2815. if (err)
  2816. return err;
  2817. mark_stack_slot_scratched(env, spi - i);
  2818. }
  2819. return 0;
  2820. }
  2821. /* This function is supposed to be used by the following 32-bit optimization
  2822. * code only. It returns TRUE if the source or destination register operates
  2823. * on 64-bit, otherwise return FALSE.
  2824. */
  2825. static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
  2826. u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
  2827. {
  2828. u8 code, class, op;
  2829. code = insn->code;
  2830. class = BPF_CLASS(code);
  2831. op = BPF_OP(code);
  2832. if (class == BPF_JMP) {
  2833. /* BPF_EXIT for "main" will reach here. Return TRUE
  2834. * conservatively.
  2835. */
  2836. if (op == BPF_EXIT)
  2837. return true;
  2838. if (op == BPF_CALL) {
  2839. /* BPF to BPF call will reach here because of marking
  2840. * caller saved clobber with DST_OP_NO_MARK for which we
  2841. * don't care the register def because they are anyway
  2842. * marked as NOT_INIT already.
  2843. */
  2844. if (insn->src_reg == BPF_PSEUDO_CALL)
  2845. return false;
  2846. /* Helper call will reach here because of arg type
  2847. * check, conservatively return TRUE.
  2848. */
  2849. if (t == SRC_OP)
  2850. return true;
  2851. return false;
  2852. }
  2853. }
  2854. if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
  2855. return false;
  2856. if (class == BPF_ALU64 || class == BPF_JMP ||
  2857. (class == BPF_ALU && op == BPF_END && insn->imm == 64))
  2858. return true;
  2859. if (class == BPF_ALU || class == BPF_JMP32)
  2860. return false;
  2861. if (class == BPF_LDX) {
  2862. if (t != SRC_OP)
  2863. return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
  2864. /* LDX source must be ptr. */
  2865. return true;
  2866. }
  2867. if (class == BPF_STX) {
  2868. /* BPF_STX (including atomic variants) has multiple source
  2869. * operands, one of which is a ptr. Check whether the caller is
  2870. * asking about it.
  2871. */
  2872. if (t == SRC_OP && reg->type != SCALAR_VALUE)
  2873. return true;
  2874. return BPF_SIZE(code) == BPF_DW;
  2875. }
  2876. if (class == BPF_LD) {
  2877. u8 mode = BPF_MODE(code);
  2878. /* LD_IMM64 */
  2879. if (mode == BPF_IMM)
  2880. return true;
  2881. /* Both LD_IND and LD_ABS return 32-bit data. */
  2882. if (t != SRC_OP)
  2883. return false;
  2884. /* Implicit ctx ptr. */
  2885. if (regno == BPF_REG_6)
  2886. return true;
  2887. /* Explicit source could be any width. */
  2888. return true;
  2889. }
  2890. if (class == BPF_ST)
  2891. /* The only source register for BPF_ST is a ptr. */
  2892. return true;
  2893. /* Conservatively return true at default. */
  2894. return true;
  2895. }
  2896. /* Return the regno defined by the insn, or -1. */
  2897. static int insn_def_regno(const struct bpf_insn *insn)
  2898. {
  2899. switch (BPF_CLASS(insn->code)) {
  2900. case BPF_JMP:
  2901. case BPF_JMP32:
  2902. case BPF_ST:
  2903. return -1;
  2904. case BPF_STX:
  2905. if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
  2906. BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
  2907. (insn->imm & BPF_FETCH)) {
  2908. if (insn->imm == BPF_CMPXCHG)
  2909. return BPF_REG_0;
  2910. else
  2911. return insn->src_reg;
  2912. } else {
  2913. return -1;
  2914. }
  2915. default:
  2916. return insn->dst_reg;
  2917. }
  2918. }
  2919. /* Return TRUE if INSN has defined any 32-bit value explicitly. */
  2920. static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
  2921. {
  2922. int dst_reg = insn_def_regno(insn);
  2923. if (dst_reg == -1)
  2924. return false;
  2925. return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
  2926. }
  2927. static void mark_insn_zext(struct bpf_verifier_env *env,
  2928. struct bpf_reg_state *reg)
  2929. {
  2930. s32 def_idx = reg->subreg_def;
  2931. if (def_idx == DEF_NOT_SUBREG)
  2932. return;
  2933. env->insn_aux_data[def_idx - 1].zext_dst = true;
  2934. /* The dst will be zero extended, so won't be sub-register anymore. */
  2935. reg->subreg_def = DEF_NOT_SUBREG;
  2936. }
  2937. static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
  2938. enum reg_arg_type t)
  2939. {
  2940. struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
  2941. struct bpf_reg_state *reg;
  2942. bool rw64;
  2943. if (regno >= MAX_BPF_REG) {
  2944. verbose(env, "R%d is invalid\n", regno);
  2945. return -EINVAL;
  2946. }
  2947. mark_reg_scratched(env, regno);
  2948. reg = &regs[regno];
  2949. rw64 = is_reg64(env, insn, regno, reg, t);
  2950. if (t == SRC_OP) {
  2951. /* check whether register used as source operand can be read */
  2952. if (reg->type == NOT_INIT) {
  2953. verbose(env, "R%d !read_ok\n", regno);
  2954. return -EACCES;
  2955. }
  2956. /* We don't need to worry about FP liveness because it's read-only */
  2957. if (regno == BPF_REG_FP)
  2958. return 0;
  2959. if (rw64)
  2960. mark_insn_zext(env, reg);
  2961. return mark_reg_read(env, reg, reg->parent,
  2962. rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
  2963. } else {
  2964. /* check whether register used as dest operand can be written to */
  2965. if (regno == BPF_REG_FP) {
  2966. verbose(env, "frame pointer is read only\n");
  2967. return -EACCES;
  2968. }
  2969. reg->live |= REG_LIVE_WRITTEN;
  2970. reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
  2971. if (t == DST_OP)
  2972. mark_reg_unknown(env, regs, regno);
  2973. }
  2974. return 0;
  2975. }
  2976. static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
  2977. enum reg_arg_type t)
  2978. {
  2979. struct bpf_verifier_state *vstate = env->cur_state;
  2980. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  2981. return __check_reg_arg(env, state->regs, regno, t);
  2982. }
  2983. static int insn_stack_access_flags(int frameno, int spi)
  2984. {
  2985. return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
  2986. }
  2987. static int insn_stack_access_spi(int insn_flags)
  2988. {
  2989. return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
  2990. }
  2991. static int insn_stack_access_frameno(int insn_flags)
  2992. {
  2993. return insn_flags & INSN_F_FRAMENO_MASK;
  2994. }
  2995. static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
  2996. {
  2997. env->insn_aux_data[idx].jmp_point = true;
  2998. }
  2999. static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
  3000. {
  3001. return env->insn_aux_data[insn_idx].jmp_point;
  3002. }
  3003. #define LR_FRAMENO_BITS 3
  3004. #define LR_SPI_BITS 6
  3005. #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1)
  3006. #define LR_SIZE_BITS 4
  3007. #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1)
  3008. #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1)
  3009. #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1)
  3010. #define LR_SPI_OFF LR_FRAMENO_BITS
  3011. #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS)
  3012. #define LINKED_REGS_MAX 6
  3013. struct linked_reg {
  3014. u8 frameno;
  3015. union {
  3016. u8 spi;
  3017. u8 regno;
  3018. };
  3019. bool is_reg;
  3020. };
  3021. struct linked_regs {
  3022. int cnt;
  3023. struct linked_reg entries[LINKED_REGS_MAX];
  3024. };
  3025. static struct linked_reg *linked_regs_push(struct linked_regs *s)
  3026. {
  3027. if (s->cnt < LINKED_REGS_MAX)
  3028. return &s->entries[s->cnt++];
  3029. return NULL;
  3030. }
  3031. /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
  3032. * number of elements currently in stack.
  3033. * Pack one history entry for linked registers as 10 bits in the following format:
  3034. * - 3-bits frameno
  3035. * - 6-bits spi_or_reg
  3036. * - 1-bit is_reg
  3037. */
  3038. static u64 linked_regs_pack(struct linked_regs *s)
  3039. {
  3040. u64 val = 0;
  3041. int i;
  3042. for (i = 0; i < s->cnt; ++i) {
  3043. struct linked_reg *e = &s->entries[i];
  3044. u64 tmp = 0;
  3045. tmp |= e->frameno;
  3046. tmp |= e->spi << LR_SPI_OFF;
  3047. tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
  3048. val <<= LR_ENTRY_BITS;
  3049. val |= tmp;
  3050. }
  3051. val <<= LR_SIZE_BITS;
  3052. val |= s->cnt;
  3053. return val;
  3054. }
  3055. static void linked_regs_unpack(u64 val, struct linked_regs *s)
  3056. {
  3057. int i;
  3058. s->cnt = val & LR_SIZE_MASK;
  3059. val >>= LR_SIZE_BITS;
  3060. for (i = 0; i < s->cnt; ++i) {
  3061. struct linked_reg *e = &s->entries[i];
  3062. e->frameno = val & LR_FRAMENO_MASK;
  3063. e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK;
  3064. e->is_reg = (val >> LR_IS_REG_OFF) & 0x1;
  3065. val >>= LR_ENTRY_BITS;
  3066. }
  3067. }
  3068. /* for any branch, call, exit record the history of jmps in the given state */
  3069. static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
  3070. int insn_flags, u64 linked_regs)
  3071. {
  3072. struct bpf_insn_hist_entry *p;
  3073. size_t alloc_size;
  3074. /* combine instruction flags if we already recorded this instruction */
  3075. if (env->cur_hist_ent) {
  3076. /* atomic instructions push insn_flags twice, for READ and
  3077. * WRITE sides, but they should agree on stack slot
  3078. */
  3079. WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
  3080. (env->cur_hist_ent->flags & insn_flags) != insn_flags,
  3081. "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
  3082. env->insn_idx, env->cur_hist_ent->flags, insn_flags);
  3083. env->cur_hist_ent->flags |= insn_flags;
  3084. WARN_ONCE(env->cur_hist_ent->linked_regs != 0,
  3085. "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n",
  3086. env->insn_idx, env->cur_hist_ent->linked_regs);
  3087. env->cur_hist_ent->linked_regs = linked_regs;
  3088. return 0;
  3089. }
  3090. if (cur->insn_hist_end + 1 > env->insn_hist_cap) {
  3091. alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p));
  3092. p = kvrealloc(env->insn_hist, alloc_size, GFP_USER);
  3093. if (!p)
  3094. return -ENOMEM;
  3095. env->insn_hist = p;
  3096. env->insn_hist_cap = alloc_size / sizeof(*p);
  3097. }
  3098. p = &env->insn_hist[cur->insn_hist_end];
  3099. p->idx = env->insn_idx;
  3100. p->prev_idx = env->prev_insn_idx;
  3101. p->flags = insn_flags;
  3102. p->linked_regs = linked_regs;
  3103. cur->insn_hist_end++;
  3104. env->cur_hist_ent = p;
  3105. return 0;
  3106. }
  3107. static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env,
  3108. u32 hist_start, u32 hist_end, int insn_idx)
  3109. {
  3110. if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx)
  3111. return &env->insn_hist[hist_end - 1];
  3112. return NULL;
  3113. }
  3114. /* Backtrack one insn at a time. If idx is not at the top of recorded
  3115. * history then previous instruction came from straight line execution.
  3116. * Return -ENOENT if we exhausted all instructions within given state.
  3117. *
  3118. * It's legal to have a bit of a looping with the same starting and ending
  3119. * insn index within the same state, e.g.: 3->4->5->3, so just because current
  3120. * instruction index is the same as state's first_idx doesn't mean we are
  3121. * done. If there is still some jump history left, we should keep going. We
  3122. * need to take into account that we might have a jump history between given
  3123. * state's parent and itself, due to checkpointing. In this case, we'll have
  3124. * history entry recording a jump from last instruction of parent state and
  3125. * first instruction of given state.
  3126. */
  3127. static int get_prev_insn_idx(const struct bpf_verifier_env *env,
  3128. struct bpf_verifier_state *st,
  3129. int insn_idx, u32 hist_start, u32 *hist_endp)
  3130. {
  3131. u32 hist_end = *hist_endp;
  3132. u32 cnt = hist_end - hist_start;
  3133. if (insn_idx == st->first_insn_idx) {
  3134. if (cnt == 0)
  3135. return -ENOENT;
  3136. if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx)
  3137. return -ENOENT;
  3138. }
  3139. if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) {
  3140. (*hist_endp)--;
  3141. return env->insn_hist[hist_end - 1].prev_idx;
  3142. } else {
  3143. return insn_idx - 1;
  3144. }
  3145. }
  3146. static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
  3147. {
  3148. const struct btf_type *func;
  3149. struct btf *desc_btf;
  3150. if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
  3151. return NULL;
  3152. desc_btf = find_kfunc_desc_btf(data, insn->off);
  3153. if (IS_ERR(desc_btf))
  3154. return "<error>";
  3155. func = btf_type_by_id(desc_btf, insn->imm);
  3156. return btf_name_by_offset(desc_btf, func->name_off);
  3157. }
  3158. static inline void bt_init(struct backtrack_state *bt, u32 frame)
  3159. {
  3160. bt->frame = frame;
  3161. }
  3162. static inline void bt_reset(struct backtrack_state *bt)
  3163. {
  3164. struct bpf_verifier_env *env = bt->env;
  3165. memset(bt, 0, sizeof(*bt));
  3166. bt->env = env;
  3167. }
  3168. static inline u32 bt_empty(struct backtrack_state *bt)
  3169. {
  3170. u64 mask = 0;
  3171. int i;
  3172. for (i = 0; i <= bt->frame; i++)
  3173. mask |= bt->reg_masks[i] | bt->stack_masks[i];
  3174. return mask == 0;
  3175. }
  3176. static inline int bt_subprog_enter(struct backtrack_state *bt)
  3177. {
  3178. if (bt->frame == MAX_CALL_FRAMES - 1) {
  3179. verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
  3180. WARN_ONCE(1, "verifier backtracking bug");
  3181. return -EFAULT;
  3182. }
  3183. bt->frame++;
  3184. return 0;
  3185. }
  3186. static inline int bt_subprog_exit(struct backtrack_state *bt)
  3187. {
  3188. if (bt->frame == 0) {
  3189. verbose(bt->env, "BUG subprog exit from frame 0\n");
  3190. WARN_ONCE(1, "verifier backtracking bug");
  3191. return -EFAULT;
  3192. }
  3193. bt->frame--;
  3194. return 0;
  3195. }
  3196. static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
  3197. {
  3198. bt->reg_masks[frame] |= 1 << reg;
  3199. }
  3200. static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
  3201. {
  3202. bt->reg_masks[frame] &= ~(1 << reg);
  3203. }
  3204. static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
  3205. {
  3206. bt_set_frame_reg(bt, bt->frame, reg);
  3207. }
  3208. static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
  3209. {
  3210. bt_clear_frame_reg(bt, bt->frame, reg);
  3211. }
  3212. static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
  3213. {
  3214. bt->stack_masks[frame] |= 1ull << slot;
  3215. }
  3216. static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
  3217. {
  3218. bt->stack_masks[frame] &= ~(1ull << slot);
  3219. }
  3220. static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
  3221. {
  3222. return bt->reg_masks[frame];
  3223. }
  3224. static inline u32 bt_reg_mask(struct backtrack_state *bt)
  3225. {
  3226. return bt->reg_masks[bt->frame];
  3227. }
  3228. static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
  3229. {
  3230. return bt->stack_masks[frame];
  3231. }
  3232. static inline u64 bt_stack_mask(struct backtrack_state *bt)
  3233. {
  3234. return bt->stack_masks[bt->frame];
  3235. }
  3236. static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
  3237. {
  3238. return bt->reg_masks[bt->frame] & (1 << reg);
  3239. }
  3240. static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
  3241. {
  3242. return bt->reg_masks[frame] & (1 << reg);
  3243. }
  3244. static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
  3245. {
  3246. return bt->stack_masks[frame] & (1ull << slot);
  3247. }
  3248. /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
  3249. static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
  3250. {
  3251. DECLARE_BITMAP(mask, 64);
  3252. bool first = true;
  3253. int i, n;
  3254. buf[0] = '\0';
  3255. bitmap_from_u64(mask, reg_mask);
  3256. for_each_set_bit(i, mask, 32) {
  3257. n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
  3258. first = false;
  3259. buf += n;
  3260. buf_sz -= n;
  3261. if (buf_sz < 0)
  3262. break;
  3263. }
  3264. }
  3265. /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
  3266. static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
  3267. {
  3268. DECLARE_BITMAP(mask, 64);
  3269. bool first = true;
  3270. int i, n;
  3271. buf[0] = '\0';
  3272. bitmap_from_u64(mask, stack_mask);
  3273. for_each_set_bit(i, mask, 64) {
  3274. n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
  3275. first = false;
  3276. buf += n;
  3277. buf_sz -= n;
  3278. if (buf_sz < 0)
  3279. break;
  3280. }
  3281. }
  3282. /* If any register R in hist->linked_regs is marked as precise in bt,
  3283. * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
  3284. */
  3285. static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist)
  3286. {
  3287. struct linked_regs linked_regs;
  3288. bool some_precise = false;
  3289. int i;
  3290. if (!hist || hist->linked_regs == 0)
  3291. return;
  3292. linked_regs_unpack(hist->linked_regs, &linked_regs);
  3293. for (i = 0; i < linked_regs.cnt; ++i) {
  3294. struct linked_reg *e = &linked_regs.entries[i];
  3295. if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
  3296. (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
  3297. some_precise = true;
  3298. break;
  3299. }
  3300. }
  3301. if (!some_precise)
  3302. return;
  3303. for (i = 0; i < linked_regs.cnt; ++i) {
  3304. struct linked_reg *e = &linked_regs.entries[i];
  3305. if (e->is_reg)
  3306. bt_set_frame_reg(bt, e->frameno, e->regno);
  3307. else
  3308. bt_set_frame_slot(bt, e->frameno, e->spi);
  3309. }
  3310. }
  3311. static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
  3312. /* For given verifier state backtrack_insn() is called from the last insn to
  3313. * the first insn. Its purpose is to compute a bitmask of registers and
  3314. * stack slots that needs precision in the parent verifier state.
  3315. *
  3316. * @idx is an index of the instruction we are currently processing;
  3317. * @subseq_idx is an index of the subsequent instruction that:
  3318. * - *would be* executed next, if jump history is viewed in forward order;
  3319. * - *was* processed previously during backtracking.
  3320. */
  3321. static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
  3322. struct bpf_insn_hist_entry *hist, struct backtrack_state *bt)
  3323. {
  3324. const struct bpf_insn_cbs cbs = {
  3325. .cb_call = disasm_kfunc_name,
  3326. .cb_print = verbose,
  3327. .private_data = env,
  3328. };
  3329. struct bpf_insn *insn = env->prog->insnsi + idx;
  3330. u8 class = BPF_CLASS(insn->code);
  3331. u8 opcode = BPF_OP(insn->code);
  3332. u8 mode = BPF_MODE(insn->code);
  3333. u32 dreg = insn->dst_reg;
  3334. u32 sreg = insn->src_reg;
  3335. u32 spi, i, fr;
  3336. if (insn->code == 0)
  3337. return 0;
  3338. if (env->log.level & BPF_LOG_LEVEL2) {
  3339. fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
  3340. verbose(env, "mark_precise: frame%d: regs=%s ",
  3341. bt->frame, env->tmp_str_buf);
  3342. fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
  3343. verbose(env, "stack=%s before ", env->tmp_str_buf);
  3344. verbose(env, "%d: ", idx);
  3345. print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  3346. }
  3347. /* If there is a history record that some registers gained range at this insn,
  3348. * propagate precision marks to those registers, so that bt_is_reg_set()
  3349. * accounts for these registers.
  3350. */
  3351. bt_sync_linked_regs(bt, hist);
  3352. if (class == BPF_ALU || class == BPF_ALU64) {
  3353. if (!bt_is_reg_set(bt, dreg))
  3354. return 0;
  3355. if (opcode == BPF_END || opcode == BPF_NEG) {
  3356. /* sreg is reserved and unused
  3357. * dreg still need precision before this insn
  3358. */
  3359. return 0;
  3360. } else if (opcode == BPF_MOV) {
  3361. if (BPF_SRC(insn->code) == BPF_X) {
  3362. /* dreg = sreg or dreg = (s8, s16, s32)sreg
  3363. * dreg needs precision after this insn
  3364. * sreg needs precision before this insn
  3365. */
  3366. bt_clear_reg(bt, dreg);
  3367. if (sreg != BPF_REG_FP)
  3368. bt_set_reg(bt, sreg);
  3369. } else {
  3370. /* dreg = K
  3371. * dreg needs precision after this insn.
  3372. * Corresponding register is already marked
  3373. * as precise=true in this verifier state.
  3374. * No further markings in parent are necessary
  3375. */
  3376. bt_clear_reg(bt, dreg);
  3377. }
  3378. } else {
  3379. if (BPF_SRC(insn->code) == BPF_X) {
  3380. /* dreg += sreg
  3381. * both dreg and sreg need precision
  3382. * before this insn
  3383. */
  3384. if (sreg != BPF_REG_FP)
  3385. bt_set_reg(bt, sreg);
  3386. } /* else dreg += K
  3387. * dreg still needs precision before this insn
  3388. */
  3389. }
  3390. } else if (class == BPF_LDX) {
  3391. if (!bt_is_reg_set(bt, dreg))
  3392. return 0;
  3393. bt_clear_reg(bt, dreg);
  3394. /* scalars can only be spilled into stack w/o losing precision.
  3395. * Load from any other memory can be zero extended.
  3396. * The desire to keep that precision is already indicated
  3397. * by 'precise' mark in corresponding register of this state.
  3398. * No further tracking necessary.
  3399. */
  3400. if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
  3401. return 0;
  3402. /* dreg = *(u64 *)[fp - off] was a fill from the stack.
  3403. * that [fp - off] slot contains scalar that needs to be
  3404. * tracked with precision
  3405. */
  3406. spi = insn_stack_access_spi(hist->flags);
  3407. fr = insn_stack_access_frameno(hist->flags);
  3408. bt_set_frame_slot(bt, fr, spi);
  3409. } else if (class == BPF_STX || class == BPF_ST) {
  3410. if (bt_is_reg_set(bt, dreg))
  3411. /* stx & st shouldn't be using _scalar_ dst_reg
  3412. * to access memory. It means backtracking
  3413. * encountered a case of pointer subtraction.
  3414. */
  3415. return -ENOTSUPP;
  3416. /* scalars can only be spilled into stack */
  3417. if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
  3418. return 0;
  3419. spi = insn_stack_access_spi(hist->flags);
  3420. fr = insn_stack_access_frameno(hist->flags);
  3421. if (!bt_is_frame_slot_set(bt, fr, spi))
  3422. return 0;
  3423. bt_clear_frame_slot(bt, fr, spi);
  3424. if (class == BPF_STX)
  3425. bt_set_reg(bt, sreg);
  3426. } else if (class == BPF_JMP || class == BPF_JMP32) {
  3427. if (bpf_pseudo_call(insn)) {
  3428. int subprog_insn_idx, subprog;
  3429. subprog_insn_idx = idx + insn->imm + 1;
  3430. subprog = find_subprog(env, subprog_insn_idx);
  3431. if (subprog < 0)
  3432. return -EFAULT;
  3433. if (subprog_is_global(env, subprog)) {
  3434. /* check that jump history doesn't have any
  3435. * extra instructions from subprog; the next
  3436. * instruction after call to global subprog
  3437. * should be literally next instruction in
  3438. * caller program
  3439. */
  3440. WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
  3441. /* r1-r5 are invalidated after subprog call,
  3442. * so for global func call it shouldn't be set
  3443. * anymore
  3444. */
  3445. if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
  3446. verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
  3447. WARN_ONCE(1, "verifier backtracking bug");
  3448. return -EFAULT;
  3449. }
  3450. /* global subprog always sets R0 */
  3451. bt_clear_reg(bt, BPF_REG_0);
  3452. return 0;
  3453. } else {
  3454. /* static subprog call instruction, which
  3455. * means that we are exiting current subprog,
  3456. * so only r1-r5 could be still requested as
  3457. * precise, r0 and r6-r10 or any stack slot in
  3458. * the current frame should be zero by now
  3459. */
  3460. if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
  3461. verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
  3462. WARN_ONCE(1, "verifier backtracking bug");
  3463. return -EFAULT;
  3464. }
  3465. /* we are now tracking register spills correctly,
  3466. * so any instance of leftover slots is a bug
  3467. */
  3468. if (bt_stack_mask(bt) != 0) {
  3469. verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
  3470. WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
  3471. return -EFAULT;
  3472. }
  3473. /* propagate r1-r5 to the caller */
  3474. for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
  3475. if (bt_is_reg_set(bt, i)) {
  3476. bt_clear_reg(bt, i);
  3477. bt_set_frame_reg(bt, bt->frame - 1, i);
  3478. }
  3479. }
  3480. if (bt_subprog_exit(bt))
  3481. return -EFAULT;
  3482. return 0;
  3483. }
  3484. } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
  3485. /* exit from callback subprog to callback-calling helper or
  3486. * kfunc call. Use idx/subseq_idx check to discern it from
  3487. * straight line code backtracking.
  3488. * Unlike the subprog call handling above, we shouldn't
  3489. * propagate precision of r1-r5 (if any requested), as they are
  3490. * not actually arguments passed directly to callback subprogs
  3491. */
  3492. if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
  3493. verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
  3494. WARN_ONCE(1, "verifier backtracking bug");
  3495. return -EFAULT;
  3496. }
  3497. if (bt_stack_mask(bt) != 0) {
  3498. verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
  3499. WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
  3500. return -EFAULT;
  3501. }
  3502. /* clear r1-r5 in callback subprog's mask */
  3503. for (i = BPF_REG_1; i <= BPF_REG_5; i++)
  3504. bt_clear_reg(bt, i);
  3505. if (bt_subprog_exit(bt))
  3506. return -EFAULT;
  3507. return 0;
  3508. } else if (opcode == BPF_CALL) {
  3509. /* kfunc with imm==0 is invalid and fixup_kfunc_call will
  3510. * catch this error later. Make backtracking conservative
  3511. * with ENOTSUPP.
  3512. */
  3513. if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
  3514. return -ENOTSUPP;
  3515. /* regular helper call sets R0 */
  3516. bt_clear_reg(bt, BPF_REG_0);
  3517. if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
  3518. /* if backtracing was looking for registers R1-R5
  3519. * they should have been found already.
  3520. */
  3521. verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
  3522. WARN_ONCE(1, "verifier backtracking bug");
  3523. return -EFAULT;
  3524. }
  3525. } else if (opcode == BPF_EXIT) {
  3526. bool r0_precise;
  3527. /* Backtracking to a nested function call, 'idx' is a part of
  3528. * the inner frame 'subseq_idx' is a part of the outer frame.
  3529. * In case of a regular function call, instructions giving
  3530. * precision to registers R1-R5 should have been found already.
  3531. * In case of a callback, it is ok to have R1-R5 marked for
  3532. * backtracking, as these registers are set by the function
  3533. * invoking callback.
  3534. */
  3535. if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
  3536. for (i = BPF_REG_1; i <= BPF_REG_5; i++)
  3537. bt_clear_reg(bt, i);
  3538. if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
  3539. verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
  3540. WARN_ONCE(1, "verifier backtracking bug");
  3541. return -EFAULT;
  3542. }
  3543. /* BPF_EXIT in subprog or callback always returns
  3544. * right after the call instruction, so by checking
  3545. * whether the instruction at subseq_idx-1 is subprog
  3546. * call or not we can distinguish actual exit from
  3547. * *subprog* from exit from *callback*. In the former
  3548. * case, we need to propagate r0 precision, if
  3549. * necessary. In the former we never do that.
  3550. */
  3551. r0_precise = subseq_idx - 1 >= 0 &&
  3552. bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
  3553. bt_is_reg_set(bt, BPF_REG_0);
  3554. bt_clear_reg(bt, BPF_REG_0);
  3555. if (bt_subprog_enter(bt))
  3556. return -EFAULT;
  3557. if (r0_precise)
  3558. bt_set_reg(bt, BPF_REG_0);
  3559. /* r6-r9 and stack slots will stay set in caller frame
  3560. * bitmasks until we return back from callee(s)
  3561. */
  3562. return 0;
  3563. } else if (BPF_SRC(insn->code) == BPF_X) {
  3564. if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
  3565. return 0;
  3566. /* dreg <cond> sreg
  3567. * Both dreg and sreg need precision before
  3568. * this insn. If only sreg was marked precise
  3569. * before it would be equally necessary to
  3570. * propagate it to dreg.
  3571. */
  3572. if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
  3573. bt_set_reg(bt, sreg);
  3574. if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
  3575. bt_set_reg(bt, dreg);
  3576. } else if (BPF_SRC(insn->code) == BPF_K) {
  3577. /* dreg <cond> K
  3578. * Only dreg still needs precision before
  3579. * this insn, so for the K-based conditional
  3580. * there is nothing new to be marked.
  3581. */
  3582. }
  3583. } else if (class == BPF_LD) {
  3584. if (!bt_is_reg_set(bt, dreg))
  3585. return 0;
  3586. bt_clear_reg(bt, dreg);
  3587. /* It's ld_imm64 or ld_abs or ld_ind.
  3588. * For ld_imm64 no further tracking of precision
  3589. * into parent is necessary
  3590. */
  3591. if (mode == BPF_IND || mode == BPF_ABS)
  3592. /* to be analyzed */
  3593. return -ENOTSUPP;
  3594. }
  3595. /* Propagate precision marks to linked registers, to account for
  3596. * registers marked as precise in this function.
  3597. */
  3598. bt_sync_linked_regs(bt, hist);
  3599. return 0;
  3600. }
  3601. /* the scalar precision tracking algorithm:
  3602. * . at the start all registers have precise=false.
  3603. * . scalar ranges are tracked as normal through alu and jmp insns.
  3604. * . once precise value of the scalar register is used in:
  3605. * . ptr + scalar alu
  3606. * . if (scalar cond K|scalar)
  3607. * . helper_call(.., scalar, ...) where ARG_CONST is expected
  3608. * backtrack through the verifier states and mark all registers and
  3609. * stack slots with spilled constants that these scalar regisers
  3610. * should be precise.
  3611. * . during state pruning two registers (or spilled stack slots)
  3612. * are equivalent if both are not precise.
  3613. *
  3614. * Note the verifier cannot simply walk register parentage chain,
  3615. * since many different registers and stack slots could have been
  3616. * used to compute single precise scalar.
  3617. *
  3618. * The approach of starting with precise=true for all registers and then
  3619. * backtrack to mark a register as not precise when the verifier detects
  3620. * that program doesn't care about specific value (e.g., when helper
  3621. * takes register as ARG_ANYTHING parameter) is not safe.
  3622. *
  3623. * It's ok to walk single parentage chain of the verifier states.
  3624. * It's possible that this backtracking will go all the way till 1st insn.
  3625. * All other branches will be explored for needing precision later.
  3626. *
  3627. * The backtracking needs to deal with cases like:
  3628. * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
  3629. * r9 -= r8
  3630. * r5 = r9
  3631. * if r5 > 0x79f goto pc+7
  3632. * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
  3633. * r5 += 1
  3634. * ...
  3635. * call bpf_perf_event_output#25
  3636. * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
  3637. *
  3638. * and this case:
  3639. * r6 = 1
  3640. * call foo // uses callee's r6 inside to compute r0
  3641. * r0 += r6
  3642. * if r0 == 0 goto
  3643. *
  3644. * to track above reg_mask/stack_mask needs to be independent for each frame.
  3645. *
  3646. * Also if parent's curframe > frame where backtracking started,
  3647. * the verifier need to mark registers in both frames, otherwise callees
  3648. * may incorrectly prune callers. This is similar to
  3649. * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
  3650. *
  3651. * For now backtracking falls back into conservative marking.
  3652. */
  3653. static void mark_all_scalars_precise(struct bpf_verifier_env *env,
  3654. struct bpf_verifier_state *st)
  3655. {
  3656. struct bpf_func_state *func;
  3657. struct bpf_reg_state *reg;
  3658. int i, j;
  3659. if (env->log.level & BPF_LOG_LEVEL2) {
  3660. verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
  3661. st->curframe);
  3662. }
  3663. /* big hammer: mark all scalars precise in this path.
  3664. * pop_stack may still get !precise scalars.
  3665. * We also skip current state and go straight to first parent state,
  3666. * because precision markings in current non-checkpointed state are
  3667. * not needed. See why in the comment in __mark_chain_precision below.
  3668. */
  3669. for (st = st->parent; st; st = st->parent) {
  3670. for (i = 0; i <= st->curframe; i++) {
  3671. func = st->frame[i];
  3672. for (j = 0; j < BPF_REG_FP; j++) {
  3673. reg = &func->regs[j];
  3674. if (reg->type != SCALAR_VALUE || reg->precise)
  3675. continue;
  3676. reg->precise = true;
  3677. if (env->log.level & BPF_LOG_LEVEL2) {
  3678. verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
  3679. i, j);
  3680. }
  3681. }
  3682. for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
  3683. if (!is_spilled_reg(&func->stack[j]))
  3684. continue;
  3685. reg = &func->stack[j].spilled_ptr;
  3686. if (reg->type != SCALAR_VALUE || reg->precise)
  3687. continue;
  3688. reg->precise = true;
  3689. if (env->log.level & BPF_LOG_LEVEL2) {
  3690. verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
  3691. i, -(j + 1) * 8);
  3692. }
  3693. }
  3694. }
  3695. }
  3696. }
  3697. static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
  3698. {
  3699. struct bpf_func_state *func;
  3700. struct bpf_reg_state *reg;
  3701. int i, j;
  3702. for (i = 0; i <= st->curframe; i++) {
  3703. func = st->frame[i];
  3704. for (j = 0; j < BPF_REG_FP; j++) {
  3705. reg = &func->regs[j];
  3706. if (reg->type != SCALAR_VALUE)
  3707. continue;
  3708. reg->precise = false;
  3709. }
  3710. for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
  3711. if (!is_spilled_reg(&func->stack[j]))
  3712. continue;
  3713. reg = &func->stack[j].spilled_ptr;
  3714. if (reg->type != SCALAR_VALUE)
  3715. continue;
  3716. reg->precise = false;
  3717. }
  3718. }
  3719. }
  3720. /*
  3721. * __mark_chain_precision() backtracks BPF program instruction sequence and
  3722. * chain of verifier states making sure that register *regno* (if regno >= 0)
  3723. * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
  3724. * SCALARS, as well as any other registers and slots that contribute to
  3725. * a tracked state of given registers/stack slots, depending on specific BPF
  3726. * assembly instructions (see backtrack_insns() for exact instruction handling
  3727. * logic). This backtracking relies on recorded insn_hist and is able to
  3728. * traverse entire chain of parent states. This process ends only when all the
  3729. * necessary registers/slots and their transitive dependencies are marked as
  3730. * precise.
  3731. *
  3732. * One important and subtle aspect is that precise marks *do not matter* in
  3733. * the currently verified state (current state). It is important to understand
  3734. * why this is the case.
  3735. *
  3736. * First, note that current state is the state that is not yet "checkpointed",
  3737. * i.e., it is not yet put into env->explored_states, and it has no children
  3738. * states as well. It's ephemeral, and can end up either a) being discarded if
  3739. * compatible explored state is found at some point or BPF_EXIT instruction is
  3740. * reached or b) checkpointed and put into env->explored_states, branching out
  3741. * into one or more children states.
  3742. *
  3743. * In the former case, precise markings in current state are completely
  3744. * ignored by state comparison code (see regsafe() for details). Only
  3745. * checkpointed ("old") state precise markings are important, and if old
  3746. * state's register/slot is precise, regsafe() assumes current state's
  3747. * register/slot as precise and checks value ranges exactly and precisely. If
  3748. * states turn out to be compatible, current state's necessary precise
  3749. * markings and any required parent states' precise markings are enforced
  3750. * after the fact with propagate_precision() logic, after the fact. But it's
  3751. * important to realize that in this case, even after marking current state
  3752. * registers/slots as precise, we immediately discard current state. So what
  3753. * actually matters is any of the precise markings propagated into current
  3754. * state's parent states, which are always checkpointed (due to b) case above).
  3755. * As such, for scenario a) it doesn't matter if current state has precise
  3756. * markings set or not.
  3757. *
  3758. * Now, for the scenario b), checkpointing and forking into child(ren)
  3759. * state(s). Note that before current state gets to checkpointing step, any
  3760. * processed instruction always assumes precise SCALAR register/slot
  3761. * knowledge: if precise value or range is useful to prune jump branch, BPF
  3762. * verifier takes this opportunity enthusiastically. Similarly, when
  3763. * register's value is used to calculate offset or memory address, exact
  3764. * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
  3765. * what we mentioned above about state comparison ignoring precise markings
  3766. * during state comparison, BPF verifier ignores and also assumes precise
  3767. * markings *at will* during instruction verification process. But as verifier
  3768. * assumes precision, it also propagates any precision dependencies across
  3769. * parent states, which are not yet finalized, so can be further restricted
  3770. * based on new knowledge gained from restrictions enforced by their children
  3771. * states. This is so that once those parent states are finalized, i.e., when
  3772. * they have no more active children state, state comparison logic in
  3773. * is_state_visited() would enforce strict and precise SCALAR ranges, if
  3774. * required for correctness.
  3775. *
  3776. * To build a bit more intuition, note also that once a state is checkpointed,
  3777. * the path we took to get to that state is not important. This is crucial
  3778. * property for state pruning. When state is checkpointed and finalized at
  3779. * some instruction index, it can be correctly and safely used to "short
  3780. * circuit" any *compatible* state that reaches exactly the same instruction
  3781. * index. I.e., if we jumped to that instruction from a completely different
  3782. * code path than original finalized state was derived from, it doesn't
  3783. * matter, current state can be discarded because from that instruction
  3784. * forward having a compatible state will ensure we will safely reach the
  3785. * exit. States describe preconditions for further exploration, but completely
  3786. * forget the history of how we got here.
  3787. *
  3788. * This also means that even if we needed precise SCALAR range to get to
  3789. * finalized state, but from that point forward *that same* SCALAR register is
  3790. * never used in a precise context (i.e., it's precise value is not needed for
  3791. * correctness), it's correct and safe to mark such register as "imprecise"
  3792. * (i.e., precise marking set to false). This is what we rely on when we do
  3793. * not set precise marking in current state. If no child state requires
  3794. * precision for any given SCALAR register, it's safe to dictate that it can
  3795. * be imprecise. If any child state does require this register to be precise,
  3796. * we'll mark it precise later retroactively during precise markings
  3797. * propagation from child state to parent states.
  3798. *
  3799. * Skipping precise marking setting in current state is a mild version of
  3800. * relying on the above observation. But we can utilize this property even
  3801. * more aggressively by proactively forgetting any precise marking in the
  3802. * current state (which we inherited from the parent state), right before we
  3803. * checkpoint it and branch off into new child state. This is done by
  3804. * mark_all_scalars_imprecise() to hopefully get more permissive and generic
  3805. * finalized states which help in short circuiting more future states.
  3806. */
  3807. static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
  3808. {
  3809. struct backtrack_state *bt = &env->bt;
  3810. struct bpf_verifier_state *st = env->cur_state;
  3811. int first_idx = st->first_insn_idx;
  3812. int last_idx = env->insn_idx;
  3813. int subseq_idx = -1;
  3814. struct bpf_func_state *func;
  3815. struct bpf_reg_state *reg;
  3816. bool skip_first = true;
  3817. int i, fr, err;
  3818. if (!env->bpf_capable)
  3819. return 0;
  3820. /* set frame number from which we are starting to backtrack */
  3821. bt_init(bt, env->cur_state->curframe);
  3822. /* Do sanity checks against current state of register and/or stack
  3823. * slot, but don't set precise flag in current state, as precision
  3824. * tracking in the current state is unnecessary.
  3825. */
  3826. func = st->frame[bt->frame];
  3827. if (regno >= 0) {
  3828. reg = &func->regs[regno];
  3829. if (reg->type != SCALAR_VALUE) {
  3830. WARN_ONCE(1, "backtracing misuse");
  3831. return -EFAULT;
  3832. }
  3833. bt_set_reg(bt, regno);
  3834. }
  3835. if (bt_empty(bt))
  3836. return 0;
  3837. for (;;) {
  3838. DECLARE_BITMAP(mask, 64);
  3839. u32 hist_start = st->insn_hist_start;
  3840. u32 hist_end = st->insn_hist_end;
  3841. struct bpf_insn_hist_entry *hist;
  3842. if (env->log.level & BPF_LOG_LEVEL2) {
  3843. verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
  3844. bt->frame, last_idx, first_idx, subseq_idx);
  3845. }
  3846. if (last_idx < 0) {
  3847. /* we are at the entry into subprog, which
  3848. * is expected for global funcs, but only if
  3849. * requested precise registers are R1-R5
  3850. * (which are global func's input arguments)
  3851. */
  3852. if (st->curframe == 0 &&
  3853. st->frame[0]->subprogno > 0 &&
  3854. st->frame[0]->callsite == BPF_MAIN_FUNC &&
  3855. bt_stack_mask(bt) == 0 &&
  3856. (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
  3857. bitmap_from_u64(mask, bt_reg_mask(bt));
  3858. for_each_set_bit(i, mask, 32) {
  3859. reg = &st->frame[0]->regs[i];
  3860. bt_clear_reg(bt, i);
  3861. if (reg->type == SCALAR_VALUE)
  3862. reg->precise = true;
  3863. }
  3864. return 0;
  3865. }
  3866. verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
  3867. st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
  3868. WARN_ONCE(1, "verifier backtracking bug");
  3869. return -EFAULT;
  3870. }
  3871. for (i = last_idx;;) {
  3872. if (skip_first) {
  3873. err = 0;
  3874. skip_first = false;
  3875. } else {
  3876. hist = get_insn_hist_entry(env, hist_start, hist_end, i);
  3877. err = backtrack_insn(env, i, subseq_idx, hist, bt);
  3878. }
  3879. if (err == -ENOTSUPP) {
  3880. mark_all_scalars_precise(env, env->cur_state);
  3881. bt_reset(bt);
  3882. return 0;
  3883. } else if (err) {
  3884. return err;
  3885. }
  3886. if (bt_empty(bt))
  3887. /* Found assignment(s) into tracked register in this state.
  3888. * Since this state is already marked, just return.
  3889. * Nothing to be tracked further in the parent state.
  3890. */
  3891. return 0;
  3892. subseq_idx = i;
  3893. i = get_prev_insn_idx(env, st, i, hist_start, &hist_end);
  3894. if (i == -ENOENT)
  3895. break;
  3896. if (i >= env->prog->len) {
  3897. /* This can happen if backtracking reached insn 0
  3898. * and there are still reg_mask or stack_mask
  3899. * to backtrack.
  3900. * It means the backtracking missed the spot where
  3901. * particular register was initialized with a constant.
  3902. */
  3903. verbose(env, "BUG backtracking idx %d\n", i);
  3904. WARN_ONCE(1, "verifier backtracking bug");
  3905. return -EFAULT;
  3906. }
  3907. }
  3908. st = st->parent;
  3909. if (!st)
  3910. break;
  3911. for (fr = bt->frame; fr >= 0; fr--) {
  3912. func = st->frame[fr];
  3913. bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
  3914. for_each_set_bit(i, mask, 32) {
  3915. reg = &func->regs[i];
  3916. if (reg->type != SCALAR_VALUE) {
  3917. bt_clear_frame_reg(bt, fr, i);
  3918. continue;
  3919. }
  3920. if (reg->precise)
  3921. bt_clear_frame_reg(bt, fr, i);
  3922. else
  3923. reg->precise = true;
  3924. }
  3925. bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
  3926. for_each_set_bit(i, mask, 64) {
  3927. if (i >= func->allocated_stack / BPF_REG_SIZE) {
  3928. verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
  3929. i, func->allocated_stack / BPF_REG_SIZE);
  3930. WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
  3931. return -EFAULT;
  3932. }
  3933. if (!is_spilled_scalar_reg(&func->stack[i])) {
  3934. bt_clear_frame_slot(bt, fr, i);
  3935. continue;
  3936. }
  3937. reg = &func->stack[i].spilled_ptr;
  3938. if (reg->precise)
  3939. bt_clear_frame_slot(bt, fr, i);
  3940. else
  3941. reg->precise = true;
  3942. }
  3943. if (env->log.level & BPF_LOG_LEVEL2) {
  3944. fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
  3945. bt_frame_reg_mask(bt, fr));
  3946. verbose(env, "mark_precise: frame%d: parent state regs=%s ",
  3947. fr, env->tmp_str_buf);
  3948. fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
  3949. bt_frame_stack_mask(bt, fr));
  3950. verbose(env, "stack=%s: ", env->tmp_str_buf);
  3951. print_verifier_state(env, func, true);
  3952. }
  3953. }
  3954. if (bt_empty(bt))
  3955. return 0;
  3956. subseq_idx = first_idx;
  3957. last_idx = st->last_insn_idx;
  3958. first_idx = st->first_insn_idx;
  3959. }
  3960. /* if we still have requested precise regs or slots, we missed
  3961. * something (e.g., stack access through non-r10 register), so
  3962. * fallback to marking all precise
  3963. */
  3964. if (!bt_empty(bt)) {
  3965. mark_all_scalars_precise(env, env->cur_state);
  3966. bt_reset(bt);
  3967. }
  3968. return 0;
  3969. }
  3970. int mark_chain_precision(struct bpf_verifier_env *env, int regno)
  3971. {
  3972. return __mark_chain_precision(env, regno);
  3973. }
  3974. /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
  3975. * desired reg and stack masks across all relevant frames
  3976. */
  3977. static int mark_chain_precision_batch(struct bpf_verifier_env *env)
  3978. {
  3979. return __mark_chain_precision(env, -1);
  3980. }
  3981. static bool is_spillable_regtype(enum bpf_reg_type type)
  3982. {
  3983. switch (base_type(type)) {
  3984. case PTR_TO_MAP_VALUE:
  3985. case PTR_TO_STACK:
  3986. case PTR_TO_CTX:
  3987. case PTR_TO_PACKET:
  3988. case PTR_TO_PACKET_META:
  3989. case PTR_TO_PACKET_END:
  3990. case PTR_TO_FLOW_KEYS:
  3991. case CONST_PTR_TO_MAP:
  3992. case PTR_TO_SOCKET:
  3993. case PTR_TO_SOCK_COMMON:
  3994. case PTR_TO_TCP_SOCK:
  3995. case PTR_TO_XDP_SOCK:
  3996. case PTR_TO_BTF_ID:
  3997. case PTR_TO_BUF:
  3998. case PTR_TO_MEM:
  3999. case PTR_TO_FUNC:
  4000. case PTR_TO_MAP_KEY:
  4001. case PTR_TO_ARENA:
  4002. return true;
  4003. default:
  4004. return false;
  4005. }
  4006. }
  4007. /* Does this register contain a constant zero? */
  4008. static bool register_is_null(struct bpf_reg_state *reg)
  4009. {
  4010. return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
  4011. }
  4012. /* check if register is a constant scalar value */
  4013. static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
  4014. {
  4015. return reg->type == SCALAR_VALUE &&
  4016. tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
  4017. }
  4018. /* assuming is_reg_const() is true, return constant value of a register */
  4019. static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
  4020. {
  4021. return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
  4022. }
  4023. static bool __is_pointer_value(bool allow_ptr_leaks,
  4024. const struct bpf_reg_state *reg)
  4025. {
  4026. if (allow_ptr_leaks)
  4027. return false;
  4028. return reg->type != SCALAR_VALUE;
  4029. }
  4030. static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
  4031. struct bpf_reg_state *src_reg)
  4032. {
  4033. if (src_reg->type != SCALAR_VALUE)
  4034. return;
  4035. if (src_reg->id & BPF_ADD_CONST) {
  4036. /*
  4037. * The verifier is processing rX = rY insn and
  4038. * rY->id has special linked register already.
  4039. * Cleared it, since multiple rX += const are not supported.
  4040. */
  4041. src_reg->id = 0;
  4042. src_reg->off = 0;
  4043. }
  4044. if (!src_reg->id && !tnum_is_const(src_reg->var_off))
  4045. /* Ensure that src_reg has a valid ID that will be copied to
  4046. * dst_reg and then will be used by sync_linked_regs() to
  4047. * propagate min/max range.
  4048. */
  4049. src_reg->id = ++env->id_gen;
  4050. }
  4051. /* Copy src state preserving dst->parent and dst->live fields */
  4052. static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
  4053. {
  4054. struct bpf_reg_state *parent = dst->parent;
  4055. enum bpf_reg_liveness live = dst->live;
  4056. *dst = *src;
  4057. dst->parent = parent;
  4058. dst->live = live;
  4059. }
  4060. static void save_register_state(struct bpf_verifier_env *env,
  4061. struct bpf_func_state *state,
  4062. int spi, struct bpf_reg_state *reg,
  4063. int size)
  4064. {
  4065. int i;
  4066. copy_register_state(&state->stack[spi].spilled_ptr, reg);
  4067. if (size == BPF_REG_SIZE)
  4068. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  4069. for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
  4070. state->stack[spi].slot_type[i - 1] = STACK_SPILL;
  4071. /* size < 8 bytes spill */
  4072. for (; i; i--)
  4073. mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
  4074. }
  4075. static bool is_bpf_st_mem(struct bpf_insn *insn)
  4076. {
  4077. return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
  4078. }
  4079. static int get_reg_width(struct bpf_reg_state *reg)
  4080. {
  4081. return fls64(reg->umax_value);
  4082. }
  4083. /* See comment for mark_fastcall_pattern_for_call() */
  4084. static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
  4085. struct bpf_func_state *state, int insn_idx, int off)
  4086. {
  4087. struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
  4088. struct bpf_insn_aux_data *aux = env->insn_aux_data;
  4089. int i;
  4090. if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
  4091. return;
  4092. /* access to the region [max_stack_depth .. fastcall_stack_off)
  4093. * from something that is not a part of the fastcall pattern,
  4094. * disable fastcall rewrites for current subprogram by setting
  4095. * fastcall_stack_off to a value smaller than any possible offset.
  4096. */
  4097. subprog->fastcall_stack_off = S16_MIN;
  4098. /* reset fastcall aux flags within subprogram,
  4099. * happens at most once per subprogram
  4100. */
  4101. for (i = subprog->start; i < (subprog + 1)->start; ++i) {
  4102. aux[i].fastcall_spills_num = 0;
  4103. aux[i].fastcall_pattern = 0;
  4104. }
  4105. }
  4106. /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
  4107. * stack boundary and alignment are checked in check_mem_access()
  4108. */
  4109. static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
  4110. /* stack frame we're writing to */
  4111. struct bpf_func_state *state,
  4112. int off, int size, int value_regno,
  4113. int insn_idx)
  4114. {
  4115. struct bpf_func_state *cur; /* state of the current function */
  4116. int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
  4117. struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
  4118. struct bpf_reg_state *reg = NULL;
  4119. int insn_flags = insn_stack_access_flags(state->frameno, spi);
  4120. /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
  4121. * so it's aligned access and [off, off + size) are within stack limits
  4122. */
  4123. if (!env->allow_ptr_leaks &&
  4124. is_spilled_reg(&state->stack[spi]) &&
  4125. !is_spilled_scalar_reg(&state->stack[spi]) &&
  4126. size != BPF_REG_SIZE) {
  4127. verbose(env, "attempt to corrupt spilled pointer on stack\n");
  4128. return -EACCES;
  4129. }
  4130. cur = env->cur_state->frame[env->cur_state->curframe];
  4131. if (value_regno >= 0)
  4132. reg = &cur->regs[value_regno];
  4133. if (!env->bypass_spec_v4) {
  4134. bool sanitize = reg && is_spillable_regtype(reg->type);
  4135. for (i = 0; i < size; i++) {
  4136. u8 type = state->stack[spi].slot_type[i];
  4137. if (type != STACK_MISC && type != STACK_ZERO) {
  4138. sanitize = true;
  4139. break;
  4140. }
  4141. }
  4142. if (sanitize)
  4143. env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
  4144. }
  4145. err = destroy_if_dynptr_stack_slot(env, state, spi);
  4146. if (err)
  4147. return err;
  4148. check_fastcall_stack_contract(env, state, insn_idx, off);
  4149. mark_stack_slot_scratched(env, spi);
  4150. if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
  4151. bool reg_value_fits;
  4152. reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
  4153. /* Make sure that reg had an ID to build a relation on spill. */
  4154. if (reg_value_fits)
  4155. assign_scalar_id_before_mov(env, reg);
  4156. save_register_state(env, state, spi, reg, size);
  4157. /* Break the relation on a narrowing spill. */
  4158. if (!reg_value_fits)
  4159. state->stack[spi].spilled_ptr.id = 0;
  4160. } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
  4161. env->bpf_capable) {
  4162. struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
  4163. memset(tmp_reg, 0, sizeof(*tmp_reg));
  4164. __mark_reg_known(tmp_reg, insn->imm);
  4165. tmp_reg->type = SCALAR_VALUE;
  4166. save_register_state(env, state, spi, tmp_reg, size);
  4167. } else if (reg && is_spillable_regtype(reg->type)) {
  4168. /* register containing pointer is being spilled into stack */
  4169. if (size != BPF_REG_SIZE) {
  4170. verbose_linfo(env, insn_idx, "; ");
  4171. verbose(env, "invalid size of register spill\n");
  4172. return -EACCES;
  4173. }
  4174. if (state != cur && reg->type == PTR_TO_STACK) {
  4175. verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
  4176. return -EINVAL;
  4177. }
  4178. save_register_state(env, state, spi, reg, size);
  4179. } else {
  4180. u8 type = STACK_MISC;
  4181. /* regular write of data into stack destroys any spilled ptr */
  4182. state->stack[spi].spilled_ptr.type = NOT_INIT;
  4183. /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
  4184. if (is_stack_slot_special(&state->stack[spi]))
  4185. for (i = 0; i < BPF_REG_SIZE; i++)
  4186. scrub_spilled_slot(&state->stack[spi].slot_type[i]);
  4187. /* only mark the slot as written if all 8 bytes were written
  4188. * otherwise read propagation may incorrectly stop too soon
  4189. * when stack slots are partially written.
  4190. * This heuristic means that read propagation will be
  4191. * conservative, since it will add reg_live_read marks
  4192. * to stack slots all the way to first state when programs
  4193. * writes+reads less than 8 bytes
  4194. */
  4195. if (size == BPF_REG_SIZE)
  4196. state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
  4197. /* when we zero initialize stack slots mark them as such */
  4198. if ((reg && register_is_null(reg)) ||
  4199. (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
  4200. /* STACK_ZERO case happened because register spill
  4201. * wasn't properly aligned at the stack slot boundary,
  4202. * so it's not a register spill anymore; force
  4203. * originating register to be precise to make
  4204. * STACK_ZERO correct for subsequent states
  4205. */
  4206. err = mark_chain_precision(env, value_regno);
  4207. if (err)
  4208. return err;
  4209. type = STACK_ZERO;
  4210. }
  4211. /* Mark slots affected by this stack write. */
  4212. for (i = 0; i < size; i++)
  4213. state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
  4214. insn_flags = 0; /* not a register spill */
  4215. }
  4216. if (insn_flags)
  4217. return push_insn_history(env, env->cur_state, insn_flags, 0);
  4218. return 0;
  4219. }
  4220. /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
  4221. * known to contain a variable offset.
  4222. * This function checks whether the write is permitted and conservatively
  4223. * tracks the effects of the write, considering that each stack slot in the
  4224. * dynamic range is potentially written to.
  4225. *
  4226. * 'off' includes 'regno->off'.
  4227. * 'value_regno' can be -1, meaning that an unknown value is being written to
  4228. * the stack.
  4229. *
  4230. * Spilled pointers in range are not marked as written because we don't know
  4231. * what's going to be actually written. This means that read propagation for
  4232. * future reads cannot be terminated by this write.
  4233. *
  4234. * For privileged programs, uninitialized stack slots are considered
  4235. * initialized by this write (even though we don't know exactly what offsets
  4236. * are going to be written to). The idea is that we don't want the verifier to
  4237. * reject future reads that access slots written to through variable offsets.
  4238. */
  4239. static int check_stack_write_var_off(struct bpf_verifier_env *env,
  4240. /* func where register points to */
  4241. struct bpf_func_state *state,
  4242. int ptr_regno, int off, int size,
  4243. int value_regno, int insn_idx)
  4244. {
  4245. struct bpf_func_state *cur; /* state of the current function */
  4246. int min_off, max_off;
  4247. int i, err;
  4248. struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
  4249. struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
  4250. bool writing_zero = false;
  4251. /* set if the fact that we're writing a zero is used to let any
  4252. * stack slots remain STACK_ZERO
  4253. */
  4254. bool zero_used = false;
  4255. cur = env->cur_state->frame[env->cur_state->curframe];
  4256. ptr_reg = &cur->regs[ptr_regno];
  4257. min_off = ptr_reg->smin_value + off;
  4258. max_off = ptr_reg->smax_value + off + size;
  4259. if (value_regno >= 0)
  4260. value_reg = &cur->regs[value_regno];
  4261. if ((value_reg && register_is_null(value_reg)) ||
  4262. (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
  4263. writing_zero = true;
  4264. for (i = min_off; i < max_off; i++) {
  4265. int spi;
  4266. spi = __get_spi(i);
  4267. err = destroy_if_dynptr_stack_slot(env, state, spi);
  4268. if (err)
  4269. return err;
  4270. }
  4271. check_fastcall_stack_contract(env, state, insn_idx, min_off);
  4272. /* Variable offset writes destroy any spilled pointers in range. */
  4273. for (i = min_off; i < max_off; i++) {
  4274. u8 new_type, *stype;
  4275. int slot, spi;
  4276. slot = -i - 1;
  4277. spi = slot / BPF_REG_SIZE;
  4278. stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
  4279. mark_stack_slot_scratched(env, spi);
  4280. if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
  4281. /* Reject the write if range we may write to has not
  4282. * been initialized beforehand. If we didn't reject
  4283. * here, the ptr status would be erased below (even
  4284. * though not all slots are actually overwritten),
  4285. * possibly opening the door to leaks.
  4286. *
  4287. * We do however catch STACK_INVALID case below, and
  4288. * only allow reading possibly uninitialized memory
  4289. * later for CAP_PERFMON, as the write may not happen to
  4290. * that slot.
  4291. */
  4292. verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
  4293. insn_idx, i);
  4294. return -EINVAL;
  4295. }
  4296. /* If writing_zero and the spi slot contains a spill of value 0,
  4297. * maintain the spill type.
  4298. */
  4299. if (writing_zero && *stype == STACK_SPILL &&
  4300. is_spilled_scalar_reg(&state->stack[spi])) {
  4301. struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
  4302. if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
  4303. zero_used = true;
  4304. continue;
  4305. }
  4306. }
  4307. /* Erase all other spilled pointers. */
  4308. state->stack[spi].spilled_ptr.type = NOT_INIT;
  4309. /* Update the slot type. */
  4310. new_type = STACK_MISC;
  4311. if (writing_zero && *stype == STACK_ZERO) {
  4312. new_type = STACK_ZERO;
  4313. zero_used = true;
  4314. }
  4315. /* If the slot is STACK_INVALID, we check whether it's OK to
  4316. * pretend that it will be initialized by this write. The slot
  4317. * might not actually be written to, and so if we mark it as
  4318. * initialized future reads might leak uninitialized memory.
  4319. * For privileged programs, we will accept such reads to slots
  4320. * that may or may not be written because, if we're reject
  4321. * them, the error would be too confusing.
  4322. */
  4323. if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
  4324. verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
  4325. insn_idx, i);
  4326. return -EINVAL;
  4327. }
  4328. *stype = new_type;
  4329. }
  4330. if (zero_used) {
  4331. /* backtracking doesn't work for STACK_ZERO yet. */
  4332. err = mark_chain_precision(env, value_regno);
  4333. if (err)
  4334. return err;
  4335. }
  4336. return 0;
  4337. }
  4338. /* When register 'dst_regno' is assigned some values from stack[min_off,
  4339. * max_off), we set the register's type according to the types of the
  4340. * respective stack slots. If all the stack values are known to be zeros, then
  4341. * so is the destination reg. Otherwise, the register is considered to be
  4342. * SCALAR. This function does not deal with register filling; the caller must
  4343. * ensure that all spilled registers in the stack range have been marked as
  4344. * read.
  4345. */
  4346. static void mark_reg_stack_read(struct bpf_verifier_env *env,
  4347. /* func where src register points to */
  4348. struct bpf_func_state *ptr_state,
  4349. int min_off, int max_off, int dst_regno)
  4350. {
  4351. struct bpf_verifier_state *vstate = env->cur_state;
  4352. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  4353. int i, slot, spi;
  4354. u8 *stype;
  4355. int zeros = 0;
  4356. for (i = min_off; i < max_off; i++) {
  4357. slot = -i - 1;
  4358. spi = slot / BPF_REG_SIZE;
  4359. mark_stack_slot_scratched(env, spi);
  4360. stype = ptr_state->stack[spi].slot_type;
  4361. if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
  4362. break;
  4363. zeros++;
  4364. }
  4365. if (zeros == max_off - min_off) {
  4366. /* Any access_size read into register is zero extended,
  4367. * so the whole register == const_zero.
  4368. */
  4369. __mark_reg_const_zero(env, &state->regs[dst_regno]);
  4370. } else {
  4371. /* have read misc data from the stack */
  4372. mark_reg_unknown(env, state->regs, dst_regno);
  4373. }
  4374. state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
  4375. }
  4376. /* Read the stack at 'off' and put the results into the register indicated by
  4377. * 'dst_regno'. It handles reg filling if the addressed stack slot is a
  4378. * spilled reg.
  4379. *
  4380. * 'dst_regno' can be -1, meaning that the read value is not going to a
  4381. * register.
  4382. *
  4383. * The access is assumed to be within the current stack bounds.
  4384. */
  4385. static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
  4386. /* func where src register points to */
  4387. struct bpf_func_state *reg_state,
  4388. int off, int size, int dst_regno)
  4389. {
  4390. struct bpf_verifier_state *vstate = env->cur_state;
  4391. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  4392. int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
  4393. struct bpf_reg_state *reg;
  4394. u8 *stype, type;
  4395. int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
  4396. stype = reg_state->stack[spi].slot_type;
  4397. reg = &reg_state->stack[spi].spilled_ptr;
  4398. mark_stack_slot_scratched(env, spi);
  4399. check_fastcall_stack_contract(env, state, env->insn_idx, off);
  4400. if (is_spilled_reg(&reg_state->stack[spi])) {
  4401. u8 spill_size = 1;
  4402. for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
  4403. spill_size++;
  4404. if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
  4405. if (reg->type != SCALAR_VALUE) {
  4406. verbose_linfo(env, env->insn_idx, "; ");
  4407. verbose(env, "invalid size of register fill\n");
  4408. return -EACCES;
  4409. }
  4410. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  4411. if (dst_regno < 0)
  4412. return 0;
  4413. if (size <= spill_size &&
  4414. bpf_stack_narrow_access_ok(off, size, spill_size)) {
  4415. /* The earlier check_reg_arg() has decided the
  4416. * subreg_def for this insn. Save it first.
  4417. */
  4418. s32 subreg_def = state->regs[dst_regno].subreg_def;
  4419. copy_register_state(&state->regs[dst_regno], reg);
  4420. state->regs[dst_regno].subreg_def = subreg_def;
  4421. /* Break the relation on a narrowing fill.
  4422. * coerce_reg_to_size will adjust the boundaries.
  4423. */
  4424. if (get_reg_width(reg) > size * BITS_PER_BYTE)
  4425. state->regs[dst_regno].id = 0;
  4426. } else {
  4427. int spill_cnt = 0, zero_cnt = 0;
  4428. for (i = 0; i < size; i++) {
  4429. type = stype[(slot - i) % BPF_REG_SIZE];
  4430. if (type == STACK_SPILL) {
  4431. spill_cnt++;
  4432. continue;
  4433. }
  4434. if (type == STACK_MISC)
  4435. continue;
  4436. if (type == STACK_ZERO) {
  4437. zero_cnt++;
  4438. continue;
  4439. }
  4440. if (type == STACK_INVALID && env->allow_uninit_stack)
  4441. continue;
  4442. verbose(env, "invalid read from stack off %d+%d size %d\n",
  4443. off, i, size);
  4444. return -EACCES;
  4445. }
  4446. if (spill_cnt == size &&
  4447. tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
  4448. __mark_reg_const_zero(env, &state->regs[dst_regno]);
  4449. /* this IS register fill, so keep insn_flags */
  4450. } else if (zero_cnt == size) {
  4451. /* similarly to mark_reg_stack_read(), preserve zeroes */
  4452. __mark_reg_const_zero(env, &state->regs[dst_regno]);
  4453. insn_flags = 0; /* not restoring original register state */
  4454. } else {
  4455. mark_reg_unknown(env, state->regs, dst_regno);
  4456. insn_flags = 0; /* not restoring original register state */
  4457. }
  4458. }
  4459. state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
  4460. } else if (dst_regno >= 0) {
  4461. /* restore register state from stack */
  4462. copy_register_state(&state->regs[dst_regno], reg);
  4463. /* mark reg as written since spilled pointer state likely
  4464. * has its liveness marks cleared by is_state_visited()
  4465. * which resets stack/reg liveness for state transitions
  4466. */
  4467. state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
  4468. } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
  4469. /* If dst_regno==-1, the caller is asking us whether
  4470. * it is acceptable to use this value as a SCALAR_VALUE
  4471. * (e.g. for XADD).
  4472. * We must not allow unprivileged callers to do that
  4473. * with spilled pointers.
  4474. */
  4475. verbose(env, "leaking pointer from stack off %d\n",
  4476. off);
  4477. return -EACCES;
  4478. }
  4479. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  4480. } else {
  4481. for (i = 0; i < size; i++) {
  4482. type = stype[(slot - i) % BPF_REG_SIZE];
  4483. if (type == STACK_MISC)
  4484. continue;
  4485. if (type == STACK_ZERO)
  4486. continue;
  4487. if (type == STACK_INVALID && env->allow_uninit_stack)
  4488. continue;
  4489. verbose(env, "invalid read from stack off %d+%d size %d\n",
  4490. off, i, size);
  4491. return -EACCES;
  4492. }
  4493. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  4494. if (dst_regno >= 0)
  4495. mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
  4496. insn_flags = 0; /* we are not restoring spilled register */
  4497. }
  4498. if (insn_flags)
  4499. return push_insn_history(env, env->cur_state, insn_flags, 0);
  4500. return 0;
  4501. }
  4502. enum bpf_access_src {
  4503. ACCESS_DIRECT = 1, /* the access is performed by an instruction */
  4504. ACCESS_HELPER = 2, /* the access is performed by a helper */
  4505. };
  4506. static int check_stack_range_initialized(struct bpf_verifier_env *env,
  4507. int regno, int off, int access_size,
  4508. bool zero_size_allowed,
  4509. enum bpf_access_src type,
  4510. struct bpf_call_arg_meta *meta);
  4511. static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
  4512. {
  4513. return cur_regs(env) + regno;
  4514. }
  4515. /* Read the stack at 'ptr_regno + off' and put the result into the register
  4516. * 'dst_regno'.
  4517. * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
  4518. * but not its variable offset.
  4519. * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
  4520. *
  4521. * As opposed to check_stack_read_fixed_off, this function doesn't deal with
  4522. * filling registers (i.e. reads of spilled register cannot be detected when
  4523. * the offset is not fixed). We conservatively mark 'dst_regno' as containing
  4524. * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
  4525. * offset; for a fixed offset check_stack_read_fixed_off should be used
  4526. * instead.
  4527. */
  4528. static int check_stack_read_var_off(struct bpf_verifier_env *env,
  4529. int ptr_regno, int off, int size, int dst_regno)
  4530. {
  4531. /* The state of the source register. */
  4532. struct bpf_reg_state *reg = reg_state(env, ptr_regno);
  4533. struct bpf_func_state *ptr_state = func(env, reg);
  4534. int err;
  4535. int min_off, max_off;
  4536. /* Note that we pass a NULL meta, so raw access will not be permitted.
  4537. */
  4538. err = check_stack_range_initialized(env, ptr_regno, off, size,
  4539. false, ACCESS_DIRECT, NULL);
  4540. if (err)
  4541. return err;
  4542. min_off = reg->smin_value + off;
  4543. max_off = reg->smax_value + off;
  4544. mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
  4545. check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
  4546. return 0;
  4547. }
  4548. /* check_stack_read dispatches to check_stack_read_fixed_off or
  4549. * check_stack_read_var_off.
  4550. *
  4551. * The caller must ensure that the offset falls within the allocated stack
  4552. * bounds.
  4553. *
  4554. * 'dst_regno' is a register which will receive the value from the stack. It
  4555. * can be -1, meaning that the read value is not going to a register.
  4556. */
  4557. static int check_stack_read(struct bpf_verifier_env *env,
  4558. int ptr_regno, int off, int size,
  4559. int dst_regno)
  4560. {
  4561. struct bpf_reg_state *reg = reg_state(env, ptr_regno);
  4562. struct bpf_func_state *state = func(env, reg);
  4563. int err;
  4564. /* Some accesses are only permitted with a static offset. */
  4565. bool var_off = !tnum_is_const(reg->var_off);
  4566. /* The offset is required to be static when reads don't go to a
  4567. * register, in order to not leak pointers (see
  4568. * check_stack_read_fixed_off).
  4569. */
  4570. if (dst_regno < 0 && var_off) {
  4571. char tn_buf[48];
  4572. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  4573. verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
  4574. tn_buf, off, size);
  4575. return -EACCES;
  4576. }
  4577. /* Variable offset is prohibited for unprivileged mode for simplicity
  4578. * since it requires corresponding support in Spectre masking for stack
  4579. * ALU. See also retrieve_ptr_limit(). The check in
  4580. * check_stack_access_for_ptr_arithmetic() called by
  4581. * adjust_ptr_min_max_vals() prevents users from creating stack pointers
  4582. * with variable offsets, therefore no check is required here. Further,
  4583. * just checking it here would be insufficient as speculative stack
  4584. * writes could still lead to unsafe speculative behaviour.
  4585. */
  4586. if (!var_off) {
  4587. off += reg->var_off.value;
  4588. err = check_stack_read_fixed_off(env, state, off, size,
  4589. dst_regno);
  4590. } else {
  4591. /* Variable offset stack reads need more conservative handling
  4592. * than fixed offset ones. Note that dst_regno >= 0 on this
  4593. * branch.
  4594. */
  4595. err = check_stack_read_var_off(env, ptr_regno, off, size,
  4596. dst_regno);
  4597. }
  4598. return err;
  4599. }
  4600. /* check_stack_write dispatches to check_stack_write_fixed_off or
  4601. * check_stack_write_var_off.
  4602. *
  4603. * 'ptr_regno' is the register used as a pointer into the stack.
  4604. * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
  4605. * 'value_regno' is the register whose value we're writing to the stack. It can
  4606. * be -1, meaning that we're not writing from a register.
  4607. *
  4608. * The caller must ensure that the offset falls within the maximum stack size.
  4609. */
  4610. static int check_stack_write(struct bpf_verifier_env *env,
  4611. int ptr_regno, int off, int size,
  4612. int value_regno, int insn_idx)
  4613. {
  4614. struct bpf_reg_state *reg = reg_state(env, ptr_regno);
  4615. struct bpf_func_state *state = func(env, reg);
  4616. int err;
  4617. if (tnum_is_const(reg->var_off)) {
  4618. off += reg->var_off.value;
  4619. err = check_stack_write_fixed_off(env, state, off, size,
  4620. value_regno, insn_idx);
  4621. } else {
  4622. /* Variable offset stack reads need more conservative handling
  4623. * than fixed offset ones.
  4624. */
  4625. err = check_stack_write_var_off(env, state,
  4626. ptr_regno, off, size,
  4627. value_regno, insn_idx);
  4628. }
  4629. return err;
  4630. }
  4631. static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
  4632. int off, int size, enum bpf_access_type type)
  4633. {
  4634. struct bpf_reg_state *regs = cur_regs(env);
  4635. struct bpf_map *map = regs[regno].map_ptr;
  4636. u32 cap = bpf_map_flags_to_cap(map);
  4637. if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
  4638. verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
  4639. map->value_size, off, size);
  4640. return -EACCES;
  4641. }
  4642. if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
  4643. verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
  4644. map->value_size, off, size);
  4645. return -EACCES;
  4646. }
  4647. return 0;
  4648. }
  4649. /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
  4650. static int __check_mem_access(struct bpf_verifier_env *env, int regno,
  4651. int off, int size, u32 mem_size,
  4652. bool zero_size_allowed)
  4653. {
  4654. bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
  4655. struct bpf_reg_state *reg;
  4656. if (off >= 0 && size_ok && (u64)off + size <= mem_size)
  4657. return 0;
  4658. reg = &cur_regs(env)[regno];
  4659. switch (reg->type) {
  4660. case PTR_TO_MAP_KEY:
  4661. verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
  4662. mem_size, off, size);
  4663. break;
  4664. case PTR_TO_MAP_VALUE:
  4665. verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
  4666. mem_size, off, size);
  4667. break;
  4668. case PTR_TO_PACKET:
  4669. case PTR_TO_PACKET_META:
  4670. case PTR_TO_PACKET_END:
  4671. verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
  4672. off, size, regno, reg->id, off, mem_size);
  4673. break;
  4674. case PTR_TO_MEM:
  4675. default:
  4676. verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
  4677. mem_size, off, size);
  4678. }
  4679. return -EACCES;
  4680. }
  4681. /* check read/write into a memory region with possible variable offset */
  4682. static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
  4683. int off, int size, u32 mem_size,
  4684. bool zero_size_allowed)
  4685. {
  4686. struct bpf_verifier_state *vstate = env->cur_state;
  4687. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  4688. struct bpf_reg_state *reg = &state->regs[regno];
  4689. int err;
  4690. /* We may have adjusted the register pointing to memory region, so we
  4691. * need to try adding each of min_value and max_value to off
  4692. * to make sure our theoretical access will be safe.
  4693. *
  4694. * The minimum value is only important with signed
  4695. * comparisons where we can't assume the floor of a
  4696. * value is 0. If we are using signed variables for our
  4697. * index'es we need to make sure that whatever we use
  4698. * will have a set floor within our range.
  4699. */
  4700. if (reg->smin_value < 0 &&
  4701. (reg->smin_value == S64_MIN ||
  4702. (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
  4703. reg->smin_value + off < 0)) {
  4704. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  4705. regno);
  4706. return -EACCES;
  4707. }
  4708. err = __check_mem_access(env, regno, reg->smin_value + off, size,
  4709. mem_size, zero_size_allowed);
  4710. if (err) {
  4711. verbose(env, "R%d min value is outside of the allowed memory range\n",
  4712. regno);
  4713. return err;
  4714. }
  4715. /* If we haven't set a max value then we need to bail since we can't be
  4716. * sure we won't do bad things.
  4717. * If reg->umax_value + off could overflow, treat that as unbounded too.
  4718. */
  4719. if (reg->umax_value >= BPF_MAX_VAR_OFF) {
  4720. verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
  4721. regno);
  4722. return -EACCES;
  4723. }
  4724. err = __check_mem_access(env, regno, reg->umax_value + off, size,
  4725. mem_size, zero_size_allowed);
  4726. if (err) {
  4727. verbose(env, "R%d max value is outside of the allowed memory range\n",
  4728. regno);
  4729. return err;
  4730. }
  4731. return 0;
  4732. }
  4733. static int __check_ptr_off_reg(struct bpf_verifier_env *env,
  4734. const struct bpf_reg_state *reg, int regno,
  4735. bool fixed_off_ok)
  4736. {
  4737. /* Access to this pointer-typed register or passing it to a helper
  4738. * is only allowed in its original, unmodified form.
  4739. */
  4740. if (reg->off < 0) {
  4741. verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
  4742. reg_type_str(env, reg->type), regno, reg->off);
  4743. return -EACCES;
  4744. }
  4745. if (!fixed_off_ok && reg->off) {
  4746. verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
  4747. reg_type_str(env, reg->type), regno, reg->off);
  4748. return -EACCES;
  4749. }
  4750. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  4751. char tn_buf[48];
  4752. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  4753. verbose(env, "variable %s access var_off=%s disallowed\n",
  4754. reg_type_str(env, reg->type), tn_buf);
  4755. return -EACCES;
  4756. }
  4757. return 0;
  4758. }
  4759. static int check_ptr_off_reg(struct bpf_verifier_env *env,
  4760. const struct bpf_reg_state *reg, int regno)
  4761. {
  4762. return __check_ptr_off_reg(env, reg, regno, false);
  4763. }
  4764. static int map_kptr_match_type(struct bpf_verifier_env *env,
  4765. struct btf_field *kptr_field,
  4766. struct bpf_reg_state *reg, u32 regno)
  4767. {
  4768. const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
  4769. int perm_flags;
  4770. const char *reg_name = "";
  4771. if (btf_is_kernel(reg->btf)) {
  4772. perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
  4773. /* Only unreferenced case accepts untrusted pointers */
  4774. if (kptr_field->type == BPF_KPTR_UNREF)
  4775. perm_flags |= PTR_UNTRUSTED;
  4776. } else {
  4777. perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
  4778. if (kptr_field->type == BPF_KPTR_PERCPU)
  4779. perm_flags |= MEM_PERCPU;
  4780. }
  4781. if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
  4782. goto bad_type;
  4783. /* We need to verify reg->type and reg->btf, before accessing reg->btf */
  4784. reg_name = btf_type_name(reg->btf, reg->btf_id);
  4785. /* For ref_ptr case, release function check should ensure we get one
  4786. * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
  4787. * normal store of unreferenced kptr, we must ensure var_off is zero.
  4788. * Since ref_ptr cannot be accessed directly by BPF insns, checks for
  4789. * reg->off and reg->ref_obj_id are not needed here.
  4790. */
  4791. if (__check_ptr_off_reg(env, reg, regno, true))
  4792. return -EACCES;
  4793. /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
  4794. * we also need to take into account the reg->off.
  4795. *
  4796. * We want to support cases like:
  4797. *
  4798. * struct foo {
  4799. * struct bar br;
  4800. * struct baz bz;
  4801. * };
  4802. *
  4803. * struct foo *v;
  4804. * v = func(); // PTR_TO_BTF_ID
  4805. * val->foo = v; // reg->off is zero, btf and btf_id match type
  4806. * val->bar = &v->br; // reg->off is still zero, but we need to retry with
  4807. * // first member type of struct after comparison fails
  4808. * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
  4809. * // to match type
  4810. *
  4811. * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
  4812. * is zero. We must also ensure that btf_struct_ids_match does not walk
  4813. * the struct to match type against first member of struct, i.e. reject
  4814. * second case from above. Hence, when type is BPF_KPTR_REF, we set
  4815. * strict mode to true for type match.
  4816. */
  4817. if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
  4818. kptr_field->kptr.btf, kptr_field->kptr.btf_id,
  4819. kptr_field->type != BPF_KPTR_UNREF))
  4820. goto bad_type;
  4821. return 0;
  4822. bad_type:
  4823. verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
  4824. reg_type_str(env, reg->type), reg_name);
  4825. verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
  4826. if (kptr_field->type == BPF_KPTR_UNREF)
  4827. verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
  4828. targ_name);
  4829. else
  4830. verbose(env, "\n");
  4831. return -EINVAL;
  4832. }
  4833. static bool in_sleepable(struct bpf_verifier_env *env)
  4834. {
  4835. return env->prog->sleepable ||
  4836. (env->cur_state && env->cur_state->in_sleepable);
  4837. }
  4838. /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
  4839. * can dereference RCU protected pointers and result is PTR_TRUSTED.
  4840. */
  4841. static bool in_rcu_cs(struct bpf_verifier_env *env)
  4842. {
  4843. return env->cur_state->active_rcu_lock ||
  4844. env->cur_state->active_lock.ptr ||
  4845. !in_sleepable(env);
  4846. }
  4847. /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
  4848. BTF_SET_START(rcu_protected_types)
  4849. BTF_ID(struct, prog_test_ref_kfunc)
  4850. #ifdef CONFIG_CGROUPS
  4851. BTF_ID(struct, cgroup)
  4852. #endif
  4853. #ifdef CONFIG_BPF_JIT
  4854. BTF_ID(struct, bpf_cpumask)
  4855. #endif
  4856. BTF_ID(struct, task_struct)
  4857. BTF_ID(struct, bpf_crypto_ctx)
  4858. BTF_SET_END(rcu_protected_types)
  4859. static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
  4860. {
  4861. if (!btf_is_kernel(btf))
  4862. return true;
  4863. return btf_id_set_contains(&rcu_protected_types, btf_id);
  4864. }
  4865. static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
  4866. {
  4867. struct btf_struct_meta *meta;
  4868. if (btf_is_kernel(kptr_field->kptr.btf))
  4869. return NULL;
  4870. meta = btf_find_struct_meta(kptr_field->kptr.btf,
  4871. kptr_field->kptr.btf_id);
  4872. return meta ? meta->record : NULL;
  4873. }
  4874. static bool rcu_safe_kptr(const struct btf_field *field)
  4875. {
  4876. const struct btf_field_kptr *kptr = &field->kptr;
  4877. return field->type == BPF_KPTR_PERCPU ||
  4878. (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
  4879. }
  4880. static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
  4881. {
  4882. struct btf_record *rec;
  4883. u32 ret;
  4884. ret = PTR_MAYBE_NULL;
  4885. if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
  4886. ret |= MEM_RCU;
  4887. if (kptr_field->type == BPF_KPTR_PERCPU)
  4888. ret |= MEM_PERCPU;
  4889. else if (!btf_is_kernel(kptr_field->kptr.btf))
  4890. ret |= MEM_ALLOC;
  4891. rec = kptr_pointee_btf_record(kptr_field);
  4892. if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
  4893. ret |= NON_OWN_REF;
  4894. } else {
  4895. ret |= PTR_UNTRUSTED;
  4896. }
  4897. return ret;
  4898. }
  4899. static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
  4900. int value_regno, int insn_idx,
  4901. struct btf_field *kptr_field)
  4902. {
  4903. struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
  4904. int class = BPF_CLASS(insn->code);
  4905. struct bpf_reg_state *val_reg;
  4906. /* Things we already checked for in check_map_access and caller:
  4907. * - Reject cases where variable offset may touch kptr
  4908. * - size of access (must be BPF_DW)
  4909. * - tnum_is_const(reg->var_off)
  4910. * - kptr_field->offset == off + reg->var_off.value
  4911. */
  4912. /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
  4913. if (BPF_MODE(insn->code) != BPF_MEM) {
  4914. verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
  4915. return -EACCES;
  4916. }
  4917. /* We only allow loading referenced kptr, since it will be marked as
  4918. * untrusted, similar to unreferenced kptr.
  4919. */
  4920. if (class != BPF_LDX &&
  4921. (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
  4922. verbose(env, "store to referenced kptr disallowed\n");
  4923. return -EACCES;
  4924. }
  4925. if (class == BPF_LDX) {
  4926. val_reg = reg_state(env, value_regno);
  4927. /* We can simply mark the value_regno receiving the pointer
  4928. * value from map as PTR_TO_BTF_ID, with the correct type.
  4929. */
  4930. mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
  4931. kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
  4932. } else if (class == BPF_STX) {
  4933. val_reg = reg_state(env, value_regno);
  4934. if (!register_is_null(val_reg) &&
  4935. map_kptr_match_type(env, kptr_field, val_reg, value_regno))
  4936. return -EACCES;
  4937. } else if (class == BPF_ST) {
  4938. if (insn->imm) {
  4939. verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
  4940. kptr_field->offset);
  4941. return -EACCES;
  4942. }
  4943. } else {
  4944. verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
  4945. return -EACCES;
  4946. }
  4947. return 0;
  4948. }
  4949. /* check read/write into a map element with possible variable offset */
  4950. static int check_map_access(struct bpf_verifier_env *env, u32 regno,
  4951. int off, int size, bool zero_size_allowed,
  4952. enum bpf_access_src src)
  4953. {
  4954. struct bpf_verifier_state *vstate = env->cur_state;
  4955. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  4956. struct bpf_reg_state *reg = &state->regs[regno];
  4957. struct bpf_map *map = reg->map_ptr;
  4958. struct btf_record *rec;
  4959. int err, i;
  4960. err = check_mem_region_access(env, regno, off, size, map->value_size,
  4961. zero_size_allowed);
  4962. if (err)
  4963. return err;
  4964. if (IS_ERR_OR_NULL(map->record))
  4965. return 0;
  4966. rec = map->record;
  4967. for (i = 0; i < rec->cnt; i++) {
  4968. struct btf_field *field = &rec->fields[i];
  4969. u32 p = field->offset;
  4970. /* If any part of a field can be touched by load/store, reject
  4971. * this program. To check that [x1, x2) overlaps with [y1, y2),
  4972. * it is sufficient to check x1 < y2 && y1 < x2.
  4973. */
  4974. if (reg->smin_value + off < p + field->size &&
  4975. p < reg->umax_value + off + size) {
  4976. switch (field->type) {
  4977. case BPF_KPTR_UNREF:
  4978. case BPF_KPTR_REF:
  4979. case BPF_KPTR_PERCPU:
  4980. if (src != ACCESS_DIRECT) {
  4981. verbose(env, "kptr cannot be accessed indirectly by helper\n");
  4982. return -EACCES;
  4983. }
  4984. if (!tnum_is_const(reg->var_off)) {
  4985. verbose(env, "kptr access cannot have variable offset\n");
  4986. return -EACCES;
  4987. }
  4988. if (p != off + reg->var_off.value) {
  4989. verbose(env, "kptr access misaligned expected=%u off=%llu\n",
  4990. p, off + reg->var_off.value);
  4991. return -EACCES;
  4992. }
  4993. if (size != bpf_size_to_bytes(BPF_DW)) {
  4994. verbose(env, "kptr access size must be BPF_DW\n");
  4995. return -EACCES;
  4996. }
  4997. break;
  4998. default:
  4999. verbose(env, "%s cannot be accessed directly by load/store\n",
  5000. btf_field_type_name(field->type));
  5001. return -EACCES;
  5002. }
  5003. }
  5004. }
  5005. return 0;
  5006. }
  5007. #define MAX_PACKET_OFF 0xffff
  5008. static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
  5009. const struct bpf_call_arg_meta *meta,
  5010. enum bpf_access_type t)
  5011. {
  5012. enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
  5013. switch (prog_type) {
  5014. /* Program types only with direct read access go here! */
  5015. case BPF_PROG_TYPE_LWT_IN:
  5016. case BPF_PROG_TYPE_LWT_OUT:
  5017. case BPF_PROG_TYPE_LWT_SEG6LOCAL:
  5018. case BPF_PROG_TYPE_SK_REUSEPORT:
  5019. case BPF_PROG_TYPE_FLOW_DISSECTOR:
  5020. case BPF_PROG_TYPE_CGROUP_SKB:
  5021. if (t == BPF_WRITE)
  5022. return false;
  5023. fallthrough;
  5024. /* Program types with direct read + write access go here! */
  5025. case BPF_PROG_TYPE_SCHED_CLS:
  5026. case BPF_PROG_TYPE_SCHED_ACT:
  5027. case BPF_PROG_TYPE_XDP:
  5028. case BPF_PROG_TYPE_LWT_XMIT:
  5029. case BPF_PROG_TYPE_SK_SKB:
  5030. case BPF_PROG_TYPE_SK_MSG:
  5031. if (meta)
  5032. return meta->pkt_access;
  5033. env->seen_direct_write = true;
  5034. return true;
  5035. case BPF_PROG_TYPE_CGROUP_SOCKOPT:
  5036. if (t == BPF_WRITE)
  5037. env->seen_direct_write = true;
  5038. return true;
  5039. default:
  5040. return false;
  5041. }
  5042. }
  5043. static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
  5044. int size, bool zero_size_allowed)
  5045. {
  5046. struct bpf_reg_state *regs = cur_regs(env);
  5047. struct bpf_reg_state *reg = &regs[regno];
  5048. int err;
  5049. /* We may have added a variable offset to the packet pointer; but any
  5050. * reg->range we have comes after that. We are only checking the fixed
  5051. * offset.
  5052. */
  5053. /* We don't allow negative numbers, because we aren't tracking enough
  5054. * detail to prove they're safe.
  5055. */
  5056. if (reg->smin_value < 0) {
  5057. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  5058. regno);
  5059. return -EACCES;
  5060. }
  5061. err = reg->range < 0 ? -EINVAL :
  5062. __check_mem_access(env, regno, off, size, reg->range,
  5063. zero_size_allowed);
  5064. if (err) {
  5065. verbose(env, "R%d offset is outside of the packet\n", regno);
  5066. return err;
  5067. }
  5068. /* __check_mem_access has made sure "off + size - 1" is within u16.
  5069. * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
  5070. * otherwise find_good_pkt_pointers would have refused to set range info
  5071. * that __check_mem_access would have rejected this pkt access.
  5072. * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
  5073. */
  5074. env->prog->aux->max_pkt_offset =
  5075. max_t(u32, env->prog->aux->max_pkt_offset,
  5076. off + reg->umax_value + size - 1);
  5077. return err;
  5078. }
  5079. /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
  5080. static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
  5081. enum bpf_access_type t, enum bpf_reg_type *reg_type,
  5082. struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx)
  5083. {
  5084. struct bpf_insn_access_aux info = {
  5085. .reg_type = *reg_type,
  5086. .log = &env->log,
  5087. .is_retval = false,
  5088. .is_ldsx = is_ldsx,
  5089. };
  5090. if (env->ops->is_valid_access &&
  5091. env->ops->is_valid_access(off, size, t, env->prog, &info)) {
  5092. /* A non zero info.ctx_field_size indicates that this field is a
  5093. * candidate for later verifier transformation to load the whole
  5094. * field and then apply a mask when accessed with a narrower
  5095. * access than actual ctx access size. A zero info.ctx_field_size
  5096. * will only allow for whole field access and rejects any other
  5097. * type of narrower access.
  5098. */
  5099. *reg_type = info.reg_type;
  5100. *is_retval = info.is_retval;
  5101. if (base_type(*reg_type) == PTR_TO_BTF_ID) {
  5102. *btf = info.btf;
  5103. *btf_id = info.btf_id;
  5104. } else {
  5105. env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
  5106. }
  5107. /* remember the offset of last byte accessed in ctx */
  5108. if (env->prog->aux->max_ctx_offset < off + size)
  5109. env->prog->aux->max_ctx_offset = off + size;
  5110. return 0;
  5111. }
  5112. verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
  5113. return -EACCES;
  5114. }
  5115. static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
  5116. int size)
  5117. {
  5118. if (size < 0 || off < 0 ||
  5119. (u64)off + size > sizeof(struct bpf_flow_keys)) {
  5120. verbose(env, "invalid access to flow keys off=%d size=%d\n",
  5121. off, size);
  5122. return -EACCES;
  5123. }
  5124. return 0;
  5125. }
  5126. static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
  5127. u32 regno, int off, int size,
  5128. enum bpf_access_type t)
  5129. {
  5130. struct bpf_reg_state *regs = cur_regs(env);
  5131. struct bpf_reg_state *reg = &regs[regno];
  5132. struct bpf_insn_access_aux info = {};
  5133. bool valid;
  5134. if (reg->smin_value < 0) {
  5135. verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
  5136. regno);
  5137. return -EACCES;
  5138. }
  5139. switch (reg->type) {
  5140. case PTR_TO_SOCK_COMMON:
  5141. valid = bpf_sock_common_is_valid_access(off, size, t, &info);
  5142. break;
  5143. case PTR_TO_SOCKET:
  5144. valid = bpf_sock_is_valid_access(off, size, t, &info);
  5145. break;
  5146. case PTR_TO_TCP_SOCK:
  5147. valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
  5148. break;
  5149. case PTR_TO_XDP_SOCK:
  5150. valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
  5151. break;
  5152. default:
  5153. valid = false;
  5154. }
  5155. if (valid) {
  5156. env->insn_aux_data[insn_idx].ctx_field_size =
  5157. info.ctx_field_size;
  5158. return 0;
  5159. }
  5160. verbose(env, "R%d invalid %s access off=%d size=%d\n",
  5161. regno, reg_type_str(env, reg->type), off, size);
  5162. return -EACCES;
  5163. }
  5164. static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
  5165. {
  5166. return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
  5167. }
  5168. static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
  5169. {
  5170. const struct bpf_reg_state *reg = reg_state(env, regno);
  5171. return reg->type == PTR_TO_CTX;
  5172. }
  5173. static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
  5174. {
  5175. const struct bpf_reg_state *reg = reg_state(env, regno);
  5176. return type_is_sk_pointer(reg->type);
  5177. }
  5178. static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
  5179. {
  5180. const struct bpf_reg_state *reg = reg_state(env, regno);
  5181. return type_is_pkt_pointer(reg->type);
  5182. }
  5183. static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
  5184. {
  5185. const struct bpf_reg_state *reg = reg_state(env, regno);
  5186. /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
  5187. return reg->type == PTR_TO_FLOW_KEYS;
  5188. }
  5189. static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
  5190. {
  5191. const struct bpf_reg_state *reg = reg_state(env, regno);
  5192. return reg->type == PTR_TO_ARENA;
  5193. }
  5194. static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
  5195. #ifdef CONFIG_NET
  5196. [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
  5197. [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
  5198. [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
  5199. #endif
  5200. [CONST_PTR_TO_MAP] = btf_bpf_map_id,
  5201. };
  5202. static bool is_trusted_reg(const struct bpf_reg_state *reg)
  5203. {
  5204. /* A referenced register is always trusted. */
  5205. if (reg->ref_obj_id)
  5206. return true;
  5207. /* Types listed in the reg2btf_ids are always trusted */
  5208. if (reg2btf_ids[base_type(reg->type)] &&
  5209. !bpf_type_has_unsafe_modifiers(reg->type))
  5210. return true;
  5211. /* If a register is not referenced, it is trusted if it has the
  5212. * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
  5213. * other type modifiers may be safe, but we elect to take an opt-in
  5214. * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
  5215. * not.
  5216. *
  5217. * Eventually, we should make PTR_TRUSTED the single source of truth
  5218. * for whether a register is trusted.
  5219. */
  5220. return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
  5221. !bpf_type_has_unsafe_modifiers(reg->type);
  5222. }
  5223. static bool is_rcu_reg(const struct bpf_reg_state *reg)
  5224. {
  5225. return reg->type & MEM_RCU;
  5226. }
  5227. static void clear_trusted_flags(enum bpf_type_flag *flag)
  5228. {
  5229. *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
  5230. }
  5231. static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
  5232. const struct bpf_reg_state *reg,
  5233. int off, int size, bool strict)
  5234. {
  5235. struct tnum reg_off;
  5236. int ip_align;
  5237. /* Byte size accesses are always allowed. */
  5238. if (!strict || size == 1)
  5239. return 0;
  5240. /* For platforms that do not have a Kconfig enabling
  5241. * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
  5242. * NET_IP_ALIGN is universally set to '2'. And on platforms
  5243. * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
  5244. * to this code only in strict mode where we want to emulate
  5245. * the NET_IP_ALIGN==2 checking. Therefore use an
  5246. * unconditional IP align value of '2'.
  5247. */
  5248. ip_align = 2;
  5249. reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
  5250. if (!tnum_is_aligned(reg_off, size)) {
  5251. char tn_buf[48];
  5252. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  5253. verbose(env,
  5254. "misaligned packet access off %d+%s+%d+%d size %d\n",
  5255. ip_align, tn_buf, reg->off, off, size);
  5256. return -EACCES;
  5257. }
  5258. return 0;
  5259. }
  5260. static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
  5261. const struct bpf_reg_state *reg,
  5262. const char *pointer_desc,
  5263. int off, int size, bool strict)
  5264. {
  5265. struct tnum reg_off;
  5266. /* Byte size accesses are always allowed. */
  5267. if (!strict || size == 1)
  5268. return 0;
  5269. reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
  5270. if (!tnum_is_aligned(reg_off, size)) {
  5271. char tn_buf[48];
  5272. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  5273. verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
  5274. pointer_desc, tn_buf, reg->off, off, size);
  5275. return -EACCES;
  5276. }
  5277. return 0;
  5278. }
  5279. static int check_ptr_alignment(struct bpf_verifier_env *env,
  5280. const struct bpf_reg_state *reg, int off,
  5281. int size, bool strict_alignment_once)
  5282. {
  5283. bool strict = env->strict_alignment || strict_alignment_once;
  5284. const char *pointer_desc = "";
  5285. switch (reg->type) {
  5286. case PTR_TO_PACKET:
  5287. case PTR_TO_PACKET_META:
  5288. /* Special case, because of NET_IP_ALIGN. Given metadata sits
  5289. * right in front, treat it the very same way.
  5290. */
  5291. return check_pkt_ptr_alignment(env, reg, off, size, strict);
  5292. case PTR_TO_FLOW_KEYS:
  5293. pointer_desc = "flow keys ";
  5294. break;
  5295. case PTR_TO_MAP_KEY:
  5296. pointer_desc = "key ";
  5297. break;
  5298. case PTR_TO_MAP_VALUE:
  5299. pointer_desc = "value ";
  5300. break;
  5301. case PTR_TO_CTX:
  5302. pointer_desc = "context ";
  5303. break;
  5304. case PTR_TO_STACK:
  5305. pointer_desc = "stack ";
  5306. /* The stack spill tracking logic in check_stack_write_fixed_off()
  5307. * and check_stack_read_fixed_off() relies on stack accesses being
  5308. * aligned.
  5309. */
  5310. strict = true;
  5311. break;
  5312. case PTR_TO_SOCKET:
  5313. pointer_desc = "sock ";
  5314. break;
  5315. case PTR_TO_SOCK_COMMON:
  5316. pointer_desc = "sock_common ";
  5317. break;
  5318. case PTR_TO_TCP_SOCK:
  5319. pointer_desc = "tcp_sock ";
  5320. break;
  5321. case PTR_TO_XDP_SOCK:
  5322. pointer_desc = "xdp_sock ";
  5323. break;
  5324. case PTR_TO_ARENA:
  5325. return 0;
  5326. default:
  5327. break;
  5328. }
  5329. return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
  5330. strict);
  5331. }
  5332. static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
  5333. {
  5334. if (env->prog->jit_requested)
  5335. return round_up(stack_depth, 16);
  5336. /* round up to 32-bytes, since this is granularity
  5337. * of interpreter stack size
  5338. */
  5339. return round_up(max_t(u32, stack_depth, 1), 32);
  5340. }
  5341. /* starting from main bpf function walk all instructions of the function
  5342. * and recursively walk all callees that given function can call.
  5343. * Ignore jump and exit insns.
  5344. * Since recursion is prevented by check_cfg() this algorithm
  5345. * only needs a local stack of MAX_CALL_FRAMES to remember callsites
  5346. */
  5347. static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
  5348. {
  5349. struct bpf_subprog_info *subprog = env->subprog_info;
  5350. struct bpf_insn *insn = env->prog->insnsi;
  5351. int depth = 0, frame = 0, i, subprog_end;
  5352. bool tail_call_reachable = false;
  5353. int ret_insn[MAX_CALL_FRAMES];
  5354. int ret_prog[MAX_CALL_FRAMES];
  5355. int j;
  5356. i = subprog[idx].start;
  5357. process_func:
  5358. /* protect against potential stack overflow that might happen when
  5359. * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
  5360. * depth for such case down to 256 so that the worst case scenario
  5361. * would result in 8k stack size (32 which is tailcall limit * 256 =
  5362. * 8k).
  5363. *
  5364. * To get the idea what might happen, see an example:
  5365. * func1 -> sub rsp, 128
  5366. * subfunc1 -> sub rsp, 256
  5367. * tailcall1 -> add rsp, 256
  5368. * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
  5369. * subfunc2 -> sub rsp, 64
  5370. * subfunc22 -> sub rsp, 128
  5371. * tailcall2 -> add rsp, 128
  5372. * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
  5373. *
  5374. * tailcall will unwind the current stack frame but it will not get rid
  5375. * of caller's stack as shown on the example above.
  5376. */
  5377. if (idx && subprog[idx].has_tail_call && depth >= 256) {
  5378. verbose(env,
  5379. "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
  5380. depth);
  5381. return -EACCES;
  5382. }
  5383. depth += round_up_stack_depth(env, subprog[idx].stack_depth);
  5384. if (depth > MAX_BPF_STACK) {
  5385. verbose(env, "combined stack size of %d calls is %d. Too large\n",
  5386. frame + 1, depth);
  5387. return -EACCES;
  5388. }
  5389. continue_func:
  5390. subprog_end = subprog[idx + 1].start;
  5391. for (; i < subprog_end; i++) {
  5392. int next_insn, sidx;
  5393. if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
  5394. bool err = false;
  5395. if (!is_bpf_throw_kfunc(insn + i))
  5396. continue;
  5397. if (subprog[idx].is_cb)
  5398. err = true;
  5399. for (int c = 0; c < frame && !err; c++) {
  5400. if (subprog[ret_prog[c]].is_cb) {
  5401. err = true;
  5402. break;
  5403. }
  5404. }
  5405. if (!err)
  5406. continue;
  5407. verbose(env,
  5408. "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
  5409. i, idx);
  5410. return -EINVAL;
  5411. }
  5412. if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
  5413. continue;
  5414. /* remember insn and function to return to */
  5415. ret_insn[frame] = i + 1;
  5416. ret_prog[frame] = idx;
  5417. /* find the callee */
  5418. next_insn = i + insn[i].imm + 1;
  5419. sidx = find_subprog(env, next_insn);
  5420. if (sidx < 0) {
  5421. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  5422. next_insn);
  5423. return -EFAULT;
  5424. }
  5425. if (subprog[sidx].is_async_cb) {
  5426. if (subprog[sidx].has_tail_call) {
  5427. verbose(env, "verifier bug. subprog has tail_call and async cb\n");
  5428. return -EFAULT;
  5429. }
  5430. /* async callbacks don't increase bpf prog stack size unless called directly */
  5431. if (!bpf_pseudo_call(insn + i))
  5432. continue;
  5433. if (subprog[sidx].is_exception_cb) {
  5434. verbose(env, "insn %d cannot call exception cb directly\n", i);
  5435. return -EINVAL;
  5436. }
  5437. }
  5438. i = next_insn;
  5439. idx = sidx;
  5440. if (subprog[idx].has_tail_call)
  5441. tail_call_reachable = true;
  5442. frame++;
  5443. if (frame >= MAX_CALL_FRAMES) {
  5444. verbose(env, "the call stack of %d frames is too deep !\n",
  5445. frame);
  5446. return -E2BIG;
  5447. }
  5448. goto process_func;
  5449. }
  5450. /* if tail call got detected across bpf2bpf calls then mark each of the
  5451. * currently present subprog frames as tail call reachable subprogs;
  5452. * this info will be utilized by JIT so that we will be preserving the
  5453. * tail call counter throughout bpf2bpf calls combined with tailcalls
  5454. */
  5455. if (tail_call_reachable)
  5456. for (j = 0; j < frame; j++) {
  5457. if (subprog[ret_prog[j]].is_exception_cb) {
  5458. verbose(env, "cannot tail call within exception cb\n");
  5459. return -EINVAL;
  5460. }
  5461. subprog[ret_prog[j]].tail_call_reachable = true;
  5462. }
  5463. if (subprog[0].tail_call_reachable)
  5464. env->prog->aux->tail_call_reachable = true;
  5465. /* end of for() loop means the last insn of the 'subprog'
  5466. * was reached. Doesn't matter whether it was JA or EXIT
  5467. */
  5468. if (frame == 0)
  5469. return 0;
  5470. depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
  5471. frame--;
  5472. i = ret_insn[frame];
  5473. idx = ret_prog[frame];
  5474. goto continue_func;
  5475. }
  5476. static int check_max_stack_depth(struct bpf_verifier_env *env)
  5477. {
  5478. struct bpf_subprog_info *si = env->subprog_info;
  5479. int ret;
  5480. for (int i = 0; i < env->subprog_cnt; i++) {
  5481. if (!i || si[i].is_async_cb) {
  5482. ret = check_max_stack_depth_subprog(env, i);
  5483. if (ret < 0)
  5484. return ret;
  5485. }
  5486. continue;
  5487. }
  5488. return 0;
  5489. }
  5490. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  5491. static int get_callee_stack_depth(struct bpf_verifier_env *env,
  5492. const struct bpf_insn *insn, int idx)
  5493. {
  5494. int start = idx + insn->imm + 1, subprog;
  5495. subprog = find_subprog(env, start);
  5496. if (subprog < 0) {
  5497. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  5498. start);
  5499. return -EFAULT;
  5500. }
  5501. return env->subprog_info[subprog].stack_depth;
  5502. }
  5503. #endif
  5504. static int __check_buffer_access(struct bpf_verifier_env *env,
  5505. const char *buf_info,
  5506. const struct bpf_reg_state *reg,
  5507. int regno, int off, int size)
  5508. {
  5509. if (off < 0) {
  5510. verbose(env,
  5511. "R%d invalid %s buffer access: off=%d, size=%d\n",
  5512. regno, buf_info, off, size);
  5513. return -EACCES;
  5514. }
  5515. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  5516. char tn_buf[48];
  5517. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  5518. verbose(env,
  5519. "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
  5520. regno, off, tn_buf);
  5521. return -EACCES;
  5522. }
  5523. return 0;
  5524. }
  5525. static int check_tp_buffer_access(struct bpf_verifier_env *env,
  5526. const struct bpf_reg_state *reg,
  5527. int regno, int off, int size)
  5528. {
  5529. int err;
  5530. err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
  5531. if (err)
  5532. return err;
  5533. if (off + size > env->prog->aux->max_tp_access)
  5534. env->prog->aux->max_tp_access = off + size;
  5535. return 0;
  5536. }
  5537. static int check_buffer_access(struct bpf_verifier_env *env,
  5538. const struct bpf_reg_state *reg,
  5539. int regno, int off, int size,
  5540. bool zero_size_allowed,
  5541. u32 *max_access)
  5542. {
  5543. const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
  5544. int err;
  5545. err = __check_buffer_access(env, buf_info, reg, regno, off, size);
  5546. if (err)
  5547. return err;
  5548. if (off + size > *max_access)
  5549. *max_access = off + size;
  5550. return 0;
  5551. }
  5552. /* BPF architecture zero extends alu32 ops into 64-bit registesr */
  5553. static void zext_32_to_64(struct bpf_reg_state *reg)
  5554. {
  5555. reg->var_off = tnum_subreg(reg->var_off);
  5556. __reg_assign_32_into_64(reg);
  5557. }
  5558. /* truncate register to smaller size (in bytes)
  5559. * must be called with size < BPF_REG_SIZE
  5560. */
  5561. static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
  5562. {
  5563. u64 mask;
  5564. /* clear high bits in bit representation */
  5565. reg->var_off = tnum_cast(reg->var_off, size);
  5566. /* fix arithmetic bounds */
  5567. mask = ((u64)1 << (size * 8)) - 1;
  5568. if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
  5569. reg->umin_value &= mask;
  5570. reg->umax_value &= mask;
  5571. } else {
  5572. reg->umin_value = 0;
  5573. reg->umax_value = mask;
  5574. }
  5575. reg->smin_value = reg->umin_value;
  5576. reg->smax_value = reg->umax_value;
  5577. /* If size is smaller than 32bit register the 32bit register
  5578. * values are also truncated so we push 64-bit bounds into
  5579. * 32-bit bounds. Above were truncated < 32-bits already.
  5580. */
  5581. if (size < 4)
  5582. __mark_reg32_unbounded(reg);
  5583. reg_bounds_sync(reg);
  5584. }
  5585. static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
  5586. {
  5587. if (size == 1) {
  5588. reg->smin_value = reg->s32_min_value = S8_MIN;
  5589. reg->smax_value = reg->s32_max_value = S8_MAX;
  5590. } else if (size == 2) {
  5591. reg->smin_value = reg->s32_min_value = S16_MIN;
  5592. reg->smax_value = reg->s32_max_value = S16_MAX;
  5593. } else {
  5594. /* size == 4 */
  5595. reg->smin_value = reg->s32_min_value = S32_MIN;
  5596. reg->smax_value = reg->s32_max_value = S32_MAX;
  5597. }
  5598. reg->umin_value = reg->u32_min_value = 0;
  5599. reg->umax_value = U64_MAX;
  5600. reg->u32_max_value = U32_MAX;
  5601. reg->var_off = tnum_unknown;
  5602. }
  5603. static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
  5604. {
  5605. s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
  5606. u64 top_smax_value, top_smin_value;
  5607. u64 num_bits = size * 8;
  5608. if (tnum_is_const(reg->var_off)) {
  5609. u64_cval = reg->var_off.value;
  5610. if (size == 1)
  5611. reg->var_off = tnum_const((s8)u64_cval);
  5612. else if (size == 2)
  5613. reg->var_off = tnum_const((s16)u64_cval);
  5614. else
  5615. /* size == 4 */
  5616. reg->var_off = tnum_const((s32)u64_cval);
  5617. u64_cval = reg->var_off.value;
  5618. reg->smax_value = reg->smin_value = u64_cval;
  5619. reg->umax_value = reg->umin_value = u64_cval;
  5620. reg->s32_max_value = reg->s32_min_value = u64_cval;
  5621. reg->u32_max_value = reg->u32_min_value = u64_cval;
  5622. return;
  5623. }
  5624. top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
  5625. top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
  5626. if (top_smax_value != top_smin_value)
  5627. goto out;
  5628. /* find the s64_min and s64_min after sign extension */
  5629. if (size == 1) {
  5630. init_s64_max = (s8)reg->smax_value;
  5631. init_s64_min = (s8)reg->smin_value;
  5632. } else if (size == 2) {
  5633. init_s64_max = (s16)reg->smax_value;
  5634. init_s64_min = (s16)reg->smin_value;
  5635. } else {
  5636. init_s64_max = (s32)reg->smax_value;
  5637. init_s64_min = (s32)reg->smin_value;
  5638. }
  5639. s64_max = max(init_s64_max, init_s64_min);
  5640. s64_min = min(init_s64_max, init_s64_min);
  5641. /* both of s64_max/s64_min positive or negative */
  5642. if ((s64_max >= 0) == (s64_min >= 0)) {
  5643. reg->s32_min_value = reg->smin_value = s64_min;
  5644. reg->s32_max_value = reg->smax_value = s64_max;
  5645. reg->u32_min_value = reg->umin_value = s64_min;
  5646. reg->u32_max_value = reg->umax_value = s64_max;
  5647. reg->var_off = tnum_range(s64_min, s64_max);
  5648. return;
  5649. }
  5650. out:
  5651. set_sext64_default_val(reg, size);
  5652. }
  5653. static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
  5654. {
  5655. if (size == 1) {
  5656. reg->s32_min_value = S8_MIN;
  5657. reg->s32_max_value = S8_MAX;
  5658. } else {
  5659. /* size == 2 */
  5660. reg->s32_min_value = S16_MIN;
  5661. reg->s32_max_value = S16_MAX;
  5662. }
  5663. reg->u32_min_value = 0;
  5664. reg->u32_max_value = U32_MAX;
  5665. reg->var_off = tnum_subreg(tnum_unknown);
  5666. }
  5667. static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
  5668. {
  5669. s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
  5670. u32 top_smax_value, top_smin_value;
  5671. u32 num_bits = size * 8;
  5672. if (tnum_is_const(reg->var_off)) {
  5673. u32_val = reg->var_off.value;
  5674. if (size == 1)
  5675. reg->var_off = tnum_const((s8)u32_val);
  5676. else
  5677. reg->var_off = tnum_const((s16)u32_val);
  5678. u32_val = reg->var_off.value;
  5679. reg->s32_min_value = reg->s32_max_value = u32_val;
  5680. reg->u32_min_value = reg->u32_max_value = u32_val;
  5681. return;
  5682. }
  5683. top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
  5684. top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
  5685. if (top_smax_value != top_smin_value)
  5686. goto out;
  5687. /* find the s32_min and s32_min after sign extension */
  5688. if (size == 1) {
  5689. init_s32_max = (s8)reg->s32_max_value;
  5690. init_s32_min = (s8)reg->s32_min_value;
  5691. } else {
  5692. /* size == 2 */
  5693. init_s32_max = (s16)reg->s32_max_value;
  5694. init_s32_min = (s16)reg->s32_min_value;
  5695. }
  5696. s32_max = max(init_s32_max, init_s32_min);
  5697. s32_min = min(init_s32_max, init_s32_min);
  5698. if ((s32_min >= 0) == (s32_max >= 0)) {
  5699. reg->s32_min_value = s32_min;
  5700. reg->s32_max_value = s32_max;
  5701. reg->u32_min_value = (u32)s32_min;
  5702. reg->u32_max_value = (u32)s32_max;
  5703. reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
  5704. return;
  5705. }
  5706. out:
  5707. set_sext32_default_val(reg, size);
  5708. }
  5709. static bool bpf_map_is_rdonly(const struct bpf_map *map)
  5710. {
  5711. /* A map is considered read-only if the following condition are true:
  5712. *
  5713. * 1) BPF program side cannot change any of the map content. The
  5714. * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
  5715. * and was set at map creation time.
  5716. * 2) The map value(s) have been initialized from user space by a
  5717. * loader and then "frozen", such that no new map update/delete
  5718. * operations from syscall side are possible for the rest of
  5719. * the map's lifetime from that point onwards.
  5720. * 3) Any parallel/pending map update/delete operations from syscall
  5721. * side have been completed. Only after that point, it's safe to
  5722. * assume that map value(s) are immutable.
  5723. */
  5724. return (map->map_flags & BPF_F_RDONLY_PROG) &&
  5725. READ_ONCE(map->frozen) &&
  5726. !bpf_map_write_active(map);
  5727. }
  5728. static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
  5729. bool is_ldsx)
  5730. {
  5731. void *ptr;
  5732. u64 addr;
  5733. int err;
  5734. err = map->ops->map_direct_value_addr(map, &addr, off);
  5735. if (err)
  5736. return err;
  5737. ptr = (void *)(long)addr + off;
  5738. switch (size) {
  5739. case sizeof(u8):
  5740. *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
  5741. break;
  5742. case sizeof(u16):
  5743. *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
  5744. break;
  5745. case sizeof(u32):
  5746. *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
  5747. break;
  5748. case sizeof(u64):
  5749. *val = *(u64 *)ptr;
  5750. break;
  5751. default:
  5752. return -EINVAL;
  5753. }
  5754. return 0;
  5755. }
  5756. #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
  5757. #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
  5758. #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
  5759. #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null)
  5760. /*
  5761. * Allow list few fields as RCU trusted or full trusted.
  5762. * This logic doesn't allow mix tagging and will be removed once GCC supports
  5763. * btf_type_tag.
  5764. */
  5765. /* RCU trusted: these fields are trusted in RCU CS and never NULL */
  5766. BTF_TYPE_SAFE_RCU(struct task_struct) {
  5767. const cpumask_t *cpus_ptr;
  5768. struct css_set __rcu *cgroups;
  5769. struct task_struct __rcu *real_parent;
  5770. struct task_struct *group_leader;
  5771. };
  5772. BTF_TYPE_SAFE_RCU(struct cgroup) {
  5773. /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
  5774. struct kernfs_node *kn;
  5775. };
  5776. BTF_TYPE_SAFE_RCU(struct css_set) {
  5777. struct cgroup *dfl_cgrp;
  5778. };
  5779. /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
  5780. BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
  5781. struct file __rcu *exe_file;
  5782. };
  5783. /* skb->sk, req->sk are not RCU protected, but we mark them as such
  5784. * because bpf prog accessible sockets are SOCK_RCU_FREE.
  5785. */
  5786. BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
  5787. struct sock *sk;
  5788. };
  5789. BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
  5790. struct sock *sk;
  5791. };
  5792. /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
  5793. BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
  5794. struct seq_file *seq;
  5795. };
  5796. BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
  5797. struct bpf_iter_meta *meta;
  5798. struct task_struct *task;
  5799. };
  5800. BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
  5801. struct file *file;
  5802. };
  5803. BTF_TYPE_SAFE_TRUSTED(struct file) {
  5804. struct inode *f_inode;
  5805. };
  5806. BTF_TYPE_SAFE_TRUSTED(struct dentry) {
  5807. /* no negative dentry-s in places where bpf can see it */
  5808. struct inode *d_inode;
  5809. };
  5810. BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
  5811. struct sock *sk;
  5812. };
  5813. static bool type_is_rcu(struct bpf_verifier_env *env,
  5814. struct bpf_reg_state *reg,
  5815. const char *field_name, u32 btf_id)
  5816. {
  5817. BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
  5818. BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
  5819. BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
  5820. return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
  5821. }
  5822. static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
  5823. struct bpf_reg_state *reg,
  5824. const char *field_name, u32 btf_id)
  5825. {
  5826. BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
  5827. BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
  5828. BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
  5829. return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
  5830. }
  5831. static bool type_is_trusted(struct bpf_verifier_env *env,
  5832. struct bpf_reg_state *reg,
  5833. const char *field_name, u32 btf_id)
  5834. {
  5835. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
  5836. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
  5837. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
  5838. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
  5839. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
  5840. return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
  5841. }
  5842. static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
  5843. struct bpf_reg_state *reg,
  5844. const char *field_name, u32 btf_id)
  5845. {
  5846. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
  5847. return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
  5848. "__safe_trusted_or_null");
  5849. }
  5850. static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
  5851. struct bpf_reg_state *regs,
  5852. int regno, int off, int size,
  5853. enum bpf_access_type atype,
  5854. int value_regno)
  5855. {
  5856. struct bpf_reg_state *reg = regs + regno;
  5857. const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
  5858. const char *tname = btf_name_by_offset(reg->btf, t->name_off);
  5859. const char *field_name = NULL;
  5860. enum bpf_type_flag flag = 0;
  5861. u32 btf_id = 0;
  5862. int ret;
  5863. if (!env->allow_ptr_leaks) {
  5864. verbose(env,
  5865. "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
  5866. tname);
  5867. return -EPERM;
  5868. }
  5869. if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
  5870. verbose(env,
  5871. "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
  5872. tname);
  5873. return -EINVAL;
  5874. }
  5875. if (off < 0) {
  5876. verbose(env,
  5877. "R%d is ptr_%s invalid negative access: off=%d\n",
  5878. regno, tname, off);
  5879. return -EACCES;
  5880. }
  5881. if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
  5882. char tn_buf[48];
  5883. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  5884. verbose(env,
  5885. "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
  5886. regno, tname, off, tn_buf);
  5887. return -EACCES;
  5888. }
  5889. if (reg->type & MEM_USER) {
  5890. verbose(env,
  5891. "R%d is ptr_%s access user memory: off=%d\n",
  5892. regno, tname, off);
  5893. return -EACCES;
  5894. }
  5895. if (reg->type & MEM_PERCPU) {
  5896. verbose(env,
  5897. "R%d is ptr_%s access percpu memory: off=%d\n",
  5898. regno, tname, off);
  5899. return -EACCES;
  5900. }
  5901. if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
  5902. if (!btf_is_kernel(reg->btf)) {
  5903. verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
  5904. return -EFAULT;
  5905. }
  5906. ret = env->ops->btf_struct_access(&env->log, reg, off, size);
  5907. } else {
  5908. /* Writes are permitted with default btf_struct_access for
  5909. * program allocated objects (which always have ref_obj_id > 0),
  5910. * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
  5911. */
  5912. if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
  5913. verbose(env, "only read is supported\n");
  5914. return -EACCES;
  5915. }
  5916. if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
  5917. !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
  5918. verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
  5919. return -EFAULT;
  5920. }
  5921. ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
  5922. }
  5923. if (ret < 0)
  5924. return ret;
  5925. if (ret != PTR_TO_BTF_ID) {
  5926. /* just mark; */
  5927. } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
  5928. /* If this is an untrusted pointer, all pointers formed by walking it
  5929. * also inherit the untrusted flag.
  5930. */
  5931. flag = PTR_UNTRUSTED;
  5932. } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
  5933. /* By default any pointer obtained from walking a trusted pointer is no
  5934. * longer trusted, unless the field being accessed has explicitly been
  5935. * marked as inheriting its parent's state of trust (either full or RCU).
  5936. * For example:
  5937. * 'cgroups' pointer is untrusted if task->cgroups dereference
  5938. * happened in a sleepable program outside of bpf_rcu_read_lock()
  5939. * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
  5940. * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
  5941. *
  5942. * A regular RCU-protected pointer with __rcu tag can also be deemed
  5943. * trusted if we are in an RCU CS. Such pointer can be NULL.
  5944. */
  5945. if (type_is_trusted(env, reg, field_name, btf_id)) {
  5946. flag |= PTR_TRUSTED;
  5947. } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
  5948. flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
  5949. } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
  5950. if (type_is_rcu(env, reg, field_name, btf_id)) {
  5951. /* ignore __rcu tag and mark it MEM_RCU */
  5952. flag |= MEM_RCU;
  5953. } else if (flag & MEM_RCU ||
  5954. type_is_rcu_or_null(env, reg, field_name, btf_id)) {
  5955. /* __rcu tagged pointers can be NULL */
  5956. flag |= MEM_RCU | PTR_MAYBE_NULL;
  5957. /* We always trust them */
  5958. if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
  5959. flag & PTR_UNTRUSTED)
  5960. flag &= ~PTR_UNTRUSTED;
  5961. } else if (flag & (MEM_PERCPU | MEM_USER)) {
  5962. /* keep as-is */
  5963. } else {
  5964. /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
  5965. clear_trusted_flags(&flag);
  5966. }
  5967. } else {
  5968. /*
  5969. * If not in RCU CS or MEM_RCU pointer can be NULL then
  5970. * aggressively mark as untrusted otherwise such
  5971. * pointers will be plain PTR_TO_BTF_ID without flags
  5972. * and will be allowed to be passed into helpers for
  5973. * compat reasons.
  5974. */
  5975. flag = PTR_UNTRUSTED;
  5976. }
  5977. } else {
  5978. /* Old compat. Deprecated */
  5979. clear_trusted_flags(&flag);
  5980. }
  5981. if (atype == BPF_READ && value_regno >= 0)
  5982. mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
  5983. return 0;
  5984. }
  5985. static int check_ptr_to_map_access(struct bpf_verifier_env *env,
  5986. struct bpf_reg_state *regs,
  5987. int regno, int off, int size,
  5988. enum bpf_access_type atype,
  5989. int value_regno)
  5990. {
  5991. struct bpf_reg_state *reg = regs + regno;
  5992. struct bpf_map *map = reg->map_ptr;
  5993. struct bpf_reg_state map_reg;
  5994. enum bpf_type_flag flag = 0;
  5995. const struct btf_type *t;
  5996. const char *tname;
  5997. u32 btf_id;
  5998. int ret;
  5999. if (!btf_vmlinux) {
  6000. verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
  6001. return -ENOTSUPP;
  6002. }
  6003. if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
  6004. verbose(env, "map_ptr access not supported for map type %d\n",
  6005. map->map_type);
  6006. return -ENOTSUPP;
  6007. }
  6008. t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
  6009. tname = btf_name_by_offset(btf_vmlinux, t->name_off);
  6010. if (!env->allow_ptr_leaks) {
  6011. verbose(env,
  6012. "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
  6013. tname);
  6014. return -EPERM;
  6015. }
  6016. if (off < 0) {
  6017. verbose(env, "R%d is %s invalid negative access: off=%d\n",
  6018. regno, tname, off);
  6019. return -EACCES;
  6020. }
  6021. if (atype != BPF_READ) {
  6022. verbose(env, "only read from %s is supported\n", tname);
  6023. return -EACCES;
  6024. }
  6025. /* Simulate access to a PTR_TO_BTF_ID */
  6026. memset(&map_reg, 0, sizeof(map_reg));
  6027. mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
  6028. ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
  6029. if (ret < 0)
  6030. return ret;
  6031. if (value_regno >= 0)
  6032. mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
  6033. return 0;
  6034. }
  6035. /* Check that the stack access at the given offset is within bounds. The
  6036. * maximum valid offset is -1.
  6037. *
  6038. * The minimum valid offset is -MAX_BPF_STACK for writes, and
  6039. * -state->allocated_stack for reads.
  6040. */
  6041. static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
  6042. s64 off,
  6043. struct bpf_func_state *state,
  6044. enum bpf_access_type t)
  6045. {
  6046. int min_valid_off;
  6047. if (t == BPF_WRITE || env->allow_uninit_stack)
  6048. min_valid_off = -MAX_BPF_STACK;
  6049. else
  6050. min_valid_off = -state->allocated_stack;
  6051. if (off < min_valid_off || off > -1)
  6052. return -EACCES;
  6053. return 0;
  6054. }
  6055. /* Check that the stack access at 'regno + off' falls within the maximum stack
  6056. * bounds.
  6057. *
  6058. * 'off' includes `regno->offset`, but not its dynamic part (if any).
  6059. */
  6060. static int check_stack_access_within_bounds(
  6061. struct bpf_verifier_env *env,
  6062. int regno, int off, int access_size,
  6063. enum bpf_access_src src, enum bpf_access_type type)
  6064. {
  6065. struct bpf_reg_state *regs = cur_regs(env);
  6066. struct bpf_reg_state *reg = regs + regno;
  6067. struct bpf_func_state *state = func(env, reg);
  6068. s64 min_off, max_off;
  6069. int err;
  6070. char *err_extra;
  6071. if (src == ACCESS_HELPER)
  6072. /* We don't know if helpers are reading or writing (or both). */
  6073. err_extra = " indirect access to";
  6074. else if (type == BPF_READ)
  6075. err_extra = " read from";
  6076. else
  6077. err_extra = " write to";
  6078. if (tnum_is_const(reg->var_off)) {
  6079. min_off = (s64)reg->var_off.value + off;
  6080. max_off = min_off + access_size;
  6081. } else {
  6082. if (reg->smax_value >= BPF_MAX_VAR_OFF ||
  6083. reg->smin_value <= -BPF_MAX_VAR_OFF) {
  6084. verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
  6085. err_extra, regno);
  6086. return -EACCES;
  6087. }
  6088. min_off = reg->smin_value + off;
  6089. max_off = reg->smax_value + off + access_size;
  6090. }
  6091. err = check_stack_slot_within_bounds(env, min_off, state, type);
  6092. if (!err && max_off > 0)
  6093. err = -EINVAL; /* out of stack access into non-negative offsets */
  6094. if (!err && access_size < 0)
  6095. /* access_size should not be negative (or overflow an int); others checks
  6096. * along the way should have prevented such an access.
  6097. */
  6098. err = -EFAULT; /* invalid negative access size; integer overflow? */
  6099. if (err) {
  6100. if (tnum_is_const(reg->var_off)) {
  6101. verbose(env, "invalid%s stack R%d off=%d size=%d\n",
  6102. err_extra, regno, off, access_size);
  6103. } else {
  6104. char tn_buf[48];
  6105. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  6106. verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
  6107. err_extra, regno, tn_buf, off, access_size);
  6108. }
  6109. return err;
  6110. }
  6111. /* Note that there is no stack access with offset zero, so the needed stack
  6112. * size is -min_off, not -min_off+1.
  6113. */
  6114. return grow_stack_state(env, state, -min_off /* size */);
  6115. }
  6116. static bool get_func_retval_range(struct bpf_prog *prog,
  6117. struct bpf_retval_range *range)
  6118. {
  6119. if (prog->type == BPF_PROG_TYPE_LSM &&
  6120. prog->expected_attach_type == BPF_LSM_MAC &&
  6121. !bpf_lsm_get_retval_range(prog, range)) {
  6122. return true;
  6123. }
  6124. return false;
  6125. }
  6126. /* check whether memory at (regno + off) is accessible for t = (read | write)
  6127. * if t==write, value_regno is a register which value is stored into memory
  6128. * if t==read, value_regno is a register which will receive the value from memory
  6129. * if t==write && value_regno==-1, some unknown value is stored into memory
  6130. * if t==read && value_regno==-1, don't care what we read from memory
  6131. */
  6132. static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
  6133. int off, int bpf_size, enum bpf_access_type t,
  6134. int value_regno, bool strict_alignment_once, bool is_ldsx)
  6135. {
  6136. struct bpf_reg_state *regs = cur_regs(env);
  6137. struct bpf_reg_state *reg = regs + regno;
  6138. int size, err = 0;
  6139. size = bpf_size_to_bytes(bpf_size);
  6140. if (size < 0)
  6141. return size;
  6142. /* alignment checks will add in reg->off themselves */
  6143. err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
  6144. if (err)
  6145. return err;
  6146. /* for access checks, reg->off is just part of off */
  6147. off += reg->off;
  6148. if (reg->type == PTR_TO_MAP_KEY) {
  6149. if (t == BPF_WRITE) {
  6150. verbose(env, "write to change key R%d not allowed\n", regno);
  6151. return -EACCES;
  6152. }
  6153. err = check_mem_region_access(env, regno, off, size,
  6154. reg->map_ptr->key_size, false);
  6155. if (err)
  6156. return err;
  6157. if (value_regno >= 0)
  6158. mark_reg_unknown(env, regs, value_regno);
  6159. } else if (reg->type == PTR_TO_MAP_VALUE) {
  6160. struct btf_field *kptr_field = NULL;
  6161. if (t == BPF_WRITE && value_regno >= 0 &&
  6162. is_pointer_value(env, value_regno)) {
  6163. verbose(env, "R%d leaks addr into map\n", value_regno);
  6164. return -EACCES;
  6165. }
  6166. err = check_map_access_type(env, regno, off, size, t);
  6167. if (err)
  6168. return err;
  6169. err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
  6170. if (err)
  6171. return err;
  6172. if (tnum_is_const(reg->var_off))
  6173. kptr_field = btf_record_find(reg->map_ptr->record,
  6174. off + reg->var_off.value, BPF_KPTR);
  6175. if (kptr_field) {
  6176. err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
  6177. } else if (t == BPF_READ && value_regno >= 0) {
  6178. struct bpf_map *map = reg->map_ptr;
  6179. /* if map is read-only, track its contents as scalars */
  6180. if (tnum_is_const(reg->var_off) &&
  6181. bpf_map_is_rdonly(map) &&
  6182. map->ops->map_direct_value_addr) {
  6183. int map_off = off + reg->var_off.value;
  6184. u64 val = 0;
  6185. err = bpf_map_direct_read(map, map_off, size,
  6186. &val, is_ldsx);
  6187. if (err)
  6188. return err;
  6189. regs[value_regno].type = SCALAR_VALUE;
  6190. __mark_reg_known(&regs[value_regno], val);
  6191. } else {
  6192. mark_reg_unknown(env, regs, value_regno);
  6193. }
  6194. }
  6195. } else if (base_type(reg->type) == PTR_TO_MEM) {
  6196. bool rdonly_mem = type_is_rdonly_mem(reg->type);
  6197. if (type_may_be_null(reg->type)) {
  6198. verbose(env, "R%d invalid mem access '%s'\n", regno,
  6199. reg_type_str(env, reg->type));
  6200. return -EACCES;
  6201. }
  6202. if (t == BPF_WRITE && rdonly_mem) {
  6203. verbose(env, "R%d cannot write into %s\n",
  6204. regno, reg_type_str(env, reg->type));
  6205. return -EACCES;
  6206. }
  6207. if (t == BPF_WRITE && value_regno >= 0 &&
  6208. is_pointer_value(env, value_regno)) {
  6209. verbose(env, "R%d leaks addr into mem\n", value_regno);
  6210. return -EACCES;
  6211. }
  6212. err = check_mem_region_access(env, regno, off, size,
  6213. reg->mem_size, false);
  6214. if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
  6215. mark_reg_unknown(env, regs, value_regno);
  6216. } else if (reg->type == PTR_TO_CTX) {
  6217. bool is_retval = false;
  6218. struct bpf_retval_range range;
  6219. enum bpf_reg_type reg_type = SCALAR_VALUE;
  6220. struct btf *btf = NULL;
  6221. u32 btf_id = 0;
  6222. if (t == BPF_WRITE && value_regno >= 0 &&
  6223. is_pointer_value(env, value_regno)) {
  6224. verbose(env, "R%d leaks addr into ctx\n", value_regno);
  6225. return -EACCES;
  6226. }
  6227. err = check_ptr_off_reg(env, reg, regno);
  6228. if (err < 0)
  6229. return err;
  6230. err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
  6231. &btf_id, &is_retval, is_ldsx);
  6232. if (err)
  6233. verbose_linfo(env, insn_idx, "; ");
  6234. if (!err && t == BPF_READ && value_regno >= 0) {
  6235. /* ctx access returns either a scalar, or a
  6236. * PTR_TO_PACKET[_META,_END]. In the latter
  6237. * case, we know the offset is zero.
  6238. */
  6239. if (reg_type == SCALAR_VALUE) {
  6240. if (is_retval && get_func_retval_range(env->prog, &range)) {
  6241. err = __mark_reg_s32_range(env, regs, value_regno,
  6242. range.minval, range.maxval);
  6243. if (err)
  6244. return err;
  6245. } else {
  6246. mark_reg_unknown(env, regs, value_regno);
  6247. }
  6248. } else {
  6249. mark_reg_known_zero(env, regs,
  6250. value_regno);
  6251. if (type_may_be_null(reg_type))
  6252. regs[value_regno].id = ++env->id_gen;
  6253. /* A load of ctx field could have different
  6254. * actual load size with the one encoded in the
  6255. * insn. When the dst is PTR, it is for sure not
  6256. * a sub-register.
  6257. */
  6258. regs[value_regno].subreg_def = DEF_NOT_SUBREG;
  6259. if (base_type(reg_type) == PTR_TO_BTF_ID) {
  6260. regs[value_regno].btf = btf;
  6261. regs[value_regno].btf_id = btf_id;
  6262. }
  6263. }
  6264. regs[value_regno].type = reg_type;
  6265. }
  6266. } else if (reg->type == PTR_TO_STACK) {
  6267. /* Basic bounds checks. */
  6268. err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
  6269. if (err)
  6270. return err;
  6271. if (t == BPF_READ)
  6272. err = check_stack_read(env, regno, off, size,
  6273. value_regno);
  6274. else
  6275. err = check_stack_write(env, regno, off, size,
  6276. value_regno, insn_idx);
  6277. } else if (reg_is_pkt_pointer(reg)) {
  6278. if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
  6279. verbose(env, "cannot write into packet\n");
  6280. return -EACCES;
  6281. }
  6282. if (t == BPF_WRITE && value_regno >= 0 &&
  6283. is_pointer_value(env, value_regno)) {
  6284. verbose(env, "R%d leaks addr into packet\n",
  6285. value_regno);
  6286. return -EACCES;
  6287. }
  6288. err = check_packet_access(env, regno, off, size, false);
  6289. if (!err && t == BPF_READ && value_regno >= 0)
  6290. mark_reg_unknown(env, regs, value_regno);
  6291. } else if (reg->type == PTR_TO_FLOW_KEYS) {
  6292. if (t == BPF_WRITE && value_regno >= 0 &&
  6293. is_pointer_value(env, value_regno)) {
  6294. verbose(env, "R%d leaks addr into flow keys\n",
  6295. value_regno);
  6296. return -EACCES;
  6297. }
  6298. err = check_flow_keys_access(env, off, size);
  6299. if (!err && t == BPF_READ && value_regno >= 0)
  6300. mark_reg_unknown(env, regs, value_regno);
  6301. } else if (type_is_sk_pointer(reg->type)) {
  6302. if (t == BPF_WRITE) {
  6303. verbose(env, "R%d cannot write into %s\n",
  6304. regno, reg_type_str(env, reg->type));
  6305. return -EACCES;
  6306. }
  6307. err = check_sock_access(env, insn_idx, regno, off, size, t);
  6308. if (!err && value_regno >= 0)
  6309. mark_reg_unknown(env, regs, value_regno);
  6310. } else if (reg->type == PTR_TO_TP_BUFFER) {
  6311. err = check_tp_buffer_access(env, reg, regno, off, size);
  6312. if (!err && t == BPF_READ && value_regno >= 0)
  6313. mark_reg_unknown(env, regs, value_regno);
  6314. } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
  6315. !type_may_be_null(reg->type)) {
  6316. err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
  6317. value_regno);
  6318. } else if (reg->type == CONST_PTR_TO_MAP) {
  6319. err = check_ptr_to_map_access(env, regs, regno, off, size, t,
  6320. value_regno);
  6321. } else if (base_type(reg->type) == PTR_TO_BUF) {
  6322. bool rdonly_mem = type_is_rdonly_mem(reg->type);
  6323. u32 *max_access;
  6324. if (rdonly_mem) {
  6325. if (t == BPF_WRITE) {
  6326. verbose(env, "R%d cannot write into %s\n",
  6327. regno, reg_type_str(env, reg->type));
  6328. return -EACCES;
  6329. }
  6330. max_access = &env->prog->aux->max_rdonly_access;
  6331. } else {
  6332. max_access = &env->prog->aux->max_rdwr_access;
  6333. }
  6334. err = check_buffer_access(env, reg, regno, off, size, false,
  6335. max_access);
  6336. if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
  6337. mark_reg_unknown(env, regs, value_regno);
  6338. } else if (reg->type == PTR_TO_ARENA) {
  6339. if (t == BPF_READ && value_regno >= 0)
  6340. mark_reg_unknown(env, regs, value_regno);
  6341. } else {
  6342. verbose(env, "R%d invalid mem access '%s'\n", regno,
  6343. reg_type_str(env, reg->type));
  6344. return -EACCES;
  6345. }
  6346. if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
  6347. regs[value_regno].type == SCALAR_VALUE) {
  6348. if (!is_ldsx)
  6349. /* b/h/w load zero-extends, mark upper bits as known 0 */
  6350. coerce_reg_to_size(&regs[value_regno], size);
  6351. else
  6352. coerce_reg_to_size_sx(&regs[value_regno], size);
  6353. }
  6354. return err;
  6355. }
  6356. static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
  6357. bool allow_trust_mismatch);
  6358. static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
  6359. {
  6360. int load_reg;
  6361. int err;
  6362. switch (insn->imm) {
  6363. case BPF_ADD:
  6364. case BPF_ADD | BPF_FETCH:
  6365. case BPF_AND:
  6366. case BPF_AND | BPF_FETCH:
  6367. case BPF_OR:
  6368. case BPF_OR | BPF_FETCH:
  6369. case BPF_XOR:
  6370. case BPF_XOR | BPF_FETCH:
  6371. case BPF_XCHG:
  6372. case BPF_CMPXCHG:
  6373. break;
  6374. default:
  6375. verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
  6376. return -EINVAL;
  6377. }
  6378. if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
  6379. verbose(env, "invalid atomic operand size\n");
  6380. return -EINVAL;
  6381. }
  6382. /* check src1 operand */
  6383. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  6384. if (err)
  6385. return err;
  6386. /* check src2 operand */
  6387. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  6388. if (err)
  6389. return err;
  6390. if (insn->imm == BPF_CMPXCHG) {
  6391. /* Check comparison of R0 with memory location */
  6392. const u32 aux_reg = BPF_REG_0;
  6393. err = check_reg_arg(env, aux_reg, SRC_OP);
  6394. if (err)
  6395. return err;
  6396. if (is_pointer_value(env, aux_reg)) {
  6397. verbose(env, "R%d leaks addr into mem\n", aux_reg);
  6398. return -EACCES;
  6399. }
  6400. }
  6401. if (is_pointer_value(env, insn->src_reg)) {
  6402. verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
  6403. return -EACCES;
  6404. }
  6405. if (is_ctx_reg(env, insn->dst_reg) ||
  6406. is_pkt_reg(env, insn->dst_reg) ||
  6407. is_flow_key_reg(env, insn->dst_reg) ||
  6408. is_sk_reg(env, insn->dst_reg) ||
  6409. (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
  6410. verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
  6411. insn->dst_reg,
  6412. reg_type_str(env, reg_state(env, insn->dst_reg)->type));
  6413. return -EACCES;
  6414. }
  6415. if (insn->imm & BPF_FETCH) {
  6416. if (insn->imm == BPF_CMPXCHG)
  6417. load_reg = BPF_REG_0;
  6418. else
  6419. load_reg = insn->src_reg;
  6420. /* check and record load of old value */
  6421. err = check_reg_arg(env, load_reg, DST_OP);
  6422. if (err)
  6423. return err;
  6424. } else {
  6425. /* This instruction accesses a memory location but doesn't
  6426. * actually load it into a register.
  6427. */
  6428. load_reg = -1;
  6429. }
  6430. /* Check whether we can read the memory, with second call for fetch
  6431. * case to simulate the register fill.
  6432. */
  6433. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  6434. BPF_SIZE(insn->code), BPF_READ, -1, true, false);
  6435. if (!err && load_reg >= 0)
  6436. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  6437. BPF_SIZE(insn->code), BPF_READ, load_reg,
  6438. true, false);
  6439. if (err)
  6440. return err;
  6441. if (is_arena_reg(env, insn->dst_reg)) {
  6442. err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
  6443. if (err)
  6444. return err;
  6445. }
  6446. /* Check whether we can write into the same memory. */
  6447. err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
  6448. BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
  6449. if (err)
  6450. return err;
  6451. return 0;
  6452. }
  6453. /* When register 'regno' is used to read the stack (either directly or through
  6454. * a helper function) make sure that it's within stack boundary and, depending
  6455. * on the access type and privileges, that all elements of the stack are
  6456. * initialized.
  6457. *
  6458. * 'off' includes 'regno->off', but not its dynamic part (if any).
  6459. *
  6460. * All registers that have been spilled on the stack in the slots within the
  6461. * read offsets are marked as read.
  6462. */
  6463. static int check_stack_range_initialized(
  6464. struct bpf_verifier_env *env, int regno, int off,
  6465. int access_size, bool zero_size_allowed,
  6466. enum bpf_access_src type, struct bpf_call_arg_meta *meta)
  6467. {
  6468. struct bpf_reg_state *reg = reg_state(env, regno);
  6469. struct bpf_func_state *state = func(env, reg);
  6470. int err, min_off, max_off, i, j, slot, spi;
  6471. char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
  6472. enum bpf_access_type bounds_check_type;
  6473. /* Some accesses can write anything into the stack, others are
  6474. * read-only.
  6475. */
  6476. bool clobber = false;
  6477. if (access_size == 0 && !zero_size_allowed) {
  6478. verbose(env, "invalid zero-sized read\n");
  6479. return -EACCES;
  6480. }
  6481. if (type == ACCESS_HELPER) {
  6482. /* The bounds checks for writes are more permissive than for
  6483. * reads. However, if raw_mode is not set, we'll do extra
  6484. * checks below.
  6485. */
  6486. bounds_check_type = BPF_WRITE;
  6487. clobber = true;
  6488. } else {
  6489. bounds_check_type = BPF_READ;
  6490. }
  6491. err = check_stack_access_within_bounds(env, regno, off, access_size,
  6492. type, bounds_check_type);
  6493. if (err)
  6494. return err;
  6495. if (tnum_is_const(reg->var_off)) {
  6496. min_off = max_off = reg->var_off.value + off;
  6497. } else {
  6498. /* Variable offset is prohibited for unprivileged mode for
  6499. * simplicity since it requires corresponding support in
  6500. * Spectre masking for stack ALU.
  6501. * See also retrieve_ptr_limit().
  6502. */
  6503. if (!env->bypass_spec_v1) {
  6504. char tn_buf[48];
  6505. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  6506. verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
  6507. regno, err_extra, tn_buf);
  6508. return -EACCES;
  6509. }
  6510. /* Only initialized buffer on stack is allowed to be accessed
  6511. * with variable offset. With uninitialized buffer it's hard to
  6512. * guarantee that whole memory is marked as initialized on
  6513. * helper return since specific bounds are unknown what may
  6514. * cause uninitialized stack leaking.
  6515. */
  6516. if (meta && meta->raw_mode)
  6517. meta = NULL;
  6518. min_off = reg->smin_value + off;
  6519. max_off = reg->smax_value + off;
  6520. }
  6521. if (meta && meta->raw_mode) {
  6522. /* Ensure we won't be overwriting dynptrs when simulating byte
  6523. * by byte access in check_helper_call using meta.access_size.
  6524. * This would be a problem if we have a helper in the future
  6525. * which takes:
  6526. *
  6527. * helper(uninit_mem, len, dynptr)
  6528. *
  6529. * Now, uninint_mem may overlap with dynptr pointer. Hence, it
  6530. * may end up writing to dynptr itself when touching memory from
  6531. * arg 1. This can be relaxed on a case by case basis for known
  6532. * safe cases, but reject due to the possibilitiy of aliasing by
  6533. * default.
  6534. */
  6535. for (i = min_off; i < max_off + access_size; i++) {
  6536. int stack_off = -i - 1;
  6537. spi = __get_spi(i);
  6538. /* raw_mode may write past allocated_stack */
  6539. if (state->allocated_stack <= stack_off)
  6540. continue;
  6541. if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
  6542. verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
  6543. return -EACCES;
  6544. }
  6545. }
  6546. meta->access_size = access_size;
  6547. meta->regno = regno;
  6548. return 0;
  6549. }
  6550. for (i = min_off; i < max_off + access_size; i++) {
  6551. u8 *stype;
  6552. slot = -i - 1;
  6553. spi = slot / BPF_REG_SIZE;
  6554. if (state->allocated_stack <= slot) {
  6555. verbose(env, "verifier bug: allocated_stack too small");
  6556. return -EFAULT;
  6557. }
  6558. stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
  6559. if (*stype == STACK_MISC)
  6560. goto mark;
  6561. if ((*stype == STACK_ZERO) ||
  6562. (*stype == STACK_INVALID && env->allow_uninit_stack)) {
  6563. if (clobber) {
  6564. /* helper can write anything into the stack */
  6565. *stype = STACK_MISC;
  6566. }
  6567. goto mark;
  6568. }
  6569. if (is_spilled_reg(&state->stack[spi]) &&
  6570. (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
  6571. env->allow_ptr_leaks)) {
  6572. if (clobber) {
  6573. __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
  6574. for (j = 0; j < BPF_REG_SIZE; j++)
  6575. scrub_spilled_slot(&state->stack[spi].slot_type[j]);
  6576. }
  6577. goto mark;
  6578. }
  6579. if (tnum_is_const(reg->var_off)) {
  6580. verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
  6581. err_extra, regno, min_off, i - min_off, access_size);
  6582. } else {
  6583. char tn_buf[48];
  6584. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  6585. verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
  6586. err_extra, regno, tn_buf, i - min_off, access_size);
  6587. }
  6588. return -EACCES;
  6589. mark:
  6590. /* reading any byte out of 8-byte 'spill_slot' will cause
  6591. * the whole slot to be marked as 'read'
  6592. */
  6593. mark_reg_read(env, &state->stack[spi].spilled_ptr,
  6594. state->stack[spi].spilled_ptr.parent,
  6595. REG_LIVE_READ64);
  6596. /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
  6597. * be sure that whether stack slot is written to or not. Hence,
  6598. * we must still conservatively propagate reads upwards even if
  6599. * helper may write to the entire memory range.
  6600. */
  6601. }
  6602. return 0;
  6603. }
  6604. static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
  6605. int access_size, enum bpf_access_type access_type,
  6606. bool zero_size_allowed,
  6607. struct bpf_call_arg_meta *meta)
  6608. {
  6609. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  6610. u32 *max_access;
  6611. switch (base_type(reg->type)) {
  6612. case PTR_TO_PACKET:
  6613. case PTR_TO_PACKET_META:
  6614. return check_packet_access(env, regno, reg->off, access_size,
  6615. zero_size_allowed);
  6616. case PTR_TO_MAP_KEY:
  6617. if (access_type == BPF_WRITE) {
  6618. verbose(env, "R%d cannot write into %s\n", regno,
  6619. reg_type_str(env, reg->type));
  6620. return -EACCES;
  6621. }
  6622. return check_mem_region_access(env, regno, reg->off, access_size,
  6623. reg->map_ptr->key_size, false);
  6624. case PTR_TO_MAP_VALUE:
  6625. if (check_map_access_type(env, regno, reg->off, access_size, access_type))
  6626. return -EACCES;
  6627. return check_map_access(env, regno, reg->off, access_size,
  6628. zero_size_allowed, ACCESS_HELPER);
  6629. case PTR_TO_MEM:
  6630. if (type_is_rdonly_mem(reg->type)) {
  6631. if (access_type == BPF_WRITE) {
  6632. verbose(env, "R%d cannot write into %s\n", regno,
  6633. reg_type_str(env, reg->type));
  6634. return -EACCES;
  6635. }
  6636. }
  6637. return check_mem_region_access(env, regno, reg->off,
  6638. access_size, reg->mem_size,
  6639. zero_size_allowed);
  6640. case PTR_TO_BUF:
  6641. if (type_is_rdonly_mem(reg->type)) {
  6642. if (access_type == BPF_WRITE) {
  6643. verbose(env, "R%d cannot write into %s\n", regno,
  6644. reg_type_str(env, reg->type));
  6645. return -EACCES;
  6646. }
  6647. max_access = &env->prog->aux->max_rdonly_access;
  6648. } else {
  6649. max_access = &env->prog->aux->max_rdwr_access;
  6650. }
  6651. return check_buffer_access(env, reg, regno, reg->off,
  6652. access_size, zero_size_allowed,
  6653. max_access);
  6654. case PTR_TO_STACK:
  6655. return check_stack_range_initialized(
  6656. env,
  6657. regno, reg->off, access_size,
  6658. zero_size_allowed, ACCESS_HELPER, meta);
  6659. case PTR_TO_BTF_ID:
  6660. return check_ptr_to_btf_access(env, regs, regno, reg->off,
  6661. access_size, BPF_READ, -1);
  6662. case PTR_TO_CTX:
  6663. /* in case the function doesn't know how to access the context,
  6664. * (because we are in a program of type SYSCALL for example), we
  6665. * can not statically check its size.
  6666. * Dynamically check it now.
  6667. */
  6668. if (!env->ops->convert_ctx_access) {
  6669. int offset = access_size - 1;
  6670. /* Allow zero-byte read from PTR_TO_CTX */
  6671. if (access_size == 0)
  6672. return zero_size_allowed ? 0 : -EACCES;
  6673. return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
  6674. access_type, -1, false, false);
  6675. }
  6676. fallthrough;
  6677. default: /* scalar_value or invalid ptr */
  6678. /* Allow zero-byte read from NULL, regardless of pointer type */
  6679. if (zero_size_allowed && access_size == 0 &&
  6680. register_is_null(reg))
  6681. return 0;
  6682. verbose(env, "R%d type=%s ", regno,
  6683. reg_type_str(env, reg->type));
  6684. verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
  6685. return -EACCES;
  6686. }
  6687. }
  6688. /* verify arguments to helpers or kfuncs consisting of a pointer and an access
  6689. * size.
  6690. *
  6691. * @regno is the register containing the access size. regno-1 is the register
  6692. * containing the pointer.
  6693. */
  6694. static int check_mem_size_reg(struct bpf_verifier_env *env,
  6695. struct bpf_reg_state *reg, u32 regno,
  6696. enum bpf_access_type access_type,
  6697. bool zero_size_allowed,
  6698. struct bpf_call_arg_meta *meta)
  6699. {
  6700. int err;
  6701. /* This is used to refine r0 return value bounds for helpers
  6702. * that enforce this value as an upper bound on return values.
  6703. * See do_refine_retval_range() for helpers that can refine
  6704. * the return value. C type of helper is u32 so we pull register
  6705. * bound from umax_value however, if negative verifier errors
  6706. * out. Only upper bounds can be learned because retval is an
  6707. * int type and negative retvals are allowed.
  6708. */
  6709. meta->msize_max_value = reg->umax_value;
  6710. /* The register is SCALAR_VALUE; the access check happens using
  6711. * its boundaries. For unprivileged variable accesses, disable
  6712. * raw mode so that the program is required to initialize all
  6713. * the memory that the helper could just partially fill up.
  6714. */
  6715. if (!tnum_is_const(reg->var_off))
  6716. meta = NULL;
  6717. if (reg->smin_value < 0) {
  6718. verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
  6719. regno);
  6720. return -EACCES;
  6721. }
  6722. if (reg->umin_value == 0 && !zero_size_allowed) {
  6723. verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
  6724. regno, reg->umin_value, reg->umax_value);
  6725. return -EACCES;
  6726. }
  6727. if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
  6728. verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
  6729. regno);
  6730. return -EACCES;
  6731. }
  6732. err = check_helper_mem_access(env, regno - 1, reg->umax_value,
  6733. access_type, zero_size_allowed, meta);
  6734. if (!err)
  6735. err = mark_chain_precision(env, regno);
  6736. return err;
  6737. }
  6738. static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  6739. u32 regno, u32 mem_size)
  6740. {
  6741. bool may_be_null = type_may_be_null(reg->type);
  6742. struct bpf_reg_state saved_reg;
  6743. int err;
  6744. if (register_is_null(reg))
  6745. return 0;
  6746. /* Assuming that the register contains a value check if the memory
  6747. * access is safe. Temporarily save and restore the register's state as
  6748. * the conversion shouldn't be visible to a caller.
  6749. */
  6750. if (may_be_null) {
  6751. saved_reg = *reg;
  6752. mark_ptr_not_null_reg(reg);
  6753. }
  6754. err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
  6755. err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
  6756. if (may_be_null)
  6757. *reg = saved_reg;
  6758. return err;
  6759. }
  6760. static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
  6761. u32 regno)
  6762. {
  6763. struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
  6764. bool may_be_null = type_may_be_null(mem_reg->type);
  6765. struct bpf_reg_state saved_reg;
  6766. struct bpf_call_arg_meta meta;
  6767. int err;
  6768. WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
  6769. memset(&meta, 0, sizeof(meta));
  6770. if (may_be_null) {
  6771. saved_reg = *mem_reg;
  6772. mark_ptr_not_null_reg(mem_reg);
  6773. }
  6774. err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
  6775. err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
  6776. if (may_be_null)
  6777. *mem_reg = saved_reg;
  6778. return err;
  6779. }
  6780. /* Implementation details:
  6781. * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
  6782. * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
  6783. * Two bpf_map_lookups (even with the same key) will have different reg->id.
  6784. * Two separate bpf_obj_new will also have different reg->id.
  6785. * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
  6786. * clears reg->id after value_or_null->value transition, since the verifier only
  6787. * cares about the range of access to valid map value pointer and doesn't care
  6788. * about actual address of the map element.
  6789. * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
  6790. * reg->id > 0 after value_or_null->value transition. By doing so
  6791. * two bpf_map_lookups will be considered two different pointers that
  6792. * point to different bpf_spin_locks. Likewise for pointers to allocated objects
  6793. * returned from bpf_obj_new.
  6794. * The verifier allows taking only one bpf_spin_lock at a time to avoid
  6795. * dead-locks.
  6796. * Since only one bpf_spin_lock is allowed the checks are simpler than
  6797. * reg_is_refcounted() logic. The verifier needs to remember only
  6798. * one spin_lock instead of array of acquired_refs.
  6799. * cur_state->active_lock remembers which map value element or allocated
  6800. * object got locked and clears it after bpf_spin_unlock.
  6801. */
  6802. static int process_spin_lock(struct bpf_verifier_env *env, int regno,
  6803. bool is_lock)
  6804. {
  6805. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  6806. struct bpf_verifier_state *cur = env->cur_state;
  6807. bool is_const = tnum_is_const(reg->var_off);
  6808. u64 val = reg->var_off.value;
  6809. struct bpf_map *map = NULL;
  6810. struct btf *btf = NULL;
  6811. struct btf_record *rec;
  6812. if (!is_const) {
  6813. verbose(env,
  6814. "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
  6815. regno);
  6816. return -EINVAL;
  6817. }
  6818. if (reg->type == PTR_TO_MAP_VALUE) {
  6819. map = reg->map_ptr;
  6820. if (!map->btf) {
  6821. verbose(env,
  6822. "map '%s' has to have BTF in order to use bpf_spin_lock\n",
  6823. map->name);
  6824. return -EINVAL;
  6825. }
  6826. } else {
  6827. btf = reg->btf;
  6828. }
  6829. rec = reg_btf_record(reg);
  6830. if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
  6831. verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
  6832. map ? map->name : "kptr");
  6833. return -EINVAL;
  6834. }
  6835. if (rec->spin_lock_off != val + reg->off) {
  6836. verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
  6837. val + reg->off, rec->spin_lock_off);
  6838. return -EINVAL;
  6839. }
  6840. if (is_lock) {
  6841. if (cur->active_lock.ptr) {
  6842. verbose(env,
  6843. "Locking two bpf_spin_locks are not allowed\n");
  6844. return -EINVAL;
  6845. }
  6846. if (map)
  6847. cur->active_lock.ptr = map;
  6848. else
  6849. cur->active_lock.ptr = btf;
  6850. cur->active_lock.id = reg->id;
  6851. } else {
  6852. void *ptr;
  6853. if (map)
  6854. ptr = map;
  6855. else
  6856. ptr = btf;
  6857. if (!cur->active_lock.ptr) {
  6858. verbose(env, "bpf_spin_unlock without taking a lock\n");
  6859. return -EINVAL;
  6860. }
  6861. if (cur->active_lock.ptr != ptr ||
  6862. cur->active_lock.id != reg->id) {
  6863. verbose(env, "bpf_spin_unlock of different lock\n");
  6864. return -EINVAL;
  6865. }
  6866. invalidate_non_owning_refs(env);
  6867. cur->active_lock.ptr = NULL;
  6868. cur->active_lock.id = 0;
  6869. }
  6870. return 0;
  6871. }
  6872. static int process_timer_func(struct bpf_verifier_env *env, int regno,
  6873. struct bpf_call_arg_meta *meta)
  6874. {
  6875. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  6876. bool is_const = tnum_is_const(reg->var_off);
  6877. struct bpf_map *map = reg->map_ptr;
  6878. u64 val = reg->var_off.value;
  6879. if (!is_const) {
  6880. verbose(env,
  6881. "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
  6882. regno);
  6883. return -EINVAL;
  6884. }
  6885. if (!map->btf) {
  6886. verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
  6887. map->name);
  6888. return -EINVAL;
  6889. }
  6890. if (!btf_record_has_field(map->record, BPF_TIMER)) {
  6891. verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
  6892. return -EINVAL;
  6893. }
  6894. if (map->record->timer_off != val + reg->off) {
  6895. verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
  6896. val + reg->off, map->record->timer_off);
  6897. return -EINVAL;
  6898. }
  6899. if (meta->map_ptr) {
  6900. verbose(env, "verifier bug. Two map pointers in a timer helper\n");
  6901. return -EFAULT;
  6902. }
  6903. if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
  6904. verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
  6905. return -EOPNOTSUPP;
  6906. }
  6907. meta->map_uid = reg->map_uid;
  6908. meta->map_ptr = map;
  6909. return 0;
  6910. }
  6911. static int process_wq_func(struct bpf_verifier_env *env, int regno,
  6912. struct bpf_kfunc_call_arg_meta *meta)
  6913. {
  6914. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  6915. struct bpf_map *map = reg->map_ptr;
  6916. u64 val = reg->var_off.value;
  6917. if (map->record->wq_off != val + reg->off) {
  6918. verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
  6919. val + reg->off, map->record->wq_off);
  6920. return -EINVAL;
  6921. }
  6922. meta->map.uid = reg->map_uid;
  6923. meta->map.ptr = map;
  6924. return 0;
  6925. }
  6926. static int process_kptr_func(struct bpf_verifier_env *env, int regno,
  6927. struct bpf_call_arg_meta *meta)
  6928. {
  6929. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  6930. struct btf_field *kptr_field;
  6931. struct bpf_map *map_ptr;
  6932. struct btf_record *rec;
  6933. u32 kptr_off;
  6934. if (type_is_ptr_alloc_obj(reg->type)) {
  6935. rec = reg_btf_record(reg);
  6936. } else { /* PTR_TO_MAP_VALUE */
  6937. map_ptr = reg->map_ptr;
  6938. if (!map_ptr->btf) {
  6939. verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
  6940. map_ptr->name);
  6941. return -EINVAL;
  6942. }
  6943. rec = map_ptr->record;
  6944. meta->map_ptr = map_ptr;
  6945. }
  6946. if (!tnum_is_const(reg->var_off)) {
  6947. verbose(env,
  6948. "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
  6949. regno);
  6950. return -EINVAL;
  6951. }
  6952. if (!btf_record_has_field(rec, BPF_KPTR)) {
  6953. verbose(env, "R%d has no valid kptr\n", regno);
  6954. return -EINVAL;
  6955. }
  6956. kptr_off = reg->off + reg->var_off.value;
  6957. kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
  6958. if (!kptr_field) {
  6959. verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
  6960. return -EACCES;
  6961. }
  6962. if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
  6963. verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
  6964. return -EACCES;
  6965. }
  6966. meta->kptr_field = kptr_field;
  6967. return 0;
  6968. }
  6969. /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
  6970. * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
  6971. *
  6972. * In both cases we deal with the first 8 bytes, but need to mark the next 8
  6973. * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
  6974. * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
  6975. *
  6976. * Mutability of bpf_dynptr is at two levels, one is at the level of struct
  6977. * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
  6978. * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
  6979. * mutate the view of the dynptr and also possibly destroy it. In the latter
  6980. * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
  6981. * memory that dynptr points to.
  6982. *
  6983. * The verifier will keep track both levels of mutation (bpf_dynptr's in
  6984. * reg->type and the memory's in reg->dynptr.type), but there is no support for
  6985. * readonly dynptr view yet, hence only the first case is tracked and checked.
  6986. *
  6987. * This is consistent with how C applies the const modifier to a struct object,
  6988. * where the pointer itself inside bpf_dynptr becomes const but not what it
  6989. * points to.
  6990. *
  6991. * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
  6992. * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
  6993. */
  6994. static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
  6995. enum bpf_arg_type arg_type, int clone_ref_obj_id)
  6996. {
  6997. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  6998. int err;
  6999. if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
  7000. verbose(env,
  7001. "arg#%d expected pointer to stack or const struct bpf_dynptr\n",
  7002. regno - 1);
  7003. return -EINVAL;
  7004. }
  7005. /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
  7006. * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
  7007. */
  7008. if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
  7009. verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
  7010. return -EFAULT;
  7011. }
  7012. /* MEM_UNINIT - Points to memory that is an appropriate candidate for
  7013. * constructing a mutable bpf_dynptr object.
  7014. *
  7015. * Currently, this is only possible with PTR_TO_STACK
  7016. * pointing to a region of at least 16 bytes which doesn't
  7017. * contain an existing bpf_dynptr.
  7018. *
  7019. * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
  7020. * mutated or destroyed. However, the memory it points to
  7021. * may be mutated.
  7022. *
  7023. * None - Points to a initialized dynptr that can be mutated and
  7024. * destroyed, including mutation of the memory it points
  7025. * to.
  7026. */
  7027. if (arg_type & MEM_UNINIT) {
  7028. int i;
  7029. if (!is_dynptr_reg_valid_uninit(env, reg)) {
  7030. verbose(env, "Dynptr has to be an uninitialized dynptr\n");
  7031. return -EINVAL;
  7032. }
  7033. /* we write BPF_DW bits (8 bytes) at a time */
  7034. for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
  7035. err = check_mem_access(env, insn_idx, regno,
  7036. i, BPF_DW, BPF_WRITE, -1, false, false);
  7037. if (err)
  7038. return err;
  7039. }
  7040. err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
  7041. } else /* MEM_RDONLY and None case from above */ {
  7042. /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
  7043. if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
  7044. verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
  7045. return -EINVAL;
  7046. }
  7047. if (!is_dynptr_reg_valid_init(env, reg)) {
  7048. verbose(env,
  7049. "Expected an initialized dynptr as arg #%d\n",
  7050. regno - 1);
  7051. return -EINVAL;
  7052. }
  7053. /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
  7054. if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
  7055. verbose(env,
  7056. "Expected a dynptr of type %s as arg #%d\n",
  7057. dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
  7058. return -EINVAL;
  7059. }
  7060. err = mark_dynptr_read(env, reg);
  7061. }
  7062. return err;
  7063. }
  7064. static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
  7065. {
  7066. struct bpf_func_state *state = func(env, reg);
  7067. return state->stack[spi].spilled_ptr.ref_obj_id;
  7068. }
  7069. static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
  7070. {
  7071. return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
  7072. }
  7073. static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
  7074. {
  7075. return meta->kfunc_flags & KF_ITER_NEW;
  7076. }
  7077. static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
  7078. {
  7079. return meta->kfunc_flags & KF_ITER_NEXT;
  7080. }
  7081. static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
  7082. {
  7083. return meta->kfunc_flags & KF_ITER_DESTROY;
  7084. }
  7085. static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
  7086. const struct btf_param *arg)
  7087. {
  7088. /* btf_check_iter_kfuncs() guarantees that first argument of any iter
  7089. * kfunc is iter state pointer
  7090. */
  7091. if (is_iter_kfunc(meta))
  7092. return arg_idx == 0;
  7093. /* iter passed as an argument to a generic kfunc */
  7094. return btf_param_match_suffix(meta->btf, arg, "__iter");
  7095. }
  7096. static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
  7097. struct bpf_kfunc_call_arg_meta *meta)
  7098. {
  7099. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  7100. const struct btf_type *t;
  7101. int spi, err, i, nr_slots, btf_id;
  7102. if (reg->type != PTR_TO_STACK) {
  7103. verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
  7104. return -EINVAL;
  7105. }
  7106. /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
  7107. * ensures struct convention, so we wouldn't need to do any BTF
  7108. * validation here. But given iter state can be passed as a parameter
  7109. * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
  7110. * conservative here.
  7111. */
  7112. btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
  7113. if (btf_id < 0) {
  7114. verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
  7115. return -EINVAL;
  7116. }
  7117. t = btf_type_by_id(meta->btf, btf_id);
  7118. nr_slots = t->size / BPF_REG_SIZE;
  7119. if (is_iter_new_kfunc(meta)) {
  7120. /* bpf_iter_<type>_new() expects pointer to uninit iter state */
  7121. if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
  7122. verbose(env, "expected uninitialized iter_%s as arg #%d\n",
  7123. iter_type_str(meta->btf, btf_id), regno - 1);
  7124. return -EINVAL;
  7125. }
  7126. for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
  7127. err = check_mem_access(env, insn_idx, regno,
  7128. i, BPF_DW, BPF_WRITE, -1, false, false);
  7129. if (err)
  7130. return err;
  7131. }
  7132. err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
  7133. if (err)
  7134. return err;
  7135. } else {
  7136. /* iter_next() or iter_destroy(), as well as any kfunc
  7137. * accepting iter argument, expect initialized iter state
  7138. */
  7139. err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
  7140. switch (err) {
  7141. case 0:
  7142. break;
  7143. case -EINVAL:
  7144. verbose(env, "expected an initialized iter_%s as arg #%d\n",
  7145. iter_type_str(meta->btf, btf_id), regno - 1);
  7146. return err;
  7147. case -EPROTO:
  7148. verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
  7149. return err;
  7150. default:
  7151. return err;
  7152. }
  7153. spi = iter_get_spi(env, reg, nr_slots);
  7154. if (spi < 0)
  7155. return spi;
  7156. err = mark_iter_read(env, reg, spi, nr_slots);
  7157. if (err)
  7158. return err;
  7159. /* remember meta->iter info for process_iter_next_call() */
  7160. meta->iter.spi = spi;
  7161. meta->iter.frameno = reg->frameno;
  7162. meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
  7163. if (is_iter_destroy_kfunc(meta)) {
  7164. err = unmark_stack_slots_iter(env, reg, nr_slots);
  7165. if (err)
  7166. return err;
  7167. }
  7168. }
  7169. return 0;
  7170. }
  7171. /* Look for a previous loop entry at insn_idx: nearest parent state
  7172. * stopped at insn_idx with callsites matching those in cur->frame.
  7173. */
  7174. static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
  7175. struct bpf_verifier_state *cur,
  7176. int insn_idx)
  7177. {
  7178. struct bpf_verifier_state_list *sl;
  7179. struct bpf_verifier_state *st;
  7180. /* Explored states are pushed in stack order, most recent states come first */
  7181. sl = *explored_state(env, insn_idx);
  7182. for (; sl; sl = sl->next) {
  7183. /* If st->branches != 0 state is a part of current DFS verification path,
  7184. * hence cur & st for a loop.
  7185. */
  7186. st = &sl->state;
  7187. if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
  7188. st->dfs_depth < cur->dfs_depth)
  7189. return st;
  7190. }
  7191. return NULL;
  7192. }
  7193. static void reset_idmap_scratch(struct bpf_verifier_env *env);
  7194. static bool regs_exact(const struct bpf_reg_state *rold,
  7195. const struct bpf_reg_state *rcur,
  7196. struct bpf_idmap *idmap);
  7197. static void maybe_widen_reg(struct bpf_verifier_env *env,
  7198. struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
  7199. struct bpf_idmap *idmap)
  7200. {
  7201. if (rold->type != SCALAR_VALUE)
  7202. return;
  7203. if (rold->type != rcur->type)
  7204. return;
  7205. if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
  7206. return;
  7207. __mark_reg_unknown(env, rcur);
  7208. }
  7209. static int widen_imprecise_scalars(struct bpf_verifier_env *env,
  7210. struct bpf_verifier_state *old,
  7211. struct bpf_verifier_state *cur)
  7212. {
  7213. struct bpf_func_state *fold, *fcur;
  7214. int i, fr;
  7215. reset_idmap_scratch(env);
  7216. for (fr = old->curframe; fr >= 0; fr--) {
  7217. fold = old->frame[fr];
  7218. fcur = cur->frame[fr];
  7219. for (i = 0; i < MAX_BPF_REG; i++)
  7220. maybe_widen_reg(env,
  7221. &fold->regs[i],
  7222. &fcur->regs[i],
  7223. &env->idmap_scratch);
  7224. for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
  7225. if (!is_spilled_reg(&fold->stack[i]) ||
  7226. !is_spilled_reg(&fcur->stack[i]))
  7227. continue;
  7228. maybe_widen_reg(env,
  7229. &fold->stack[i].spilled_ptr,
  7230. &fcur->stack[i].spilled_ptr,
  7231. &env->idmap_scratch);
  7232. }
  7233. }
  7234. return 0;
  7235. }
  7236. static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
  7237. struct bpf_kfunc_call_arg_meta *meta)
  7238. {
  7239. int iter_frameno = meta->iter.frameno;
  7240. int iter_spi = meta->iter.spi;
  7241. return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
  7242. }
  7243. /* process_iter_next_call() is called when verifier gets to iterator's next
  7244. * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
  7245. * to it as just "iter_next()" in comments below.
  7246. *
  7247. * BPF verifier relies on a crucial contract for any iter_next()
  7248. * implementation: it should *eventually* return NULL, and once that happens
  7249. * it should keep returning NULL. That is, once iterator exhausts elements to
  7250. * iterate, it should never reset or spuriously return new elements.
  7251. *
  7252. * With the assumption of such contract, process_iter_next_call() simulates
  7253. * a fork in the verifier state to validate loop logic correctness and safety
  7254. * without having to simulate infinite amount of iterations.
  7255. *
  7256. * In current state, we first assume that iter_next() returned NULL and
  7257. * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
  7258. * conditions we should not form an infinite loop and should eventually reach
  7259. * exit.
  7260. *
  7261. * Besides that, we also fork current state and enqueue it for later
  7262. * verification. In a forked state we keep iterator state as ACTIVE
  7263. * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
  7264. * also bump iteration depth to prevent erroneous infinite loop detection
  7265. * later on (see iter_active_depths_differ() comment for details). In this
  7266. * state we assume that we'll eventually loop back to another iter_next()
  7267. * calls (it could be in exactly same location or in some other instruction,
  7268. * it doesn't matter, we don't make any unnecessary assumptions about this,
  7269. * everything revolves around iterator state in a stack slot, not which
  7270. * instruction is calling iter_next()). When that happens, we either will come
  7271. * to iter_next() with equivalent state and can conclude that next iteration
  7272. * will proceed in exactly the same way as we just verified, so it's safe to
  7273. * assume that loop converges. If not, we'll go on another iteration
  7274. * simulation with a different input state, until all possible starting states
  7275. * are validated or we reach maximum number of instructions limit.
  7276. *
  7277. * This way, we will either exhaustively discover all possible input states
  7278. * that iterator loop can start with and eventually will converge, or we'll
  7279. * effectively regress into bounded loop simulation logic and either reach
  7280. * maximum number of instructions if loop is not provably convergent, or there
  7281. * is some statically known limit on number of iterations (e.g., if there is
  7282. * an explicit `if n > 100 then break;` statement somewhere in the loop).
  7283. *
  7284. * Iteration convergence logic in is_state_visited() relies on exact
  7285. * states comparison, which ignores read and precision marks.
  7286. * This is necessary because read and precision marks are not finalized
  7287. * while in the loop. Exact comparison might preclude convergence for
  7288. * simple programs like below:
  7289. *
  7290. * i = 0;
  7291. * while(iter_next(&it))
  7292. * i++;
  7293. *
  7294. * At each iteration step i++ would produce a new distinct state and
  7295. * eventually instruction processing limit would be reached.
  7296. *
  7297. * To avoid such behavior speculatively forget (widen) range for
  7298. * imprecise scalar registers, if those registers were not precise at the
  7299. * end of the previous iteration and do not match exactly.
  7300. *
  7301. * This is a conservative heuristic that allows to verify wide range of programs,
  7302. * however it precludes verification of programs that conjure an
  7303. * imprecise value on the first loop iteration and use it as precise on a second.
  7304. * For example, the following safe program would fail to verify:
  7305. *
  7306. * struct bpf_num_iter it;
  7307. * int arr[10];
  7308. * int i = 0, a = 0;
  7309. * bpf_iter_num_new(&it, 0, 10);
  7310. * while (bpf_iter_num_next(&it)) {
  7311. * if (a == 0) {
  7312. * a = 1;
  7313. * i = 7; // Because i changed verifier would forget
  7314. * // it's range on second loop entry.
  7315. * } else {
  7316. * arr[i] = 42; // This would fail to verify.
  7317. * }
  7318. * }
  7319. * bpf_iter_num_destroy(&it);
  7320. */
  7321. static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
  7322. struct bpf_kfunc_call_arg_meta *meta)
  7323. {
  7324. struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
  7325. struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
  7326. struct bpf_reg_state *cur_iter, *queued_iter;
  7327. BTF_TYPE_EMIT(struct bpf_iter);
  7328. cur_iter = get_iter_from_state(cur_st, meta);
  7329. if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
  7330. cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
  7331. verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
  7332. cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
  7333. return -EFAULT;
  7334. }
  7335. if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
  7336. /* Because iter_next() call is a checkpoint is_state_visitied()
  7337. * should guarantee parent state with same call sites and insn_idx.
  7338. */
  7339. if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
  7340. !same_callsites(cur_st->parent, cur_st)) {
  7341. verbose(env, "bug: bad parent state for iter next call");
  7342. return -EFAULT;
  7343. }
  7344. /* Note cur_st->parent in the call below, it is necessary to skip
  7345. * checkpoint created for cur_st by is_state_visited()
  7346. * right at this instruction.
  7347. */
  7348. prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
  7349. /* branch out active iter state */
  7350. queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
  7351. if (!queued_st)
  7352. return -ENOMEM;
  7353. queued_iter = get_iter_from_state(queued_st, meta);
  7354. queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
  7355. queued_iter->iter.depth++;
  7356. if (prev_st)
  7357. widen_imprecise_scalars(env, prev_st, queued_st);
  7358. queued_fr = queued_st->frame[queued_st->curframe];
  7359. mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
  7360. }
  7361. /* switch to DRAINED state, but keep the depth unchanged */
  7362. /* mark current iter state as drained and assume returned NULL */
  7363. cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
  7364. __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
  7365. return 0;
  7366. }
  7367. static bool arg_type_is_mem_size(enum bpf_arg_type type)
  7368. {
  7369. return type == ARG_CONST_SIZE ||
  7370. type == ARG_CONST_SIZE_OR_ZERO;
  7371. }
  7372. static bool arg_type_is_raw_mem(enum bpf_arg_type type)
  7373. {
  7374. return base_type(type) == ARG_PTR_TO_MEM &&
  7375. type & MEM_UNINIT;
  7376. }
  7377. static bool arg_type_is_release(enum bpf_arg_type type)
  7378. {
  7379. return type & OBJ_RELEASE;
  7380. }
  7381. static bool arg_type_is_dynptr(enum bpf_arg_type type)
  7382. {
  7383. return base_type(type) == ARG_PTR_TO_DYNPTR;
  7384. }
  7385. static int resolve_map_arg_type(struct bpf_verifier_env *env,
  7386. const struct bpf_call_arg_meta *meta,
  7387. enum bpf_arg_type *arg_type)
  7388. {
  7389. if (!meta->map_ptr) {
  7390. /* kernel subsystem misconfigured verifier */
  7391. verbose(env, "invalid map_ptr to access map->type\n");
  7392. return -EACCES;
  7393. }
  7394. switch (meta->map_ptr->map_type) {
  7395. case BPF_MAP_TYPE_SOCKMAP:
  7396. case BPF_MAP_TYPE_SOCKHASH:
  7397. if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
  7398. *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
  7399. } else {
  7400. verbose(env, "invalid arg_type for sockmap/sockhash\n");
  7401. return -EINVAL;
  7402. }
  7403. break;
  7404. case BPF_MAP_TYPE_BLOOM_FILTER:
  7405. if (meta->func_id == BPF_FUNC_map_peek_elem)
  7406. *arg_type = ARG_PTR_TO_MAP_VALUE;
  7407. break;
  7408. default:
  7409. break;
  7410. }
  7411. return 0;
  7412. }
  7413. struct bpf_reg_types {
  7414. const enum bpf_reg_type types[10];
  7415. u32 *btf_id;
  7416. };
  7417. static const struct bpf_reg_types sock_types = {
  7418. .types = {
  7419. PTR_TO_SOCK_COMMON,
  7420. PTR_TO_SOCKET,
  7421. PTR_TO_TCP_SOCK,
  7422. PTR_TO_XDP_SOCK,
  7423. },
  7424. };
  7425. #ifdef CONFIG_NET
  7426. static const struct bpf_reg_types btf_id_sock_common_types = {
  7427. .types = {
  7428. PTR_TO_SOCK_COMMON,
  7429. PTR_TO_SOCKET,
  7430. PTR_TO_TCP_SOCK,
  7431. PTR_TO_XDP_SOCK,
  7432. PTR_TO_BTF_ID,
  7433. PTR_TO_BTF_ID | PTR_TRUSTED,
  7434. },
  7435. .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
  7436. };
  7437. #endif
  7438. static const struct bpf_reg_types mem_types = {
  7439. .types = {
  7440. PTR_TO_STACK,
  7441. PTR_TO_PACKET,
  7442. PTR_TO_PACKET_META,
  7443. PTR_TO_MAP_KEY,
  7444. PTR_TO_MAP_VALUE,
  7445. PTR_TO_MEM,
  7446. PTR_TO_MEM | MEM_RINGBUF,
  7447. PTR_TO_BUF,
  7448. PTR_TO_BTF_ID | PTR_TRUSTED,
  7449. },
  7450. };
  7451. static const struct bpf_reg_types spin_lock_types = {
  7452. .types = {
  7453. PTR_TO_MAP_VALUE,
  7454. PTR_TO_BTF_ID | MEM_ALLOC,
  7455. }
  7456. };
  7457. static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
  7458. static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
  7459. static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
  7460. static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
  7461. static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
  7462. static const struct bpf_reg_types btf_ptr_types = {
  7463. .types = {
  7464. PTR_TO_BTF_ID,
  7465. PTR_TO_BTF_ID | PTR_TRUSTED,
  7466. PTR_TO_BTF_ID | MEM_RCU,
  7467. },
  7468. };
  7469. static const struct bpf_reg_types percpu_btf_ptr_types = {
  7470. .types = {
  7471. PTR_TO_BTF_ID | MEM_PERCPU,
  7472. PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
  7473. PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
  7474. }
  7475. };
  7476. static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
  7477. static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
  7478. static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
  7479. static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
  7480. static const struct bpf_reg_types kptr_xchg_dest_types = {
  7481. .types = {
  7482. PTR_TO_MAP_VALUE,
  7483. PTR_TO_BTF_ID | MEM_ALLOC
  7484. }
  7485. };
  7486. static const struct bpf_reg_types dynptr_types = {
  7487. .types = {
  7488. PTR_TO_STACK,
  7489. CONST_PTR_TO_DYNPTR,
  7490. }
  7491. };
  7492. static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
  7493. [ARG_PTR_TO_MAP_KEY] = &mem_types,
  7494. [ARG_PTR_TO_MAP_VALUE] = &mem_types,
  7495. [ARG_CONST_SIZE] = &scalar_types,
  7496. [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
  7497. [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
  7498. [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
  7499. [ARG_PTR_TO_CTX] = &context_types,
  7500. [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
  7501. #ifdef CONFIG_NET
  7502. [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
  7503. #endif
  7504. [ARG_PTR_TO_SOCKET] = &fullsock_types,
  7505. [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
  7506. [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
  7507. [ARG_PTR_TO_MEM] = &mem_types,
  7508. [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
  7509. [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
  7510. [ARG_PTR_TO_FUNC] = &func_ptr_types,
  7511. [ARG_PTR_TO_STACK] = &stack_ptr_types,
  7512. [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
  7513. [ARG_PTR_TO_TIMER] = &timer_types,
  7514. [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types,
  7515. [ARG_PTR_TO_DYNPTR] = &dynptr_types,
  7516. };
  7517. static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
  7518. enum bpf_arg_type arg_type,
  7519. const u32 *arg_btf_id,
  7520. struct bpf_call_arg_meta *meta)
  7521. {
  7522. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  7523. enum bpf_reg_type expected, type = reg->type;
  7524. const struct bpf_reg_types *compatible;
  7525. int i, j;
  7526. compatible = compatible_reg_types[base_type(arg_type)];
  7527. if (!compatible) {
  7528. verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
  7529. return -EFAULT;
  7530. }
  7531. /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
  7532. * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
  7533. *
  7534. * Same for MAYBE_NULL:
  7535. *
  7536. * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
  7537. * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
  7538. *
  7539. * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
  7540. *
  7541. * Therefore we fold these flags depending on the arg_type before comparison.
  7542. */
  7543. if (arg_type & MEM_RDONLY)
  7544. type &= ~MEM_RDONLY;
  7545. if (arg_type & PTR_MAYBE_NULL)
  7546. type &= ~PTR_MAYBE_NULL;
  7547. if (base_type(arg_type) == ARG_PTR_TO_MEM)
  7548. type &= ~DYNPTR_TYPE_FLAG_MASK;
  7549. /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
  7550. if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
  7551. type &= ~MEM_ALLOC;
  7552. type &= ~MEM_PERCPU;
  7553. }
  7554. for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
  7555. expected = compatible->types[i];
  7556. if (expected == NOT_INIT)
  7557. break;
  7558. if (type == expected)
  7559. goto found;
  7560. }
  7561. verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
  7562. for (j = 0; j + 1 < i; j++)
  7563. verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
  7564. verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
  7565. return -EACCES;
  7566. found:
  7567. if (base_type(reg->type) != PTR_TO_BTF_ID)
  7568. return 0;
  7569. if (compatible == &mem_types) {
  7570. if (!(arg_type & MEM_RDONLY)) {
  7571. verbose(env,
  7572. "%s() may write into memory pointed by R%d type=%s\n",
  7573. func_id_name(meta->func_id),
  7574. regno, reg_type_str(env, reg->type));
  7575. return -EACCES;
  7576. }
  7577. return 0;
  7578. }
  7579. switch ((int)reg->type) {
  7580. case PTR_TO_BTF_ID:
  7581. case PTR_TO_BTF_ID | PTR_TRUSTED:
  7582. case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
  7583. case PTR_TO_BTF_ID | MEM_RCU:
  7584. case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
  7585. case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
  7586. {
  7587. /* For bpf_sk_release, it needs to match against first member
  7588. * 'struct sock_common', hence make an exception for it. This
  7589. * allows bpf_sk_release to work for multiple socket types.
  7590. */
  7591. bool strict_type_match = arg_type_is_release(arg_type) &&
  7592. meta->func_id != BPF_FUNC_sk_release;
  7593. if (type_may_be_null(reg->type) &&
  7594. (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
  7595. verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
  7596. return -EACCES;
  7597. }
  7598. if (!arg_btf_id) {
  7599. if (!compatible->btf_id) {
  7600. verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
  7601. return -EFAULT;
  7602. }
  7603. arg_btf_id = compatible->btf_id;
  7604. }
  7605. if (meta->func_id == BPF_FUNC_kptr_xchg) {
  7606. if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
  7607. return -EACCES;
  7608. } else {
  7609. if (arg_btf_id == BPF_PTR_POISON) {
  7610. verbose(env, "verifier internal error:");
  7611. verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
  7612. regno);
  7613. return -EACCES;
  7614. }
  7615. if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
  7616. btf_vmlinux, *arg_btf_id,
  7617. strict_type_match)) {
  7618. verbose(env, "R%d is of type %s but %s is expected\n",
  7619. regno, btf_type_name(reg->btf, reg->btf_id),
  7620. btf_type_name(btf_vmlinux, *arg_btf_id));
  7621. return -EACCES;
  7622. }
  7623. }
  7624. break;
  7625. }
  7626. case PTR_TO_BTF_ID | MEM_ALLOC:
  7627. case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
  7628. if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
  7629. meta->func_id != BPF_FUNC_kptr_xchg) {
  7630. verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
  7631. return -EFAULT;
  7632. }
  7633. /* Check if local kptr in src arg matches kptr in dst arg */
  7634. if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
  7635. if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
  7636. return -EACCES;
  7637. }
  7638. break;
  7639. case PTR_TO_BTF_ID | MEM_PERCPU:
  7640. case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
  7641. case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
  7642. /* Handled by helper specific checks */
  7643. break;
  7644. default:
  7645. verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
  7646. return -EFAULT;
  7647. }
  7648. return 0;
  7649. }
  7650. static struct btf_field *
  7651. reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
  7652. {
  7653. struct btf_field *field;
  7654. struct btf_record *rec;
  7655. rec = reg_btf_record(reg);
  7656. if (!rec)
  7657. return NULL;
  7658. field = btf_record_find(rec, off, fields);
  7659. if (!field)
  7660. return NULL;
  7661. return field;
  7662. }
  7663. static int check_func_arg_reg_off(struct bpf_verifier_env *env,
  7664. const struct bpf_reg_state *reg, int regno,
  7665. enum bpf_arg_type arg_type)
  7666. {
  7667. u32 type = reg->type;
  7668. /* When referenced register is passed to release function, its fixed
  7669. * offset must be 0.
  7670. *
  7671. * We will check arg_type_is_release reg has ref_obj_id when storing
  7672. * meta->release_regno.
  7673. */
  7674. if (arg_type_is_release(arg_type)) {
  7675. /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
  7676. * may not directly point to the object being released, but to
  7677. * dynptr pointing to such object, which might be at some offset
  7678. * on the stack. In that case, we simply to fallback to the
  7679. * default handling.
  7680. */
  7681. if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
  7682. return 0;
  7683. /* Doing check_ptr_off_reg check for the offset will catch this
  7684. * because fixed_off_ok is false, but checking here allows us
  7685. * to give the user a better error message.
  7686. */
  7687. if (reg->off) {
  7688. verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
  7689. regno);
  7690. return -EINVAL;
  7691. }
  7692. return __check_ptr_off_reg(env, reg, regno, false);
  7693. }
  7694. switch (type) {
  7695. /* Pointer types where both fixed and variable offset is explicitly allowed: */
  7696. case PTR_TO_STACK:
  7697. case PTR_TO_PACKET:
  7698. case PTR_TO_PACKET_META:
  7699. case PTR_TO_MAP_KEY:
  7700. case PTR_TO_MAP_VALUE:
  7701. case PTR_TO_MEM:
  7702. case PTR_TO_MEM | MEM_RDONLY:
  7703. case PTR_TO_MEM | MEM_RINGBUF:
  7704. case PTR_TO_BUF:
  7705. case PTR_TO_BUF | MEM_RDONLY:
  7706. case PTR_TO_ARENA:
  7707. case SCALAR_VALUE:
  7708. return 0;
  7709. /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
  7710. * fixed offset.
  7711. */
  7712. case PTR_TO_BTF_ID:
  7713. case PTR_TO_BTF_ID | MEM_ALLOC:
  7714. case PTR_TO_BTF_ID | PTR_TRUSTED:
  7715. case PTR_TO_BTF_ID | MEM_RCU:
  7716. case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
  7717. case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
  7718. /* When referenced PTR_TO_BTF_ID is passed to release function,
  7719. * its fixed offset must be 0. In the other cases, fixed offset
  7720. * can be non-zero. This was already checked above. So pass
  7721. * fixed_off_ok as true to allow fixed offset for all other
  7722. * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
  7723. * still need to do checks instead of returning.
  7724. */
  7725. return __check_ptr_off_reg(env, reg, regno, true);
  7726. default:
  7727. return __check_ptr_off_reg(env, reg, regno, false);
  7728. }
  7729. }
  7730. static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
  7731. const struct bpf_func_proto *fn,
  7732. struct bpf_reg_state *regs)
  7733. {
  7734. struct bpf_reg_state *state = NULL;
  7735. int i;
  7736. for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
  7737. if (arg_type_is_dynptr(fn->arg_type[i])) {
  7738. if (state) {
  7739. verbose(env, "verifier internal error: multiple dynptr args\n");
  7740. return NULL;
  7741. }
  7742. state = &regs[BPF_REG_1 + i];
  7743. }
  7744. if (!state)
  7745. verbose(env, "verifier internal error: no dynptr arg found\n");
  7746. return state;
  7747. }
  7748. static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  7749. {
  7750. struct bpf_func_state *state = func(env, reg);
  7751. int spi;
  7752. if (reg->type == CONST_PTR_TO_DYNPTR)
  7753. return reg->id;
  7754. spi = dynptr_get_spi(env, reg);
  7755. if (spi < 0)
  7756. return spi;
  7757. return state->stack[spi].spilled_ptr.id;
  7758. }
  7759. static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  7760. {
  7761. struct bpf_func_state *state = func(env, reg);
  7762. int spi;
  7763. if (reg->type == CONST_PTR_TO_DYNPTR)
  7764. return reg->ref_obj_id;
  7765. spi = dynptr_get_spi(env, reg);
  7766. if (spi < 0)
  7767. return spi;
  7768. return state->stack[spi].spilled_ptr.ref_obj_id;
  7769. }
  7770. static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
  7771. struct bpf_reg_state *reg)
  7772. {
  7773. struct bpf_func_state *state = func(env, reg);
  7774. int spi;
  7775. if (reg->type == CONST_PTR_TO_DYNPTR)
  7776. return reg->dynptr.type;
  7777. spi = __get_spi(reg->off);
  7778. if (spi < 0) {
  7779. verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
  7780. return BPF_DYNPTR_TYPE_INVALID;
  7781. }
  7782. return state->stack[spi].spilled_ptr.dynptr.type;
  7783. }
  7784. static int check_reg_const_str(struct bpf_verifier_env *env,
  7785. struct bpf_reg_state *reg, u32 regno)
  7786. {
  7787. struct bpf_map *map = reg->map_ptr;
  7788. int err;
  7789. int map_off;
  7790. u64 map_addr;
  7791. char *str_ptr;
  7792. if (reg->type != PTR_TO_MAP_VALUE)
  7793. return -EINVAL;
  7794. if (!bpf_map_is_rdonly(map)) {
  7795. verbose(env, "R%d does not point to a readonly map'\n", regno);
  7796. return -EACCES;
  7797. }
  7798. if (!tnum_is_const(reg->var_off)) {
  7799. verbose(env, "R%d is not a constant address'\n", regno);
  7800. return -EACCES;
  7801. }
  7802. if (!map->ops->map_direct_value_addr) {
  7803. verbose(env, "no direct value access support for this map type\n");
  7804. return -EACCES;
  7805. }
  7806. err = check_map_access(env, regno, reg->off,
  7807. map->value_size - reg->off, false,
  7808. ACCESS_HELPER);
  7809. if (err)
  7810. return err;
  7811. map_off = reg->off + reg->var_off.value;
  7812. err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
  7813. if (err) {
  7814. verbose(env, "direct value access on string failed\n");
  7815. return err;
  7816. }
  7817. str_ptr = (char *)(long)(map_addr);
  7818. if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
  7819. verbose(env, "string is not zero-terminated\n");
  7820. return -EINVAL;
  7821. }
  7822. return 0;
  7823. }
  7824. static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
  7825. struct bpf_call_arg_meta *meta,
  7826. const struct bpf_func_proto *fn,
  7827. int insn_idx)
  7828. {
  7829. u32 regno = BPF_REG_1 + arg;
  7830. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
  7831. enum bpf_arg_type arg_type = fn->arg_type[arg];
  7832. enum bpf_reg_type type = reg->type;
  7833. u32 *arg_btf_id = NULL;
  7834. int err = 0;
  7835. if (arg_type == ARG_DONTCARE)
  7836. return 0;
  7837. err = check_reg_arg(env, regno, SRC_OP);
  7838. if (err)
  7839. return err;
  7840. if (arg_type == ARG_ANYTHING) {
  7841. if (is_pointer_value(env, regno)) {
  7842. verbose(env, "R%d leaks addr into helper function\n",
  7843. regno);
  7844. return -EACCES;
  7845. }
  7846. return 0;
  7847. }
  7848. if (type_is_pkt_pointer(type) &&
  7849. !may_access_direct_pkt_data(env, meta, BPF_READ)) {
  7850. verbose(env, "helper access to the packet is not allowed\n");
  7851. return -EACCES;
  7852. }
  7853. if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
  7854. err = resolve_map_arg_type(env, meta, &arg_type);
  7855. if (err)
  7856. return err;
  7857. }
  7858. if (register_is_null(reg) && type_may_be_null(arg_type))
  7859. /* A NULL register has a SCALAR_VALUE type, so skip
  7860. * type checking.
  7861. */
  7862. goto skip_type_check;
  7863. /* arg_btf_id and arg_size are in a union. */
  7864. if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
  7865. base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
  7866. arg_btf_id = fn->arg_btf_id[arg];
  7867. err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
  7868. if (err)
  7869. return err;
  7870. err = check_func_arg_reg_off(env, reg, regno, arg_type);
  7871. if (err)
  7872. return err;
  7873. skip_type_check:
  7874. if (arg_type_is_release(arg_type)) {
  7875. if (arg_type_is_dynptr(arg_type)) {
  7876. struct bpf_func_state *state = func(env, reg);
  7877. int spi;
  7878. /* Only dynptr created on stack can be released, thus
  7879. * the get_spi and stack state checks for spilled_ptr
  7880. * should only be done before process_dynptr_func for
  7881. * PTR_TO_STACK.
  7882. */
  7883. if (reg->type == PTR_TO_STACK) {
  7884. spi = dynptr_get_spi(env, reg);
  7885. if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
  7886. verbose(env, "arg %d is an unacquired reference\n", regno);
  7887. return -EINVAL;
  7888. }
  7889. } else {
  7890. verbose(env, "cannot release unowned const bpf_dynptr\n");
  7891. return -EINVAL;
  7892. }
  7893. } else if (!reg->ref_obj_id && !register_is_null(reg)) {
  7894. verbose(env, "R%d must be referenced when passed to release function\n",
  7895. regno);
  7896. return -EINVAL;
  7897. }
  7898. if (meta->release_regno) {
  7899. verbose(env, "verifier internal error: more than one release argument\n");
  7900. return -EFAULT;
  7901. }
  7902. meta->release_regno = regno;
  7903. }
  7904. if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
  7905. if (meta->ref_obj_id) {
  7906. verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
  7907. regno, reg->ref_obj_id,
  7908. meta->ref_obj_id);
  7909. return -EFAULT;
  7910. }
  7911. meta->ref_obj_id = reg->ref_obj_id;
  7912. }
  7913. switch (base_type(arg_type)) {
  7914. case ARG_CONST_MAP_PTR:
  7915. /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
  7916. if (meta->map_ptr) {
  7917. /* Use map_uid (which is unique id of inner map) to reject:
  7918. * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
  7919. * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
  7920. * if (inner_map1 && inner_map2) {
  7921. * timer = bpf_map_lookup_elem(inner_map1);
  7922. * if (timer)
  7923. * // mismatch would have been allowed
  7924. * bpf_timer_init(timer, inner_map2);
  7925. * }
  7926. *
  7927. * Comparing map_ptr is enough to distinguish normal and outer maps.
  7928. */
  7929. if (meta->map_ptr != reg->map_ptr ||
  7930. meta->map_uid != reg->map_uid) {
  7931. verbose(env,
  7932. "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
  7933. meta->map_uid, reg->map_uid);
  7934. return -EINVAL;
  7935. }
  7936. }
  7937. meta->map_ptr = reg->map_ptr;
  7938. meta->map_uid = reg->map_uid;
  7939. break;
  7940. case ARG_PTR_TO_MAP_KEY:
  7941. /* bpf_map_xxx(..., map_ptr, ..., key) call:
  7942. * check that [key, key + map->key_size) are within
  7943. * stack limits and initialized
  7944. */
  7945. if (!meta->map_ptr) {
  7946. /* in function declaration map_ptr must come before
  7947. * map_key, so that it's verified and known before
  7948. * we have to check map_key here. Otherwise it means
  7949. * that kernel subsystem misconfigured verifier
  7950. */
  7951. verbose(env, "invalid map_ptr to access map->key\n");
  7952. return -EACCES;
  7953. }
  7954. err = check_helper_mem_access(env, regno, meta->map_ptr->key_size,
  7955. BPF_READ, false, NULL);
  7956. break;
  7957. case ARG_PTR_TO_MAP_VALUE:
  7958. if (type_may_be_null(arg_type) && register_is_null(reg))
  7959. return 0;
  7960. /* bpf_map_xxx(..., map_ptr, ..., value) call:
  7961. * check [value, value + map->value_size) validity
  7962. */
  7963. if (!meta->map_ptr) {
  7964. /* kernel subsystem misconfigured verifier */
  7965. verbose(env, "invalid map_ptr to access map->value\n");
  7966. return -EACCES;
  7967. }
  7968. meta->raw_mode = arg_type & MEM_UNINIT;
  7969. err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
  7970. arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
  7971. false, meta);
  7972. break;
  7973. case ARG_PTR_TO_PERCPU_BTF_ID:
  7974. if (!reg->btf_id) {
  7975. verbose(env, "Helper has invalid btf_id in R%d\n", regno);
  7976. return -EACCES;
  7977. }
  7978. meta->ret_btf = reg->btf;
  7979. meta->ret_btf_id = reg->btf_id;
  7980. break;
  7981. case ARG_PTR_TO_SPIN_LOCK:
  7982. if (in_rbtree_lock_required_cb(env)) {
  7983. verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
  7984. return -EACCES;
  7985. }
  7986. if (meta->func_id == BPF_FUNC_spin_lock) {
  7987. err = process_spin_lock(env, regno, true);
  7988. if (err)
  7989. return err;
  7990. } else if (meta->func_id == BPF_FUNC_spin_unlock) {
  7991. err = process_spin_lock(env, regno, false);
  7992. if (err)
  7993. return err;
  7994. } else {
  7995. verbose(env, "verifier internal error\n");
  7996. return -EFAULT;
  7997. }
  7998. break;
  7999. case ARG_PTR_TO_TIMER:
  8000. err = process_timer_func(env, regno, meta);
  8001. if (err)
  8002. return err;
  8003. break;
  8004. case ARG_PTR_TO_FUNC:
  8005. meta->subprogno = reg->subprogno;
  8006. break;
  8007. case ARG_PTR_TO_MEM:
  8008. /* The access to this pointer is only checked when we hit the
  8009. * next is_mem_size argument below.
  8010. */
  8011. meta->raw_mode = arg_type & MEM_UNINIT;
  8012. if (arg_type & MEM_FIXED_SIZE) {
  8013. err = check_helper_mem_access(env, regno, fn->arg_size[arg],
  8014. arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
  8015. false, meta);
  8016. if (err)
  8017. return err;
  8018. if (arg_type & MEM_ALIGNED)
  8019. err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
  8020. }
  8021. break;
  8022. case ARG_CONST_SIZE:
  8023. err = check_mem_size_reg(env, reg, regno,
  8024. fn->arg_type[arg - 1] & MEM_WRITE ?
  8025. BPF_WRITE : BPF_READ,
  8026. false, meta);
  8027. break;
  8028. case ARG_CONST_SIZE_OR_ZERO:
  8029. err = check_mem_size_reg(env, reg, regno,
  8030. fn->arg_type[arg - 1] & MEM_WRITE ?
  8031. BPF_WRITE : BPF_READ,
  8032. true, meta);
  8033. break;
  8034. case ARG_PTR_TO_DYNPTR:
  8035. err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
  8036. if (err)
  8037. return err;
  8038. break;
  8039. case ARG_CONST_ALLOC_SIZE_OR_ZERO:
  8040. if (!tnum_is_const(reg->var_off)) {
  8041. verbose(env, "R%d is not a known constant'\n",
  8042. regno);
  8043. return -EACCES;
  8044. }
  8045. meta->mem_size = reg->var_off.value;
  8046. err = mark_chain_precision(env, regno);
  8047. if (err)
  8048. return err;
  8049. break;
  8050. case ARG_PTR_TO_CONST_STR:
  8051. {
  8052. err = check_reg_const_str(env, reg, regno);
  8053. if (err)
  8054. return err;
  8055. break;
  8056. }
  8057. case ARG_KPTR_XCHG_DEST:
  8058. err = process_kptr_func(env, regno, meta);
  8059. if (err)
  8060. return err;
  8061. break;
  8062. }
  8063. return err;
  8064. }
  8065. static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
  8066. {
  8067. enum bpf_attach_type eatype = env->prog->expected_attach_type;
  8068. enum bpf_prog_type type = resolve_prog_type(env->prog);
  8069. if (func_id != BPF_FUNC_map_update_elem &&
  8070. func_id != BPF_FUNC_map_delete_elem)
  8071. return false;
  8072. /* It's not possible to get access to a locked struct sock in these
  8073. * contexts, so updating is safe.
  8074. */
  8075. switch (type) {
  8076. case BPF_PROG_TYPE_TRACING:
  8077. if (eatype == BPF_TRACE_ITER)
  8078. return true;
  8079. break;
  8080. case BPF_PROG_TYPE_SOCK_OPS:
  8081. /* map_update allowed only via dedicated helpers with event type checks */
  8082. if (func_id == BPF_FUNC_map_delete_elem)
  8083. return true;
  8084. break;
  8085. case BPF_PROG_TYPE_SOCKET_FILTER:
  8086. case BPF_PROG_TYPE_SCHED_CLS:
  8087. case BPF_PROG_TYPE_SCHED_ACT:
  8088. case BPF_PROG_TYPE_XDP:
  8089. case BPF_PROG_TYPE_SK_REUSEPORT:
  8090. case BPF_PROG_TYPE_FLOW_DISSECTOR:
  8091. case BPF_PROG_TYPE_SK_LOOKUP:
  8092. return true;
  8093. default:
  8094. break;
  8095. }
  8096. verbose(env, "cannot update sockmap in this context\n");
  8097. return false;
  8098. }
  8099. static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
  8100. {
  8101. return env->prog->jit_requested &&
  8102. bpf_jit_supports_subprog_tailcalls();
  8103. }
  8104. static int check_map_func_compatibility(struct bpf_verifier_env *env,
  8105. struct bpf_map *map, int func_id)
  8106. {
  8107. if (!map)
  8108. return 0;
  8109. /* We need a two way check, first is from map perspective ... */
  8110. switch (map->map_type) {
  8111. case BPF_MAP_TYPE_PROG_ARRAY:
  8112. if (func_id != BPF_FUNC_tail_call)
  8113. goto error;
  8114. break;
  8115. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  8116. if (func_id != BPF_FUNC_perf_event_read &&
  8117. func_id != BPF_FUNC_perf_event_output &&
  8118. func_id != BPF_FUNC_skb_output &&
  8119. func_id != BPF_FUNC_perf_event_read_value &&
  8120. func_id != BPF_FUNC_xdp_output)
  8121. goto error;
  8122. break;
  8123. case BPF_MAP_TYPE_RINGBUF:
  8124. if (func_id != BPF_FUNC_ringbuf_output &&
  8125. func_id != BPF_FUNC_ringbuf_reserve &&
  8126. func_id != BPF_FUNC_ringbuf_query &&
  8127. func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
  8128. func_id != BPF_FUNC_ringbuf_submit_dynptr &&
  8129. func_id != BPF_FUNC_ringbuf_discard_dynptr)
  8130. goto error;
  8131. break;
  8132. case BPF_MAP_TYPE_USER_RINGBUF:
  8133. if (func_id != BPF_FUNC_user_ringbuf_drain)
  8134. goto error;
  8135. break;
  8136. case BPF_MAP_TYPE_STACK_TRACE:
  8137. if (func_id != BPF_FUNC_get_stackid)
  8138. goto error;
  8139. break;
  8140. case BPF_MAP_TYPE_CGROUP_ARRAY:
  8141. if (func_id != BPF_FUNC_skb_under_cgroup &&
  8142. func_id != BPF_FUNC_current_task_under_cgroup)
  8143. goto error;
  8144. break;
  8145. case BPF_MAP_TYPE_CGROUP_STORAGE:
  8146. case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
  8147. if (func_id != BPF_FUNC_get_local_storage)
  8148. goto error;
  8149. break;
  8150. case BPF_MAP_TYPE_DEVMAP:
  8151. case BPF_MAP_TYPE_DEVMAP_HASH:
  8152. if (func_id != BPF_FUNC_redirect_map &&
  8153. func_id != BPF_FUNC_map_lookup_elem)
  8154. goto error;
  8155. break;
  8156. /* Restrict bpf side of cpumap and xskmap, open when use-cases
  8157. * appear.
  8158. */
  8159. case BPF_MAP_TYPE_CPUMAP:
  8160. if (func_id != BPF_FUNC_redirect_map)
  8161. goto error;
  8162. break;
  8163. case BPF_MAP_TYPE_XSKMAP:
  8164. if (func_id != BPF_FUNC_redirect_map &&
  8165. func_id != BPF_FUNC_map_lookup_elem)
  8166. goto error;
  8167. break;
  8168. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  8169. case BPF_MAP_TYPE_HASH_OF_MAPS:
  8170. if (func_id != BPF_FUNC_map_lookup_elem)
  8171. goto error;
  8172. break;
  8173. case BPF_MAP_TYPE_SOCKMAP:
  8174. if (func_id != BPF_FUNC_sk_redirect_map &&
  8175. func_id != BPF_FUNC_sock_map_update &&
  8176. func_id != BPF_FUNC_msg_redirect_map &&
  8177. func_id != BPF_FUNC_sk_select_reuseport &&
  8178. func_id != BPF_FUNC_map_lookup_elem &&
  8179. !may_update_sockmap(env, func_id))
  8180. goto error;
  8181. break;
  8182. case BPF_MAP_TYPE_SOCKHASH:
  8183. if (func_id != BPF_FUNC_sk_redirect_hash &&
  8184. func_id != BPF_FUNC_sock_hash_update &&
  8185. func_id != BPF_FUNC_msg_redirect_hash &&
  8186. func_id != BPF_FUNC_sk_select_reuseport &&
  8187. func_id != BPF_FUNC_map_lookup_elem &&
  8188. !may_update_sockmap(env, func_id))
  8189. goto error;
  8190. break;
  8191. case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
  8192. if (func_id != BPF_FUNC_sk_select_reuseport)
  8193. goto error;
  8194. break;
  8195. case BPF_MAP_TYPE_QUEUE:
  8196. case BPF_MAP_TYPE_STACK:
  8197. if (func_id != BPF_FUNC_map_peek_elem &&
  8198. func_id != BPF_FUNC_map_pop_elem &&
  8199. func_id != BPF_FUNC_map_push_elem)
  8200. goto error;
  8201. break;
  8202. case BPF_MAP_TYPE_SK_STORAGE:
  8203. if (func_id != BPF_FUNC_sk_storage_get &&
  8204. func_id != BPF_FUNC_sk_storage_delete &&
  8205. func_id != BPF_FUNC_kptr_xchg)
  8206. goto error;
  8207. break;
  8208. case BPF_MAP_TYPE_INODE_STORAGE:
  8209. if (func_id != BPF_FUNC_inode_storage_get &&
  8210. func_id != BPF_FUNC_inode_storage_delete &&
  8211. func_id != BPF_FUNC_kptr_xchg)
  8212. goto error;
  8213. break;
  8214. case BPF_MAP_TYPE_TASK_STORAGE:
  8215. if (func_id != BPF_FUNC_task_storage_get &&
  8216. func_id != BPF_FUNC_task_storage_delete &&
  8217. func_id != BPF_FUNC_kptr_xchg)
  8218. goto error;
  8219. break;
  8220. case BPF_MAP_TYPE_CGRP_STORAGE:
  8221. if (func_id != BPF_FUNC_cgrp_storage_get &&
  8222. func_id != BPF_FUNC_cgrp_storage_delete &&
  8223. func_id != BPF_FUNC_kptr_xchg)
  8224. goto error;
  8225. break;
  8226. case BPF_MAP_TYPE_BLOOM_FILTER:
  8227. if (func_id != BPF_FUNC_map_peek_elem &&
  8228. func_id != BPF_FUNC_map_push_elem)
  8229. goto error;
  8230. break;
  8231. default:
  8232. break;
  8233. }
  8234. /* ... and second from the function itself. */
  8235. switch (func_id) {
  8236. case BPF_FUNC_tail_call:
  8237. if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
  8238. goto error;
  8239. if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
  8240. verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
  8241. return -EINVAL;
  8242. }
  8243. break;
  8244. case BPF_FUNC_perf_event_read:
  8245. case BPF_FUNC_perf_event_output:
  8246. case BPF_FUNC_perf_event_read_value:
  8247. case BPF_FUNC_skb_output:
  8248. case BPF_FUNC_xdp_output:
  8249. if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
  8250. goto error;
  8251. break;
  8252. case BPF_FUNC_ringbuf_output:
  8253. case BPF_FUNC_ringbuf_reserve:
  8254. case BPF_FUNC_ringbuf_query:
  8255. case BPF_FUNC_ringbuf_reserve_dynptr:
  8256. case BPF_FUNC_ringbuf_submit_dynptr:
  8257. case BPF_FUNC_ringbuf_discard_dynptr:
  8258. if (map->map_type != BPF_MAP_TYPE_RINGBUF)
  8259. goto error;
  8260. break;
  8261. case BPF_FUNC_user_ringbuf_drain:
  8262. if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
  8263. goto error;
  8264. break;
  8265. case BPF_FUNC_get_stackid:
  8266. if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
  8267. goto error;
  8268. break;
  8269. case BPF_FUNC_current_task_under_cgroup:
  8270. case BPF_FUNC_skb_under_cgroup:
  8271. if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
  8272. goto error;
  8273. break;
  8274. case BPF_FUNC_redirect_map:
  8275. if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
  8276. map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
  8277. map->map_type != BPF_MAP_TYPE_CPUMAP &&
  8278. map->map_type != BPF_MAP_TYPE_XSKMAP)
  8279. goto error;
  8280. break;
  8281. case BPF_FUNC_sk_redirect_map:
  8282. case BPF_FUNC_msg_redirect_map:
  8283. case BPF_FUNC_sock_map_update:
  8284. if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
  8285. goto error;
  8286. break;
  8287. case BPF_FUNC_sk_redirect_hash:
  8288. case BPF_FUNC_msg_redirect_hash:
  8289. case BPF_FUNC_sock_hash_update:
  8290. if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
  8291. goto error;
  8292. break;
  8293. case BPF_FUNC_get_local_storage:
  8294. if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
  8295. map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
  8296. goto error;
  8297. break;
  8298. case BPF_FUNC_sk_select_reuseport:
  8299. if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
  8300. map->map_type != BPF_MAP_TYPE_SOCKMAP &&
  8301. map->map_type != BPF_MAP_TYPE_SOCKHASH)
  8302. goto error;
  8303. break;
  8304. case BPF_FUNC_map_pop_elem:
  8305. if (map->map_type != BPF_MAP_TYPE_QUEUE &&
  8306. map->map_type != BPF_MAP_TYPE_STACK)
  8307. goto error;
  8308. break;
  8309. case BPF_FUNC_map_peek_elem:
  8310. case BPF_FUNC_map_push_elem:
  8311. if (map->map_type != BPF_MAP_TYPE_QUEUE &&
  8312. map->map_type != BPF_MAP_TYPE_STACK &&
  8313. map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
  8314. goto error;
  8315. break;
  8316. case BPF_FUNC_map_lookup_percpu_elem:
  8317. if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
  8318. map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
  8319. map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
  8320. goto error;
  8321. break;
  8322. case BPF_FUNC_sk_storage_get:
  8323. case BPF_FUNC_sk_storage_delete:
  8324. if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
  8325. goto error;
  8326. break;
  8327. case BPF_FUNC_inode_storage_get:
  8328. case BPF_FUNC_inode_storage_delete:
  8329. if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
  8330. goto error;
  8331. break;
  8332. case BPF_FUNC_task_storage_get:
  8333. case BPF_FUNC_task_storage_delete:
  8334. if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
  8335. goto error;
  8336. break;
  8337. case BPF_FUNC_cgrp_storage_get:
  8338. case BPF_FUNC_cgrp_storage_delete:
  8339. if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
  8340. goto error;
  8341. break;
  8342. default:
  8343. break;
  8344. }
  8345. return 0;
  8346. error:
  8347. verbose(env, "cannot pass map_type %d into func %s#%d\n",
  8348. map->map_type, func_id_name(func_id), func_id);
  8349. return -EINVAL;
  8350. }
  8351. static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
  8352. {
  8353. int count = 0;
  8354. if (arg_type_is_raw_mem(fn->arg1_type))
  8355. count++;
  8356. if (arg_type_is_raw_mem(fn->arg2_type))
  8357. count++;
  8358. if (arg_type_is_raw_mem(fn->arg3_type))
  8359. count++;
  8360. if (arg_type_is_raw_mem(fn->arg4_type))
  8361. count++;
  8362. if (arg_type_is_raw_mem(fn->arg5_type))
  8363. count++;
  8364. /* We only support one arg being in raw mode at the moment,
  8365. * which is sufficient for the helper functions we have
  8366. * right now.
  8367. */
  8368. return count <= 1;
  8369. }
  8370. static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
  8371. {
  8372. bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
  8373. bool has_size = fn->arg_size[arg] != 0;
  8374. bool is_next_size = false;
  8375. if (arg + 1 < ARRAY_SIZE(fn->arg_type))
  8376. is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
  8377. if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
  8378. return is_next_size;
  8379. return has_size == is_next_size || is_next_size == is_fixed;
  8380. }
  8381. static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
  8382. {
  8383. /* bpf_xxx(..., buf, len) call will access 'len'
  8384. * bytes from memory 'buf'. Both arg types need
  8385. * to be paired, so make sure there's no buggy
  8386. * helper function specification.
  8387. */
  8388. if (arg_type_is_mem_size(fn->arg1_type) ||
  8389. check_args_pair_invalid(fn, 0) ||
  8390. check_args_pair_invalid(fn, 1) ||
  8391. check_args_pair_invalid(fn, 2) ||
  8392. check_args_pair_invalid(fn, 3) ||
  8393. check_args_pair_invalid(fn, 4))
  8394. return false;
  8395. return true;
  8396. }
  8397. static bool check_btf_id_ok(const struct bpf_func_proto *fn)
  8398. {
  8399. int i;
  8400. for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
  8401. if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
  8402. return !!fn->arg_btf_id[i];
  8403. if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
  8404. return fn->arg_btf_id[i] == BPF_PTR_POISON;
  8405. if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
  8406. /* arg_btf_id and arg_size are in a union. */
  8407. (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
  8408. !(fn->arg_type[i] & MEM_FIXED_SIZE)))
  8409. return false;
  8410. }
  8411. return true;
  8412. }
  8413. static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
  8414. {
  8415. return check_raw_mode_ok(fn) &&
  8416. check_arg_pair_ok(fn) &&
  8417. check_btf_id_ok(fn) ? 0 : -EINVAL;
  8418. }
  8419. /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
  8420. * are now invalid, so turn them into unknown SCALAR_VALUE.
  8421. *
  8422. * This also applies to dynptr slices belonging to skb and xdp dynptrs,
  8423. * since these slices point to packet data.
  8424. */
  8425. static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
  8426. {
  8427. struct bpf_func_state *state;
  8428. struct bpf_reg_state *reg;
  8429. bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
  8430. if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
  8431. mark_reg_invalid(env, reg);
  8432. }));
  8433. }
  8434. enum {
  8435. AT_PKT_END = -1,
  8436. BEYOND_PKT_END = -2,
  8437. };
  8438. static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
  8439. {
  8440. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  8441. struct bpf_reg_state *reg = &state->regs[regn];
  8442. if (reg->type != PTR_TO_PACKET)
  8443. /* PTR_TO_PACKET_META is not supported yet */
  8444. return;
  8445. /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
  8446. * How far beyond pkt_end it goes is unknown.
  8447. * if (!range_open) it's the case of pkt >= pkt_end
  8448. * if (range_open) it's the case of pkt > pkt_end
  8449. * hence this pointer is at least 1 byte bigger than pkt_end
  8450. */
  8451. if (range_open)
  8452. reg->range = BEYOND_PKT_END;
  8453. else
  8454. reg->range = AT_PKT_END;
  8455. }
  8456. /* The pointer with the specified id has released its reference to kernel
  8457. * resources. Identify all copies of the same pointer and clear the reference.
  8458. */
  8459. static int release_reference(struct bpf_verifier_env *env,
  8460. int ref_obj_id)
  8461. {
  8462. struct bpf_func_state *state;
  8463. struct bpf_reg_state *reg;
  8464. int err;
  8465. err = release_reference_state(cur_func(env), ref_obj_id);
  8466. if (err)
  8467. return err;
  8468. bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
  8469. if (reg->ref_obj_id == ref_obj_id)
  8470. mark_reg_invalid(env, reg);
  8471. }));
  8472. return 0;
  8473. }
  8474. static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
  8475. {
  8476. struct bpf_func_state *unused;
  8477. struct bpf_reg_state *reg;
  8478. bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
  8479. if (type_is_non_owning_ref(reg->type))
  8480. mark_reg_invalid(env, reg);
  8481. }));
  8482. }
  8483. static void clear_caller_saved_regs(struct bpf_verifier_env *env,
  8484. struct bpf_reg_state *regs)
  8485. {
  8486. int i;
  8487. /* after the call registers r0 - r5 were scratched */
  8488. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  8489. mark_reg_not_init(env, regs, caller_saved[i]);
  8490. __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
  8491. }
  8492. }
  8493. typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
  8494. struct bpf_func_state *caller,
  8495. struct bpf_func_state *callee,
  8496. int insn_idx);
  8497. static int set_callee_state(struct bpf_verifier_env *env,
  8498. struct bpf_func_state *caller,
  8499. struct bpf_func_state *callee, int insn_idx);
  8500. static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
  8501. set_callee_state_fn set_callee_state_cb,
  8502. struct bpf_verifier_state *state)
  8503. {
  8504. struct bpf_func_state *caller, *callee;
  8505. int err;
  8506. if (state->curframe + 1 >= MAX_CALL_FRAMES) {
  8507. verbose(env, "the call stack of %d frames is too deep\n",
  8508. state->curframe + 2);
  8509. return -E2BIG;
  8510. }
  8511. if (state->frame[state->curframe + 1]) {
  8512. verbose(env, "verifier bug. Frame %d already allocated\n",
  8513. state->curframe + 1);
  8514. return -EFAULT;
  8515. }
  8516. caller = state->frame[state->curframe];
  8517. callee = kzalloc(sizeof(*callee), GFP_KERNEL);
  8518. if (!callee)
  8519. return -ENOMEM;
  8520. state->frame[state->curframe + 1] = callee;
  8521. /* callee cannot access r0, r6 - r9 for reading and has to write
  8522. * into its own stack before reading from it.
  8523. * callee can read/write into caller's stack
  8524. */
  8525. init_func_state(env, callee,
  8526. /* remember the callsite, it will be used by bpf_exit */
  8527. callsite,
  8528. state->curframe + 1 /* frameno within this callchain */,
  8529. subprog /* subprog number within this prog */);
  8530. /* Transfer references to the callee */
  8531. err = copy_reference_state(callee, caller);
  8532. err = err ?: set_callee_state_cb(env, caller, callee, callsite);
  8533. if (err)
  8534. goto err_out;
  8535. /* only increment it after check_reg_arg() finished */
  8536. state->curframe++;
  8537. return 0;
  8538. err_out:
  8539. free_func_state(callee);
  8540. state->frame[state->curframe + 1] = NULL;
  8541. return err;
  8542. }
  8543. static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
  8544. const struct btf *btf,
  8545. struct bpf_reg_state *regs)
  8546. {
  8547. struct bpf_subprog_info *sub = subprog_info(env, subprog);
  8548. struct bpf_verifier_log *log = &env->log;
  8549. u32 i;
  8550. int ret;
  8551. ret = btf_prepare_func_args(env, subprog);
  8552. if (ret)
  8553. return ret;
  8554. /* check that BTF function arguments match actual types that the
  8555. * verifier sees.
  8556. */
  8557. for (i = 0; i < sub->arg_cnt; i++) {
  8558. u32 regno = i + 1;
  8559. struct bpf_reg_state *reg = &regs[regno];
  8560. struct bpf_subprog_arg_info *arg = &sub->args[i];
  8561. if (arg->arg_type == ARG_ANYTHING) {
  8562. if (reg->type != SCALAR_VALUE) {
  8563. bpf_log(log, "R%d is not a scalar\n", regno);
  8564. return -EINVAL;
  8565. }
  8566. } else if (arg->arg_type == ARG_PTR_TO_CTX) {
  8567. ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
  8568. if (ret < 0)
  8569. return ret;
  8570. /* If function expects ctx type in BTF check that caller
  8571. * is passing PTR_TO_CTX.
  8572. */
  8573. if (reg->type != PTR_TO_CTX) {
  8574. bpf_log(log, "arg#%d expects pointer to ctx\n", i);
  8575. return -EINVAL;
  8576. }
  8577. } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
  8578. ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
  8579. if (ret < 0)
  8580. return ret;
  8581. if (check_mem_reg(env, reg, regno, arg->mem_size))
  8582. return -EINVAL;
  8583. if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
  8584. bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
  8585. return -EINVAL;
  8586. }
  8587. } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
  8588. /*
  8589. * Can pass any value and the kernel won't crash, but
  8590. * only PTR_TO_ARENA or SCALAR make sense. Everything
  8591. * else is a bug in the bpf program. Point it out to
  8592. * the user at the verification time instead of
  8593. * run-time debug nightmare.
  8594. */
  8595. if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
  8596. bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
  8597. return -EINVAL;
  8598. }
  8599. } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
  8600. ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
  8601. if (ret)
  8602. return ret;
  8603. ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
  8604. if (ret)
  8605. return ret;
  8606. } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
  8607. struct bpf_call_arg_meta meta;
  8608. int err;
  8609. if (register_is_null(reg) && type_may_be_null(arg->arg_type))
  8610. continue;
  8611. memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
  8612. err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
  8613. err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
  8614. if (err)
  8615. return err;
  8616. } else {
  8617. bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
  8618. i, arg->arg_type);
  8619. return -EFAULT;
  8620. }
  8621. }
  8622. return 0;
  8623. }
  8624. /* Compare BTF of a function call with given bpf_reg_state.
  8625. * Returns:
  8626. * EFAULT - there is a verifier bug. Abort verification.
  8627. * EINVAL - there is a type mismatch or BTF is not available.
  8628. * 0 - BTF matches with what bpf_reg_state expects.
  8629. * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
  8630. */
  8631. static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
  8632. struct bpf_reg_state *regs)
  8633. {
  8634. struct bpf_prog *prog = env->prog;
  8635. struct btf *btf = prog->aux->btf;
  8636. u32 btf_id;
  8637. int err;
  8638. if (!prog->aux->func_info)
  8639. return -EINVAL;
  8640. btf_id = prog->aux->func_info[subprog].type_id;
  8641. if (!btf_id)
  8642. return -EFAULT;
  8643. if (prog->aux->func_info_aux[subprog].unreliable)
  8644. return -EINVAL;
  8645. err = btf_check_func_arg_match(env, subprog, btf, regs);
  8646. /* Compiler optimizations can remove arguments from static functions
  8647. * or mismatched type can be passed into a global function.
  8648. * In such cases mark the function as unreliable from BTF point of view.
  8649. */
  8650. if (err)
  8651. prog->aux->func_info_aux[subprog].unreliable = true;
  8652. return err;
  8653. }
  8654. static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  8655. int insn_idx, int subprog,
  8656. set_callee_state_fn set_callee_state_cb)
  8657. {
  8658. struct bpf_verifier_state *state = env->cur_state, *callback_state;
  8659. struct bpf_func_state *caller, *callee;
  8660. int err;
  8661. caller = state->frame[state->curframe];
  8662. err = btf_check_subprog_call(env, subprog, caller->regs);
  8663. if (err == -EFAULT)
  8664. return err;
  8665. /* set_callee_state is used for direct subprog calls, but we are
  8666. * interested in validating only BPF helpers that can call subprogs as
  8667. * callbacks
  8668. */
  8669. env->subprog_info[subprog].is_cb = true;
  8670. if (bpf_pseudo_kfunc_call(insn) &&
  8671. !is_callback_calling_kfunc(insn->imm)) {
  8672. verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
  8673. func_id_name(insn->imm), insn->imm);
  8674. return -EFAULT;
  8675. } else if (!bpf_pseudo_kfunc_call(insn) &&
  8676. !is_callback_calling_function(insn->imm)) { /* helper */
  8677. verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
  8678. func_id_name(insn->imm), insn->imm);
  8679. return -EFAULT;
  8680. }
  8681. if (is_async_callback_calling_insn(insn)) {
  8682. struct bpf_verifier_state *async_cb;
  8683. /* there is no real recursion here. timer and workqueue callbacks are async */
  8684. env->subprog_info[subprog].is_async_cb = true;
  8685. async_cb = push_async_cb(env, env->subprog_info[subprog].start,
  8686. insn_idx, subprog,
  8687. is_bpf_wq_set_callback_impl_kfunc(insn->imm));
  8688. if (!async_cb)
  8689. return -EFAULT;
  8690. callee = async_cb->frame[0];
  8691. callee->async_entry_cnt = caller->async_entry_cnt + 1;
  8692. /* Convert bpf_timer_set_callback() args into timer callback args */
  8693. err = set_callee_state_cb(env, caller, callee, insn_idx);
  8694. if (err)
  8695. return err;
  8696. return 0;
  8697. }
  8698. /* for callback functions enqueue entry to callback and
  8699. * proceed with next instruction within current frame.
  8700. */
  8701. callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
  8702. if (!callback_state)
  8703. return -ENOMEM;
  8704. err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
  8705. callback_state);
  8706. if (err)
  8707. return err;
  8708. callback_state->callback_unroll_depth++;
  8709. callback_state->frame[callback_state->curframe - 1]->callback_depth++;
  8710. caller->callback_depth = 0;
  8711. return 0;
  8712. }
  8713. static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  8714. int *insn_idx)
  8715. {
  8716. struct bpf_verifier_state *state = env->cur_state;
  8717. struct bpf_func_state *caller;
  8718. int err, subprog, target_insn;
  8719. target_insn = *insn_idx + insn->imm + 1;
  8720. subprog = find_subprog(env, target_insn);
  8721. if (subprog < 0) {
  8722. verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
  8723. return -EFAULT;
  8724. }
  8725. caller = state->frame[state->curframe];
  8726. err = btf_check_subprog_call(env, subprog, caller->regs);
  8727. if (err == -EFAULT)
  8728. return err;
  8729. if (subprog_is_global(env, subprog)) {
  8730. const char *sub_name = subprog_name(env, subprog);
  8731. /* Only global subprogs cannot be called with a lock held. */
  8732. if (env->cur_state->active_lock.ptr) {
  8733. verbose(env, "global function calls are not allowed while holding a lock,\n"
  8734. "use static function instead\n");
  8735. return -EINVAL;
  8736. }
  8737. /* Only global subprogs cannot be called with preemption disabled. */
  8738. if (env->cur_state->active_preempt_lock) {
  8739. verbose(env, "global function calls are not allowed with preemption disabled,\n"
  8740. "use static function instead\n");
  8741. return -EINVAL;
  8742. }
  8743. if (err) {
  8744. verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
  8745. subprog, sub_name);
  8746. return err;
  8747. }
  8748. verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
  8749. subprog, sub_name);
  8750. if (env->subprog_info[subprog].changes_pkt_data)
  8751. clear_all_pkt_pointers(env);
  8752. /* mark global subprog for verifying after main prog */
  8753. subprog_aux(env, subprog)->called = true;
  8754. clear_caller_saved_regs(env, caller->regs);
  8755. /* All global functions return a 64-bit SCALAR_VALUE */
  8756. mark_reg_unknown(env, caller->regs, BPF_REG_0);
  8757. caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
  8758. /* continue with next insn after call */
  8759. return 0;
  8760. }
  8761. /* for regular function entry setup new frame and continue
  8762. * from that frame.
  8763. */
  8764. err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
  8765. if (err)
  8766. return err;
  8767. clear_caller_saved_regs(env, caller->regs);
  8768. /* and go analyze first insn of the callee */
  8769. *insn_idx = env->subprog_info[subprog].start - 1;
  8770. if (env->log.level & BPF_LOG_LEVEL) {
  8771. verbose(env, "caller:\n");
  8772. print_verifier_state(env, caller, true);
  8773. verbose(env, "callee:\n");
  8774. print_verifier_state(env, state->frame[state->curframe], true);
  8775. }
  8776. return 0;
  8777. }
  8778. int map_set_for_each_callback_args(struct bpf_verifier_env *env,
  8779. struct bpf_func_state *caller,
  8780. struct bpf_func_state *callee)
  8781. {
  8782. /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
  8783. * void *callback_ctx, u64 flags);
  8784. * callback_fn(struct bpf_map *map, void *key, void *value,
  8785. * void *callback_ctx);
  8786. */
  8787. callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
  8788. callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
  8789. __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
  8790. callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
  8791. callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
  8792. __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
  8793. callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
  8794. /* pointer to stack or null */
  8795. callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
  8796. /* unused */
  8797. __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  8798. return 0;
  8799. }
  8800. static int set_callee_state(struct bpf_verifier_env *env,
  8801. struct bpf_func_state *caller,
  8802. struct bpf_func_state *callee, int insn_idx)
  8803. {
  8804. int i;
  8805. /* copy r1 - r5 args that callee can access. The copy includes parent
  8806. * pointers, which connects us up to the liveness chain
  8807. */
  8808. for (i = BPF_REG_1; i <= BPF_REG_5; i++)
  8809. callee->regs[i] = caller->regs[i];
  8810. return 0;
  8811. }
  8812. static int set_map_elem_callback_state(struct bpf_verifier_env *env,
  8813. struct bpf_func_state *caller,
  8814. struct bpf_func_state *callee,
  8815. int insn_idx)
  8816. {
  8817. struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
  8818. struct bpf_map *map;
  8819. int err;
  8820. /* valid map_ptr and poison value does not matter */
  8821. map = insn_aux->map_ptr_state.map_ptr;
  8822. if (!map->ops->map_set_for_each_callback_args ||
  8823. !map->ops->map_for_each_callback) {
  8824. verbose(env, "callback function not allowed for map\n");
  8825. return -ENOTSUPP;
  8826. }
  8827. err = map->ops->map_set_for_each_callback_args(env, caller, callee);
  8828. if (err)
  8829. return err;
  8830. callee->in_callback_fn = true;
  8831. callee->callback_ret_range = retval_range(0, 1);
  8832. return 0;
  8833. }
  8834. static int set_loop_callback_state(struct bpf_verifier_env *env,
  8835. struct bpf_func_state *caller,
  8836. struct bpf_func_state *callee,
  8837. int insn_idx)
  8838. {
  8839. /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
  8840. * u64 flags);
  8841. * callback_fn(u32 index, void *callback_ctx);
  8842. */
  8843. callee->regs[BPF_REG_1].type = SCALAR_VALUE;
  8844. callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
  8845. /* unused */
  8846. __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
  8847. __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
  8848. __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  8849. callee->in_callback_fn = true;
  8850. callee->callback_ret_range = retval_range(0, 1);
  8851. return 0;
  8852. }
  8853. static int set_timer_callback_state(struct bpf_verifier_env *env,
  8854. struct bpf_func_state *caller,
  8855. struct bpf_func_state *callee,
  8856. int insn_idx)
  8857. {
  8858. struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
  8859. /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
  8860. * callback_fn(struct bpf_map *map, void *key, void *value);
  8861. */
  8862. callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
  8863. __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
  8864. callee->regs[BPF_REG_1].map_ptr = map_ptr;
  8865. callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
  8866. __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
  8867. callee->regs[BPF_REG_2].map_ptr = map_ptr;
  8868. callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
  8869. __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
  8870. callee->regs[BPF_REG_3].map_ptr = map_ptr;
  8871. /* unused */
  8872. __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
  8873. __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  8874. callee->in_async_callback_fn = true;
  8875. callee->callback_ret_range = retval_range(0, 1);
  8876. return 0;
  8877. }
  8878. static int set_find_vma_callback_state(struct bpf_verifier_env *env,
  8879. struct bpf_func_state *caller,
  8880. struct bpf_func_state *callee,
  8881. int insn_idx)
  8882. {
  8883. /* bpf_find_vma(struct task_struct *task, u64 addr,
  8884. * void *callback_fn, void *callback_ctx, u64 flags)
  8885. * (callback_fn)(struct task_struct *task,
  8886. * struct vm_area_struct *vma, void *callback_ctx);
  8887. */
  8888. callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
  8889. callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
  8890. __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
  8891. callee->regs[BPF_REG_2].btf = btf_vmlinux;
  8892. callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
  8893. /* pointer to stack or null */
  8894. callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
  8895. /* unused */
  8896. __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
  8897. __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  8898. callee->in_callback_fn = true;
  8899. callee->callback_ret_range = retval_range(0, 1);
  8900. return 0;
  8901. }
  8902. static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
  8903. struct bpf_func_state *caller,
  8904. struct bpf_func_state *callee,
  8905. int insn_idx)
  8906. {
  8907. /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
  8908. * callback_ctx, u64 flags);
  8909. * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
  8910. */
  8911. __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
  8912. mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
  8913. callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
  8914. /* unused */
  8915. __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
  8916. __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
  8917. __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  8918. callee->in_callback_fn = true;
  8919. callee->callback_ret_range = retval_range(0, 1);
  8920. return 0;
  8921. }
  8922. static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
  8923. struct bpf_func_state *caller,
  8924. struct bpf_func_state *callee,
  8925. int insn_idx)
  8926. {
  8927. /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
  8928. * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
  8929. *
  8930. * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
  8931. * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
  8932. * by this point, so look at 'root'
  8933. */
  8934. struct btf_field *field;
  8935. field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
  8936. BPF_RB_ROOT);
  8937. if (!field || !field->graph_root.value_btf_id)
  8938. return -EFAULT;
  8939. mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
  8940. ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
  8941. mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
  8942. ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
  8943. __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
  8944. __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
  8945. __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
  8946. callee->in_callback_fn = true;
  8947. callee->callback_ret_range = retval_range(0, 1);
  8948. return 0;
  8949. }
  8950. static bool is_rbtree_lock_required_kfunc(u32 btf_id);
  8951. /* Are we currently verifying the callback for a rbtree helper that must
  8952. * be called with lock held? If so, no need to complain about unreleased
  8953. * lock
  8954. */
  8955. static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
  8956. {
  8957. struct bpf_verifier_state *state = env->cur_state;
  8958. struct bpf_insn *insn = env->prog->insnsi;
  8959. struct bpf_func_state *callee;
  8960. int kfunc_btf_id;
  8961. if (!state->curframe)
  8962. return false;
  8963. callee = state->frame[state->curframe];
  8964. if (!callee->in_callback_fn)
  8965. return false;
  8966. kfunc_btf_id = insn[callee->callsite].imm;
  8967. return is_rbtree_lock_required_kfunc(kfunc_btf_id);
  8968. }
  8969. static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
  8970. bool return_32bit)
  8971. {
  8972. if (return_32bit)
  8973. return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
  8974. else
  8975. return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
  8976. }
  8977. static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
  8978. {
  8979. struct bpf_verifier_state *state = env->cur_state, *prev_st;
  8980. struct bpf_func_state *caller, *callee;
  8981. struct bpf_reg_state *r0;
  8982. bool in_callback_fn;
  8983. int err;
  8984. callee = state->frame[state->curframe];
  8985. r0 = &callee->regs[BPF_REG_0];
  8986. if (r0->type == PTR_TO_STACK) {
  8987. /* technically it's ok to return caller's stack pointer
  8988. * (or caller's caller's pointer) back to the caller,
  8989. * since these pointers are valid. Only current stack
  8990. * pointer will be invalid as soon as function exits,
  8991. * but let's be conservative
  8992. */
  8993. verbose(env, "cannot return stack pointer to the caller\n");
  8994. return -EINVAL;
  8995. }
  8996. caller = state->frame[state->curframe - 1];
  8997. if (callee->in_callback_fn) {
  8998. if (r0->type != SCALAR_VALUE) {
  8999. verbose(env, "R0 not a scalar value\n");
  9000. return -EACCES;
  9001. }
  9002. /* we are going to rely on register's precise value */
  9003. err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
  9004. err = err ?: mark_chain_precision(env, BPF_REG_0);
  9005. if (err)
  9006. return err;
  9007. /* enforce R0 return value range, and bpf_callback_t returns 64bit */
  9008. if (!retval_range_within(callee->callback_ret_range, r0, false)) {
  9009. verbose_invalid_scalar(env, r0, callee->callback_ret_range,
  9010. "At callback return", "R0");
  9011. return -EINVAL;
  9012. }
  9013. if (!calls_callback(env, callee->callsite)) {
  9014. verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
  9015. *insn_idx, callee->callsite);
  9016. return -EFAULT;
  9017. }
  9018. } else {
  9019. /* return to the caller whatever r0 had in the callee */
  9020. caller->regs[BPF_REG_0] = *r0;
  9021. }
  9022. /* callback_fn frame should have released its own additions to parent's
  9023. * reference state at this point, or check_reference_leak would
  9024. * complain, hence it must be the same as the caller. There is no need
  9025. * to copy it back.
  9026. */
  9027. if (!callee->in_callback_fn) {
  9028. /* Transfer references to the caller */
  9029. err = copy_reference_state(caller, callee);
  9030. if (err)
  9031. return err;
  9032. }
  9033. /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
  9034. * there function call logic would reschedule callback visit. If iteration
  9035. * converges is_state_visited() would prune that visit eventually.
  9036. */
  9037. in_callback_fn = callee->in_callback_fn;
  9038. if (in_callback_fn)
  9039. *insn_idx = callee->callsite;
  9040. else
  9041. *insn_idx = callee->callsite + 1;
  9042. if (env->log.level & BPF_LOG_LEVEL) {
  9043. verbose(env, "returning from callee:\n");
  9044. print_verifier_state(env, callee, true);
  9045. verbose(env, "to caller at %d:\n", *insn_idx);
  9046. print_verifier_state(env, caller, true);
  9047. }
  9048. /* clear everything in the callee. In case of exceptional exits using
  9049. * bpf_throw, this will be done by copy_verifier_state for extra frames. */
  9050. free_func_state(callee);
  9051. state->frame[state->curframe--] = NULL;
  9052. /* for callbacks widen imprecise scalars to make programs like below verify:
  9053. *
  9054. * struct ctx { int i; }
  9055. * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
  9056. * ...
  9057. * struct ctx = { .i = 0; }
  9058. * bpf_loop(100, cb, &ctx, 0);
  9059. *
  9060. * This is similar to what is done in process_iter_next_call() for open
  9061. * coded iterators.
  9062. */
  9063. prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
  9064. if (prev_st) {
  9065. err = widen_imprecise_scalars(env, prev_st, state);
  9066. if (err)
  9067. return err;
  9068. }
  9069. return 0;
  9070. }
  9071. static int do_refine_retval_range(struct bpf_verifier_env *env,
  9072. struct bpf_reg_state *regs, int ret_type,
  9073. int func_id,
  9074. struct bpf_call_arg_meta *meta)
  9075. {
  9076. struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
  9077. if (ret_type != RET_INTEGER)
  9078. return 0;
  9079. switch (func_id) {
  9080. case BPF_FUNC_get_stack:
  9081. case BPF_FUNC_get_task_stack:
  9082. case BPF_FUNC_probe_read_str:
  9083. case BPF_FUNC_probe_read_kernel_str:
  9084. case BPF_FUNC_probe_read_user_str:
  9085. ret_reg->smax_value = meta->msize_max_value;
  9086. ret_reg->s32_max_value = meta->msize_max_value;
  9087. ret_reg->smin_value = -MAX_ERRNO;
  9088. ret_reg->s32_min_value = -MAX_ERRNO;
  9089. reg_bounds_sync(ret_reg);
  9090. break;
  9091. case BPF_FUNC_get_smp_processor_id:
  9092. ret_reg->umax_value = nr_cpu_ids - 1;
  9093. ret_reg->u32_max_value = nr_cpu_ids - 1;
  9094. ret_reg->smax_value = nr_cpu_ids - 1;
  9095. ret_reg->s32_max_value = nr_cpu_ids - 1;
  9096. ret_reg->umin_value = 0;
  9097. ret_reg->u32_min_value = 0;
  9098. ret_reg->smin_value = 0;
  9099. ret_reg->s32_min_value = 0;
  9100. reg_bounds_sync(ret_reg);
  9101. break;
  9102. }
  9103. return reg_bounds_sanity_check(env, ret_reg, "retval");
  9104. }
  9105. static int
  9106. record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  9107. int func_id, int insn_idx)
  9108. {
  9109. struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  9110. struct bpf_map *map = meta->map_ptr;
  9111. if (func_id != BPF_FUNC_tail_call &&
  9112. func_id != BPF_FUNC_map_lookup_elem &&
  9113. func_id != BPF_FUNC_map_update_elem &&
  9114. func_id != BPF_FUNC_map_delete_elem &&
  9115. func_id != BPF_FUNC_map_push_elem &&
  9116. func_id != BPF_FUNC_map_pop_elem &&
  9117. func_id != BPF_FUNC_map_peek_elem &&
  9118. func_id != BPF_FUNC_for_each_map_elem &&
  9119. func_id != BPF_FUNC_redirect_map &&
  9120. func_id != BPF_FUNC_map_lookup_percpu_elem)
  9121. return 0;
  9122. if (map == NULL) {
  9123. verbose(env, "kernel subsystem misconfigured verifier\n");
  9124. return -EINVAL;
  9125. }
  9126. /* In case of read-only, some additional restrictions
  9127. * need to be applied in order to prevent altering the
  9128. * state of the map from program side.
  9129. */
  9130. if ((map->map_flags & BPF_F_RDONLY_PROG) &&
  9131. (func_id == BPF_FUNC_map_delete_elem ||
  9132. func_id == BPF_FUNC_map_update_elem ||
  9133. func_id == BPF_FUNC_map_push_elem ||
  9134. func_id == BPF_FUNC_map_pop_elem)) {
  9135. verbose(env, "write into map forbidden\n");
  9136. return -EACCES;
  9137. }
  9138. if (!aux->map_ptr_state.map_ptr)
  9139. bpf_map_ptr_store(aux, meta->map_ptr,
  9140. !meta->map_ptr->bypass_spec_v1, false);
  9141. else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
  9142. bpf_map_ptr_store(aux, meta->map_ptr,
  9143. !meta->map_ptr->bypass_spec_v1, true);
  9144. return 0;
  9145. }
  9146. static int
  9147. record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
  9148. int func_id, int insn_idx)
  9149. {
  9150. struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
  9151. struct bpf_reg_state *regs = cur_regs(env), *reg;
  9152. struct bpf_map *map = meta->map_ptr;
  9153. u64 val, max;
  9154. int err;
  9155. if (func_id != BPF_FUNC_tail_call)
  9156. return 0;
  9157. if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
  9158. verbose(env, "kernel subsystem misconfigured verifier\n");
  9159. return -EINVAL;
  9160. }
  9161. reg = &regs[BPF_REG_3];
  9162. val = reg->var_off.value;
  9163. max = map->max_entries;
  9164. if (!(is_reg_const(reg, false) && val < max)) {
  9165. bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
  9166. return 0;
  9167. }
  9168. err = mark_chain_precision(env, BPF_REG_3);
  9169. if (err)
  9170. return err;
  9171. if (bpf_map_key_unseen(aux))
  9172. bpf_map_key_store(aux, val);
  9173. else if (!bpf_map_key_poisoned(aux) &&
  9174. bpf_map_key_immediate(aux) != val)
  9175. bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
  9176. return 0;
  9177. }
  9178. static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
  9179. {
  9180. struct bpf_func_state *state = cur_func(env);
  9181. bool refs_lingering = false;
  9182. int i;
  9183. if (!exception_exit && state->frameno && !state->in_callback_fn)
  9184. return 0;
  9185. for (i = 0; i < state->acquired_refs; i++) {
  9186. if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
  9187. continue;
  9188. verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
  9189. state->refs[i].id, state->refs[i].insn_idx);
  9190. refs_lingering = true;
  9191. }
  9192. return refs_lingering ? -EINVAL : 0;
  9193. }
  9194. static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
  9195. struct bpf_reg_state *regs)
  9196. {
  9197. struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
  9198. struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
  9199. struct bpf_map *fmt_map = fmt_reg->map_ptr;
  9200. struct bpf_bprintf_data data = {};
  9201. int err, fmt_map_off, num_args;
  9202. u64 fmt_addr;
  9203. char *fmt;
  9204. /* data must be an array of u64 */
  9205. if (data_len_reg->var_off.value % 8)
  9206. return -EINVAL;
  9207. num_args = data_len_reg->var_off.value / 8;
  9208. /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
  9209. * and map_direct_value_addr is set.
  9210. */
  9211. fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
  9212. err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
  9213. fmt_map_off);
  9214. if (err) {
  9215. verbose(env, "verifier bug\n");
  9216. return -EFAULT;
  9217. }
  9218. fmt = (char *)(long)fmt_addr + fmt_map_off;
  9219. /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
  9220. * can focus on validating the format specifiers.
  9221. */
  9222. err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
  9223. if (err < 0)
  9224. verbose(env, "Invalid format string\n");
  9225. return err;
  9226. }
  9227. static int check_get_func_ip(struct bpf_verifier_env *env)
  9228. {
  9229. enum bpf_prog_type type = resolve_prog_type(env->prog);
  9230. int func_id = BPF_FUNC_get_func_ip;
  9231. if (type == BPF_PROG_TYPE_TRACING) {
  9232. if (!bpf_prog_has_trampoline(env->prog)) {
  9233. verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
  9234. func_id_name(func_id), func_id);
  9235. return -ENOTSUPP;
  9236. }
  9237. return 0;
  9238. } else if (type == BPF_PROG_TYPE_KPROBE) {
  9239. return 0;
  9240. }
  9241. verbose(env, "func %s#%d not supported for program type %d\n",
  9242. func_id_name(func_id), func_id, type);
  9243. return -ENOTSUPP;
  9244. }
  9245. static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
  9246. {
  9247. return &env->insn_aux_data[env->insn_idx];
  9248. }
  9249. static bool loop_flag_is_zero(struct bpf_verifier_env *env)
  9250. {
  9251. struct bpf_reg_state *regs = cur_regs(env);
  9252. struct bpf_reg_state *reg = &regs[BPF_REG_4];
  9253. bool reg_is_null = register_is_null(reg);
  9254. if (reg_is_null)
  9255. mark_chain_precision(env, BPF_REG_4);
  9256. return reg_is_null;
  9257. }
  9258. static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
  9259. {
  9260. struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
  9261. if (!state->initialized) {
  9262. state->initialized = 1;
  9263. state->fit_for_inline = loop_flag_is_zero(env);
  9264. state->callback_subprogno = subprogno;
  9265. return;
  9266. }
  9267. if (!state->fit_for_inline)
  9268. return;
  9269. state->fit_for_inline = (loop_flag_is_zero(env) &&
  9270. state->callback_subprogno == subprogno);
  9271. }
  9272. static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
  9273. const struct bpf_func_proto **ptr)
  9274. {
  9275. if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
  9276. return -ERANGE;
  9277. if (!env->ops->get_func_proto)
  9278. return -EINVAL;
  9279. *ptr = env->ops->get_func_proto(func_id, env->prog);
  9280. return *ptr && (*ptr)->func ? 0 : -EINVAL;
  9281. }
  9282. static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  9283. int *insn_idx_p)
  9284. {
  9285. enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
  9286. bool returns_cpu_specific_alloc_ptr = false;
  9287. const struct bpf_func_proto *fn = NULL;
  9288. enum bpf_return_type ret_type;
  9289. enum bpf_type_flag ret_flag;
  9290. struct bpf_reg_state *regs;
  9291. struct bpf_call_arg_meta meta;
  9292. int insn_idx = *insn_idx_p;
  9293. bool changes_data;
  9294. int i, err, func_id;
  9295. /* find function prototype */
  9296. func_id = insn->imm;
  9297. err = get_helper_proto(env, insn->imm, &fn);
  9298. if (err == -ERANGE) {
  9299. verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
  9300. return -EINVAL;
  9301. }
  9302. if (err) {
  9303. verbose(env, "program of this type cannot use helper %s#%d\n",
  9304. func_id_name(func_id), func_id);
  9305. return err;
  9306. }
  9307. /* eBPF programs must be GPL compatible to use GPL-ed functions */
  9308. if (!env->prog->gpl_compatible && fn->gpl_only) {
  9309. verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
  9310. return -EINVAL;
  9311. }
  9312. if (fn->allowed && !fn->allowed(env->prog)) {
  9313. verbose(env, "helper call is not allowed in probe\n");
  9314. return -EINVAL;
  9315. }
  9316. if (!in_sleepable(env) && fn->might_sleep) {
  9317. verbose(env, "helper call might sleep in a non-sleepable prog\n");
  9318. return -EINVAL;
  9319. }
  9320. /* With LD_ABS/IND some JITs save/restore skb from r1. */
  9321. changes_data = bpf_helper_changes_pkt_data(func_id);
  9322. if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
  9323. verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
  9324. func_id_name(func_id), func_id);
  9325. return -EINVAL;
  9326. }
  9327. memset(&meta, 0, sizeof(meta));
  9328. meta.pkt_access = fn->pkt_access;
  9329. err = check_func_proto(fn, func_id);
  9330. if (err) {
  9331. verbose(env, "kernel subsystem misconfigured func %s#%d\n",
  9332. func_id_name(func_id), func_id);
  9333. return err;
  9334. }
  9335. if (env->cur_state->active_rcu_lock) {
  9336. if (fn->might_sleep) {
  9337. verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
  9338. func_id_name(func_id), func_id);
  9339. return -EINVAL;
  9340. }
  9341. if (in_sleepable(env) && is_storage_get_function(func_id))
  9342. env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
  9343. }
  9344. if (env->cur_state->active_preempt_lock) {
  9345. if (fn->might_sleep) {
  9346. verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
  9347. func_id_name(func_id), func_id);
  9348. return -EINVAL;
  9349. }
  9350. if (in_sleepable(env) && is_storage_get_function(func_id))
  9351. env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
  9352. }
  9353. meta.func_id = func_id;
  9354. /* check args */
  9355. for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
  9356. err = check_func_arg(env, i, &meta, fn, insn_idx);
  9357. if (err)
  9358. return err;
  9359. }
  9360. err = record_func_map(env, &meta, func_id, insn_idx);
  9361. if (err)
  9362. return err;
  9363. err = record_func_key(env, &meta, func_id, insn_idx);
  9364. if (err)
  9365. return err;
  9366. /* Mark slots with STACK_MISC in case of raw mode, stack offset
  9367. * is inferred from register state.
  9368. */
  9369. for (i = 0; i < meta.access_size; i++) {
  9370. err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
  9371. BPF_WRITE, -1, false, false);
  9372. if (err)
  9373. return err;
  9374. }
  9375. regs = cur_regs(env);
  9376. if (meta.release_regno) {
  9377. err = -EINVAL;
  9378. /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
  9379. * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
  9380. * is safe to do directly.
  9381. */
  9382. if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
  9383. if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
  9384. verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
  9385. return -EFAULT;
  9386. }
  9387. err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
  9388. } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
  9389. u32 ref_obj_id = meta.ref_obj_id;
  9390. bool in_rcu = in_rcu_cs(env);
  9391. struct bpf_func_state *state;
  9392. struct bpf_reg_state *reg;
  9393. err = release_reference_state(cur_func(env), ref_obj_id);
  9394. if (!err) {
  9395. bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
  9396. if (reg->ref_obj_id == ref_obj_id) {
  9397. if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
  9398. reg->ref_obj_id = 0;
  9399. reg->type &= ~MEM_ALLOC;
  9400. reg->type |= MEM_RCU;
  9401. } else {
  9402. mark_reg_invalid(env, reg);
  9403. }
  9404. }
  9405. }));
  9406. }
  9407. } else if (meta.ref_obj_id) {
  9408. err = release_reference(env, meta.ref_obj_id);
  9409. } else if (register_is_null(&regs[meta.release_regno])) {
  9410. /* meta.ref_obj_id can only be 0 if register that is meant to be
  9411. * released is NULL, which must be > R0.
  9412. */
  9413. err = 0;
  9414. }
  9415. if (err) {
  9416. verbose(env, "func %s#%d reference has not been acquired before\n",
  9417. func_id_name(func_id), func_id);
  9418. return err;
  9419. }
  9420. }
  9421. switch (func_id) {
  9422. case BPF_FUNC_tail_call:
  9423. if (env->cur_state->active_lock.ptr) {
  9424. verbose(env, "tail_call cannot be used inside bpf_spin_lock-ed region\n");
  9425. return -EINVAL;
  9426. }
  9427. err = check_reference_leak(env, false);
  9428. if (err) {
  9429. verbose(env, "tail_call would lead to reference leak\n");
  9430. return err;
  9431. }
  9432. if (env->cur_state->active_rcu_lock) {
  9433. verbose(env, "tail_call cannot be used inside bpf_rcu_read_lock-ed region\n");
  9434. return -EINVAL;
  9435. }
  9436. if (env->cur_state->active_preempt_lock) {
  9437. verbose(env, "tail_call cannot be used inside bpf_preempt_disable-ed region\n");
  9438. return -EINVAL;
  9439. }
  9440. break;
  9441. case BPF_FUNC_get_local_storage:
  9442. /* check that flags argument in get_local_storage(map, flags) is 0,
  9443. * this is required because get_local_storage() can't return an error.
  9444. */
  9445. if (!register_is_null(&regs[BPF_REG_2])) {
  9446. verbose(env, "get_local_storage() doesn't support non-zero flags\n");
  9447. return -EINVAL;
  9448. }
  9449. break;
  9450. case BPF_FUNC_for_each_map_elem:
  9451. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  9452. set_map_elem_callback_state);
  9453. break;
  9454. case BPF_FUNC_timer_set_callback:
  9455. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  9456. set_timer_callback_state);
  9457. break;
  9458. case BPF_FUNC_find_vma:
  9459. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  9460. set_find_vma_callback_state);
  9461. break;
  9462. case BPF_FUNC_snprintf:
  9463. err = check_bpf_snprintf_call(env, regs);
  9464. break;
  9465. case BPF_FUNC_loop:
  9466. update_loop_inline_state(env, meta.subprogno);
  9467. /* Verifier relies on R1 value to determine if bpf_loop() iteration
  9468. * is finished, thus mark it precise.
  9469. */
  9470. err = mark_chain_precision(env, BPF_REG_1);
  9471. if (err)
  9472. return err;
  9473. if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
  9474. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  9475. set_loop_callback_state);
  9476. } else {
  9477. cur_func(env)->callback_depth = 0;
  9478. if (env->log.level & BPF_LOG_LEVEL2)
  9479. verbose(env, "frame%d bpf_loop iteration limit reached\n",
  9480. env->cur_state->curframe);
  9481. }
  9482. break;
  9483. case BPF_FUNC_dynptr_from_mem:
  9484. if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
  9485. verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
  9486. reg_type_str(env, regs[BPF_REG_1].type));
  9487. return -EACCES;
  9488. }
  9489. break;
  9490. case BPF_FUNC_set_retval:
  9491. if (prog_type == BPF_PROG_TYPE_LSM &&
  9492. env->prog->expected_attach_type == BPF_LSM_CGROUP) {
  9493. if (!env->prog->aux->attach_func_proto->type) {
  9494. /* Make sure programs that attach to void
  9495. * hooks don't try to modify return value.
  9496. */
  9497. verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
  9498. return -EINVAL;
  9499. }
  9500. }
  9501. break;
  9502. case BPF_FUNC_dynptr_data:
  9503. {
  9504. struct bpf_reg_state *reg;
  9505. int id, ref_obj_id;
  9506. reg = get_dynptr_arg_reg(env, fn, regs);
  9507. if (!reg)
  9508. return -EFAULT;
  9509. if (meta.dynptr_id) {
  9510. verbose(env, "verifier internal error: meta.dynptr_id already set\n");
  9511. return -EFAULT;
  9512. }
  9513. if (meta.ref_obj_id) {
  9514. verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
  9515. return -EFAULT;
  9516. }
  9517. id = dynptr_id(env, reg);
  9518. if (id < 0) {
  9519. verbose(env, "verifier internal error: failed to obtain dynptr id\n");
  9520. return id;
  9521. }
  9522. ref_obj_id = dynptr_ref_obj_id(env, reg);
  9523. if (ref_obj_id < 0) {
  9524. verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
  9525. return ref_obj_id;
  9526. }
  9527. meta.dynptr_id = id;
  9528. meta.ref_obj_id = ref_obj_id;
  9529. break;
  9530. }
  9531. case BPF_FUNC_dynptr_write:
  9532. {
  9533. enum bpf_dynptr_type dynptr_type;
  9534. struct bpf_reg_state *reg;
  9535. reg = get_dynptr_arg_reg(env, fn, regs);
  9536. if (!reg)
  9537. return -EFAULT;
  9538. dynptr_type = dynptr_get_type(env, reg);
  9539. if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
  9540. return -EFAULT;
  9541. if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
  9542. /* this will trigger clear_all_pkt_pointers(), which will
  9543. * invalidate all dynptr slices associated with the skb
  9544. */
  9545. changes_data = true;
  9546. break;
  9547. }
  9548. case BPF_FUNC_per_cpu_ptr:
  9549. case BPF_FUNC_this_cpu_ptr:
  9550. {
  9551. struct bpf_reg_state *reg = &regs[BPF_REG_1];
  9552. const struct btf_type *type;
  9553. if (reg->type & MEM_RCU) {
  9554. type = btf_type_by_id(reg->btf, reg->btf_id);
  9555. if (!type || !btf_type_is_struct(type)) {
  9556. verbose(env, "Helper has invalid btf/btf_id in R1\n");
  9557. return -EFAULT;
  9558. }
  9559. returns_cpu_specific_alloc_ptr = true;
  9560. env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
  9561. }
  9562. break;
  9563. }
  9564. case BPF_FUNC_user_ringbuf_drain:
  9565. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  9566. set_user_ringbuf_callback_state);
  9567. break;
  9568. }
  9569. if (err)
  9570. return err;
  9571. /* reset caller saved regs */
  9572. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  9573. mark_reg_not_init(env, regs, caller_saved[i]);
  9574. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  9575. }
  9576. /* helper call returns 64-bit value. */
  9577. regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
  9578. /* update return register (already marked as written above) */
  9579. ret_type = fn->ret_type;
  9580. ret_flag = type_flag(ret_type);
  9581. switch (base_type(ret_type)) {
  9582. case RET_INTEGER:
  9583. /* sets type to SCALAR_VALUE */
  9584. mark_reg_unknown(env, regs, BPF_REG_0);
  9585. break;
  9586. case RET_VOID:
  9587. regs[BPF_REG_0].type = NOT_INIT;
  9588. break;
  9589. case RET_PTR_TO_MAP_VALUE:
  9590. /* There is no offset yet applied, variable or fixed */
  9591. mark_reg_known_zero(env, regs, BPF_REG_0);
  9592. /* remember map_ptr, so that check_map_access()
  9593. * can check 'value_size' boundary of memory access
  9594. * to map element returned from bpf_map_lookup_elem()
  9595. */
  9596. if (meta.map_ptr == NULL) {
  9597. verbose(env,
  9598. "kernel subsystem misconfigured verifier\n");
  9599. return -EINVAL;
  9600. }
  9601. regs[BPF_REG_0].map_ptr = meta.map_ptr;
  9602. regs[BPF_REG_0].map_uid = meta.map_uid;
  9603. regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
  9604. if (!type_may_be_null(ret_type) &&
  9605. btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
  9606. regs[BPF_REG_0].id = ++env->id_gen;
  9607. }
  9608. break;
  9609. case RET_PTR_TO_SOCKET:
  9610. mark_reg_known_zero(env, regs, BPF_REG_0);
  9611. regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
  9612. break;
  9613. case RET_PTR_TO_SOCK_COMMON:
  9614. mark_reg_known_zero(env, regs, BPF_REG_0);
  9615. regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
  9616. break;
  9617. case RET_PTR_TO_TCP_SOCK:
  9618. mark_reg_known_zero(env, regs, BPF_REG_0);
  9619. regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
  9620. break;
  9621. case RET_PTR_TO_MEM:
  9622. mark_reg_known_zero(env, regs, BPF_REG_0);
  9623. regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
  9624. regs[BPF_REG_0].mem_size = meta.mem_size;
  9625. break;
  9626. case RET_PTR_TO_MEM_OR_BTF_ID:
  9627. {
  9628. const struct btf_type *t;
  9629. mark_reg_known_zero(env, regs, BPF_REG_0);
  9630. t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
  9631. if (!btf_type_is_struct(t)) {
  9632. u32 tsize;
  9633. const struct btf_type *ret;
  9634. const char *tname;
  9635. /* resolve the type size of ksym. */
  9636. ret = btf_resolve_size(meta.ret_btf, t, &tsize);
  9637. if (IS_ERR(ret)) {
  9638. tname = btf_name_by_offset(meta.ret_btf, t->name_off);
  9639. verbose(env, "unable to resolve the size of type '%s': %ld\n",
  9640. tname, PTR_ERR(ret));
  9641. return -EINVAL;
  9642. }
  9643. regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
  9644. regs[BPF_REG_0].mem_size = tsize;
  9645. } else {
  9646. if (returns_cpu_specific_alloc_ptr) {
  9647. regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
  9648. } else {
  9649. /* MEM_RDONLY may be carried from ret_flag, but it
  9650. * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
  9651. * it will confuse the check of PTR_TO_BTF_ID in
  9652. * check_mem_access().
  9653. */
  9654. ret_flag &= ~MEM_RDONLY;
  9655. regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
  9656. }
  9657. regs[BPF_REG_0].btf = meta.ret_btf;
  9658. regs[BPF_REG_0].btf_id = meta.ret_btf_id;
  9659. }
  9660. break;
  9661. }
  9662. case RET_PTR_TO_BTF_ID:
  9663. {
  9664. struct btf *ret_btf;
  9665. int ret_btf_id;
  9666. mark_reg_known_zero(env, regs, BPF_REG_0);
  9667. regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
  9668. if (func_id == BPF_FUNC_kptr_xchg) {
  9669. ret_btf = meta.kptr_field->kptr.btf;
  9670. ret_btf_id = meta.kptr_field->kptr.btf_id;
  9671. if (!btf_is_kernel(ret_btf)) {
  9672. regs[BPF_REG_0].type |= MEM_ALLOC;
  9673. if (meta.kptr_field->type == BPF_KPTR_PERCPU)
  9674. regs[BPF_REG_0].type |= MEM_PERCPU;
  9675. }
  9676. } else {
  9677. if (fn->ret_btf_id == BPF_PTR_POISON) {
  9678. verbose(env, "verifier internal error:");
  9679. verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
  9680. func_id_name(func_id));
  9681. return -EINVAL;
  9682. }
  9683. ret_btf = btf_vmlinux;
  9684. ret_btf_id = *fn->ret_btf_id;
  9685. }
  9686. if (ret_btf_id == 0) {
  9687. verbose(env, "invalid return type %u of func %s#%d\n",
  9688. base_type(ret_type), func_id_name(func_id),
  9689. func_id);
  9690. return -EINVAL;
  9691. }
  9692. regs[BPF_REG_0].btf = ret_btf;
  9693. regs[BPF_REG_0].btf_id = ret_btf_id;
  9694. break;
  9695. }
  9696. default:
  9697. verbose(env, "unknown return type %u of func %s#%d\n",
  9698. base_type(ret_type), func_id_name(func_id), func_id);
  9699. return -EINVAL;
  9700. }
  9701. if (type_may_be_null(regs[BPF_REG_0].type))
  9702. regs[BPF_REG_0].id = ++env->id_gen;
  9703. if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
  9704. verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
  9705. func_id_name(func_id), func_id);
  9706. return -EFAULT;
  9707. }
  9708. if (is_dynptr_ref_function(func_id))
  9709. regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
  9710. if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
  9711. /* For release_reference() */
  9712. regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
  9713. } else if (is_acquire_function(func_id, meta.map_ptr)) {
  9714. int id = acquire_reference_state(env, insn_idx);
  9715. if (id < 0)
  9716. return id;
  9717. /* For mark_ptr_or_null_reg() */
  9718. regs[BPF_REG_0].id = id;
  9719. /* For release_reference() */
  9720. regs[BPF_REG_0].ref_obj_id = id;
  9721. }
  9722. err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
  9723. if (err)
  9724. return err;
  9725. err = check_map_func_compatibility(env, meta.map_ptr, func_id);
  9726. if (err)
  9727. return err;
  9728. if ((func_id == BPF_FUNC_get_stack ||
  9729. func_id == BPF_FUNC_get_task_stack) &&
  9730. !env->prog->has_callchain_buf) {
  9731. const char *err_str;
  9732. #ifdef CONFIG_PERF_EVENTS
  9733. err = get_callchain_buffers(sysctl_perf_event_max_stack);
  9734. err_str = "cannot get callchain buffer for func %s#%d\n";
  9735. #else
  9736. err = -ENOTSUPP;
  9737. err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
  9738. #endif
  9739. if (err) {
  9740. verbose(env, err_str, func_id_name(func_id), func_id);
  9741. return err;
  9742. }
  9743. env->prog->has_callchain_buf = true;
  9744. }
  9745. if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
  9746. env->prog->call_get_stack = true;
  9747. if (func_id == BPF_FUNC_get_func_ip) {
  9748. if (check_get_func_ip(env))
  9749. return -ENOTSUPP;
  9750. env->prog->call_get_func_ip = true;
  9751. }
  9752. if (changes_data)
  9753. clear_all_pkt_pointers(env);
  9754. return 0;
  9755. }
  9756. /* mark_btf_func_reg_size() is used when the reg size is determined by
  9757. * the BTF func_proto's return value size and argument.
  9758. */
  9759. static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
  9760. size_t reg_size)
  9761. {
  9762. struct bpf_reg_state *reg = &cur_regs(env)[regno];
  9763. if (regno == BPF_REG_0) {
  9764. /* Function return value */
  9765. reg->live |= REG_LIVE_WRITTEN;
  9766. reg->subreg_def = reg_size == sizeof(u64) ?
  9767. DEF_NOT_SUBREG : env->insn_idx + 1;
  9768. } else {
  9769. /* Function argument */
  9770. if (reg_size == sizeof(u64)) {
  9771. mark_insn_zext(env, reg);
  9772. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
  9773. } else {
  9774. mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
  9775. }
  9776. }
  9777. }
  9778. static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
  9779. {
  9780. return meta->kfunc_flags & KF_ACQUIRE;
  9781. }
  9782. static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
  9783. {
  9784. return meta->kfunc_flags & KF_RELEASE;
  9785. }
  9786. static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
  9787. {
  9788. return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
  9789. }
  9790. static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
  9791. {
  9792. return meta->kfunc_flags & KF_SLEEPABLE;
  9793. }
  9794. static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
  9795. {
  9796. return meta->kfunc_flags & KF_DESTRUCTIVE;
  9797. }
  9798. static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
  9799. {
  9800. return meta->kfunc_flags & KF_RCU;
  9801. }
  9802. static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
  9803. {
  9804. return meta->kfunc_flags & KF_RCU_PROTECTED;
  9805. }
  9806. static bool is_kfunc_arg_mem_size(const struct btf *btf,
  9807. const struct btf_param *arg,
  9808. const struct bpf_reg_state *reg)
  9809. {
  9810. const struct btf_type *t;
  9811. t = btf_type_skip_modifiers(btf, arg->type, NULL);
  9812. if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
  9813. return false;
  9814. return btf_param_match_suffix(btf, arg, "__sz");
  9815. }
  9816. static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
  9817. const struct btf_param *arg,
  9818. const struct bpf_reg_state *reg)
  9819. {
  9820. const struct btf_type *t;
  9821. t = btf_type_skip_modifiers(btf, arg->type, NULL);
  9822. if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
  9823. return false;
  9824. return btf_param_match_suffix(btf, arg, "__szk");
  9825. }
  9826. static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
  9827. {
  9828. return btf_param_match_suffix(btf, arg, "__opt");
  9829. }
  9830. static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
  9831. {
  9832. return btf_param_match_suffix(btf, arg, "__k");
  9833. }
  9834. static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
  9835. {
  9836. return btf_param_match_suffix(btf, arg, "__ign");
  9837. }
  9838. static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
  9839. {
  9840. return btf_param_match_suffix(btf, arg, "__map");
  9841. }
  9842. static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
  9843. {
  9844. return btf_param_match_suffix(btf, arg, "__alloc");
  9845. }
  9846. static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
  9847. {
  9848. return btf_param_match_suffix(btf, arg, "__uninit");
  9849. }
  9850. static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
  9851. {
  9852. return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
  9853. }
  9854. static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
  9855. {
  9856. return btf_param_match_suffix(btf, arg, "__nullable");
  9857. }
  9858. static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
  9859. {
  9860. return btf_param_match_suffix(btf, arg, "__str");
  9861. }
  9862. static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
  9863. const struct btf_param *arg,
  9864. const char *name)
  9865. {
  9866. int len, target_len = strlen(name);
  9867. const char *param_name;
  9868. param_name = btf_name_by_offset(btf, arg->name_off);
  9869. if (str_is_empty(param_name))
  9870. return false;
  9871. len = strlen(param_name);
  9872. if (len != target_len)
  9873. return false;
  9874. if (strcmp(param_name, name))
  9875. return false;
  9876. return true;
  9877. }
  9878. enum {
  9879. KF_ARG_DYNPTR_ID,
  9880. KF_ARG_LIST_HEAD_ID,
  9881. KF_ARG_LIST_NODE_ID,
  9882. KF_ARG_RB_ROOT_ID,
  9883. KF_ARG_RB_NODE_ID,
  9884. KF_ARG_WORKQUEUE_ID,
  9885. };
  9886. BTF_ID_LIST(kf_arg_btf_ids)
  9887. BTF_ID(struct, bpf_dynptr)
  9888. BTF_ID(struct, bpf_list_head)
  9889. BTF_ID(struct, bpf_list_node)
  9890. BTF_ID(struct, bpf_rb_root)
  9891. BTF_ID(struct, bpf_rb_node)
  9892. BTF_ID(struct, bpf_wq)
  9893. static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
  9894. const struct btf_param *arg, int type)
  9895. {
  9896. const struct btf_type *t;
  9897. u32 res_id;
  9898. t = btf_type_skip_modifiers(btf, arg->type, NULL);
  9899. if (!t)
  9900. return false;
  9901. if (!btf_type_is_ptr(t))
  9902. return false;
  9903. t = btf_type_skip_modifiers(btf, t->type, &res_id);
  9904. if (!t)
  9905. return false;
  9906. return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
  9907. }
  9908. static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
  9909. {
  9910. return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
  9911. }
  9912. static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
  9913. {
  9914. return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
  9915. }
  9916. static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
  9917. {
  9918. return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
  9919. }
  9920. static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
  9921. {
  9922. return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
  9923. }
  9924. static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
  9925. {
  9926. return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
  9927. }
  9928. static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
  9929. {
  9930. return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
  9931. }
  9932. static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
  9933. const struct btf_param *arg)
  9934. {
  9935. const struct btf_type *t;
  9936. t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
  9937. if (!t)
  9938. return false;
  9939. return true;
  9940. }
  9941. /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
  9942. static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
  9943. const struct btf *btf,
  9944. const struct btf_type *t, int rec)
  9945. {
  9946. const struct btf_type *member_type;
  9947. const struct btf_member *member;
  9948. u32 i;
  9949. if (!btf_type_is_struct(t))
  9950. return false;
  9951. for_each_member(i, t, member) {
  9952. const struct btf_array *array;
  9953. member_type = btf_type_skip_modifiers(btf, member->type, NULL);
  9954. if (btf_type_is_struct(member_type)) {
  9955. if (rec >= 3) {
  9956. verbose(env, "max struct nesting depth exceeded\n");
  9957. return false;
  9958. }
  9959. if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
  9960. return false;
  9961. continue;
  9962. }
  9963. if (btf_type_is_array(member_type)) {
  9964. array = btf_array(member_type);
  9965. if (!array->nelems)
  9966. return false;
  9967. member_type = btf_type_skip_modifiers(btf, array->type, NULL);
  9968. if (!btf_type_is_scalar(member_type))
  9969. return false;
  9970. continue;
  9971. }
  9972. if (!btf_type_is_scalar(member_type))
  9973. return false;
  9974. }
  9975. return true;
  9976. }
  9977. enum kfunc_ptr_arg_type {
  9978. KF_ARG_PTR_TO_CTX,
  9979. KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
  9980. KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
  9981. KF_ARG_PTR_TO_DYNPTR,
  9982. KF_ARG_PTR_TO_ITER,
  9983. KF_ARG_PTR_TO_LIST_HEAD,
  9984. KF_ARG_PTR_TO_LIST_NODE,
  9985. KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
  9986. KF_ARG_PTR_TO_MEM,
  9987. KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
  9988. KF_ARG_PTR_TO_CALLBACK,
  9989. KF_ARG_PTR_TO_RB_ROOT,
  9990. KF_ARG_PTR_TO_RB_NODE,
  9991. KF_ARG_PTR_TO_NULL,
  9992. KF_ARG_PTR_TO_CONST_STR,
  9993. KF_ARG_PTR_TO_MAP,
  9994. KF_ARG_PTR_TO_WORKQUEUE,
  9995. };
  9996. enum special_kfunc_type {
  9997. KF_bpf_obj_new_impl,
  9998. KF_bpf_obj_drop_impl,
  9999. KF_bpf_refcount_acquire_impl,
  10000. KF_bpf_list_push_front_impl,
  10001. KF_bpf_list_push_back_impl,
  10002. KF_bpf_list_pop_front,
  10003. KF_bpf_list_pop_back,
  10004. KF_bpf_cast_to_kern_ctx,
  10005. KF_bpf_rdonly_cast,
  10006. KF_bpf_rcu_read_lock,
  10007. KF_bpf_rcu_read_unlock,
  10008. KF_bpf_rbtree_remove,
  10009. KF_bpf_rbtree_add_impl,
  10010. KF_bpf_rbtree_first,
  10011. KF_bpf_dynptr_from_skb,
  10012. KF_bpf_dynptr_from_xdp,
  10013. KF_bpf_dynptr_slice,
  10014. KF_bpf_dynptr_slice_rdwr,
  10015. KF_bpf_dynptr_clone,
  10016. KF_bpf_percpu_obj_new_impl,
  10017. KF_bpf_percpu_obj_drop_impl,
  10018. KF_bpf_throw,
  10019. KF_bpf_wq_set_callback_impl,
  10020. KF_bpf_preempt_disable,
  10021. KF_bpf_preempt_enable,
  10022. KF_bpf_iter_css_task_new,
  10023. KF_bpf_session_cookie,
  10024. };
  10025. BTF_SET_START(special_kfunc_set)
  10026. BTF_ID(func, bpf_obj_new_impl)
  10027. BTF_ID(func, bpf_obj_drop_impl)
  10028. BTF_ID(func, bpf_refcount_acquire_impl)
  10029. BTF_ID(func, bpf_list_push_front_impl)
  10030. BTF_ID(func, bpf_list_push_back_impl)
  10031. BTF_ID(func, bpf_list_pop_front)
  10032. BTF_ID(func, bpf_list_pop_back)
  10033. BTF_ID(func, bpf_cast_to_kern_ctx)
  10034. BTF_ID(func, bpf_rdonly_cast)
  10035. BTF_ID(func, bpf_rbtree_remove)
  10036. BTF_ID(func, bpf_rbtree_add_impl)
  10037. BTF_ID(func, bpf_rbtree_first)
  10038. BTF_ID(func, bpf_dynptr_from_skb)
  10039. BTF_ID(func, bpf_dynptr_from_xdp)
  10040. BTF_ID(func, bpf_dynptr_slice)
  10041. BTF_ID(func, bpf_dynptr_slice_rdwr)
  10042. BTF_ID(func, bpf_dynptr_clone)
  10043. BTF_ID(func, bpf_percpu_obj_new_impl)
  10044. BTF_ID(func, bpf_percpu_obj_drop_impl)
  10045. BTF_ID(func, bpf_throw)
  10046. BTF_ID(func, bpf_wq_set_callback_impl)
  10047. #ifdef CONFIG_CGROUPS
  10048. BTF_ID(func, bpf_iter_css_task_new)
  10049. #endif
  10050. BTF_SET_END(special_kfunc_set)
  10051. BTF_ID_LIST(special_kfunc_list)
  10052. BTF_ID(func, bpf_obj_new_impl)
  10053. BTF_ID(func, bpf_obj_drop_impl)
  10054. BTF_ID(func, bpf_refcount_acquire_impl)
  10055. BTF_ID(func, bpf_list_push_front_impl)
  10056. BTF_ID(func, bpf_list_push_back_impl)
  10057. BTF_ID(func, bpf_list_pop_front)
  10058. BTF_ID(func, bpf_list_pop_back)
  10059. BTF_ID(func, bpf_cast_to_kern_ctx)
  10060. BTF_ID(func, bpf_rdonly_cast)
  10061. BTF_ID(func, bpf_rcu_read_lock)
  10062. BTF_ID(func, bpf_rcu_read_unlock)
  10063. BTF_ID(func, bpf_rbtree_remove)
  10064. BTF_ID(func, bpf_rbtree_add_impl)
  10065. BTF_ID(func, bpf_rbtree_first)
  10066. BTF_ID(func, bpf_dynptr_from_skb)
  10067. BTF_ID(func, bpf_dynptr_from_xdp)
  10068. BTF_ID(func, bpf_dynptr_slice)
  10069. BTF_ID(func, bpf_dynptr_slice_rdwr)
  10070. BTF_ID(func, bpf_dynptr_clone)
  10071. BTF_ID(func, bpf_percpu_obj_new_impl)
  10072. BTF_ID(func, bpf_percpu_obj_drop_impl)
  10073. BTF_ID(func, bpf_throw)
  10074. BTF_ID(func, bpf_wq_set_callback_impl)
  10075. BTF_ID(func, bpf_preempt_disable)
  10076. BTF_ID(func, bpf_preempt_enable)
  10077. #ifdef CONFIG_CGROUPS
  10078. BTF_ID(func, bpf_iter_css_task_new)
  10079. #else
  10080. BTF_ID_UNUSED
  10081. #endif
  10082. #ifdef CONFIG_BPF_EVENTS
  10083. BTF_ID(func, bpf_session_cookie)
  10084. #else
  10085. BTF_ID_UNUSED
  10086. #endif
  10087. static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
  10088. {
  10089. if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
  10090. meta->arg_owning_ref) {
  10091. return false;
  10092. }
  10093. return meta->kfunc_flags & KF_RET_NULL;
  10094. }
  10095. static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
  10096. {
  10097. return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
  10098. }
  10099. static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
  10100. {
  10101. return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
  10102. }
  10103. static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
  10104. {
  10105. return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
  10106. }
  10107. static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
  10108. {
  10109. return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
  10110. }
  10111. static enum kfunc_ptr_arg_type
  10112. get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
  10113. struct bpf_kfunc_call_arg_meta *meta,
  10114. const struct btf_type *t, const struct btf_type *ref_t,
  10115. const char *ref_tname, const struct btf_param *args,
  10116. int argno, int nargs)
  10117. {
  10118. u32 regno = argno + 1;
  10119. struct bpf_reg_state *regs = cur_regs(env);
  10120. struct bpf_reg_state *reg = &regs[regno];
  10121. bool arg_mem_size = false;
  10122. if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
  10123. return KF_ARG_PTR_TO_CTX;
  10124. /* In this function, we verify the kfunc's BTF as per the argument type,
  10125. * leaving the rest of the verification with respect to the register
  10126. * type to our caller. When a set of conditions hold in the BTF type of
  10127. * arguments, we resolve it to a known kfunc_ptr_arg_type.
  10128. */
  10129. if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
  10130. return KF_ARG_PTR_TO_CTX;
  10131. if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
  10132. return KF_ARG_PTR_TO_NULL;
  10133. if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
  10134. return KF_ARG_PTR_TO_ALLOC_BTF_ID;
  10135. if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
  10136. return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
  10137. if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
  10138. return KF_ARG_PTR_TO_DYNPTR;
  10139. if (is_kfunc_arg_iter(meta, argno, &args[argno]))
  10140. return KF_ARG_PTR_TO_ITER;
  10141. if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
  10142. return KF_ARG_PTR_TO_LIST_HEAD;
  10143. if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
  10144. return KF_ARG_PTR_TO_LIST_NODE;
  10145. if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
  10146. return KF_ARG_PTR_TO_RB_ROOT;
  10147. if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
  10148. return KF_ARG_PTR_TO_RB_NODE;
  10149. if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
  10150. return KF_ARG_PTR_TO_CONST_STR;
  10151. if (is_kfunc_arg_map(meta->btf, &args[argno]))
  10152. return KF_ARG_PTR_TO_MAP;
  10153. if (is_kfunc_arg_wq(meta->btf, &args[argno]))
  10154. return KF_ARG_PTR_TO_WORKQUEUE;
  10155. if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
  10156. if (!btf_type_is_struct(ref_t)) {
  10157. verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
  10158. meta->func_name, argno, btf_type_str(ref_t), ref_tname);
  10159. return -EINVAL;
  10160. }
  10161. return KF_ARG_PTR_TO_BTF_ID;
  10162. }
  10163. if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
  10164. return KF_ARG_PTR_TO_CALLBACK;
  10165. if (argno + 1 < nargs &&
  10166. (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
  10167. is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
  10168. arg_mem_size = true;
  10169. /* This is the catch all argument type of register types supported by
  10170. * check_helper_mem_access. However, we only allow when argument type is
  10171. * pointer to scalar, or struct composed (recursively) of scalars. When
  10172. * arg_mem_size is true, the pointer can be void *.
  10173. */
  10174. if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
  10175. (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
  10176. verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
  10177. argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
  10178. return -EINVAL;
  10179. }
  10180. return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
  10181. }
  10182. static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
  10183. struct bpf_reg_state *reg,
  10184. const struct btf_type *ref_t,
  10185. const char *ref_tname, u32 ref_id,
  10186. struct bpf_kfunc_call_arg_meta *meta,
  10187. int argno)
  10188. {
  10189. const struct btf_type *reg_ref_t;
  10190. bool strict_type_match = false;
  10191. const struct btf *reg_btf;
  10192. const char *reg_ref_tname;
  10193. bool taking_projection;
  10194. bool struct_same;
  10195. u32 reg_ref_id;
  10196. if (base_type(reg->type) == PTR_TO_BTF_ID) {
  10197. reg_btf = reg->btf;
  10198. reg_ref_id = reg->btf_id;
  10199. } else {
  10200. reg_btf = btf_vmlinux;
  10201. reg_ref_id = *reg2btf_ids[base_type(reg->type)];
  10202. }
  10203. /* Enforce strict type matching for calls to kfuncs that are acquiring
  10204. * or releasing a reference, or are no-cast aliases. We do _not_
  10205. * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
  10206. * as we want to enable BPF programs to pass types that are bitwise
  10207. * equivalent without forcing them to explicitly cast with something
  10208. * like bpf_cast_to_kern_ctx().
  10209. *
  10210. * For example, say we had a type like the following:
  10211. *
  10212. * struct bpf_cpumask {
  10213. * cpumask_t cpumask;
  10214. * refcount_t usage;
  10215. * };
  10216. *
  10217. * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
  10218. * to a struct cpumask, so it would be safe to pass a struct
  10219. * bpf_cpumask * to a kfunc expecting a struct cpumask *.
  10220. *
  10221. * The philosophy here is similar to how we allow scalars of different
  10222. * types to be passed to kfuncs as long as the size is the same. The
  10223. * only difference here is that we're simply allowing
  10224. * btf_struct_ids_match() to walk the struct at the 0th offset, and
  10225. * resolve types.
  10226. */
  10227. if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
  10228. btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
  10229. strict_type_match = true;
  10230. WARN_ON_ONCE(is_kfunc_release(meta) &&
  10231. (reg->off || !tnum_is_const(reg->var_off) ||
  10232. reg->var_off.value));
  10233. reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
  10234. reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
  10235. struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
  10236. /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
  10237. * actually use it -- it must cast to the underlying type. So we allow
  10238. * caller to pass in the underlying type.
  10239. */
  10240. taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
  10241. if (!taking_projection && !struct_same) {
  10242. verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
  10243. meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
  10244. btf_type_str(reg_ref_t), reg_ref_tname);
  10245. return -EINVAL;
  10246. }
  10247. return 0;
  10248. }
  10249. static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  10250. {
  10251. struct bpf_verifier_state *state = env->cur_state;
  10252. struct btf_record *rec = reg_btf_record(reg);
  10253. if (!state->active_lock.ptr) {
  10254. verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
  10255. return -EFAULT;
  10256. }
  10257. if (type_flag(reg->type) & NON_OWN_REF) {
  10258. verbose(env, "verifier internal error: NON_OWN_REF already set\n");
  10259. return -EFAULT;
  10260. }
  10261. reg->type |= NON_OWN_REF;
  10262. if (rec->refcount_off >= 0)
  10263. reg->type |= MEM_RCU;
  10264. return 0;
  10265. }
  10266. static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
  10267. {
  10268. struct bpf_func_state *state, *unused;
  10269. struct bpf_reg_state *reg;
  10270. int i;
  10271. state = cur_func(env);
  10272. if (!ref_obj_id) {
  10273. verbose(env, "verifier internal error: ref_obj_id is zero for "
  10274. "owning -> non-owning conversion\n");
  10275. return -EFAULT;
  10276. }
  10277. for (i = 0; i < state->acquired_refs; i++) {
  10278. if (state->refs[i].id != ref_obj_id)
  10279. continue;
  10280. /* Clear ref_obj_id here so release_reference doesn't clobber
  10281. * the whole reg
  10282. */
  10283. bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
  10284. if (reg->ref_obj_id == ref_obj_id) {
  10285. reg->ref_obj_id = 0;
  10286. ref_set_non_owning(env, reg);
  10287. }
  10288. }));
  10289. return 0;
  10290. }
  10291. verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
  10292. return -EFAULT;
  10293. }
  10294. /* Implementation details:
  10295. *
  10296. * Each register points to some region of memory, which we define as an
  10297. * allocation. Each allocation may embed a bpf_spin_lock which protects any
  10298. * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
  10299. * allocation. The lock and the data it protects are colocated in the same
  10300. * memory region.
  10301. *
  10302. * Hence, everytime a register holds a pointer value pointing to such
  10303. * allocation, the verifier preserves a unique reg->id for it.
  10304. *
  10305. * The verifier remembers the lock 'ptr' and the lock 'id' whenever
  10306. * bpf_spin_lock is called.
  10307. *
  10308. * To enable this, lock state in the verifier captures two values:
  10309. * active_lock.ptr = Register's type specific pointer
  10310. * active_lock.id = A unique ID for each register pointer value
  10311. *
  10312. * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
  10313. * supported register types.
  10314. *
  10315. * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
  10316. * allocated objects is the reg->btf pointer.
  10317. *
  10318. * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
  10319. * can establish the provenance of the map value statically for each distinct
  10320. * lookup into such maps. They always contain a single map value hence unique
  10321. * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
  10322. *
  10323. * So, in case of global variables, they use array maps with max_entries = 1,
  10324. * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
  10325. * into the same map value as max_entries is 1, as described above).
  10326. *
  10327. * In case of inner map lookups, the inner map pointer has same map_ptr as the
  10328. * outer map pointer (in verifier context), but each lookup into an inner map
  10329. * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
  10330. * maps from the same outer map share the same map_ptr as active_lock.ptr, they
  10331. * will get different reg->id assigned to each lookup, hence different
  10332. * active_lock.id.
  10333. *
  10334. * In case of allocated objects, active_lock.ptr is the reg->btf, and the
  10335. * reg->id is a unique ID preserved after the NULL pointer check on the pointer
  10336. * returned from bpf_obj_new. Each allocation receives a new reg->id.
  10337. */
  10338. static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
  10339. {
  10340. void *ptr;
  10341. u32 id;
  10342. switch ((int)reg->type) {
  10343. case PTR_TO_MAP_VALUE:
  10344. ptr = reg->map_ptr;
  10345. break;
  10346. case PTR_TO_BTF_ID | MEM_ALLOC:
  10347. ptr = reg->btf;
  10348. break;
  10349. default:
  10350. verbose(env, "verifier internal error: unknown reg type for lock check\n");
  10351. return -EFAULT;
  10352. }
  10353. id = reg->id;
  10354. if (!env->cur_state->active_lock.ptr)
  10355. return -EINVAL;
  10356. if (env->cur_state->active_lock.ptr != ptr ||
  10357. env->cur_state->active_lock.id != id) {
  10358. verbose(env, "held lock and object are not in the same allocation\n");
  10359. return -EINVAL;
  10360. }
  10361. return 0;
  10362. }
  10363. static bool is_bpf_list_api_kfunc(u32 btf_id)
  10364. {
  10365. return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
  10366. btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
  10367. btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
  10368. btf_id == special_kfunc_list[KF_bpf_list_pop_back];
  10369. }
  10370. static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
  10371. {
  10372. return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
  10373. btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
  10374. btf_id == special_kfunc_list[KF_bpf_rbtree_first];
  10375. }
  10376. static bool is_bpf_graph_api_kfunc(u32 btf_id)
  10377. {
  10378. return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
  10379. btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
  10380. }
  10381. static bool is_sync_callback_calling_kfunc(u32 btf_id)
  10382. {
  10383. return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
  10384. }
  10385. static bool is_async_callback_calling_kfunc(u32 btf_id)
  10386. {
  10387. return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
  10388. }
  10389. static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
  10390. {
  10391. return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
  10392. insn->imm == special_kfunc_list[KF_bpf_throw];
  10393. }
  10394. static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
  10395. {
  10396. return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
  10397. }
  10398. static bool is_callback_calling_kfunc(u32 btf_id)
  10399. {
  10400. return is_sync_callback_calling_kfunc(btf_id) ||
  10401. is_async_callback_calling_kfunc(btf_id);
  10402. }
  10403. static bool is_rbtree_lock_required_kfunc(u32 btf_id)
  10404. {
  10405. return is_bpf_rbtree_api_kfunc(btf_id);
  10406. }
  10407. static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
  10408. enum btf_field_type head_field_type,
  10409. u32 kfunc_btf_id)
  10410. {
  10411. bool ret;
  10412. switch (head_field_type) {
  10413. case BPF_LIST_HEAD:
  10414. ret = is_bpf_list_api_kfunc(kfunc_btf_id);
  10415. break;
  10416. case BPF_RB_ROOT:
  10417. ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
  10418. break;
  10419. default:
  10420. verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
  10421. btf_field_type_name(head_field_type));
  10422. return false;
  10423. }
  10424. if (!ret)
  10425. verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
  10426. btf_field_type_name(head_field_type));
  10427. return ret;
  10428. }
  10429. static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
  10430. enum btf_field_type node_field_type,
  10431. u32 kfunc_btf_id)
  10432. {
  10433. bool ret;
  10434. switch (node_field_type) {
  10435. case BPF_LIST_NODE:
  10436. ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
  10437. kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
  10438. break;
  10439. case BPF_RB_NODE:
  10440. ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
  10441. kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
  10442. break;
  10443. default:
  10444. verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
  10445. btf_field_type_name(node_field_type));
  10446. return false;
  10447. }
  10448. if (!ret)
  10449. verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
  10450. btf_field_type_name(node_field_type));
  10451. return ret;
  10452. }
  10453. static int
  10454. __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
  10455. struct bpf_reg_state *reg, u32 regno,
  10456. struct bpf_kfunc_call_arg_meta *meta,
  10457. enum btf_field_type head_field_type,
  10458. struct btf_field **head_field)
  10459. {
  10460. const char *head_type_name;
  10461. struct btf_field *field;
  10462. struct btf_record *rec;
  10463. u32 head_off;
  10464. if (meta->btf != btf_vmlinux) {
  10465. verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
  10466. return -EFAULT;
  10467. }
  10468. if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
  10469. return -EFAULT;
  10470. head_type_name = btf_field_type_name(head_field_type);
  10471. if (!tnum_is_const(reg->var_off)) {
  10472. verbose(env,
  10473. "R%d doesn't have constant offset. %s has to be at the constant offset\n",
  10474. regno, head_type_name);
  10475. return -EINVAL;
  10476. }
  10477. rec = reg_btf_record(reg);
  10478. head_off = reg->off + reg->var_off.value;
  10479. field = btf_record_find(rec, head_off, head_field_type);
  10480. if (!field) {
  10481. verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
  10482. return -EINVAL;
  10483. }
  10484. /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
  10485. if (check_reg_allocation_locked(env, reg)) {
  10486. verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
  10487. rec->spin_lock_off, head_type_name);
  10488. return -EINVAL;
  10489. }
  10490. if (*head_field) {
  10491. verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
  10492. return -EFAULT;
  10493. }
  10494. *head_field = field;
  10495. return 0;
  10496. }
  10497. static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
  10498. struct bpf_reg_state *reg, u32 regno,
  10499. struct bpf_kfunc_call_arg_meta *meta)
  10500. {
  10501. return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
  10502. &meta->arg_list_head.field);
  10503. }
  10504. static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
  10505. struct bpf_reg_state *reg, u32 regno,
  10506. struct bpf_kfunc_call_arg_meta *meta)
  10507. {
  10508. return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
  10509. &meta->arg_rbtree_root.field);
  10510. }
  10511. static int
  10512. __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
  10513. struct bpf_reg_state *reg, u32 regno,
  10514. struct bpf_kfunc_call_arg_meta *meta,
  10515. enum btf_field_type head_field_type,
  10516. enum btf_field_type node_field_type,
  10517. struct btf_field **node_field)
  10518. {
  10519. const char *node_type_name;
  10520. const struct btf_type *et, *t;
  10521. struct btf_field *field;
  10522. u32 node_off;
  10523. if (meta->btf != btf_vmlinux) {
  10524. verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
  10525. return -EFAULT;
  10526. }
  10527. if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
  10528. return -EFAULT;
  10529. node_type_name = btf_field_type_name(node_field_type);
  10530. if (!tnum_is_const(reg->var_off)) {
  10531. verbose(env,
  10532. "R%d doesn't have constant offset. %s has to be at the constant offset\n",
  10533. regno, node_type_name);
  10534. return -EINVAL;
  10535. }
  10536. node_off = reg->off + reg->var_off.value;
  10537. field = reg_find_field_offset(reg, node_off, node_field_type);
  10538. if (!field) {
  10539. verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
  10540. return -EINVAL;
  10541. }
  10542. field = *node_field;
  10543. et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
  10544. t = btf_type_by_id(reg->btf, reg->btf_id);
  10545. if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
  10546. field->graph_root.value_btf_id, true)) {
  10547. verbose(env, "operation on %s expects arg#1 %s at offset=%d "
  10548. "in struct %s, but arg is at offset=%d in struct %s\n",
  10549. btf_field_type_name(head_field_type),
  10550. btf_field_type_name(node_field_type),
  10551. field->graph_root.node_offset,
  10552. btf_name_by_offset(field->graph_root.btf, et->name_off),
  10553. node_off, btf_name_by_offset(reg->btf, t->name_off));
  10554. return -EINVAL;
  10555. }
  10556. meta->arg_btf = reg->btf;
  10557. meta->arg_btf_id = reg->btf_id;
  10558. if (node_off != field->graph_root.node_offset) {
  10559. verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
  10560. node_off, btf_field_type_name(node_field_type),
  10561. field->graph_root.node_offset,
  10562. btf_name_by_offset(field->graph_root.btf, et->name_off));
  10563. return -EINVAL;
  10564. }
  10565. return 0;
  10566. }
  10567. static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
  10568. struct bpf_reg_state *reg, u32 regno,
  10569. struct bpf_kfunc_call_arg_meta *meta)
  10570. {
  10571. return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
  10572. BPF_LIST_HEAD, BPF_LIST_NODE,
  10573. &meta->arg_list_head.field);
  10574. }
  10575. static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
  10576. struct bpf_reg_state *reg, u32 regno,
  10577. struct bpf_kfunc_call_arg_meta *meta)
  10578. {
  10579. return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
  10580. BPF_RB_ROOT, BPF_RB_NODE,
  10581. &meta->arg_rbtree_root.field);
  10582. }
  10583. /*
  10584. * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
  10585. * LSM hooks and iters (both sleepable and non-sleepable) are safe.
  10586. * Any sleepable progs are also safe since bpf_check_attach_target() enforce
  10587. * them can only be attached to some specific hook points.
  10588. */
  10589. static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
  10590. {
  10591. enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
  10592. switch (prog_type) {
  10593. case BPF_PROG_TYPE_LSM:
  10594. return true;
  10595. case BPF_PROG_TYPE_TRACING:
  10596. if (env->prog->expected_attach_type == BPF_TRACE_ITER)
  10597. return true;
  10598. fallthrough;
  10599. default:
  10600. return in_sleepable(env);
  10601. }
  10602. }
  10603. static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
  10604. int insn_idx)
  10605. {
  10606. const char *func_name = meta->func_name, *ref_tname;
  10607. const struct btf *btf = meta->btf;
  10608. const struct btf_param *args;
  10609. struct btf_record *rec;
  10610. u32 i, nargs;
  10611. int ret;
  10612. args = (const struct btf_param *)(meta->func_proto + 1);
  10613. nargs = btf_type_vlen(meta->func_proto);
  10614. if (nargs > MAX_BPF_FUNC_REG_ARGS) {
  10615. verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
  10616. MAX_BPF_FUNC_REG_ARGS);
  10617. return -EINVAL;
  10618. }
  10619. /* Check that BTF function arguments match actual types that the
  10620. * verifier sees.
  10621. */
  10622. for (i = 0; i < nargs; i++) {
  10623. struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
  10624. const struct btf_type *t, *ref_t, *resolve_ret;
  10625. enum bpf_arg_type arg_type = ARG_DONTCARE;
  10626. u32 regno = i + 1, ref_id, type_size;
  10627. bool is_ret_buf_sz = false;
  10628. int kf_arg_type;
  10629. t = btf_type_skip_modifiers(btf, args[i].type, NULL);
  10630. if (is_kfunc_arg_ignore(btf, &args[i]))
  10631. continue;
  10632. if (btf_type_is_scalar(t)) {
  10633. if (reg->type != SCALAR_VALUE) {
  10634. verbose(env, "R%d is not a scalar\n", regno);
  10635. return -EINVAL;
  10636. }
  10637. if (is_kfunc_arg_constant(meta->btf, &args[i])) {
  10638. if (meta->arg_constant.found) {
  10639. verbose(env, "verifier internal error: only one constant argument permitted\n");
  10640. return -EFAULT;
  10641. }
  10642. if (!tnum_is_const(reg->var_off)) {
  10643. verbose(env, "R%d must be a known constant\n", regno);
  10644. return -EINVAL;
  10645. }
  10646. ret = mark_chain_precision(env, regno);
  10647. if (ret < 0)
  10648. return ret;
  10649. meta->arg_constant.found = true;
  10650. meta->arg_constant.value = reg->var_off.value;
  10651. } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
  10652. meta->r0_rdonly = true;
  10653. is_ret_buf_sz = true;
  10654. } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
  10655. is_ret_buf_sz = true;
  10656. }
  10657. if (is_ret_buf_sz) {
  10658. if (meta->r0_size) {
  10659. verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
  10660. return -EINVAL;
  10661. }
  10662. if (!tnum_is_const(reg->var_off)) {
  10663. verbose(env, "R%d is not a const\n", regno);
  10664. return -EINVAL;
  10665. }
  10666. meta->r0_size = reg->var_off.value;
  10667. ret = mark_chain_precision(env, regno);
  10668. if (ret)
  10669. return ret;
  10670. }
  10671. continue;
  10672. }
  10673. if (!btf_type_is_ptr(t)) {
  10674. verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
  10675. return -EINVAL;
  10676. }
  10677. if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
  10678. (register_is_null(reg) || type_may_be_null(reg->type)) &&
  10679. !is_kfunc_arg_nullable(meta->btf, &args[i])) {
  10680. verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
  10681. return -EACCES;
  10682. }
  10683. if (reg->ref_obj_id) {
  10684. if (is_kfunc_release(meta) && meta->ref_obj_id) {
  10685. verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
  10686. regno, reg->ref_obj_id,
  10687. meta->ref_obj_id);
  10688. return -EFAULT;
  10689. }
  10690. meta->ref_obj_id = reg->ref_obj_id;
  10691. if (is_kfunc_release(meta))
  10692. meta->release_regno = regno;
  10693. }
  10694. ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
  10695. ref_tname = btf_name_by_offset(btf, ref_t->name_off);
  10696. kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
  10697. if (kf_arg_type < 0)
  10698. return kf_arg_type;
  10699. switch (kf_arg_type) {
  10700. case KF_ARG_PTR_TO_NULL:
  10701. continue;
  10702. case KF_ARG_PTR_TO_MAP:
  10703. if (!reg->map_ptr) {
  10704. verbose(env, "pointer in R%d isn't map pointer\n", regno);
  10705. return -EINVAL;
  10706. }
  10707. if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
  10708. /* Use map_uid (which is unique id of inner map) to reject:
  10709. * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
  10710. * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
  10711. * if (inner_map1 && inner_map2) {
  10712. * wq = bpf_map_lookup_elem(inner_map1);
  10713. * if (wq)
  10714. * // mismatch would have been allowed
  10715. * bpf_wq_init(wq, inner_map2);
  10716. * }
  10717. *
  10718. * Comparing map_ptr is enough to distinguish normal and outer maps.
  10719. */
  10720. if (meta->map.ptr != reg->map_ptr ||
  10721. meta->map.uid != reg->map_uid) {
  10722. verbose(env,
  10723. "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
  10724. meta->map.uid, reg->map_uid);
  10725. return -EINVAL;
  10726. }
  10727. }
  10728. meta->map.ptr = reg->map_ptr;
  10729. meta->map.uid = reg->map_uid;
  10730. fallthrough;
  10731. case KF_ARG_PTR_TO_ALLOC_BTF_ID:
  10732. case KF_ARG_PTR_TO_BTF_ID:
  10733. if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
  10734. break;
  10735. if (!is_trusted_reg(reg)) {
  10736. if (!is_kfunc_rcu(meta)) {
  10737. verbose(env, "R%d must be referenced or trusted\n", regno);
  10738. return -EINVAL;
  10739. }
  10740. if (!is_rcu_reg(reg)) {
  10741. verbose(env, "R%d must be a rcu pointer\n", regno);
  10742. return -EINVAL;
  10743. }
  10744. }
  10745. fallthrough;
  10746. case KF_ARG_PTR_TO_CTX:
  10747. case KF_ARG_PTR_TO_DYNPTR:
  10748. case KF_ARG_PTR_TO_ITER:
  10749. case KF_ARG_PTR_TO_LIST_HEAD:
  10750. case KF_ARG_PTR_TO_LIST_NODE:
  10751. case KF_ARG_PTR_TO_RB_ROOT:
  10752. case KF_ARG_PTR_TO_RB_NODE:
  10753. case KF_ARG_PTR_TO_MEM:
  10754. case KF_ARG_PTR_TO_MEM_SIZE:
  10755. case KF_ARG_PTR_TO_CALLBACK:
  10756. case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
  10757. case KF_ARG_PTR_TO_CONST_STR:
  10758. case KF_ARG_PTR_TO_WORKQUEUE:
  10759. break;
  10760. default:
  10761. WARN_ON_ONCE(1);
  10762. return -EFAULT;
  10763. }
  10764. if (is_kfunc_release(meta) && reg->ref_obj_id)
  10765. arg_type |= OBJ_RELEASE;
  10766. ret = check_func_arg_reg_off(env, reg, regno, arg_type);
  10767. if (ret < 0)
  10768. return ret;
  10769. switch (kf_arg_type) {
  10770. case KF_ARG_PTR_TO_CTX:
  10771. if (reg->type != PTR_TO_CTX) {
  10772. verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
  10773. i, reg_type_str(env, reg->type));
  10774. return -EINVAL;
  10775. }
  10776. if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
  10777. ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
  10778. if (ret < 0)
  10779. return -EINVAL;
  10780. meta->ret_btf_id = ret;
  10781. }
  10782. break;
  10783. case KF_ARG_PTR_TO_ALLOC_BTF_ID:
  10784. if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
  10785. if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
  10786. verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
  10787. return -EINVAL;
  10788. }
  10789. } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
  10790. if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
  10791. verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
  10792. return -EINVAL;
  10793. }
  10794. } else {
  10795. verbose(env, "arg#%d expected pointer to allocated object\n", i);
  10796. return -EINVAL;
  10797. }
  10798. if (!reg->ref_obj_id) {
  10799. verbose(env, "allocated object must be referenced\n");
  10800. return -EINVAL;
  10801. }
  10802. if (meta->btf == btf_vmlinux) {
  10803. meta->arg_btf = reg->btf;
  10804. meta->arg_btf_id = reg->btf_id;
  10805. }
  10806. break;
  10807. case KF_ARG_PTR_TO_DYNPTR:
  10808. {
  10809. enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
  10810. int clone_ref_obj_id = 0;
  10811. if (reg->type == CONST_PTR_TO_DYNPTR)
  10812. dynptr_arg_type |= MEM_RDONLY;
  10813. if (is_kfunc_arg_uninit(btf, &args[i]))
  10814. dynptr_arg_type |= MEM_UNINIT;
  10815. if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
  10816. dynptr_arg_type |= DYNPTR_TYPE_SKB;
  10817. } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
  10818. dynptr_arg_type |= DYNPTR_TYPE_XDP;
  10819. } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
  10820. (dynptr_arg_type & MEM_UNINIT)) {
  10821. enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
  10822. if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
  10823. verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
  10824. return -EFAULT;
  10825. }
  10826. dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
  10827. clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
  10828. if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
  10829. verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
  10830. return -EFAULT;
  10831. }
  10832. }
  10833. ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
  10834. if (ret < 0)
  10835. return ret;
  10836. if (!(dynptr_arg_type & MEM_UNINIT)) {
  10837. int id = dynptr_id(env, reg);
  10838. if (id < 0) {
  10839. verbose(env, "verifier internal error: failed to obtain dynptr id\n");
  10840. return id;
  10841. }
  10842. meta->initialized_dynptr.id = id;
  10843. meta->initialized_dynptr.type = dynptr_get_type(env, reg);
  10844. meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
  10845. }
  10846. break;
  10847. }
  10848. case KF_ARG_PTR_TO_ITER:
  10849. if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
  10850. if (!check_css_task_iter_allowlist(env)) {
  10851. verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
  10852. return -EINVAL;
  10853. }
  10854. }
  10855. ret = process_iter_arg(env, regno, insn_idx, meta);
  10856. if (ret < 0)
  10857. return ret;
  10858. break;
  10859. case KF_ARG_PTR_TO_LIST_HEAD:
  10860. if (reg->type != PTR_TO_MAP_VALUE &&
  10861. reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
  10862. verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
  10863. return -EINVAL;
  10864. }
  10865. if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
  10866. verbose(env, "allocated object must be referenced\n");
  10867. return -EINVAL;
  10868. }
  10869. ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
  10870. if (ret < 0)
  10871. return ret;
  10872. break;
  10873. case KF_ARG_PTR_TO_RB_ROOT:
  10874. if (reg->type != PTR_TO_MAP_VALUE &&
  10875. reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
  10876. verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
  10877. return -EINVAL;
  10878. }
  10879. if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
  10880. verbose(env, "allocated object must be referenced\n");
  10881. return -EINVAL;
  10882. }
  10883. ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
  10884. if (ret < 0)
  10885. return ret;
  10886. break;
  10887. case KF_ARG_PTR_TO_LIST_NODE:
  10888. if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
  10889. verbose(env, "arg#%d expected pointer to allocated object\n", i);
  10890. return -EINVAL;
  10891. }
  10892. if (!reg->ref_obj_id) {
  10893. verbose(env, "allocated object must be referenced\n");
  10894. return -EINVAL;
  10895. }
  10896. ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
  10897. if (ret < 0)
  10898. return ret;
  10899. break;
  10900. case KF_ARG_PTR_TO_RB_NODE:
  10901. if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
  10902. if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
  10903. verbose(env, "rbtree_remove node input must be non-owning ref\n");
  10904. return -EINVAL;
  10905. }
  10906. if (in_rbtree_lock_required_cb(env)) {
  10907. verbose(env, "rbtree_remove not allowed in rbtree cb\n");
  10908. return -EINVAL;
  10909. }
  10910. } else {
  10911. if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
  10912. verbose(env, "arg#%d expected pointer to allocated object\n", i);
  10913. return -EINVAL;
  10914. }
  10915. if (!reg->ref_obj_id) {
  10916. verbose(env, "allocated object must be referenced\n");
  10917. return -EINVAL;
  10918. }
  10919. }
  10920. ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
  10921. if (ret < 0)
  10922. return ret;
  10923. break;
  10924. case KF_ARG_PTR_TO_MAP:
  10925. /* If argument has '__map' suffix expect 'struct bpf_map *' */
  10926. ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
  10927. ref_t = btf_type_by_id(btf_vmlinux, ref_id);
  10928. ref_tname = btf_name_by_offset(btf, ref_t->name_off);
  10929. fallthrough;
  10930. case KF_ARG_PTR_TO_BTF_ID:
  10931. /* Only base_type is checked, further checks are done here */
  10932. if ((base_type(reg->type) != PTR_TO_BTF_ID ||
  10933. (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
  10934. !reg2btf_ids[base_type(reg->type)]) {
  10935. verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
  10936. verbose(env, "expected %s or socket\n",
  10937. reg_type_str(env, base_type(reg->type) |
  10938. (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
  10939. return -EINVAL;
  10940. }
  10941. ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
  10942. if (ret < 0)
  10943. return ret;
  10944. break;
  10945. case KF_ARG_PTR_TO_MEM:
  10946. resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
  10947. if (IS_ERR(resolve_ret)) {
  10948. verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
  10949. i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
  10950. return -EINVAL;
  10951. }
  10952. ret = check_mem_reg(env, reg, regno, type_size);
  10953. if (ret < 0)
  10954. return ret;
  10955. break;
  10956. case KF_ARG_PTR_TO_MEM_SIZE:
  10957. {
  10958. struct bpf_reg_state *buff_reg = &regs[regno];
  10959. const struct btf_param *buff_arg = &args[i];
  10960. struct bpf_reg_state *size_reg = &regs[regno + 1];
  10961. const struct btf_param *size_arg = &args[i + 1];
  10962. if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
  10963. ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
  10964. if (ret < 0) {
  10965. verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
  10966. return ret;
  10967. }
  10968. }
  10969. if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
  10970. if (meta->arg_constant.found) {
  10971. verbose(env, "verifier internal error: only one constant argument permitted\n");
  10972. return -EFAULT;
  10973. }
  10974. if (!tnum_is_const(size_reg->var_off)) {
  10975. verbose(env, "R%d must be a known constant\n", regno + 1);
  10976. return -EINVAL;
  10977. }
  10978. meta->arg_constant.found = true;
  10979. meta->arg_constant.value = size_reg->var_off.value;
  10980. }
  10981. /* Skip next '__sz' or '__szk' argument */
  10982. i++;
  10983. break;
  10984. }
  10985. case KF_ARG_PTR_TO_CALLBACK:
  10986. if (reg->type != PTR_TO_FUNC) {
  10987. verbose(env, "arg%d expected pointer to func\n", i);
  10988. return -EINVAL;
  10989. }
  10990. meta->subprogno = reg->subprogno;
  10991. break;
  10992. case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
  10993. if (!type_is_ptr_alloc_obj(reg->type)) {
  10994. verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
  10995. return -EINVAL;
  10996. }
  10997. if (!type_is_non_owning_ref(reg->type))
  10998. meta->arg_owning_ref = true;
  10999. rec = reg_btf_record(reg);
  11000. if (!rec) {
  11001. verbose(env, "verifier internal error: Couldn't find btf_record\n");
  11002. return -EFAULT;
  11003. }
  11004. if (rec->refcount_off < 0) {
  11005. verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
  11006. return -EINVAL;
  11007. }
  11008. meta->arg_btf = reg->btf;
  11009. meta->arg_btf_id = reg->btf_id;
  11010. break;
  11011. case KF_ARG_PTR_TO_CONST_STR:
  11012. if (reg->type != PTR_TO_MAP_VALUE) {
  11013. verbose(env, "arg#%d doesn't point to a const string\n", i);
  11014. return -EINVAL;
  11015. }
  11016. ret = check_reg_const_str(env, reg, regno);
  11017. if (ret)
  11018. return ret;
  11019. break;
  11020. case KF_ARG_PTR_TO_WORKQUEUE:
  11021. if (reg->type != PTR_TO_MAP_VALUE) {
  11022. verbose(env, "arg#%d doesn't point to a map value\n", i);
  11023. return -EINVAL;
  11024. }
  11025. ret = process_wq_func(env, regno, meta);
  11026. if (ret < 0)
  11027. return ret;
  11028. break;
  11029. }
  11030. }
  11031. if (is_kfunc_release(meta) && !meta->release_regno) {
  11032. verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
  11033. func_name);
  11034. return -EINVAL;
  11035. }
  11036. return 0;
  11037. }
  11038. static int fetch_kfunc_meta(struct bpf_verifier_env *env,
  11039. struct bpf_insn *insn,
  11040. struct bpf_kfunc_call_arg_meta *meta,
  11041. const char **kfunc_name)
  11042. {
  11043. const struct btf_type *func, *func_proto;
  11044. u32 func_id, *kfunc_flags;
  11045. const char *func_name;
  11046. struct btf *desc_btf;
  11047. if (kfunc_name)
  11048. *kfunc_name = NULL;
  11049. if (!insn->imm)
  11050. return -EINVAL;
  11051. desc_btf = find_kfunc_desc_btf(env, insn->off);
  11052. if (IS_ERR(desc_btf))
  11053. return PTR_ERR(desc_btf);
  11054. func_id = insn->imm;
  11055. func = btf_type_by_id(desc_btf, func_id);
  11056. func_name = btf_name_by_offset(desc_btf, func->name_off);
  11057. if (kfunc_name)
  11058. *kfunc_name = func_name;
  11059. func_proto = btf_type_by_id(desc_btf, func->type);
  11060. kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
  11061. if (!kfunc_flags) {
  11062. return -EACCES;
  11063. }
  11064. memset(meta, 0, sizeof(*meta));
  11065. meta->btf = desc_btf;
  11066. meta->func_id = func_id;
  11067. meta->kfunc_flags = *kfunc_flags;
  11068. meta->func_proto = func_proto;
  11069. meta->func_name = func_name;
  11070. return 0;
  11071. }
  11072. static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
  11073. static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  11074. int *insn_idx_p)
  11075. {
  11076. bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
  11077. u32 i, nargs, ptr_type_id, release_ref_obj_id;
  11078. struct bpf_reg_state *regs = cur_regs(env);
  11079. const char *func_name, *ptr_type_name;
  11080. const struct btf_type *t, *ptr_type;
  11081. struct bpf_kfunc_call_arg_meta meta;
  11082. struct bpf_insn_aux_data *insn_aux;
  11083. int err, insn_idx = *insn_idx_p;
  11084. const struct btf_param *args;
  11085. const struct btf_type *ret_t;
  11086. struct btf *desc_btf;
  11087. /* skip for now, but return error when we find this in fixup_kfunc_call */
  11088. if (!insn->imm)
  11089. return 0;
  11090. err = fetch_kfunc_meta(env, insn, &meta, &func_name);
  11091. if (err == -EACCES && func_name)
  11092. verbose(env, "calling kernel function %s is not allowed\n", func_name);
  11093. if (err)
  11094. return err;
  11095. desc_btf = meta.btf;
  11096. insn_aux = &env->insn_aux_data[insn_idx];
  11097. insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
  11098. if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
  11099. verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
  11100. return -EACCES;
  11101. }
  11102. sleepable = is_kfunc_sleepable(&meta);
  11103. if (sleepable && !in_sleepable(env)) {
  11104. verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
  11105. return -EACCES;
  11106. }
  11107. /* Check the arguments */
  11108. err = check_kfunc_args(env, &meta, insn_idx);
  11109. if (err < 0)
  11110. return err;
  11111. if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
  11112. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  11113. set_rbtree_add_callback_state);
  11114. if (err) {
  11115. verbose(env, "kfunc %s#%d failed callback verification\n",
  11116. func_name, meta.func_id);
  11117. return err;
  11118. }
  11119. }
  11120. if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
  11121. meta.r0_size = sizeof(u64);
  11122. meta.r0_rdonly = false;
  11123. }
  11124. if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
  11125. err = push_callback_call(env, insn, insn_idx, meta.subprogno,
  11126. set_timer_callback_state);
  11127. if (err) {
  11128. verbose(env, "kfunc %s#%d failed callback verification\n",
  11129. func_name, meta.func_id);
  11130. return err;
  11131. }
  11132. }
  11133. rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
  11134. rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
  11135. preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
  11136. preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
  11137. if (env->cur_state->active_rcu_lock) {
  11138. struct bpf_func_state *state;
  11139. struct bpf_reg_state *reg;
  11140. u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
  11141. if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
  11142. verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
  11143. return -EACCES;
  11144. }
  11145. if (rcu_lock) {
  11146. verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
  11147. return -EINVAL;
  11148. } else if (rcu_unlock) {
  11149. bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
  11150. if (reg->type & MEM_RCU) {
  11151. reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
  11152. reg->type |= PTR_UNTRUSTED;
  11153. }
  11154. }));
  11155. env->cur_state->active_rcu_lock = false;
  11156. } else if (sleepable) {
  11157. verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
  11158. return -EACCES;
  11159. }
  11160. } else if (rcu_lock) {
  11161. env->cur_state->active_rcu_lock = true;
  11162. } else if (rcu_unlock) {
  11163. verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
  11164. return -EINVAL;
  11165. }
  11166. if (env->cur_state->active_preempt_lock) {
  11167. if (preempt_disable) {
  11168. env->cur_state->active_preempt_lock++;
  11169. } else if (preempt_enable) {
  11170. env->cur_state->active_preempt_lock--;
  11171. } else if (sleepable) {
  11172. verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
  11173. return -EACCES;
  11174. }
  11175. } else if (preempt_disable) {
  11176. env->cur_state->active_preempt_lock++;
  11177. } else if (preempt_enable) {
  11178. verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
  11179. return -EINVAL;
  11180. }
  11181. /* In case of release function, we get register number of refcounted
  11182. * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
  11183. */
  11184. if (meta.release_regno) {
  11185. err = release_reference(env, regs[meta.release_regno].ref_obj_id);
  11186. if (err) {
  11187. verbose(env, "kfunc %s#%d reference has not been acquired before\n",
  11188. func_name, meta.func_id);
  11189. return err;
  11190. }
  11191. }
  11192. if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
  11193. meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
  11194. meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
  11195. release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
  11196. insn_aux->insert_off = regs[BPF_REG_2].off;
  11197. insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
  11198. err = ref_convert_owning_non_owning(env, release_ref_obj_id);
  11199. if (err) {
  11200. verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
  11201. func_name, meta.func_id);
  11202. return err;
  11203. }
  11204. err = release_reference(env, release_ref_obj_id);
  11205. if (err) {
  11206. verbose(env, "kfunc %s#%d reference has not been acquired before\n",
  11207. func_name, meta.func_id);
  11208. return err;
  11209. }
  11210. }
  11211. if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
  11212. if (!bpf_jit_supports_exceptions()) {
  11213. verbose(env, "JIT does not support calling kfunc %s#%d\n",
  11214. func_name, meta.func_id);
  11215. return -ENOTSUPP;
  11216. }
  11217. env->seen_exception = true;
  11218. /* In the case of the default callback, the cookie value passed
  11219. * to bpf_throw becomes the return value of the program.
  11220. */
  11221. if (!env->exception_callback_subprog) {
  11222. err = check_return_code(env, BPF_REG_1, "R1");
  11223. if (err < 0)
  11224. return err;
  11225. }
  11226. }
  11227. for (i = 0; i < CALLER_SAVED_REGS; i++)
  11228. mark_reg_not_init(env, regs, caller_saved[i]);
  11229. /* Check return type */
  11230. t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
  11231. if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
  11232. /* Only exception is bpf_obj_new_impl */
  11233. if (meta.btf != btf_vmlinux ||
  11234. (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
  11235. meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
  11236. meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
  11237. verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
  11238. return -EINVAL;
  11239. }
  11240. }
  11241. if (btf_type_is_scalar(t)) {
  11242. mark_reg_unknown(env, regs, BPF_REG_0);
  11243. mark_btf_func_reg_size(env, BPF_REG_0, t->size);
  11244. } else if (btf_type_is_ptr(t)) {
  11245. ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
  11246. if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
  11247. if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
  11248. meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
  11249. struct btf_struct_meta *struct_meta;
  11250. struct btf *ret_btf;
  11251. u32 ret_btf_id;
  11252. if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
  11253. return -ENOMEM;
  11254. if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
  11255. verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
  11256. return -EINVAL;
  11257. }
  11258. ret_btf = env->prog->aux->btf;
  11259. ret_btf_id = meta.arg_constant.value;
  11260. /* This may be NULL due to user not supplying a BTF */
  11261. if (!ret_btf) {
  11262. verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
  11263. return -EINVAL;
  11264. }
  11265. ret_t = btf_type_by_id(ret_btf, ret_btf_id);
  11266. if (!ret_t || !__btf_type_is_struct(ret_t)) {
  11267. verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
  11268. return -EINVAL;
  11269. }
  11270. if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
  11271. if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
  11272. verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
  11273. ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
  11274. return -EINVAL;
  11275. }
  11276. if (!bpf_global_percpu_ma_set) {
  11277. mutex_lock(&bpf_percpu_ma_lock);
  11278. if (!bpf_global_percpu_ma_set) {
  11279. /* Charge memory allocated with bpf_global_percpu_ma to
  11280. * root memcg. The obj_cgroup for root memcg is NULL.
  11281. */
  11282. err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
  11283. if (!err)
  11284. bpf_global_percpu_ma_set = true;
  11285. }
  11286. mutex_unlock(&bpf_percpu_ma_lock);
  11287. if (err)
  11288. return err;
  11289. }
  11290. mutex_lock(&bpf_percpu_ma_lock);
  11291. err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
  11292. mutex_unlock(&bpf_percpu_ma_lock);
  11293. if (err)
  11294. return err;
  11295. }
  11296. struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
  11297. if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
  11298. if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
  11299. verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
  11300. return -EINVAL;
  11301. }
  11302. if (struct_meta) {
  11303. verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
  11304. return -EINVAL;
  11305. }
  11306. }
  11307. mark_reg_known_zero(env, regs, BPF_REG_0);
  11308. regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
  11309. regs[BPF_REG_0].btf = ret_btf;
  11310. regs[BPF_REG_0].btf_id = ret_btf_id;
  11311. if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
  11312. regs[BPF_REG_0].type |= MEM_PERCPU;
  11313. insn_aux->obj_new_size = ret_t->size;
  11314. insn_aux->kptr_struct_meta = struct_meta;
  11315. } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
  11316. mark_reg_known_zero(env, regs, BPF_REG_0);
  11317. regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
  11318. regs[BPF_REG_0].btf = meta.arg_btf;
  11319. regs[BPF_REG_0].btf_id = meta.arg_btf_id;
  11320. insn_aux->kptr_struct_meta =
  11321. btf_find_struct_meta(meta.arg_btf,
  11322. meta.arg_btf_id);
  11323. } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
  11324. meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
  11325. struct btf_field *field = meta.arg_list_head.field;
  11326. mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
  11327. } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
  11328. meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
  11329. struct btf_field *field = meta.arg_rbtree_root.field;
  11330. mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
  11331. } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
  11332. mark_reg_known_zero(env, regs, BPF_REG_0);
  11333. regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
  11334. regs[BPF_REG_0].btf = desc_btf;
  11335. regs[BPF_REG_0].btf_id = meta.ret_btf_id;
  11336. } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
  11337. ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
  11338. if (!ret_t || !btf_type_is_struct(ret_t)) {
  11339. verbose(env,
  11340. "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
  11341. return -EINVAL;
  11342. }
  11343. mark_reg_known_zero(env, regs, BPF_REG_0);
  11344. regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
  11345. regs[BPF_REG_0].btf = desc_btf;
  11346. regs[BPF_REG_0].btf_id = meta.arg_constant.value;
  11347. } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
  11348. meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
  11349. enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
  11350. mark_reg_known_zero(env, regs, BPF_REG_0);
  11351. if (!meta.arg_constant.found) {
  11352. verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
  11353. return -EFAULT;
  11354. }
  11355. regs[BPF_REG_0].mem_size = meta.arg_constant.value;
  11356. /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
  11357. regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
  11358. if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
  11359. regs[BPF_REG_0].type |= MEM_RDONLY;
  11360. } else {
  11361. /* this will set env->seen_direct_write to true */
  11362. if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
  11363. verbose(env, "the prog does not allow writes to packet data\n");
  11364. return -EINVAL;
  11365. }
  11366. }
  11367. if (!meta.initialized_dynptr.id) {
  11368. verbose(env, "verifier internal error: no dynptr id\n");
  11369. return -EFAULT;
  11370. }
  11371. regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
  11372. /* we don't need to set BPF_REG_0's ref obj id
  11373. * because packet slices are not refcounted (see
  11374. * dynptr_type_refcounted)
  11375. */
  11376. } else {
  11377. verbose(env, "kernel function %s unhandled dynamic return type\n",
  11378. meta.func_name);
  11379. return -EFAULT;
  11380. }
  11381. } else if (btf_type_is_void(ptr_type)) {
  11382. /* kfunc returning 'void *' is equivalent to returning scalar */
  11383. mark_reg_unknown(env, regs, BPF_REG_0);
  11384. } else if (!__btf_type_is_struct(ptr_type)) {
  11385. if (!meta.r0_size) {
  11386. __u32 sz;
  11387. if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
  11388. meta.r0_size = sz;
  11389. meta.r0_rdonly = true;
  11390. }
  11391. }
  11392. if (!meta.r0_size) {
  11393. ptr_type_name = btf_name_by_offset(desc_btf,
  11394. ptr_type->name_off);
  11395. verbose(env,
  11396. "kernel function %s returns pointer type %s %s is not supported\n",
  11397. func_name,
  11398. btf_type_str(ptr_type),
  11399. ptr_type_name);
  11400. return -EINVAL;
  11401. }
  11402. mark_reg_known_zero(env, regs, BPF_REG_0);
  11403. regs[BPF_REG_0].type = PTR_TO_MEM;
  11404. regs[BPF_REG_0].mem_size = meta.r0_size;
  11405. if (meta.r0_rdonly)
  11406. regs[BPF_REG_0].type |= MEM_RDONLY;
  11407. /* Ensures we don't access the memory after a release_reference() */
  11408. if (meta.ref_obj_id)
  11409. regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
  11410. } else {
  11411. mark_reg_known_zero(env, regs, BPF_REG_0);
  11412. regs[BPF_REG_0].btf = desc_btf;
  11413. regs[BPF_REG_0].type = PTR_TO_BTF_ID;
  11414. regs[BPF_REG_0].btf_id = ptr_type_id;
  11415. if (is_iter_next_kfunc(&meta)) {
  11416. struct bpf_reg_state *cur_iter;
  11417. cur_iter = get_iter_from_state(env->cur_state, &meta);
  11418. if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
  11419. regs[BPF_REG_0].type |= MEM_RCU;
  11420. else
  11421. regs[BPF_REG_0].type |= PTR_TRUSTED;
  11422. }
  11423. }
  11424. if (is_kfunc_ret_null(&meta)) {
  11425. regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
  11426. /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
  11427. regs[BPF_REG_0].id = ++env->id_gen;
  11428. }
  11429. mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
  11430. if (is_kfunc_acquire(&meta)) {
  11431. int id = acquire_reference_state(env, insn_idx);
  11432. if (id < 0)
  11433. return id;
  11434. if (is_kfunc_ret_null(&meta))
  11435. regs[BPF_REG_0].id = id;
  11436. regs[BPF_REG_0].ref_obj_id = id;
  11437. } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
  11438. ref_set_non_owning(env, &regs[BPF_REG_0]);
  11439. }
  11440. if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
  11441. regs[BPF_REG_0].id = ++env->id_gen;
  11442. } else if (btf_type_is_void(t)) {
  11443. if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
  11444. if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
  11445. meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
  11446. insn_aux->kptr_struct_meta =
  11447. btf_find_struct_meta(meta.arg_btf,
  11448. meta.arg_btf_id);
  11449. }
  11450. }
  11451. }
  11452. nargs = btf_type_vlen(meta.func_proto);
  11453. args = (const struct btf_param *)(meta.func_proto + 1);
  11454. for (i = 0; i < nargs; i++) {
  11455. u32 regno = i + 1;
  11456. t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
  11457. if (btf_type_is_ptr(t))
  11458. mark_btf_func_reg_size(env, regno, sizeof(void *));
  11459. else
  11460. /* scalar. ensured by btf_check_kfunc_arg_match() */
  11461. mark_btf_func_reg_size(env, regno, t->size);
  11462. }
  11463. if (is_iter_next_kfunc(&meta)) {
  11464. err = process_iter_next_call(env, insn_idx, &meta);
  11465. if (err)
  11466. return err;
  11467. }
  11468. return 0;
  11469. }
  11470. static bool check_reg_sane_offset(struct bpf_verifier_env *env,
  11471. const struct bpf_reg_state *reg,
  11472. enum bpf_reg_type type)
  11473. {
  11474. bool known = tnum_is_const(reg->var_off);
  11475. s64 val = reg->var_off.value;
  11476. s64 smin = reg->smin_value;
  11477. if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
  11478. verbose(env, "math between %s pointer and %lld is not allowed\n",
  11479. reg_type_str(env, type), val);
  11480. return false;
  11481. }
  11482. if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
  11483. verbose(env, "%s pointer offset %d is not allowed\n",
  11484. reg_type_str(env, type), reg->off);
  11485. return false;
  11486. }
  11487. if (smin == S64_MIN) {
  11488. verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
  11489. reg_type_str(env, type));
  11490. return false;
  11491. }
  11492. if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
  11493. verbose(env, "value %lld makes %s pointer be out of bounds\n",
  11494. smin, reg_type_str(env, type));
  11495. return false;
  11496. }
  11497. return true;
  11498. }
  11499. enum {
  11500. REASON_BOUNDS = -1,
  11501. REASON_TYPE = -2,
  11502. REASON_PATHS = -3,
  11503. REASON_LIMIT = -4,
  11504. REASON_STACK = -5,
  11505. };
  11506. static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
  11507. u32 *alu_limit, bool mask_to_left)
  11508. {
  11509. u32 max = 0, ptr_limit = 0;
  11510. switch (ptr_reg->type) {
  11511. case PTR_TO_STACK:
  11512. /* Offset 0 is out-of-bounds, but acceptable start for the
  11513. * left direction, see BPF_REG_FP. Also, unknown scalar
  11514. * offset where we would need to deal with min/max bounds is
  11515. * currently prohibited for unprivileged.
  11516. */
  11517. max = MAX_BPF_STACK + mask_to_left;
  11518. ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
  11519. break;
  11520. case PTR_TO_MAP_VALUE:
  11521. max = ptr_reg->map_ptr->value_size;
  11522. ptr_limit = (mask_to_left ?
  11523. ptr_reg->smin_value :
  11524. ptr_reg->umax_value) + ptr_reg->off;
  11525. break;
  11526. default:
  11527. return REASON_TYPE;
  11528. }
  11529. if (ptr_limit >= max)
  11530. return REASON_LIMIT;
  11531. *alu_limit = ptr_limit;
  11532. return 0;
  11533. }
  11534. static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
  11535. const struct bpf_insn *insn)
  11536. {
  11537. return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
  11538. }
  11539. static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
  11540. u32 alu_state, u32 alu_limit)
  11541. {
  11542. /* If we arrived here from different branches with different
  11543. * state or limits to sanitize, then this won't work.
  11544. */
  11545. if (aux->alu_state &&
  11546. (aux->alu_state != alu_state ||
  11547. aux->alu_limit != alu_limit))
  11548. return REASON_PATHS;
  11549. /* Corresponding fixup done in do_misc_fixups(). */
  11550. aux->alu_state = alu_state;
  11551. aux->alu_limit = alu_limit;
  11552. return 0;
  11553. }
  11554. static int sanitize_val_alu(struct bpf_verifier_env *env,
  11555. struct bpf_insn *insn)
  11556. {
  11557. struct bpf_insn_aux_data *aux = cur_aux(env);
  11558. if (can_skip_alu_sanitation(env, insn))
  11559. return 0;
  11560. return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
  11561. }
  11562. static bool sanitize_needed(u8 opcode)
  11563. {
  11564. return opcode == BPF_ADD || opcode == BPF_SUB;
  11565. }
  11566. struct bpf_sanitize_info {
  11567. struct bpf_insn_aux_data aux;
  11568. bool mask_to_left;
  11569. };
  11570. static struct bpf_verifier_state *
  11571. sanitize_speculative_path(struct bpf_verifier_env *env,
  11572. const struct bpf_insn *insn,
  11573. u32 next_idx, u32 curr_idx)
  11574. {
  11575. struct bpf_verifier_state *branch;
  11576. struct bpf_reg_state *regs;
  11577. branch = push_stack(env, next_idx, curr_idx, true);
  11578. if (branch && insn) {
  11579. regs = branch->frame[branch->curframe]->regs;
  11580. if (BPF_SRC(insn->code) == BPF_K) {
  11581. mark_reg_unknown(env, regs, insn->dst_reg);
  11582. } else if (BPF_SRC(insn->code) == BPF_X) {
  11583. mark_reg_unknown(env, regs, insn->dst_reg);
  11584. mark_reg_unknown(env, regs, insn->src_reg);
  11585. }
  11586. }
  11587. return branch;
  11588. }
  11589. static int sanitize_ptr_alu(struct bpf_verifier_env *env,
  11590. struct bpf_insn *insn,
  11591. const struct bpf_reg_state *ptr_reg,
  11592. const struct bpf_reg_state *off_reg,
  11593. struct bpf_reg_state *dst_reg,
  11594. struct bpf_sanitize_info *info,
  11595. const bool commit_window)
  11596. {
  11597. struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
  11598. struct bpf_verifier_state *vstate = env->cur_state;
  11599. bool off_is_imm = tnum_is_const(off_reg->var_off);
  11600. bool off_is_neg = off_reg->smin_value < 0;
  11601. bool ptr_is_dst_reg = ptr_reg == dst_reg;
  11602. u8 opcode = BPF_OP(insn->code);
  11603. u32 alu_state, alu_limit;
  11604. struct bpf_reg_state tmp;
  11605. bool ret;
  11606. int err;
  11607. if (can_skip_alu_sanitation(env, insn))
  11608. return 0;
  11609. /* We already marked aux for masking from non-speculative
  11610. * paths, thus we got here in the first place. We only care
  11611. * to explore bad access from here.
  11612. */
  11613. if (vstate->speculative)
  11614. goto do_sim;
  11615. if (!commit_window) {
  11616. if (!tnum_is_const(off_reg->var_off) &&
  11617. (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
  11618. return REASON_BOUNDS;
  11619. info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
  11620. (opcode == BPF_SUB && !off_is_neg);
  11621. }
  11622. err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
  11623. if (err < 0)
  11624. return err;
  11625. if (commit_window) {
  11626. /* In commit phase we narrow the masking window based on
  11627. * the observed pointer move after the simulated operation.
  11628. */
  11629. alu_state = info->aux.alu_state;
  11630. alu_limit = abs(info->aux.alu_limit - alu_limit);
  11631. } else {
  11632. alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
  11633. alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
  11634. alu_state |= ptr_is_dst_reg ?
  11635. BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
  11636. /* Limit pruning on unknown scalars to enable deep search for
  11637. * potential masking differences from other program paths.
  11638. */
  11639. if (!off_is_imm)
  11640. env->explore_alu_limits = true;
  11641. }
  11642. err = update_alu_sanitation_state(aux, alu_state, alu_limit);
  11643. if (err < 0)
  11644. return err;
  11645. do_sim:
  11646. /* If we're in commit phase, we're done here given we already
  11647. * pushed the truncated dst_reg into the speculative verification
  11648. * stack.
  11649. *
  11650. * Also, when register is a known constant, we rewrite register-based
  11651. * operation to immediate-based, and thus do not need masking (and as
  11652. * a consequence, do not need to simulate the zero-truncation either).
  11653. */
  11654. if (commit_window || off_is_imm)
  11655. return 0;
  11656. /* Simulate and find potential out-of-bounds access under
  11657. * speculative execution from truncation as a result of
  11658. * masking when off was not within expected range. If off
  11659. * sits in dst, then we temporarily need to move ptr there
  11660. * to simulate dst (== 0) +/-= ptr. Needed, for example,
  11661. * for cases where we use K-based arithmetic in one direction
  11662. * and truncated reg-based in the other in order to explore
  11663. * bad access.
  11664. */
  11665. if (!ptr_is_dst_reg) {
  11666. tmp = *dst_reg;
  11667. copy_register_state(dst_reg, ptr_reg);
  11668. }
  11669. ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
  11670. env->insn_idx);
  11671. if (!ptr_is_dst_reg && ret)
  11672. *dst_reg = tmp;
  11673. return !ret ? REASON_STACK : 0;
  11674. }
  11675. static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
  11676. {
  11677. struct bpf_verifier_state *vstate = env->cur_state;
  11678. /* If we simulate paths under speculation, we don't update the
  11679. * insn as 'seen' such that when we verify unreachable paths in
  11680. * the non-speculative domain, sanitize_dead_code() can still
  11681. * rewrite/sanitize them.
  11682. */
  11683. if (!vstate->speculative)
  11684. env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
  11685. }
  11686. static int sanitize_err(struct bpf_verifier_env *env,
  11687. const struct bpf_insn *insn, int reason,
  11688. const struct bpf_reg_state *off_reg,
  11689. const struct bpf_reg_state *dst_reg)
  11690. {
  11691. static const char *err = "pointer arithmetic with it prohibited for !root";
  11692. const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
  11693. u32 dst = insn->dst_reg, src = insn->src_reg;
  11694. switch (reason) {
  11695. case REASON_BOUNDS:
  11696. verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
  11697. off_reg == dst_reg ? dst : src, err);
  11698. break;
  11699. case REASON_TYPE:
  11700. verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
  11701. off_reg == dst_reg ? src : dst, err);
  11702. break;
  11703. case REASON_PATHS:
  11704. verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
  11705. dst, op, err);
  11706. break;
  11707. case REASON_LIMIT:
  11708. verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
  11709. dst, op, err);
  11710. break;
  11711. case REASON_STACK:
  11712. verbose(env, "R%d could not be pushed for speculative verification, %s\n",
  11713. dst, err);
  11714. break;
  11715. default:
  11716. verbose(env, "verifier internal error: unknown reason (%d)\n",
  11717. reason);
  11718. break;
  11719. }
  11720. return -EACCES;
  11721. }
  11722. /* check that stack access falls within stack limits and that 'reg' doesn't
  11723. * have a variable offset.
  11724. *
  11725. * Variable offset is prohibited for unprivileged mode for simplicity since it
  11726. * requires corresponding support in Spectre masking for stack ALU. See also
  11727. * retrieve_ptr_limit().
  11728. *
  11729. *
  11730. * 'off' includes 'reg->off'.
  11731. */
  11732. static int check_stack_access_for_ptr_arithmetic(
  11733. struct bpf_verifier_env *env,
  11734. int regno,
  11735. const struct bpf_reg_state *reg,
  11736. int off)
  11737. {
  11738. if (!tnum_is_const(reg->var_off)) {
  11739. char tn_buf[48];
  11740. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  11741. verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
  11742. regno, tn_buf, off);
  11743. return -EACCES;
  11744. }
  11745. if (off >= 0 || off < -MAX_BPF_STACK) {
  11746. verbose(env, "R%d stack pointer arithmetic goes out of range, "
  11747. "prohibited for !root; off=%d\n", regno, off);
  11748. return -EACCES;
  11749. }
  11750. return 0;
  11751. }
  11752. static int sanitize_check_bounds(struct bpf_verifier_env *env,
  11753. const struct bpf_insn *insn,
  11754. const struct bpf_reg_state *dst_reg)
  11755. {
  11756. u32 dst = insn->dst_reg;
  11757. /* For unprivileged we require that resulting offset must be in bounds
  11758. * in order to be able to sanitize access later on.
  11759. */
  11760. if (env->bypass_spec_v1)
  11761. return 0;
  11762. switch (dst_reg->type) {
  11763. case PTR_TO_STACK:
  11764. if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
  11765. dst_reg->off + dst_reg->var_off.value))
  11766. return -EACCES;
  11767. break;
  11768. case PTR_TO_MAP_VALUE:
  11769. if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
  11770. verbose(env, "R%d pointer arithmetic of map value goes out of range, "
  11771. "prohibited for !root\n", dst);
  11772. return -EACCES;
  11773. }
  11774. break;
  11775. default:
  11776. break;
  11777. }
  11778. return 0;
  11779. }
  11780. /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
  11781. * Caller should also handle BPF_MOV case separately.
  11782. * If we return -EACCES, caller may want to try again treating pointer as a
  11783. * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
  11784. */
  11785. static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
  11786. struct bpf_insn *insn,
  11787. const struct bpf_reg_state *ptr_reg,
  11788. const struct bpf_reg_state *off_reg)
  11789. {
  11790. struct bpf_verifier_state *vstate = env->cur_state;
  11791. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  11792. struct bpf_reg_state *regs = state->regs, *dst_reg;
  11793. bool known = tnum_is_const(off_reg->var_off);
  11794. s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
  11795. smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
  11796. u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
  11797. umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
  11798. struct bpf_sanitize_info info = {};
  11799. u8 opcode = BPF_OP(insn->code);
  11800. u32 dst = insn->dst_reg;
  11801. int ret;
  11802. dst_reg = &regs[dst];
  11803. if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
  11804. smin_val > smax_val || umin_val > umax_val) {
  11805. /* Taint dst register if offset had invalid bounds derived from
  11806. * e.g. dead branches.
  11807. */
  11808. __mark_reg_unknown(env, dst_reg);
  11809. return 0;
  11810. }
  11811. if (BPF_CLASS(insn->code) != BPF_ALU64) {
  11812. /* 32-bit ALU ops on pointers produce (meaningless) scalars */
  11813. if (opcode == BPF_SUB && env->allow_ptr_leaks) {
  11814. __mark_reg_unknown(env, dst_reg);
  11815. return 0;
  11816. }
  11817. verbose(env,
  11818. "R%d 32-bit pointer arithmetic prohibited\n",
  11819. dst);
  11820. return -EACCES;
  11821. }
  11822. if (ptr_reg->type & PTR_MAYBE_NULL) {
  11823. verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
  11824. dst, reg_type_str(env, ptr_reg->type));
  11825. return -EACCES;
  11826. }
  11827. switch (base_type(ptr_reg->type)) {
  11828. case PTR_TO_CTX:
  11829. case PTR_TO_MAP_VALUE:
  11830. case PTR_TO_MAP_KEY:
  11831. case PTR_TO_STACK:
  11832. case PTR_TO_PACKET_META:
  11833. case PTR_TO_PACKET:
  11834. case PTR_TO_TP_BUFFER:
  11835. case PTR_TO_BTF_ID:
  11836. case PTR_TO_MEM:
  11837. case PTR_TO_BUF:
  11838. case PTR_TO_FUNC:
  11839. case CONST_PTR_TO_DYNPTR:
  11840. break;
  11841. case PTR_TO_FLOW_KEYS:
  11842. if (known)
  11843. break;
  11844. fallthrough;
  11845. case CONST_PTR_TO_MAP:
  11846. /* smin_val represents the known value */
  11847. if (known && smin_val == 0 && opcode == BPF_ADD)
  11848. break;
  11849. fallthrough;
  11850. default:
  11851. verbose(env, "R%d pointer arithmetic on %s prohibited\n",
  11852. dst, reg_type_str(env, ptr_reg->type));
  11853. return -EACCES;
  11854. }
  11855. /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
  11856. * The id may be overwritten later if we create a new variable offset.
  11857. */
  11858. dst_reg->type = ptr_reg->type;
  11859. dst_reg->id = ptr_reg->id;
  11860. if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
  11861. !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
  11862. return -EINVAL;
  11863. /* pointer types do not carry 32-bit bounds at the moment. */
  11864. __mark_reg32_unbounded(dst_reg);
  11865. if (sanitize_needed(opcode)) {
  11866. ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
  11867. &info, false);
  11868. if (ret < 0)
  11869. return sanitize_err(env, insn, ret, off_reg, dst_reg);
  11870. }
  11871. switch (opcode) {
  11872. case BPF_ADD:
  11873. /* We can take a fixed offset as long as it doesn't overflow
  11874. * the s32 'off' field
  11875. */
  11876. if (known && (ptr_reg->off + smin_val ==
  11877. (s64)(s32)(ptr_reg->off + smin_val))) {
  11878. /* pointer += K. Accumulate it into fixed offset */
  11879. dst_reg->smin_value = smin_ptr;
  11880. dst_reg->smax_value = smax_ptr;
  11881. dst_reg->umin_value = umin_ptr;
  11882. dst_reg->umax_value = umax_ptr;
  11883. dst_reg->var_off = ptr_reg->var_off;
  11884. dst_reg->off = ptr_reg->off + smin_val;
  11885. dst_reg->raw = ptr_reg->raw;
  11886. break;
  11887. }
  11888. /* A new variable offset is created. Note that off_reg->off
  11889. * == 0, since it's a scalar.
  11890. * dst_reg gets the pointer type and since some positive
  11891. * integer value was added to the pointer, give it a new 'id'
  11892. * if it's a PTR_TO_PACKET.
  11893. * this creates a new 'base' pointer, off_reg (variable) gets
  11894. * added into the variable offset, and we copy the fixed offset
  11895. * from ptr_reg.
  11896. */
  11897. if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
  11898. check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
  11899. dst_reg->smin_value = S64_MIN;
  11900. dst_reg->smax_value = S64_MAX;
  11901. }
  11902. if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
  11903. check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
  11904. dst_reg->umin_value = 0;
  11905. dst_reg->umax_value = U64_MAX;
  11906. }
  11907. dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
  11908. dst_reg->off = ptr_reg->off;
  11909. dst_reg->raw = ptr_reg->raw;
  11910. if (reg_is_pkt_pointer(ptr_reg)) {
  11911. dst_reg->id = ++env->id_gen;
  11912. /* something was added to pkt_ptr, set range to zero */
  11913. memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
  11914. }
  11915. break;
  11916. case BPF_SUB:
  11917. if (dst_reg == off_reg) {
  11918. /* scalar -= pointer. Creates an unknown scalar */
  11919. verbose(env, "R%d tried to subtract pointer from scalar\n",
  11920. dst);
  11921. return -EACCES;
  11922. }
  11923. /* We don't allow subtraction from FP, because (according to
  11924. * test_verifier.c test "invalid fp arithmetic", JITs might not
  11925. * be able to deal with it.
  11926. */
  11927. if (ptr_reg->type == PTR_TO_STACK) {
  11928. verbose(env, "R%d subtraction from stack pointer prohibited\n",
  11929. dst);
  11930. return -EACCES;
  11931. }
  11932. if (known && (ptr_reg->off - smin_val ==
  11933. (s64)(s32)(ptr_reg->off - smin_val))) {
  11934. /* pointer -= K. Subtract it from fixed offset */
  11935. dst_reg->smin_value = smin_ptr;
  11936. dst_reg->smax_value = smax_ptr;
  11937. dst_reg->umin_value = umin_ptr;
  11938. dst_reg->umax_value = umax_ptr;
  11939. dst_reg->var_off = ptr_reg->var_off;
  11940. dst_reg->id = ptr_reg->id;
  11941. dst_reg->off = ptr_reg->off - smin_val;
  11942. dst_reg->raw = ptr_reg->raw;
  11943. break;
  11944. }
  11945. /* A new variable offset is created. If the subtrahend is known
  11946. * nonnegative, then any reg->range we had before is still good.
  11947. */
  11948. if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
  11949. check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
  11950. /* Overflow possible, we know nothing */
  11951. dst_reg->smin_value = S64_MIN;
  11952. dst_reg->smax_value = S64_MAX;
  11953. }
  11954. if (umin_ptr < umax_val) {
  11955. /* Overflow possible, we know nothing */
  11956. dst_reg->umin_value = 0;
  11957. dst_reg->umax_value = U64_MAX;
  11958. } else {
  11959. /* Cannot overflow (as long as bounds are consistent) */
  11960. dst_reg->umin_value = umin_ptr - umax_val;
  11961. dst_reg->umax_value = umax_ptr - umin_val;
  11962. }
  11963. dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
  11964. dst_reg->off = ptr_reg->off;
  11965. dst_reg->raw = ptr_reg->raw;
  11966. if (reg_is_pkt_pointer(ptr_reg)) {
  11967. dst_reg->id = ++env->id_gen;
  11968. /* something was added to pkt_ptr, set range to zero */
  11969. if (smin_val < 0)
  11970. memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
  11971. }
  11972. break;
  11973. case BPF_AND:
  11974. case BPF_OR:
  11975. case BPF_XOR:
  11976. /* bitwise ops on pointers are troublesome, prohibit. */
  11977. verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
  11978. dst, bpf_alu_string[opcode >> 4]);
  11979. return -EACCES;
  11980. default:
  11981. /* other operators (e.g. MUL,LSH) produce non-pointer results */
  11982. verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
  11983. dst, bpf_alu_string[opcode >> 4]);
  11984. return -EACCES;
  11985. }
  11986. if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
  11987. return -EINVAL;
  11988. reg_bounds_sync(dst_reg);
  11989. if (sanitize_check_bounds(env, insn, dst_reg) < 0)
  11990. return -EACCES;
  11991. if (sanitize_needed(opcode)) {
  11992. ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
  11993. &info, true);
  11994. if (ret < 0)
  11995. return sanitize_err(env, insn, ret, off_reg, dst_reg);
  11996. }
  11997. return 0;
  11998. }
  11999. static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
  12000. struct bpf_reg_state *src_reg)
  12001. {
  12002. s32 *dst_smin = &dst_reg->s32_min_value;
  12003. s32 *dst_smax = &dst_reg->s32_max_value;
  12004. u32 *dst_umin = &dst_reg->u32_min_value;
  12005. u32 *dst_umax = &dst_reg->u32_max_value;
  12006. if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
  12007. check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
  12008. *dst_smin = S32_MIN;
  12009. *dst_smax = S32_MAX;
  12010. }
  12011. if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
  12012. check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
  12013. *dst_umin = 0;
  12014. *dst_umax = U32_MAX;
  12015. }
  12016. }
  12017. static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
  12018. struct bpf_reg_state *src_reg)
  12019. {
  12020. s64 *dst_smin = &dst_reg->smin_value;
  12021. s64 *dst_smax = &dst_reg->smax_value;
  12022. u64 *dst_umin = &dst_reg->umin_value;
  12023. u64 *dst_umax = &dst_reg->umax_value;
  12024. if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
  12025. check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
  12026. *dst_smin = S64_MIN;
  12027. *dst_smax = S64_MAX;
  12028. }
  12029. if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
  12030. check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
  12031. *dst_umin = 0;
  12032. *dst_umax = U64_MAX;
  12033. }
  12034. }
  12035. static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
  12036. struct bpf_reg_state *src_reg)
  12037. {
  12038. s32 *dst_smin = &dst_reg->s32_min_value;
  12039. s32 *dst_smax = &dst_reg->s32_max_value;
  12040. u32 umin_val = src_reg->u32_min_value;
  12041. u32 umax_val = src_reg->u32_max_value;
  12042. if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
  12043. check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
  12044. /* Overflow possible, we know nothing */
  12045. *dst_smin = S32_MIN;
  12046. *dst_smax = S32_MAX;
  12047. }
  12048. if (dst_reg->u32_min_value < umax_val) {
  12049. /* Overflow possible, we know nothing */
  12050. dst_reg->u32_min_value = 0;
  12051. dst_reg->u32_max_value = U32_MAX;
  12052. } else {
  12053. /* Cannot overflow (as long as bounds are consistent) */
  12054. dst_reg->u32_min_value -= umax_val;
  12055. dst_reg->u32_max_value -= umin_val;
  12056. }
  12057. }
  12058. static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
  12059. struct bpf_reg_state *src_reg)
  12060. {
  12061. s64 *dst_smin = &dst_reg->smin_value;
  12062. s64 *dst_smax = &dst_reg->smax_value;
  12063. u64 umin_val = src_reg->umin_value;
  12064. u64 umax_val = src_reg->umax_value;
  12065. if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
  12066. check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
  12067. /* Overflow possible, we know nothing */
  12068. *dst_smin = S64_MIN;
  12069. *dst_smax = S64_MAX;
  12070. }
  12071. if (dst_reg->umin_value < umax_val) {
  12072. /* Overflow possible, we know nothing */
  12073. dst_reg->umin_value = 0;
  12074. dst_reg->umax_value = U64_MAX;
  12075. } else {
  12076. /* Cannot overflow (as long as bounds are consistent) */
  12077. dst_reg->umin_value -= umax_val;
  12078. dst_reg->umax_value -= umin_val;
  12079. }
  12080. }
  12081. static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
  12082. struct bpf_reg_state *src_reg)
  12083. {
  12084. s32 smin_val = src_reg->s32_min_value;
  12085. u32 umin_val = src_reg->u32_min_value;
  12086. u32 umax_val = src_reg->u32_max_value;
  12087. if (smin_val < 0 || dst_reg->s32_min_value < 0) {
  12088. /* Ain't nobody got time to multiply that sign */
  12089. __mark_reg32_unbounded(dst_reg);
  12090. return;
  12091. }
  12092. /* Both values are positive, so we can work with unsigned and
  12093. * copy the result to signed (unless it exceeds S32_MAX).
  12094. */
  12095. if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
  12096. /* Potential overflow, we know nothing */
  12097. __mark_reg32_unbounded(dst_reg);
  12098. return;
  12099. }
  12100. dst_reg->u32_min_value *= umin_val;
  12101. dst_reg->u32_max_value *= umax_val;
  12102. if (dst_reg->u32_max_value > S32_MAX) {
  12103. /* Overflow possible, we know nothing */
  12104. dst_reg->s32_min_value = S32_MIN;
  12105. dst_reg->s32_max_value = S32_MAX;
  12106. } else {
  12107. dst_reg->s32_min_value = dst_reg->u32_min_value;
  12108. dst_reg->s32_max_value = dst_reg->u32_max_value;
  12109. }
  12110. }
  12111. static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
  12112. struct bpf_reg_state *src_reg)
  12113. {
  12114. s64 smin_val = src_reg->smin_value;
  12115. u64 umin_val = src_reg->umin_value;
  12116. u64 umax_val = src_reg->umax_value;
  12117. if (smin_val < 0 || dst_reg->smin_value < 0) {
  12118. /* Ain't nobody got time to multiply that sign */
  12119. __mark_reg64_unbounded(dst_reg);
  12120. return;
  12121. }
  12122. /* Both values are positive, so we can work with unsigned and
  12123. * copy the result to signed (unless it exceeds S64_MAX).
  12124. */
  12125. if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
  12126. /* Potential overflow, we know nothing */
  12127. __mark_reg64_unbounded(dst_reg);
  12128. return;
  12129. }
  12130. dst_reg->umin_value *= umin_val;
  12131. dst_reg->umax_value *= umax_val;
  12132. if (dst_reg->umax_value > S64_MAX) {
  12133. /* Overflow possible, we know nothing */
  12134. dst_reg->smin_value = S64_MIN;
  12135. dst_reg->smax_value = S64_MAX;
  12136. } else {
  12137. dst_reg->smin_value = dst_reg->umin_value;
  12138. dst_reg->smax_value = dst_reg->umax_value;
  12139. }
  12140. }
  12141. static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
  12142. struct bpf_reg_state *src_reg)
  12143. {
  12144. bool src_known = tnum_subreg_is_const(src_reg->var_off);
  12145. bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
  12146. struct tnum var32_off = tnum_subreg(dst_reg->var_off);
  12147. u32 umax_val = src_reg->u32_max_value;
  12148. if (src_known && dst_known) {
  12149. __mark_reg32_known(dst_reg, var32_off.value);
  12150. return;
  12151. }
  12152. /* We get our minimum from the var_off, since that's inherently
  12153. * bitwise. Our maximum is the minimum of the operands' maxima.
  12154. */
  12155. dst_reg->u32_min_value = var32_off.value;
  12156. dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
  12157. /* Safe to set s32 bounds by casting u32 result into s32 when u32
  12158. * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
  12159. */
  12160. if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
  12161. dst_reg->s32_min_value = dst_reg->u32_min_value;
  12162. dst_reg->s32_max_value = dst_reg->u32_max_value;
  12163. } else {
  12164. dst_reg->s32_min_value = S32_MIN;
  12165. dst_reg->s32_max_value = S32_MAX;
  12166. }
  12167. }
  12168. static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
  12169. struct bpf_reg_state *src_reg)
  12170. {
  12171. bool src_known = tnum_is_const(src_reg->var_off);
  12172. bool dst_known = tnum_is_const(dst_reg->var_off);
  12173. u64 umax_val = src_reg->umax_value;
  12174. if (src_known && dst_known) {
  12175. __mark_reg_known(dst_reg, dst_reg->var_off.value);
  12176. return;
  12177. }
  12178. /* We get our minimum from the var_off, since that's inherently
  12179. * bitwise. Our maximum is the minimum of the operands' maxima.
  12180. */
  12181. dst_reg->umin_value = dst_reg->var_off.value;
  12182. dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
  12183. /* Safe to set s64 bounds by casting u64 result into s64 when u64
  12184. * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
  12185. */
  12186. if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
  12187. dst_reg->smin_value = dst_reg->umin_value;
  12188. dst_reg->smax_value = dst_reg->umax_value;
  12189. } else {
  12190. dst_reg->smin_value = S64_MIN;
  12191. dst_reg->smax_value = S64_MAX;
  12192. }
  12193. /* We may learn something more from the var_off */
  12194. __update_reg_bounds(dst_reg);
  12195. }
  12196. static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
  12197. struct bpf_reg_state *src_reg)
  12198. {
  12199. bool src_known = tnum_subreg_is_const(src_reg->var_off);
  12200. bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
  12201. struct tnum var32_off = tnum_subreg(dst_reg->var_off);
  12202. u32 umin_val = src_reg->u32_min_value;
  12203. if (src_known && dst_known) {
  12204. __mark_reg32_known(dst_reg, var32_off.value);
  12205. return;
  12206. }
  12207. /* We get our maximum from the var_off, and our minimum is the
  12208. * maximum of the operands' minima
  12209. */
  12210. dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
  12211. dst_reg->u32_max_value = var32_off.value | var32_off.mask;
  12212. /* Safe to set s32 bounds by casting u32 result into s32 when u32
  12213. * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
  12214. */
  12215. if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
  12216. dst_reg->s32_min_value = dst_reg->u32_min_value;
  12217. dst_reg->s32_max_value = dst_reg->u32_max_value;
  12218. } else {
  12219. dst_reg->s32_min_value = S32_MIN;
  12220. dst_reg->s32_max_value = S32_MAX;
  12221. }
  12222. }
  12223. static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
  12224. struct bpf_reg_state *src_reg)
  12225. {
  12226. bool src_known = tnum_is_const(src_reg->var_off);
  12227. bool dst_known = tnum_is_const(dst_reg->var_off);
  12228. u64 umin_val = src_reg->umin_value;
  12229. if (src_known && dst_known) {
  12230. __mark_reg_known(dst_reg, dst_reg->var_off.value);
  12231. return;
  12232. }
  12233. /* We get our maximum from the var_off, and our minimum is the
  12234. * maximum of the operands' minima
  12235. */
  12236. dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
  12237. dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
  12238. /* Safe to set s64 bounds by casting u64 result into s64 when u64
  12239. * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
  12240. */
  12241. if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
  12242. dst_reg->smin_value = dst_reg->umin_value;
  12243. dst_reg->smax_value = dst_reg->umax_value;
  12244. } else {
  12245. dst_reg->smin_value = S64_MIN;
  12246. dst_reg->smax_value = S64_MAX;
  12247. }
  12248. /* We may learn something more from the var_off */
  12249. __update_reg_bounds(dst_reg);
  12250. }
  12251. static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
  12252. struct bpf_reg_state *src_reg)
  12253. {
  12254. bool src_known = tnum_subreg_is_const(src_reg->var_off);
  12255. bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
  12256. struct tnum var32_off = tnum_subreg(dst_reg->var_off);
  12257. if (src_known && dst_known) {
  12258. __mark_reg32_known(dst_reg, var32_off.value);
  12259. return;
  12260. }
  12261. /* We get both minimum and maximum from the var32_off. */
  12262. dst_reg->u32_min_value = var32_off.value;
  12263. dst_reg->u32_max_value = var32_off.value | var32_off.mask;
  12264. /* Safe to set s32 bounds by casting u32 result into s32 when u32
  12265. * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
  12266. */
  12267. if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
  12268. dst_reg->s32_min_value = dst_reg->u32_min_value;
  12269. dst_reg->s32_max_value = dst_reg->u32_max_value;
  12270. } else {
  12271. dst_reg->s32_min_value = S32_MIN;
  12272. dst_reg->s32_max_value = S32_MAX;
  12273. }
  12274. }
  12275. static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
  12276. struct bpf_reg_state *src_reg)
  12277. {
  12278. bool src_known = tnum_is_const(src_reg->var_off);
  12279. bool dst_known = tnum_is_const(dst_reg->var_off);
  12280. if (src_known && dst_known) {
  12281. /* dst_reg->var_off.value has been updated earlier */
  12282. __mark_reg_known(dst_reg, dst_reg->var_off.value);
  12283. return;
  12284. }
  12285. /* We get both minimum and maximum from the var_off. */
  12286. dst_reg->umin_value = dst_reg->var_off.value;
  12287. dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
  12288. /* Safe to set s64 bounds by casting u64 result into s64 when u64
  12289. * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
  12290. */
  12291. if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
  12292. dst_reg->smin_value = dst_reg->umin_value;
  12293. dst_reg->smax_value = dst_reg->umax_value;
  12294. } else {
  12295. dst_reg->smin_value = S64_MIN;
  12296. dst_reg->smax_value = S64_MAX;
  12297. }
  12298. __update_reg_bounds(dst_reg);
  12299. }
  12300. static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
  12301. u64 umin_val, u64 umax_val)
  12302. {
  12303. /* We lose all sign bit information (except what we can pick
  12304. * up from var_off)
  12305. */
  12306. dst_reg->s32_min_value = S32_MIN;
  12307. dst_reg->s32_max_value = S32_MAX;
  12308. /* If we might shift our top bit out, then we know nothing */
  12309. if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
  12310. dst_reg->u32_min_value = 0;
  12311. dst_reg->u32_max_value = U32_MAX;
  12312. } else {
  12313. dst_reg->u32_min_value <<= umin_val;
  12314. dst_reg->u32_max_value <<= umax_val;
  12315. }
  12316. }
  12317. static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
  12318. struct bpf_reg_state *src_reg)
  12319. {
  12320. u32 umax_val = src_reg->u32_max_value;
  12321. u32 umin_val = src_reg->u32_min_value;
  12322. /* u32 alu operation will zext upper bits */
  12323. struct tnum subreg = tnum_subreg(dst_reg->var_off);
  12324. __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
  12325. dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
  12326. /* Not required but being careful mark reg64 bounds as unknown so
  12327. * that we are forced to pick them up from tnum and zext later and
  12328. * if some path skips this step we are still safe.
  12329. */
  12330. __mark_reg64_unbounded(dst_reg);
  12331. __update_reg32_bounds(dst_reg);
  12332. }
  12333. static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
  12334. u64 umin_val, u64 umax_val)
  12335. {
  12336. /* Special case <<32 because it is a common compiler pattern to sign
  12337. * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
  12338. * positive we know this shift will also be positive so we can track
  12339. * bounds correctly. Otherwise we lose all sign bit information except
  12340. * what we can pick up from var_off. Perhaps we can generalize this
  12341. * later to shifts of any length.
  12342. */
  12343. if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
  12344. dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
  12345. else
  12346. dst_reg->smax_value = S64_MAX;
  12347. if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
  12348. dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
  12349. else
  12350. dst_reg->smin_value = S64_MIN;
  12351. /* If we might shift our top bit out, then we know nothing */
  12352. if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
  12353. dst_reg->umin_value = 0;
  12354. dst_reg->umax_value = U64_MAX;
  12355. } else {
  12356. dst_reg->umin_value <<= umin_val;
  12357. dst_reg->umax_value <<= umax_val;
  12358. }
  12359. }
  12360. static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
  12361. struct bpf_reg_state *src_reg)
  12362. {
  12363. u64 umax_val = src_reg->umax_value;
  12364. u64 umin_val = src_reg->umin_value;
  12365. /* scalar64 calc uses 32bit unshifted bounds so must be called first */
  12366. __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
  12367. __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
  12368. dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
  12369. /* We may learn something more from the var_off */
  12370. __update_reg_bounds(dst_reg);
  12371. }
  12372. static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
  12373. struct bpf_reg_state *src_reg)
  12374. {
  12375. struct tnum subreg = tnum_subreg(dst_reg->var_off);
  12376. u32 umax_val = src_reg->u32_max_value;
  12377. u32 umin_val = src_reg->u32_min_value;
  12378. /* BPF_RSH is an unsigned shift. If the value in dst_reg might
  12379. * be negative, then either:
  12380. * 1) src_reg might be zero, so the sign bit of the result is
  12381. * unknown, so we lose our signed bounds
  12382. * 2) it's known negative, thus the unsigned bounds capture the
  12383. * signed bounds
  12384. * 3) the signed bounds cross zero, so they tell us nothing
  12385. * about the result
  12386. * If the value in dst_reg is known nonnegative, then again the
  12387. * unsigned bounds capture the signed bounds.
  12388. * Thus, in all cases it suffices to blow away our signed bounds
  12389. * and rely on inferring new ones from the unsigned bounds and
  12390. * var_off of the result.
  12391. */
  12392. dst_reg->s32_min_value = S32_MIN;
  12393. dst_reg->s32_max_value = S32_MAX;
  12394. dst_reg->var_off = tnum_rshift(subreg, umin_val);
  12395. dst_reg->u32_min_value >>= umax_val;
  12396. dst_reg->u32_max_value >>= umin_val;
  12397. __mark_reg64_unbounded(dst_reg);
  12398. __update_reg32_bounds(dst_reg);
  12399. }
  12400. static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
  12401. struct bpf_reg_state *src_reg)
  12402. {
  12403. u64 umax_val = src_reg->umax_value;
  12404. u64 umin_val = src_reg->umin_value;
  12405. /* BPF_RSH is an unsigned shift. If the value in dst_reg might
  12406. * be negative, then either:
  12407. * 1) src_reg might be zero, so the sign bit of the result is
  12408. * unknown, so we lose our signed bounds
  12409. * 2) it's known negative, thus the unsigned bounds capture the
  12410. * signed bounds
  12411. * 3) the signed bounds cross zero, so they tell us nothing
  12412. * about the result
  12413. * If the value in dst_reg is known nonnegative, then again the
  12414. * unsigned bounds capture the signed bounds.
  12415. * Thus, in all cases it suffices to blow away our signed bounds
  12416. * and rely on inferring new ones from the unsigned bounds and
  12417. * var_off of the result.
  12418. */
  12419. dst_reg->smin_value = S64_MIN;
  12420. dst_reg->smax_value = S64_MAX;
  12421. dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
  12422. dst_reg->umin_value >>= umax_val;
  12423. dst_reg->umax_value >>= umin_val;
  12424. /* Its not easy to operate on alu32 bounds here because it depends
  12425. * on bits being shifted in. Take easy way out and mark unbounded
  12426. * so we can recalculate later from tnum.
  12427. */
  12428. __mark_reg32_unbounded(dst_reg);
  12429. __update_reg_bounds(dst_reg);
  12430. }
  12431. static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
  12432. struct bpf_reg_state *src_reg)
  12433. {
  12434. u64 umin_val = src_reg->u32_min_value;
  12435. /* Upon reaching here, src_known is true and
  12436. * umax_val is equal to umin_val.
  12437. */
  12438. dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
  12439. dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
  12440. dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
  12441. /* blow away the dst_reg umin_value/umax_value and rely on
  12442. * dst_reg var_off to refine the result.
  12443. */
  12444. dst_reg->u32_min_value = 0;
  12445. dst_reg->u32_max_value = U32_MAX;
  12446. __mark_reg64_unbounded(dst_reg);
  12447. __update_reg32_bounds(dst_reg);
  12448. }
  12449. static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
  12450. struct bpf_reg_state *src_reg)
  12451. {
  12452. u64 umin_val = src_reg->umin_value;
  12453. /* Upon reaching here, src_known is true and umax_val is equal
  12454. * to umin_val.
  12455. */
  12456. dst_reg->smin_value >>= umin_val;
  12457. dst_reg->smax_value >>= umin_val;
  12458. dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
  12459. /* blow away the dst_reg umin_value/umax_value and rely on
  12460. * dst_reg var_off to refine the result.
  12461. */
  12462. dst_reg->umin_value = 0;
  12463. dst_reg->umax_value = U64_MAX;
  12464. /* Its not easy to operate on alu32 bounds here because it depends
  12465. * on bits being shifted in from upper 32-bits. Take easy way out
  12466. * and mark unbounded so we can recalculate later from tnum.
  12467. */
  12468. __mark_reg32_unbounded(dst_reg);
  12469. __update_reg_bounds(dst_reg);
  12470. }
  12471. static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
  12472. const struct bpf_reg_state *src_reg)
  12473. {
  12474. bool src_is_const = false;
  12475. u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
  12476. if (insn_bitness == 32) {
  12477. if (tnum_subreg_is_const(src_reg->var_off)
  12478. && src_reg->s32_min_value == src_reg->s32_max_value
  12479. && src_reg->u32_min_value == src_reg->u32_max_value)
  12480. src_is_const = true;
  12481. } else {
  12482. if (tnum_is_const(src_reg->var_off)
  12483. && src_reg->smin_value == src_reg->smax_value
  12484. && src_reg->umin_value == src_reg->umax_value)
  12485. src_is_const = true;
  12486. }
  12487. switch (BPF_OP(insn->code)) {
  12488. case BPF_ADD:
  12489. case BPF_SUB:
  12490. case BPF_AND:
  12491. case BPF_XOR:
  12492. case BPF_OR:
  12493. case BPF_MUL:
  12494. return true;
  12495. /* Shift operators range is only computable if shift dimension operand
  12496. * is a constant. Shifts greater than 31 or 63 are undefined. This
  12497. * includes shifts by a negative number.
  12498. */
  12499. case BPF_LSH:
  12500. case BPF_RSH:
  12501. case BPF_ARSH:
  12502. return (src_is_const && src_reg->umax_value < insn_bitness);
  12503. default:
  12504. return false;
  12505. }
  12506. }
  12507. /* WARNING: This function does calculations on 64-bit values, but the actual
  12508. * execution may occur on 32-bit values. Therefore, things like bitshifts
  12509. * need extra checks in the 32-bit case.
  12510. */
  12511. static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
  12512. struct bpf_insn *insn,
  12513. struct bpf_reg_state *dst_reg,
  12514. struct bpf_reg_state src_reg)
  12515. {
  12516. u8 opcode = BPF_OP(insn->code);
  12517. bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
  12518. int ret;
  12519. if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
  12520. __mark_reg_unknown(env, dst_reg);
  12521. return 0;
  12522. }
  12523. if (sanitize_needed(opcode)) {
  12524. ret = sanitize_val_alu(env, insn);
  12525. if (ret < 0)
  12526. return sanitize_err(env, insn, ret, NULL, NULL);
  12527. }
  12528. /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
  12529. * There are two classes of instructions: The first class we track both
  12530. * alu32 and alu64 sign/unsigned bounds independently this provides the
  12531. * greatest amount of precision when alu operations are mixed with jmp32
  12532. * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
  12533. * and BPF_OR. This is possible because these ops have fairly easy to
  12534. * understand and calculate behavior in both 32-bit and 64-bit alu ops.
  12535. * See alu32 verifier tests for examples. The second class of
  12536. * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
  12537. * with regards to tracking sign/unsigned bounds because the bits may
  12538. * cross subreg boundaries in the alu64 case. When this happens we mark
  12539. * the reg unbounded in the subreg bound space and use the resulting
  12540. * tnum to calculate an approximation of the sign/unsigned bounds.
  12541. */
  12542. switch (opcode) {
  12543. case BPF_ADD:
  12544. scalar32_min_max_add(dst_reg, &src_reg);
  12545. scalar_min_max_add(dst_reg, &src_reg);
  12546. dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
  12547. break;
  12548. case BPF_SUB:
  12549. scalar32_min_max_sub(dst_reg, &src_reg);
  12550. scalar_min_max_sub(dst_reg, &src_reg);
  12551. dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
  12552. break;
  12553. case BPF_MUL:
  12554. dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
  12555. scalar32_min_max_mul(dst_reg, &src_reg);
  12556. scalar_min_max_mul(dst_reg, &src_reg);
  12557. break;
  12558. case BPF_AND:
  12559. dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
  12560. scalar32_min_max_and(dst_reg, &src_reg);
  12561. scalar_min_max_and(dst_reg, &src_reg);
  12562. break;
  12563. case BPF_OR:
  12564. dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
  12565. scalar32_min_max_or(dst_reg, &src_reg);
  12566. scalar_min_max_or(dst_reg, &src_reg);
  12567. break;
  12568. case BPF_XOR:
  12569. dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
  12570. scalar32_min_max_xor(dst_reg, &src_reg);
  12571. scalar_min_max_xor(dst_reg, &src_reg);
  12572. break;
  12573. case BPF_LSH:
  12574. if (alu32)
  12575. scalar32_min_max_lsh(dst_reg, &src_reg);
  12576. else
  12577. scalar_min_max_lsh(dst_reg, &src_reg);
  12578. break;
  12579. case BPF_RSH:
  12580. if (alu32)
  12581. scalar32_min_max_rsh(dst_reg, &src_reg);
  12582. else
  12583. scalar_min_max_rsh(dst_reg, &src_reg);
  12584. break;
  12585. case BPF_ARSH:
  12586. if (alu32)
  12587. scalar32_min_max_arsh(dst_reg, &src_reg);
  12588. else
  12589. scalar_min_max_arsh(dst_reg, &src_reg);
  12590. break;
  12591. default:
  12592. break;
  12593. }
  12594. /* ALU32 ops are zero extended into 64bit register */
  12595. if (alu32)
  12596. zext_32_to_64(dst_reg);
  12597. reg_bounds_sync(dst_reg);
  12598. return 0;
  12599. }
  12600. /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
  12601. * and var_off.
  12602. */
  12603. static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
  12604. struct bpf_insn *insn)
  12605. {
  12606. struct bpf_verifier_state *vstate = env->cur_state;
  12607. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  12608. struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
  12609. struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
  12610. bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
  12611. u8 opcode = BPF_OP(insn->code);
  12612. int err;
  12613. dst_reg = &regs[insn->dst_reg];
  12614. src_reg = NULL;
  12615. if (dst_reg->type == PTR_TO_ARENA) {
  12616. struct bpf_insn_aux_data *aux = cur_aux(env);
  12617. if (BPF_CLASS(insn->code) == BPF_ALU64)
  12618. /*
  12619. * 32-bit operations zero upper bits automatically.
  12620. * 64-bit operations need to be converted to 32.
  12621. */
  12622. aux->needs_zext = true;
  12623. /* Any arithmetic operations are allowed on arena pointers */
  12624. return 0;
  12625. }
  12626. if (dst_reg->type != SCALAR_VALUE)
  12627. ptr_reg = dst_reg;
  12628. if (BPF_SRC(insn->code) == BPF_X) {
  12629. src_reg = &regs[insn->src_reg];
  12630. if (src_reg->type != SCALAR_VALUE) {
  12631. if (dst_reg->type != SCALAR_VALUE) {
  12632. /* Combining two pointers by any ALU op yields
  12633. * an arbitrary scalar. Disallow all math except
  12634. * pointer subtraction
  12635. */
  12636. if (opcode == BPF_SUB && env->allow_ptr_leaks) {
  12637. mark_reg_unknown(env, regs, insn->dst_reg);
  12638. return 0;
  12639. }
  12640. verbose(env, "R%d pointer %s pointer prohibited\n",
  12641. insn->dst_reg,
  12642. bpf_alu_string[opcode >> 4]);
  12643. return -EACCES;
  12644. } else {
  12645. /* scalar += pointer
  12646. * This is legal, but we have to reverse our
  12647. * src/dest handling in computing the range
  12648. */
  12649. err = mark_chain_precision(env, insn->dst_reg);
  12650. if (err)
  12651. return err;
  12652. return adjust_ptr_min_max_vals(env, insn,
  12653. src_reg, dst_reg);
  12654. }
  12655. } else if (ptr_reg) {
  12656. /* pointer += scalar */
  12657. err = mark_chain_precision(env, insn->src_reg);
  12658. if (err)
  12659. return err;
  12660. return adjust_ptr_min_max_vals(env, insn,
  12661. dst_reg, src_reg);
  12662. } else if (dst_reg->precise) {
  12663. /* if dst_reg is precise, src_reg should be precise as well */
  12664. err = mark_chain_precision(env, insn->src_reg);
  12665. if (err)
  12666. return err;
  12667. }
  12668. } else {
  12669. /* Pretend the src is a reg with a known value, since we only
  12670. * need to be able to read from this state.
  12671. */
  12672. off_reg.type = SCALAR_VALUE;
  12673. __mark_reg_known(&off_reg, insn->imm);
  12674. src_reg = &off_reg;
  12675. if (ptr_reg) /* pointer += K */
  12676. return adjust_ptr_min_max_vals(env, insn,
  12677. ptr_reg, src_reg);
  12678. }
  12679. /* Got here implies adding two SCALAR_VALUEs */
  12680. if (WARN_ON_ONCE(ptr_reg)) {
  12681. print_verifier_state(env, state, true);
  12682. verbose(env, "verifier internal error: unexpected ptr_reg\n");
  12683. return -EINVAL;
  12684. }
  12685. if (WARN_ON(!src_reg)) {
  12686. print_verifier_state(env, state, true);
  12687. verbose(env, "verifier internal error: no src_reg\n");
  12688. return -EINVAL;
  12689. }
  12690. err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
  12691. if (err)
  12692. return err;
  12693. /*
  12694. * Compilers can generate the code
  12695. * r1 = r2
  12696. * r1 += 0x1
  12697. * if r2 < 1000 goto ...
  12698. * use r1 in memory access
  12699. * So for 64-bit alu remember constant delta between r2 and r1 and
  12700. * update r1 after 'if' condition.
  12701. */
  12702. if (env->bpf_capable &&
  12703. BPF_OP(insn->code) == BPF_ADD && !alu32 &&
  12704. dst_reg->id && is_reg_const(src_reg, false)) {
  12705. u64 val = reg_const_value(src_reg, false);
  12706. if ((dst_reg->id & BPF_ADD_CONST) ||
  12707. /* prevent overflow in sync_linked_regs() later */
  12708. val > (u32)S32_MAX) {
  12709. /*
  12710. * If the register already went through rX += val
  12711. * we cannot accumulate another val into rx->off.
  12712. */
  12713. dst_reg->off = 0;
  12714. dst_reg->id = 0;
  12715. } else {
  12716. dst_reg->id |= BPF_ADD_CONST;
  12717. dst_reg->off = val;
  12718. }
  12719. } else {
  12720. /*
  12721. * Make sure ID is cleared otherwise dst_reg min/max could be
  12722. * incorrectly propagated into other registers by sync_linked_regs()
  12723. */
  12724. dst_reg->id = 0;
  12725. }
  12726. return 0;
  12727. }
  12728. /* check validity of 32-bit and 64-bit arithmetic operations */
  12729. static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
  12730. {
  12731. struct bpf_reg_state *regs = cur_regs(env);
  12732. u8 opcode = BPF_OP(insn->code);
  12733. int err;
  12734. if (opcode == BPF_END || opcode == BPF_NEG) {
  12735. if (opcode == BPF_NEG) {
  12736. if (BPF_SRC(insn->code) != BPF_K ||
  12737. insn->src_reg != BPF_REG_0 ||
  12738. insn->off != 0 || insn->imm != 0) {
  12739. verbose(env, "BPF_NEG uses reserved fields\n");
  12740. return -EINVAL;
  12741. }
  12742. } else {
  12743. if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
  12744. (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
  12745. (BPF_CLASS(insn->code) == BPF_ALU64 &&
  12746. BPF_SRC(insn->code) != BPF_TO_LE)) {
  12747. verbose(env, "BPF_END uses reserved fields\n");
  12748. return -EINVAL;
  12749. }
  12750. }
  12751. /* check src operand */
  12752. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  12753. if (err)
  12754. return err;
  12755. if (is_pointer_value(env, insn->dst_reg)) {
  12756. verbose(env, "R%d pointer arithmetic prohibited\n",
  12757. insn->dst_reg);
  12758. return -EACCES;
  12759. }
  12760. /* check dest operand */
  12761. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  12762. if (err)
  12763. return err;
  12764. } else if (opcode == BPF_MOV) {
  12765. if (BPF_SRC(insn->code) == BPF_X) {
  12766. if (BPF_CLASS(insn->code) == BPF_ALU) {
  12767. if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
  12768. insn->imm) {
  12769. verbose(env, "BPF_MOV uses reserved fields\n");
  12770. return -EINVAL;
  12771. }
  12772. } else if (insn->off == BPF_ADDR_SPACE_CAST) {
  12773. if (insn->imm != 1 && insn->imm != 1u << 16) {
  12774. verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
  12775. return -EINVAL;
  12776. }
  12777. if (!env->prog->aux->arena) {
  12778. verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
  12779. return -EINVAL;
  12780. }
  12781. } else {
  12782. if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
  12783. insn->off != 32) || insn->imm) {
  12784. verbose(env, "BPF_MOV uses reserved fields\n");
  12785. return -EINVAL;
  12786. }
  12787. }
  12788. /* check src operand */
  12789. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  12790. if (err)
  12791. return err;
  12792. } else {
  12793. if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
  12794. verbose(env, "BPF_MOV uses reserved fields\n");
  12795. return -EINVAL;
  12796. }
  12797. }
  12798. /* check dest operand, mark as required later */
  12799. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  12800. if (err)
  12801. return err;
  12802. if (BPF_SRC(insn->code) == BPF_X) {
  12803. struct bpf_reg_state *src_reg = regs + insn->src_reg;
  12804. struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
  12805. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  12806. if (insn->imm) {
  12807. /* off == BPF_ADDR_SPACE_CAST */
  12808. mark_reg_unknown(env, regs, insn->dst_reg);
  12809. if (insn->imm == 1) { /* cast from as(1) to as(0) */
  12810. dst_reg->type = PTR_TO_ARENA;
  12811. /* PTR_TO_ARENA is 32-bit */
  12812. dst_reg->subreg_def = env->insn_idx + 1;
  12813. }
  12814. } else if (insn->off == 0) {
  12815. /* case: R1 = R2
  12816. * copy register state to dest reg
  12817. */
  12818. assign_scalar_id_before_mov(env, src_reg);
  12819. copy_register_state(dst_reg, src_reg);
  12820. dst_reg->live |= REG_LIVE_WRITTEN;
  12821. dst_reg->subreg_def = DEF_NOT_SUBREG;
  12822. } else {
  12823. /* case: R1 = (s8, s16 s32)R2 */
  12824. if (is_pointer_value(env, insn->src_reg)) {
  12825. verbose(env,
  12826. "R%d sign-extension part of pointer\n",
  12827. insn->src_reg);
  12828. return -EACCES;
  12829. } else if (src_reg->type == SCALAR_VALUE) {
  12830. bool no_sext;
  12831. no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
  12832. if (no_sext)
  12833. assign_scalar_id_before_mov(env, src_reg);
  12834. copy_register_state(dst_reg, src_reg);
  12835. if (!no_sext)
  12836. dst_reg->id = 0;
  12837. coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
  12838. dst_reg->live |= REG_LIVE_WRITTEN;
  12839. dst_reg->subreg_def = DEF_NOT_SUBREG;
  12840. } else {
  12841. mark_reg_unknown(env, regs, insn->dst_reg);
  12842. }
  12843. }
  12844. } else {
  12845. /* R1 = (u32) R2 */
  12846. if (is_pointer_value(env, insn->src_reg)) {
  12847. verbose(env,
  12848. "R%d partial copy of pointer\n",
  12849. insn->src_reg);
  12850. return -EACCES;
  12851. } else if (src_reg->type == SCALAR_VALUE) {
  12852. if (insn->off == 0) {
  12853. bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
  12854. if (is_src_reg_u32)
  12855. assign_scalar_id_before_mov(env, src_reg);
  12856. copy_register_state(dst_reg, src_reg);
  12857. /* Make sure ID is cleared if src_reg is not in u32
  12858. * range otherwise dst_reg min/max could be incorrectly
  12859. * propagated into src_reg by sync_linked_regs()
  12860. */
  12861. if (!is_src_reg_u32)
  12862. dst_reg->id = 0;
  12863. dst_reg->live |= REG_LIVE_WRITTEN;
  12864. dst_reg->subreg_def = env->insn_idx + 1;
  12865. } else {
  12866. /* case: W1 = (s8, s16)W2 */
  12867. bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
  12868. if (no_sext)
  12869. assign_scalar_id_before_mov(env, src_reg);
  12870. copy_register_state(dst_reg, src_reg);
  12871. if (!no_sext)
  12872. dst_reg->id = 0;
  12873. dst_reg->live |= REG_LIVE_WRITTEN;
  12874. dst_reg->subreg_def = env->insn_idx + 1;
  12875. coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
  12876. }
  12877. } else {
  12878. mark_reg_unknown(env, regs,
  12879. insn->dst_reg);
  12880. }
  12881. zext_32_to_64(dst_reg);
  12882. reg_bounds_sync(dst_reg);
  12883. }
  12884. } else {
  12885. /* case: R = imm
  12886. * remember the value we stored into this reg
  12887. */
  12888. /* clear any state __mark_reg_known doesn't set */
  12889. mark_reg_unknown(env, regs, insn->dst_reg);
  12890. regs[insn->dst_reg].type = SCALAR_VALUE;
  12891. if (BPF_CLASS(insn->code) == BPF_ALU64) {
  12892. __mark_reg_known(regs + insn->dst_reg,
  12893. insn->imm);
  12894. } else {
  12895. __mark_reg_known(regs + insn->dst_reg,
  12896. (u32)insn->imm);
  12897. }
  12898. }
  12899. } else if (opcode > BPF_END) {
  12900. verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
  12901. return -EINVAL;
  12902. } else { /* all other ALU ops: and, sub, xor, add, ... */
  12903. if (BPF_SRC(insn->code) == BPF_X) {
  12904. if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
  12905. (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
  12906. verbose(env, "BPF_ALU uses reserved fields\n");
  12907. return -EINVAL;
  12908. }
  12909. /* check src1 operand */
  12910. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  12911. if (err)
  12912. return err;
  12913. } else {
  12914. if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
  12915. (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
  12916. verbose(env, "BPF_ALU uses reserved fields\n");
  12917. return -EINVAL;
  12918. }
  12919. }
  12920. /* check src2 operand */
  12921. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  12922. if (err)
  12923. return err;
  12924. if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
  12925. BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
  12926. verbose(env, "div by zero\n");
  12927. return -EINVAL;
  12928. }
  12929. if ((opcode == BPF_LSH || opcode == BPF_RSH ||
  12930. opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
  12931. int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
  12932. if (insn->imm < 0 || insn->imm >= size) {
  12933. verbose(env, "invalid shift %d\n", insn->imm);
  12934. return -EINVAL;
  12935. }
  12936. }
  12937. /* check dest operand */
  12938. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  12939. err = err ?: adjust_reg_min_max_vals(env, insn);
  12940. if (err)
  12941. return err;
  12942. }
  12943. return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
  12944. }
  12945. static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
  12946. struct bpf_reg_state *dst_reg,
  12947. enum bpf_reg_type type,
  12948. bool range_right_open)
  12949. {
  12950. struct bpf_func_state *state;
  12951. struct bpf_reg_state *reg;
  12952. int new_range;
  12953. if (dst_reg->off < 0 ||
  12954. (dst_reg->off == 0 && range_right_open))
  12955. /* This doesn't give us any range */
  12956. return;
  12957. if (dst_reg->umax_value > MAX_PACKET_OFF ||
  12958. dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
  12959. /* Risk of overflow. For instance, ptr + (1<<63) may be less
  12960. * than pkt_end, but that's because it's also less than pkt.
  12961. */
  12962. return;
  12963. new_range = dst_reg->off;
  12964. if (range_right_open)
  12965. new_range++;
  12966. /* Examples for register markings:
  12967. *
  12968. * pkt_data in dst register:
  12969. *
  12970. * r2 = r3;
  12971. * r2 += 8;
  12972. * if (r2 > pkt_end) goto <handle exception>
  12973. * <access okay>
  12974. *
  12975. * r2 = r3;
  12976. * r2 += 8;
  12977. * if (r2 < pkt_end) goto <access okay>
  12978. * <handle exception>
  12979. *
  12980. * Where:
  12981. * r2 == dst_reg, pkt_end == src_reg
  12982. * r2=pkt(id=n,off=8,r=0)
  12983. * r3=pkt(id=n,off=0,r=0)
  12984. *
  12985. * pkt_data in src register:
  12986. *
  12987. * r2 = r3;
  12988. * r2 += 8;
  12989. * if (pkt_end >= r2) goto <access okay>
  12990. * <handle exception>
  12991. *
  12992. * r2 = r3;
  12993. * r2 += 8;
  12994. * if (pkt_end <= r2) goto <handle exception>
  12995. * <access okay>
  12996. *
  12997. * Where:
  12998. * pkt_end == dst_reg, r2 == src_reg
  12999. * r2=pkt(id=n,off=8,r=0)
  13000. * r3=pkt(id=n,off=0,r=0)
  13001. *
  13002. * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
  13003. * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
  13004. * and [r3, r3 + 8-1) respectively is safe to access depending on
  13005. * the check.
  13006. */
  13007. /* If our ids match, then we must have the same max_value. And we
  13008. * don't care about the other reg's fixed offset, since if it's too big
  13009. * the range won't allow anything.
  13010. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
  13011. */
  13012. bpf_for_each_reg_in_vstate(vstate, state, reg, ({
  13013. if (reg->type == type && reg->id == dst_reg->id)
  13014. /* keep the maximum range already checked */
  13015. reg->range = max(reg->range, new_range);
  13016. }));
  13017. }
  13018. /*
  13019. * <reg1> <op> <reg2>, currently assuming reg2 is a constant
  13020. */
  13021. static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
  13022. u8 opcode, bool is_jmp32)
  13023. {
  13024. struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
  13025. struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
  13026. u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
  13027. u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
  13028. s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
  13029. s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
  13030. u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
  13031. u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
  13032. s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
  13033. s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
  13034. switch (opcode) {
  13035. case BPF_JEQ:
  13036. /* constants, umin/umax and smin/smax checks would be
  13037. * redundant in this case because they all should match
  13038. */
  13039. if (tnum_is_const(t1) && tnum_is_const(t2))
  13040. return t1.value == t2.value;
  13041. /* non-overlapping ranges */
  13042. if (umin1 > umax2 || umax1 < umin2)
  13043. return 0;
  13044. if (smin1 > smax2 || smax1 < smin2)
  13045. return 0;
  13046. if (!is_jmp32) {
  13047. /* if 64-bit ranges are inconclusive, see if we can
  13048. * utilize 32-bit subrange knowledge to eliminate
  13049. * branches that can't be taken a priori
  13050. */
  13051. if (reg1->u32_min_value > reg2->u32_max_value ||
  13052. reg1->u32_max_value < reg2->u32_min_value)
  13053. return 0;
  13054. if (reg1->s32_min_value > reg2->s32_max_value ||
  13055. reg1->s32_max_value < reg2->s32_min_value)
  13056. return 0;
  13057. }
  13058. break;
  13059. case BPF_JNE:
  13060. /* constants, umin/umax and smin/smax checks would be
  13061. * redundant in this case because they all should match
  13062. */
  13063. if (tnum_is_const(t1) && tnum_is_const(t2))
  13064. return t1.value != t2.value;
  13065. /* non-overlapping ranges */
  13066. if (umin1 > umax2 || umax1 < umin2)
  13067. return 1;
  13068. if (smin1 > smax2 || smax1 < smin2)
  13069. return 1;
  13070. if (!is_jmp32) {
  13071. /* if 64-bit ranges are inconclusive, see if we can
  13072. * utilize 32-bit subrange knowledge to eliminate
  13073. * branches that can't be taken a priori
  13074. */
  13075. if (reg1->u32_min_value > reg2->u32_max_value ||
  13076. reg1->u32_max_value < reg2->u32_min_value)
  13077. return 1;
  13078. if (reg1->s32_min_value > reg2->s32_max_value ||
  13079. reg1->s32_max_value < reg2->s32_min_value)
  13080. return 1;
  13081. }
  13082. break;
  13083. case BPF_JSET:
  13084. if (!is_reg_const(reg2, is_jmp32)) {
  13085. swap(reg1, reg2);
  13086. swap(t1, t2);
  13087. }
  13088. if (!is_reg_const(reg2, is_jmp32))
  13089. return -1;
  13090. if ((~t1.mask & t1.value) & t2.value)
  13091. return 1;
  13092. if (!((t1.mask | t1.value) & t2.value))
  13093. return 0;
  13094. break;
  13095. case BPF_JGT:
  13096. if (umin1 > umax2)
  13097. return 1;
  13098. else if (umax1 <= umin2)
  13099. return 0;
  13100. break;
  13101. case BPF_JSGT:
  13102. if (smin1 > smax2)
  13103. return 1;
  13104. else if (smax1 <= smin2)
  13105. return 0;
  13106. break;
  13107. case BPF_JLT:
  13108. if (umax1 < umin2)
  13109. return 1;
  13110. else if (umin1 >= umax2)
  13111. return 0;
  13112. break;
  13113. case BPF_JSLT:
  13114. if (smax1 < smin2)
  13115. return 1;
  13116. else if (smin1 >= smax2)
  13117. return 0;
  13118. break;
  13119. case BPF_JGE:
  13120. if (umin1 >= umax2)
  13121. return 1;
  13122. else if (umax1 < umin2)
  13123. return 0;
  13124. break;
  13125. case BPF_JSGE:
  13126. if (smin1 >= smax2)
  13127. return 1;
  13128. else if (smax1 < smin2)
  13129. return 0;
  13130. break;
  13131. case BPF_JLE:
  13132. if (umax1 <= umin2)
  13133. return 1;
  13134. else if (umin1 > umax2)
  13135. return 0;
  13136. break;
  13137. case BPF_JSLE:
  13138. if (smax1 <= smin2)
  13139. return 1;
  13140. else if (smin1 > smax2)
  13141. return 0;
  13142. break;
  13143. }
  13144. return -1;
  13145. }
  13146. static int flip_opcode(u32 opcode)
  13147. {
  13148. /* How can we transform "a <op> b" into "b <op> a"? */
  13149. static const u8 opcode_flip[16] = {
  13150. /* these stay the same */
  13151. [BPF_JEQ >> 4] = BPF_JEQ,
  13152. [BPF_JNE >> 4] = BPF_JNE,
  13153. [BPF_JSET >> 4] = BPF_JSET,
  13154. /* these swap "lesser" and "greater" (L and G in the opcodes) */
  13155. [BPF_JGE >> 4] = BPF_JLE,
  13156. [BPF_JGT >> 4] = BPF_JLT,
  13157. [BPF_JLE >> 4] = BPF_JGE,
  13158. [BPF_JLT >> 4] = BPF_JGT,
  13159. [BPF_JSGE >> 4] = BPF_JSLE,
  13160. [BPF_JSGT >> 4] = BPF_JSLT,
  13161. [BPF_JSLE >> 4] = BPF_JSGE,
  13162. [BPF_JSLT >> 4] = BPF_JSGT
  13163. };
  13164. return opcode_flip[opcode >> 4];
  13165. }
  13166. static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
  13167. struct bpf_reg_state *src_reg,
  13168. u8 opcode)
  13169. {
  13170. struct bpf_reg_state *pkt;
  13171. if (src_reg->type == PTR_TO_PACKET_END) {
  13172. pkt = dst_reg;
  13173. } else if (dst_reg->type == PTR_TO_PACKET_END) {
  13174. pkt = src_reg;
  13175. opcode = flip_opcode(opcode);
  13176. } else {
  13177. return -1;
  13178. }
  13179. if (pkt->range >= 0)
  13180. return -1;
  13181. switch (opcode) {
  13182. case BPF_JLE:
  13183. /* pkt <= pkt_end */
  13184. fallthrough;
  13185. case BPF_JGT:
  13186. /* pkt > pkt_end */
  13187. if (pkt->range == BEYOND_PKT_END)
  13188. /* pkt has at last one extra byte beyond pkt_end */
  13189. return opcode == BPF_JGT;
  13190. break;
  13191. case BPF_JLT:
  13192. /* pkt < pkt_end */
  13193. fallthrough;
  13194. case BPF_JGE:
  13195. /* pkt >= pkt_end */
  13196. if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
  13197. return opcode == BPF_JGE;
  13198. break;
  13199. }
  13200. return -1;
  13201. }
  13202. /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
  13203. * and return:
  13204. * 1 - branch will be taken and "goto target" will be executed
  13205. * 0 - branch will not be taken and fall-through to next insn
  13206. * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
  13207. * range [0,10]
  13208. */
  13209. static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
  13210. u8 opcode, bool is_jmp32)
  13211. {
  13212. if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
  13213. return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
  13214. if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
  13215. u64 val;
  13216. /* arrange that reg2 is a scalar, and reg1 is a pointer */
  13217. if (!is_reg_const(reg2, is_jmp32)) {
  13218. opcode = flip_opcode(opcode);
  13219. swap(reg1, reg2);
  13220. }
  13221. /* and ensure that reg2 is a constant */
  13222. if (!is_reg_const(reg2, is_jmp32))
  13223. return -1;
  13224. if (!reg_not_null(reg1))
  13225. return -1;
  13226. /* If pointer is valid tests against zero will fail so we can
  13227. * use this to direct branch taken.
  13228. */
  13229. val = reg_const_value(reg2, is_jmp32);
  13230. if (val != 0)
  13231. return -1;
  13232. switch (opcode) {
  13233. case BPF_JEQ:
  13234. return 0;
  13235. case BPF_JNE:
  13236. return 1;
  13237. default:
  13238. return -1;
  13239. }
  13240. }
  13241. /* now deal with two scalars, but not necessarily constants */
  13242. return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
  13243. }
  13244. /* Opcode that corresponds to a *false* branch condition.
  13245. * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
  13246. */
  13247. static u8 rev_opcode(u8 opcode)
  13248. {
  13249. switch (opcode) {
  13250. case BPF_JEQ: return BPF_JNE;
  13251. case BPF_JNE: return BPF_JEQ;
  13252. /* JSET doesn't have it's reverse opcode in BPF, so add
  13253. * BPF_X flag to denote the reverse of that operation
  13254. */
  13255. case BPF_JSET: return BPF_JSET | BPF_X;
  13256. case BPF_JSET | BPF_X: return BPF_JSET;
  13257. case BPF_JGE: return BPF_JLT;
  13258. case BPF_JGT: return BPF_JLE;
  13259. case BPF_JLE: return BPF_JGT;
  13260. case BPF_JLT: return BPF_JGE;
  13261. case BPF_JSGE: return BPF_JSLT;
  13262. case BPF_JSGT: return BPF_JSLE;
  13263. case BPF_JSLE: return BPF_JSGT;
  13264. case BPF_JSLT: return BPF_JSGE;
  13265. default: return 0;
  13266. }
  13267. }
  13268. /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
  13269. static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
  13270. u8 opcode, bool is_jmp32)
  13271. {
  13272. struct tnum t;
  13273. u64 val;
  13274. /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
  13275. switch (opcode) {
  13276. case BPF_JGE:
  13277. case BPF_JGT:
  13278. case BPF_JSGE:
  13279. case BPF_JSGT:
  13280. opcode = flip_opcode(opcode);
  13281. swap(reg1, reg2);
  13282. break;
  13283. default:
  13284. break;
  13285. }
  13286. switch (opcode) {
  13287. case BPF_JEQ:
  13288. if (is_jmp32) {
  13289. reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
  13290. reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
  13291. reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
  13292. reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
  13293. reg2->u32_min_value = reg1->u32_min_value;
  13294. reg2->u32_max_value = reg1->u32_max_value;
  13295. reg2->s32_min_value = reg1->s32_min_value;
  13296. reg2->s32_max_value = reg1->s32_max_value;
  13297. t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
  13298. reg1->var_off = tnum_with_subreg(reg1->var_off, t);
  13299. reg2->var_off = tnum_with_subreg(reg2->var_off, t);
  13300. } else {
  13301. reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
  13302. reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
  13303. reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
  13304. reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
  13305. reg2->umin_value = reg1->umin_value;
  13306. reg2->umax_value = reg1->umax_value;
  13307. reg2->smin_value = reg1->smin_value;
  13308. reg2->smax_value = reg1->smax_value;
  13309. reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
  13310. reg2->var_off = reg1->var_off;
  13311. }
  13312. break;
  13313. case BPF_JNE:
  13314. if (!is_reg_const(reg2, is_jmp32))
  13315. swap(reg1, reg2);
  13316. if (!is_reg_const(reg2, is_jmp32))
  13317. break;
  13318. /* try to recompute the bound of reg1 if reg2 is a const and
  13319. * is exactly the edge of reg1.
  13320. */
  13321. val = reg_const_value(reg2, is_jmp32);
  13322. if (is_jmp32) {
  13323. /* u32_min_value is not equal to 0xffffffff at this point,
  13324. * because otherwise u32_max_value is 0xffffffff as well,
  13325. * in such a case both reg1 and reg2 would be constants,
  13326. * jump would be predicted and reg_set_min_max() won't
  13327. * be called.
  13328. *
  13329. * Same reasoning works for all {u,s}{min,max}{32,64} cases
  13330. * below.
  13331. */
  13332. if (reg1->u32_min_value == (u32)val)
  13333. reg1->u32_min_value++;
  13334. if (reg1->u32_max_value == (u32)val)
  13335. reg1->u32_max_value--;
  13336. if (reg1->s32_min_value == (s32)val)
  13337. reg1->s32_min_value++;
  13338. if (reg1->s32_max_value == (s32)val)
  13339. reg1->s32_max_value--;
  13340. } else {
  13341. if (reg1->umin_value == (u64)val)
  13342. reg1->umin_value++;
  13343. if (reg1->umax_value == (u64)val)
  13344. reg1->umax_value--;
  13345. if (reg1->smin_value == (s64)val)
  13346. reg1->smin_value++;
  13347. if (reg1->smax_value == (s64)val)
  13348. reg1->smax_value--;
  13349. }
  13350. break;
  13351. case BPF_JSET:
  13352. if (!is_reg_const(reg2, is_jmp32))
  13353. swap(reg1, reg2);
  13354. if (!is_reg_const(reg2, is_jmp32))
  13355. break;
  13356. val = reg_const_value(reg2, is_jmp32);
  13357. /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
  13358. * requires single bit to learn something useful. E.g., if we
  13359. * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
  13360. * are actually set? We can learn something definite only if
  13361. * it's a single-bit value to begin with.
  13362. *
  13363. * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
  13364. * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
  13365. * bit 1 is set, which we can readily use in adjustments.
  13366. */
  13367. if (!is_power_of_2(val))
  13368. break;
  13369. if (is_jmp32) {
  13370. t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
  13371. reg1->var_off = tnum_with_subreg(reg1->var_off, t);
  13372. } else {
  13373. reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
  13374. }
  13375. break;
  13376. case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
  13377. if (!is_reg_const(reg2, is_jmp32))
  13378. swap(reg1, reg2);
  13379. if (!is_reg_const(reg2, is_jmp32))
  13380. break;
  13381. val = reg_const_value(reg2, is_jmp32);
  13382. /* Forget the ranges before narrowing tnums, to avoid invariant
  13383. * violations if we're on a dead branch.
  13384. */
  13385. __mark_reg_unbounded(reg1);
  13386. if (is_jmp32) {
  13387. t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
  13388. reg1->var_off = tnum_with_subreg(reg1->var_off, t);
  13389. } else {
  13390. reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
  13391. }
  13392. break;
  13393. case BPF_JLE:
  13394. if (is_jmp32) {
  13395. reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
  13396. reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
  13397. } else {
  13398. reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
  13399. reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
  13400. }
  13401. break;
  13402. case BPF_JLT:
  13403. if (is_jmp32) {
  13404. reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
  13405. reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
  13406. } else {
  13407. reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
  13408. reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
  13409. }
  13410. break;
  13411. case BPF_JSLE:
  13412. if (is_jmp32) {
  13413. reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
  13414. reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
  13415. } else {
  13416. reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
  13417. reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
  13418. }
  13419. break;
  13420. case BPF_JSLT:
  13421. if (is_jmp32) {
  13422. reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
  13423. reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
  13424. } else {
  13425. reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
  13426. reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
  13427. }
  13428. break;
  13429. default:
  13430. return;
  13431. }
  13432. }
  13433. /* Adjusts the register min/max values in the case that the dst_reg and
  13434. * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
  13435. * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
  13436. * Technically we can do similar adjustments for pointers to the same object,
  13437. * but we don't support that right now.
  13438. */
  13439. static int reg_set_min_max(struct bpf_verifier_env *env,
  13440. struct bpf_reg_state *true_reg1,
  13441. struct bpf_reg_state *true_reg2,
  13442. struct bpf_reg_state *false_reg1,
  13443. struct bpf_reg_state *false_reg2,
  13444. u8 opcode, bool is_jmp32)
  13445. {
  13446. int err;
  13447. /* If either register is a pointer, we can't learn anything about its
  13448. * variable offset from the compare (unless they were a pointer into
  13449. * the same object, but we don't bother with that).
  13450. */
  13451. if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
  13452. return 0;
  13453. /* fallthrough (FALSE) branch */
  13454. regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
  13455. reg_bounds_sync(false_reg1);
  13456. reg_bounds_sync(false_reg2);
  13457. /* jump (TRUE) branch */
  13458. regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
  13459. reg_bounds_sync(true_reg1);
  13460. reg_bounds_sync(true_reg2);
  13461. err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
  13462. err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
  13463. err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
  13464. err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
  13465. return err;
  13466. }
  13467. static void mark_ptr_or_null_reg(struct bpf_func_state *state,
  13468. struct bpf_reg_state *reg, u32 id,
  13469. bool is_null)
  13470. {
  13471. if (type_may_be_null(reg->type) && reg->id == id &&
  13472. (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
  13473. /* Old offset (both fixed and variable parts) should have been
  13474. * known-zero, because we don't allow pointer arithmetic on
  13475. * pointers that might be NULL. If we see this happening, don't
  13476. * convert the register.
  13477. *
  13478. * But in some cases, some helpers that return local kptrs
  13479. * advance offset for the returned pointer. In those cases, it
  13480. * is fine to expect to see reg->off.
  13481. */
  13482. if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
  13483. return;
  13484. if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
  13485. WARN_ON_ONCE(reg->off))
  13486. return;
  13487. if (is_null) {
  13488. reg->type = SCALAR_VALUE;
  13489. /* We don't need id and ref_obj_id from this point
  13490. * onwards anymore, thus we should better reset it,
  13491. * so that state pruning has chances to take effect.
  13492. */
  13493. reg->id = 0;
  13494. reg->ref_obj_id = 0;
  13495. return;
  13496. }
  13497. mark_ptr_not_null_reg(reg);
  13498. if (!reg_may_point_to_spin_lock(reg)) {
  13499. /* For not-NULL ptr, reg->ref_obj_id will be reset
  13500. * in release_reference().
  13501. *
  13502. * reg->id is still used by spin_lock ptr. Other
  13503. * than spin_lock ptr type, reg->id can be reset.
  13504. */
  13505. reg->id = 0;
  13506. }
  13507. }
  13508. }
  13509. /* The logic is similar to find_good_pkt_pointers(), both could eventually
  13510. * be folded together at some point.
  13511. */
  13512. static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
  13513. bool is_null)
  13514. {
  13515. struct bpf_func_state *state = vstate->frame[vstate->curframe];
  13516. struct bpf_reg_state *regs = state->regs, *reg;
  13517. u32 ref_obj_id = regs[regno].ref_obj_id;
  13518. u32 id = regs[regno].id;
  13519. if (ref_obj_id && ref_obj_id == id && is_null)
  13520. /* regs[regno] is in the " == NULL" branch.
  13521. * No one could have freed the reference state before
  13522. * doing the NULL check.
  13523. */
  13524. WARN_ON_ONCE(release_reference_state(state, id));
  13525. bpf_for_each_reg_in_vstate(vstate, state, reg, ({
  13526. mark_ptr_or_null_reg(state, reg, id, is_null);
  13527. }));
  13528. }
  13529. static bool try_match_pkt_pointers(const struct bpf_insn *insn,
  13530. struct bpf_reg_state *dst_reg,
  13531. struct bpf_reg_state *src_reg,
  13532. struct bpf_verifier_state *this_branch,
  13533. struct bpf_verifier_state *other_branch)
  13534. {
  13535. if (BPF_SRC(insn->code) != BPF_X)
  13536. return false;
  13537. /* Pointers are always 64-bit. */
  13538. if (BPF_CLASS(insn->code) == BPF_JMP32)
  13539. return false;
  13540. switch (BPF_OP(insn->code)) {
  13541. case BPF_JGT:
  13542. if ((dst_reg->type == PTR_TO_PACKET &&
  13543. src_reg->type == PTR_TO_PACKET_END) ||
  13544. (dst_reg->type == PTR_TO_PACKET_META &&
  13545. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  13546. /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
  13547. find_good_pkt_pointers(this_branch, dst_reg,
  13548. dst_reg->type, false);
  13549. mark_pkt_end(other_branch, insn->dst_reg, true);
  13550. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  13551. src_reg->type == PTR_TO_PACKET) ||
  13552. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  13553. src_reg->type == PTR_TO_PACKET_META)) {
  13554. /* pkt_end > pkt_data', pkt_data > pkt_meta' */
  13555. find_good_pkt_pointers(other_branch, src_reg,
  13556. src_reg->type, true);
  13557. mark_pkt_end(this_branch, insn->src_reg, false);
  13558. } else {
  13559. return false;
  13560. }
  13561. break;
  13562. case BPF_JLT:
  13563. if ((dst_reg->type == PTR_TO_PACKET &&
  13564. src_reg->type == PTR_TO_PACKET_END) ||
  13565. (dst_reg->type == PTR_TO_PACKET_META &&
  13566. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  13567. /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
  13568. find_good_pkt_pointers(other_branch, dst_reg,
  13569. dst_reg->type, true);
  13570. mark_pkt_end(this_branch, insn->dst_reg, false);
  13571. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  13572. src_reg->type == PTR_TO_PACKET) ||
  13573. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  13574. src_reg->type == PTR_TO_PACKET_META)) {
  13575. /* pkt_end < pkt_data', pkt_data > pkt_meta' */
  13576. find_good_pkt_pointers(this_branch, src_reg,
  13577. src_reg->type, false);
  13578. mark_pkt_end(other_branch, insn->src_reg, true);
  13579. } else {
  13580. return false;
  13581. }
  13582. break;
  13583. case BPF_JGE:
  13584. if ((dst_reg->type == PTR_TO_PACKET &&
  13585. src_reg->type == PTR_TO_PACKET_END) ||
  13586. (dst_reg->type == PTR_TO_PACKET_META &&
  13587. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  13588. /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
  13589. find_good_pkt_pointers(this_branch, dst_reg,
  13590. dst_reg->type, true);
  13591. mark_pkt_end(other_branch, insn->dst_reg, false);
  13592. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  13593. src_reg->type == PTR_TO_PACKET) ||
  13594. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  13595. src_reg->type == PTR_TO_PACKET_META)) {
  13596. /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
  13597. find_good_pkt_pointers(other_branch, src_reg,
  13598. src_reg->type, false);
  13599. mark_pkt_end(this_branch, insn->src_reg, true);
  13600. } else {
  13601. return false;
  13602. }
  13603. break;
  13604. case BPF_JLE:
  13605. if ((dst_reg->type == PTR_TO_PACKET &&
  13606. src_reg->type == PTR_TO_PACKET_END) ||
  13607. (dst_reg->type == PTR_TO_PACKET_META &&
  13608. reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
  13609. /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
  13610. find_good_pkt_pointers(other_branch, dst_reg,
  13611. dst_reg->type, false);
  13612. mark_pkt_end(this_branch, insn->dst_reg, true);
  13613. } else if ((dst_reg->type == PTR_TO_PACKET_END &&
  13614. src_reg->type == PTR_TO_PACKET) ||
  13615. (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
  13616. src_reg->type == PTR_TO_PACKET_META)) {
  13617. /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
  13618. find_good_pkt_pointers(this_branch, src_reg,
  13619. src_reg->type, true);
  13620. mark_pkt_end(other_branch, insn->src_reg, false);
  13621. } else {
  13622. return false;
  13623. }
  13624. break;
  13625. default:
  13626. return false;
  13627. }
  13628. return true;
  13629. }
  13630. static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
  13631. u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
  13632. {
  13633. struct linked_reg *e;
  13634. if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
  13635. return;
  13636. e = linked_regs_push(reg_set);
  13637. if (e) {
  13638. e->frameno = frameno;
  13639. e->is_reg = is_reg;
  13640. e->regno = spi_or_reg;
  13641. } else {
  13642. reg->id = 0;
  13643. }
  13644. }
  13645. /* For all R being scalar registers or spilled scalar registers
  13646. * in verifier state, save R in linked_regs if R->id == id.
  13647. * If there are too many Rs sharing same id, reset id for leftover Rs.
  13648. */
  13649. static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
  13650. struct linked_regs *linked_regs)
  13651. {
  13652. struct bpf_func_state *func;
  13653. struct bpf_reg_state *reg;
  13654. int i, j;
  13655. id = id & ~BPF_ADD_CONST;
  13656. for (i = vstate->curframe; i >= 0; i--) {
  13657. func = vstate->frame[i];
  13658. for (j = 0; j < BPF_REG_FP; j++) {
  13659. reg = &func->regs[j];
  13660. __collect_linked_regs(linked_regs, reg, id, i, j, true);
  13661. }
  13662. for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
  13663. if (!is_spilled_reg(&func->stack[j]))
  13664. continue;
  13665. reg = &func->stack[j].spilled_ptr;
  13666. __collect_linked_regs(linked_regs, reg, id, i, j, false);
  13667. }
  13668. }
  13669. }
  13670. /* For all R in linked_regs, copy known_reg range into R
  13671. * if R->id == known_reg->id.
  13672. */
  13673. static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
  13674. struct linked_regs *linked_regs)
  13675. {
  13676. struct bpf_reg_state fake_reg;
  13677. struct bpf_reg_state *reg;
  13678. struct linked_reg *e;
  13679. int i;
  13680. for (i = 0; i < linked_regs->cnt; ++i) {
  13681. e = &linked_regs->entries[i];
  13682. reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
  13683. : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
  13684. if (reg->type != SCALAR_VALUE || reg == known_reg)
  13685. continue;
  13686. if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
  13687. continue;
  13688. if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
  13689. reg->off == known_reg->off) {
  13690. s32 saved_subreg_def = reg->subreg_def;
  13691. copy_register_state(reg, known_reg);
  13692. reg->subreg_def = saved_subreg_def;
  13693. } else {
  13694. s32 saved_subreg_def = reg->subreg_def;
  13695. s32 saved_off = reg->off;
  13696. fake_reg.type = SCALAR_VALUE;
  13697. __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
  13698. /* reg = known_reg; reg += delta */
  13699. copy_register_state(reg, known_reg);
  13700. /*
  13701. * Must preserve off, id and add_const flag,
  13702. * otherwise another sync_linked_regs() will be incorrect.
  13703. */
  13704. reg->off = saved_off;
  13705. reg->subreg_def = saved_subreg_def;
  13706. scalar32_min_max_add(reg, &fake_reg);
  13707. scalar_min_max_add(reg, &fake_reg);
  13708. reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
  13709. }
  13710. }
  13711. }
  13712. static int check_cond_jmp_op(struct bpf_verifier_env *env,
  13713. struct bpf_insn *insn, int *insn_idx)
  13714. {
  13715. struct bpf_verifier_state *this_branch = env->cur_state;
  13716. struct bpf_verifier_state *other_branch;
  13717. struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
  13718. struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
  13719. struct bpf_reg_state *eq_branch_regs;
  13720. struct linked_regs linked_regs = {};
  13721. u8 opcode = BPF_OP(insn->code);
  13722. int insn_flags = 0;
  13723. bool is_jmp32;
  13724. int pred = -1;
  13725. int err;
  13726. /* Only conditional jumps are expected to reach here. */
  13727. if (opcode == BPF_JA || opcode > BPF_JCOND) {
  13728. verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
  13729. return -EINVAL;
  13730. }
  13731. if (opcode == BPF_JCOND) {
  13732. struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
  13733. int idx = *insn_idx;
  13734. if (insn->code != (BPF_JMP | BPF_JCOND) ||
  13735. insn->src_reg != BPF_MAY_GOTO ||
  13736. insn->dst_reg || insn->imm || insn->off == 0) {
  13737. verbose(env, "invalid may_goto off %d imm %d\n",
  13738. insn->off, insn->imm);
  13739. return -EINVAL;
  13740. }
  13741. prev_st = find_prev_entry(env, cur_st->parent, idx);
  13742. /* branch out 'fallthrough' insn as a new state to explore */
  13743. queued_st = push_stack(env, idx + 1, idx, false);
  13744. if (!queued_st)
  13745. return -ENOMEM;
  13746. queued_st->may_goto_depth++;
  13747. if (prev_st)
  13748. widen_imprecise_scalars(env, prev_st, queued_st);
  13749. *insn_idx += insn->off;
  13750. return 0;
  13751. }
  13752. /* check src2 operand */
  13753. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  13754. if (err)
  13755. return err;
  13756. dst_reg = &regs[insn->dst_reg];
  13757. if (BPF_SRC(insn->code) == BPF_X) {
  13758. if (insn->imm != 0) {
  13759. verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
  13760. return -EINVAL;
  13761. }
  13762. /* check src1 operand */
  13763. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  13764. if (err)
  13765. return err;
  13766. src_reg = &regs[insn->src_reg];
  13767. if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
  13768. is_pointer_value(env, insn->src_reg)) {
  13769. verbose(env, "R%d pointer comparison prohibited\n",
  13770. insn->src_reg);
  13771. return -EACCES;
  13772. }
  13773. if (src_reg->type == PTR_TO_STACK)
  13774. insn_flags |= INSN_F_SRC_REG_STACK;
  13775. if (dst_reg->type == PTR_TO_STACK)
  13776. insn_flags |= INSN_F_DST_REG_STACK;
  13777. } else {
  13778. if (insn->src_reg != BPF_REG_0) {
  13779. verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
  13780. return -EINVAL;
  13781. }
  13782. src_reg = &env->fake_reg[0];
  13783. memset(src_reg, 0, sizeof(*src_reg));
  13784. src_reg->type = SCALAR_VALUE;
  13785. __mark_reg_known(src_reg, insn->imm);
  13786. if (dst_reg->type == PTR_TO_STACK)
  13787. insn_flags |= INSN_F_DST_REG_STACK;
  13788. }
  13789. if (insn_flags) {
  13790. err = push_insn_history(env, this_branch, insn_flags, 0);
  13791. if (err)
  13792. return err;
  13793. }
  13794. is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
  13795. pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
  13796. if (pred >= 0) {
  13797. /* If we get here with a dst_reg pointer type it is because
  13798. * above is_branch_taken() special cased the 0 comparison.
  13799. */
  13800. if (!__is_pointer_value(false, dst_reg))
  13801. err = mark_chain_precision(env, insn->dst_reg);
  13802. if (BPF_SRC(insn->code) == BPF_X && !err &&
  13803. !__is_pointer_value(false, src_reg))
  13804. err = mark_chain_precision(env, insn->src_reg);
  13805. if (err)
  13806. return err;
  13807. }
  13808. if (pred == 1) {
  13809. /* Only follow the goto, ignore fall-through. If needed, push
  13810. * the fall-through branch for simulation under speculative
  13811. * execution.
  13812. */
  13813. if (!env->bypass_spec_v1 &&
  13814. !sanitize_speculative_path(env, insn, *insn_idx + 1,
  13815. *insn_idx))
  13816. return -EFAULT;
  13817. if (env->log.level & BPF_LOG_LEVEL)
  13818. print_insn_state(env, this_branch->frame[this_branch->curframe]);
  13819. *insn_idx += insn->off;
  13820. return 0;
  13821. } else if (pred == 0) {
  13822. /* Only follow the fall-through branch, since that's where the
  13823. * program will go. If needed, push the goto branch for
  13824. * simulation under speculative execution.
  13825. */
  13826. if (!env->bypass_spec_v1 &&
  13827. !sanitize_speculative_path(env, insn,
  13828. *insn_idx + insn->off + 1,
  13829. *insn_idx))
  13830. return -EFAULT;
  13831. if (env->log.level & BPF_LOG_LEVEL)
  13832. print_insn_state(env, this_branch->frame[this_branch->curframe]);
  13833. return 0;
  13834. }
  13835. /* Push scalar registers sharing same ID to jump history,
  13836. * do this before creating 'other_branch', so that both
  13837. * 'this_branch' and 'other_branch' share this history
  13838. * if parent state is created.
  13839. */
  13840. if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
  13841. collect_linked_regs(this_branch, src_reg->id, &linked_regs);
  13842. if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
  13843. collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
  13844. if (linked_regs.cnt > 1) {
  13845. err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
  13846. if (err)
  13847. return err;
  13848. }
  13849. other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
  13850. false);
  13851. if (!other_branch)
  13852. return -EFAULT;
  13853. other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
  13854. if (BPF_SRC(insn->code) == BPF_X) {
  13855. err = reg_set_min_max(env,
  13856. &other_branch_regs[insn->dst_reg],
  13857. &other_branch_regs[insn->src_reg],
  13858. dst_reg, src_reg, opcode, is_jmp32);
  13859. } else /* BPF_SRC(insn->code) == BPF_K */ {
  13860. /* reg_set_min_max() can mangle the fake_reg. Make a copy
  13861. * so that these are two different memory locations. The
  13862. * src_reg is not used beyond here in context of K.
  13863. */
  13864. memcpy(&env->fake_reg[1], &env->fake_reg[0],
  13865. sizeof(env->fake_reg[0]));
  13866. err = reg_set_min_max(env,
  13867. &other_branch_regs[insn->dst_reg],
  13868. &env->fake_reg[0],
  13869. dst_reg, &env->fake_reg[1],
  13870. opcode, is_jmp32);
  13871. }
  13872. if (err)
  13873. return err;
  13874. if (BPF_SRC(insn->code) == BPF_X &&
  13875. src_reg->type == SCALAR_VALUE && src_reg->id &&
  13876. !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
  13877. sync_linked_regs(this_branch, src_reg, &linked_regs);
  13878. sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
  13879. }
  13880. if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
  13881. !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
  13882. sync_linked_regs(this_branch, dst_reg, &linked_regs);
  13883. sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
  13884. }
  13885. /* if one pointer register is compared to another pointer
  13886. * register check if PTR_MAYBE_NULL could be lifted.
  13887. * E.g. register A - maybe null
  13888. * register B - not null
  13889. * for JNE A, B, ... - A is not null in the false branch;
  13890. * for JEQ A, B, ... - A is not null in the true branch.
  13891. *
  13892. * Since PTR_TO_BTF_ID points to a kernel struct that does
  13893. * not need to be null checked by the BPF program, i.e.,
  13894. * could be null even without PTR_MAYBE_NULL marking, so
  13895. * only propagate nullness when neither reg is that type.
  13896. */
  13897. if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
  13898. __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
  13899. type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
  13900. base_type(src_reg->type) != PTR_TO_BTF_ID &&
  13901. base_type(dst_reg->type) != PTR_TO_BTF_ID) {
  13902. eq_branch_regs = NULL;
  13903. switch (opcode) {
  13904. case BPF_JEQ:
  13905. eq_branch_regs = other_branch_regs;
  13906. break;
  13907. case BPF_JNE:
  13908. eq_branch_regs = regs;
  13909. break;
  13910. default:
  13911. /* do nothing */
  13912. break;
  13913. }
  13914. if (eq_branch_regs) {
  13915. if (type_may_be_null(src_reg->type))
  13916. mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
  13917. else
  13918. mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
  13919. }
  13920. }
  13921. /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
  13922. * NOTE: these optimizations below are related with pointer comparison
  13923. * which will never be JMP32.
  13924. */
  13925. if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
  13926. insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
  13927. type_may_be_null(dst_reg->type)) {
  13928. /* Mark all identical registers in each branch as either
  13929. * safe or unknown depending R == 0 or R != 0 conditional.
  13930. */
  13931. mark_ptr_or_null_regs(this_branch, insn->dst_reg,
  13932. opcode == BPF_JNE);
  13933. mark_ptr_or_null_regs(other_branch, insn->dst_reg,
  13934. opcode == BPF_JEQ);
  13935. } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
  13936. this_branch, other_branch) &&
  13937. is_pointer_value(env, insn->dst_reg)) {
  13938. verbose(env, "R%d pointer comparison prohibited\n",
  13939. insn->dst_reg);
  13940. return -EACCES;
  13941. }
  13942. if (env->log.level & BPF_LOG_LEVEL)
  13943. print_insn_state(env, this_branch->frame[this_branch->curframe]);
  13944. return 0;
  13945. }
  13946. /* verify BPF_LD_IMM64 instruction */
  13947. static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
  13948. {
  13949. struct bpf_insn_aux_data *aux = cur_aux(env);
  13950. struct bpf_reg_state *regs = cur_regs(env);
  13951. struct bpf_reg_state *dst_reg;
  13952. struct bpf_map *map;
  13953. int err;
  13954. if (BPF_SIZE(insn->code) != BPF_DW) {
  13955. verbose(env, "invalid BPF_LD_IMM insn\n");
  13956. return -EINVAL;
  13957. }
  13958. if (insn->off != 0) {
  13959. verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
  13960. return -EINVAL;
  13961. }
  13962. err = check_reg_arg(env, insn->dst_reg, DST_OP);
  13963. if (err)
  13964. return err;
  13965. dst_reg = &regs[insn->dst_reg];
  13966. if (insn->src_reg == 0) {
  13967. u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
  13968. dst_reg->type = SCALAR_VALUE;
  13969. __mark_reg_known(&regs[insn->dst_reg], imm);
  13970. return 0;
  13971. }
  13972. /* All special src_reg cases are listed below. From this point onwards
  13973. * we either succeed and assign a corresponding dst_reg->type after
  13974. * zeroing the offset, or fail and reject the program.
  13975. */
  13976. mark_reg_known_zero(env, regs, insn->dst_reg);
  13977. if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
  13978. dst_reg->type = aux->btf_var.reg_type;
  13979. switch (base_type(dst_reg->type)) {
  13980. case PTR_TO_MEM:
  13981. dst_reg->mem_size = aux->btf_var.mem_size;
  13982. break;
  13983. case PTR_TO_BTF_ID:
  13984. dst_reg->btf = aux->btf_var.btf;
  13985. dst_reg->btf_id = aux->btf_var.btf_id;
  13986. break;
  13987. default:
  13988. verbose(env, "bpf verifier is misconfigured\n");
  13989. return -EFAULT;
  13990. }
  13991. return 0;
  13992. }
  13993. if (insn->src_reg == BPF_PSEUDO_FUNC) {
  13994. struct bpf_prog_aux *aux = env->prog->aux;
  13995. u32 subprogno = find_subprog(env,
  13996. env->insn_idx + insn->imm + 1);
  13997. if (!aux->func_info) {
  13998. verbose(env, "missing btf func_info\n");
  13999. return -EINVAL;
  14000. }
  14001. if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
  14002. verbose(env, "callback function not static\n");
  14003. return -EINVAL;
  14004. }
  14005. dst_reg->type = PTR_TO_FUNC;
  14006. dst_reg->subprogno = subprogno;
  14007. return 0;
  14008. }
  14009. map = env->used_maps[aux->map_index];
  14010. dst_reg->map_ptr = map;
  14011. if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
  14012. insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
  14013. if (map->map_type == BPF_MAP_TYPE_ARENA) {
  14014. __mark_reg_unknown(env, dst_reg);
  14015. return 0;
  14016. }
  14017. dst_reg->type = PTR_TO_MAP_VALUE;
  14018. dst_reg->off = aux->map_off;
  14019. WARN_ON_ONCE(map->max_entries != 1);
  14020. /* We want reg->id to be same (0) as map_value is not distinct */
  14021. } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
  14022. insn->src_reg == BPF_PSEUDO_MAP_IDX) {
  14023. dst_reg->type = CONST_PTR_TO_MAP;
  14024. } else {
  14025. verbose(env, "bpf verifier is misconfigured\n");
  14026. return -EINVAL;
  14027. }
  14028. return 0;
  14029. }
  14030. static bool may_access_skb(enum bpf_prog_type type)
  14031. {
  14032. switch (type) {
  14033. case BPF_PROG_TYPE_SOCKET_FILTER:
  14034. case BPF_PROG_TYPE_SCHED_CLS:
  14035. case BPF_PROG_TYPE_SCHED_ACT:
  14036. return true;
  14037. default:
  14038. return false;
  14039. }
  14040. }
  14041. /* verify safety of LD_ABS|LD_IND instructions:
  14042. * - they can only appear in the programs where ctx == skb
  14043. * - since they are wrappers of function calls, they scratch R1-R5 registers,
  14044. * preserve R6-R9, and store return value into R0
  14045. *
  14046. * Implicit input:
  14047. * ctx == skb == R6 == CTX
  14048. *
  14049. * Explicit input:
  14050. * SRC == any register
  14051. * IMM == 32-bit immediate
  14052. *
  14053. * Output:
  14054. * R0 - 8/16/32-bit skb data converted to cpu endianness
  14055. */
  14056. static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
  14057. {
  14058. struct bpf_reg_state *regs = cur_regs(env);
  14059. static const int ctx_reg = BPF_REG_6;
  14060. u8 mode = BPF_MODE(insn->code);
  14061. int i, err;
  14062. if (!may_access_skb(resolve_prog_type(env->prog))) {
  14063. verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
  14064. return -EINVAL;
  14065. }
  14066. if (!env->ops->gen_ld_abs) {
  14067. verbose(env, "bpf verifier is misconfigured\n");
  14068. return -EINVAL;
  14069. }
  14070. if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
  14071. BPF_SIZE(insn->code) == BPF_DW ||
  14072. (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
  14073. verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
  14074. return -EINVAL;
  14075. }
  14076. /* check whether implicit source operand (register R6) is readable */
  14077. err = check_reg_arg(env, ctx_reg, SRC_OP);
  14078. if (err)
  14079. return err;
  14080. /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
  14081. * gen_ld_abs() may terminate the program at runtime, leading to
  14082. * reference leak.
  14083. */
  14084. err = check_reference_leak(env, false);
  14085. if (err) {
  14086. verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
  14087. return err;
  14088. }
  14089. if (env->cur_state->active_lock.ptr) {
  14090. verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
  14091. return -EINVAL;
  14092. }
  14093. if (env->cur_state->active_rcu_lock) {
  14094. verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
  14095. return -EINVAL;
  14096. }
  14097. if (env->cur_state->active_preempt_lock) {
  14098. verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n");
  14099. return -EINVAL;
  14100. }
  14101. if (regs[ctx_reg].type != PTR_TO_CTX) {
  14102. verbose(env,
  14103. "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
  14104. return -EINVAL;
  14105. }
  14106. if (mode == BPF_IND) {
  14107. /* check explicit source operand */
  14108. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  14109. if (err)
  14110. return err;
  14111. }
  14112. err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
  14113. if (err < 0)
  14114. return err;
  14115. /* reset caller saved regs to unreadable */
  14116. for (i = 0; i < CALLER_SAVED_REGS; i++) {
  14117. mark_reg_not_init(env, regs, caller_saved[i]);
  14118. check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
  14119. }
  14120. /* mark destination R0 register as readable, since it contains
  14121. * the value fetched from the packet.
  14122. * Already marked as written above.
  14123. */
  14124. mark_reg_unknown(env, regs, BPF_REG_0);
  14125. /* ld_abs load up to 32-bit skb data. */
  14126. regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
  14127. return 0;
  14128. }
  14129. static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
  14130. {
  14131. const char *exit_ctx = "At program exit";
  14132. struct tnum enforce_attach_type_range = tnum_unknown;
  14133. const struct bpf_prog *prog = env->prog;
  14134. struct bpf_reg_state *reg;
  14135. struct bpf_retval_range range = retval_range(0, 1);
  14136. enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
  14137. int err;
  14138. struct bpf_func_state *frame = env->cur_state->frame[0];
  14139. const bool is_subprog = frame->subprogno;
  14140. bool return_32bit = false;
  14141. /* LSM and struct_ops func-ptr's return type could be "void" */
  14142. if (!is_subprog || frame->in_exception_callback_fn) {
  14143. switch (prog_type) {
  14144. case BPF_PROG_TYPE_LSM:
  14145. if (prog->expected_attach_type == BPF_LSM_CGROUP)
  14146. /* See below, can be 0 or 0-1 depending on hook. */
  14147. break;
  14148. fallthrough;
  14149. case BPF_PROG_TYPE_STRUCT_OPS:
  14150. if (!prog->aux->attach_func_proto->type)
  14151. return 0;
  14152. break;
  14153. default:
  14154. break;
  14155. }
  14156. }
  14157. /* eBPF calling convention is such that R0 is used
  14158. * to return the value from eBPF program.
  14159. * Make sure that it's readable at this time
  14160. * of bpf_exit, which means that program wrote
  14161. * something into it earlier
  14162. */
  14163. err = check_reg_arg(env, regno, SRC_OP);
  14164. if (err)
  14165. return err;
  14166. if (is_pointer_value(env, regno)) {
  14167. verbose(env, "R%d leaks addr as return value\n", regno);
  14168. return -EACCES;
  14169. }
  14170. reg = cur_regs(env) + regno;
  14171. if (frame->in_async_callback_fn) {
  14172. /* enforce return zero from async callbacks like timer */
  14173. exit_ctx = "At async callback return";
  14174. range = retval_range(0, 0);
  14175. goto enforce_retval;
  14176. }
  14177. if (is_subprog && !frame->in_exception_callback_fn) {
  14178. if (reg->type != SCALAR_VALUE) {
  14179. verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
  14180. regno, reg_type_str(env, reg->type));
  14181. return -EINVAL;
  14182. }
  14183. return 0;
  14184. }
  14185. switch (prog_type) {
  14186. case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
  14187. if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
  14188. env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
  14189. env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
  14190. env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
  14191. env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
  14192. env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
  14193. env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
  14194. env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
  14195. env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
  14196. range = retval_range(1, 1);
  14197. if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
  14198. env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
  14199. range = retval_range(0, 3);
  14200. break;
  14201. case BPF_PROG_TYPE_CGROUP_SKB:
  14202. if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
  14203. range = retval_range(0, 3);
  14204. enforce_attach_type_range = tnum_range(2, 3);
  14205. }
  14206. break;
  14207. case BPF_PROG_TYPE_CGROUP_SOCK:
  14208. case BPF_PROG_TYPE_SOCK_OPS:
  14209. case BPF_PROG_TYPE_CGROUP_DEVICE:
  14210. case BPF_PROG_TYPE_CGROUP_SYSCTL:
  14211. case BPF_PROG_TYPE_CGROUP_SOCKOPT:
  14212. break;
  14213. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  14214. if (!env->prog->aux->attach_btf_id)
  14215. return 0;
  14216. range = retval_range(0, 0);
  14217. break;
  14218. case BPF_PROG_TYPE_TRACING:
  14219. switch (env->prog->expected_attach_type) {
  14220. case BPF_TRACE_FENTRY:
  14221. case BPF_TRACE_FEXIT:
  14222. range = retval_range(0, 0);
  14223. break;
  14224. case BPF_TRACE_RAW_TP:
  14225. case BPF_MODIFY_RETURN:
  14226. return 0;
  14227. case BPF_TRACE_ITER:
  14228. break;
  14229. default:
  14230. return -ENOTSUPP;
  14231. }
  14232. break;
  14233. case BPF_PROG_TYPE_KPROBE:
  14234. switch (env->prog->expected_attach_type) {
  14235. case BPF_TRACE_KPROBE_SESSION:
  14236. range = retval_range(0, 1);
  14237. break;
  14238. default:
  14239. return 0;
  14240. }
  14241. break;
  14242. case BPF_PROG_TYPE_SK_LOOKUP:
  14243. range = retval_range(SK_DROP, SK_PASS);
  14244. break;
  14245. case BPF_PROG_TYPE_LSM:
  14246. if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
  14247. /* no range found, any return value is allowed */
  14248. if (!get_func_retval_range(env->prog, &range))
  14249. return 0;
  14250. /* no restricted range, any return value is allowed */
  14251. if (range.minval == S32_MIN && range.maxval == S32_MAX)
  14252. return 0;
  14253. return_32bit = true;
  14254. } else if (!env->prog->aux->attach_func_proto->type) {
  14255. /* Make sure programs that attach to void
  14256. * hooks don't try to modify return value.
  14257. */
  14258. range = retval_range(1, 1);
  14259. }
  14260. break;
  14261. case BPF_PROG_TYPE_NETFILTER:
  14262. range = retval_range(NF_DROP, NF_ACCEPT);
  14263. break;
  14264. case BPF_PROG_TYPE_EXT:
  14265. /* freplace program can return anything as its return value
  14266. * depends on the to-be-replaced kernel func or bpf program.
  14267. */
  14268. default:
  14269. return 0;
  14270. }
  14271. enforce_retval:
  14272. if (reg->type != SCALAR_VALUE) {
  14273. verbose(env, "%s the register R%d is not a known value (%s)\n",
  14274. exit_ctx, regno, reg_type_str(env, reg->type));
  14275. return -EINVAL;
  14276. }
  14277. err = mark_chain_precision(env, regno);
  14278. if (err)
  14279. return err;
  14280. if (!retval_range_within(range, reg, return_32bit)) {
  14281. verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
  14282. if (!is_subprog &&
  14283. prog->expected_attach_type == BPF_LSM_CGROUP &&
  14284. prog_type == BPF_PROG_TYPE_LSM &&
  14285. !prog->aux->attach_func_proto->type)
  14286. verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
  14287. return -EINVAL;
  14288. }
  14289. if (!tnum_is_unknown(enforce_attach_type_range) &&
  14290. tnum_in(enforce_attach_type_range, reg->var_off))
  14291. env->prog->enforce_expected_attach_type = 1;
  14292. return 0;
  14293. }
  14294. static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
  14295. {
  14296. struct bpf_subprog_info *subprog;
  14297. subprog = find_containing_subprog(env, off);
  14298. subprog->changes_pkt_data = true;
  14299. }
  14300. /* 't' is an index of a call-site.
  14301. * 'w' is a callee entry point.
  14302. * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
  14303. * Rely on DFS traversal order and absence of recursive calls to guarantee that
  14304. * callee's change_pkt_data marks would be correct at that moment.
  14305. */
  14306. static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
  14307. {
  14308. struct bpf_subprog_info *caller, *callee;
  14309. caller = find_containing_subprog(env, t);
  14310. callee = find_containing_subprog(env, w);
  14311. caller->changes_pkt_data |= callee->changes_pkt_data;
  14312. }
  14313. /* non-recursive DFS pseudo code
  14314. * 1 procedure DFS-iterative(G,v):
  14315. * 2 label v as discovered
  14316. * 3 let S be a stack
  14317. * 4 S.push(v)
  14318. * 5 while S is not empty
  14319. * 6 t <- S.peek()
  14320. * 7 if t is what we're looking for:
  14321. * 8 return t
  14322. * 9 for all edges e in G.adjacentEdges(t) do
  14323. * 10 if edge e is already labelled
  14324. * 11 continue with the next edge
  14325. * 12 w <- G.adjacentVertex(t,e)
  14326. * 13 if vertex w is not discovered and not explored
  14327. * 14 label e as tree-edge
  14328. * 15 label w as discovered
  14329. * 16 S.push(w)
  14330. * 17 continue at 5
  14331. * 18 else if vertex w is discovered
  14332. * 19 label e as back-edge
  14333. * 20 else
  14334. * 21 // vertex w is explored
  14335. * 22 label e as forward- or cross-edge
  14336. * 23 label t as explored
  14337. * 24 S.pop()
  14338. *
  14339. * convention:
  14340. * 0x10 - discovered
  14341. * 0x11 - discovered and fall-through edge labelled
  14342. * 0x12 - discovered and fall-through and branch edges labelled
  14343. * 0x20 - explored
  14344. */
  14345. enum {
  14346. DISCOVERED = 0x10,
  14347. EXPLORED = 0x20,
  14348. FALLTHROUGH = 1,
  14349. BRANCH = 2,
  14350. };
  14351. static void mark_prune_point(struct bpf_verifier_env *env, int idx)
  14352. {
  14353. env->insn_aux_data[idx].prune_point = true;
  14354. }
  14355. static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
  14356. {
  14357. return env->insn_aux_data[insn_idx].prune_point;
  14358. }
  14359. static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
  14360. {
  14361. env->insn_aux_data[idx].force_checkpoint = true;
  14362. }
  14363. static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
  14364. {
  14365. return env->insn_aux_data[insn_idx].force_checkpoint;
  14366. }
  14367. static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
  14368. {
  14369. env->insn_aux_data[idx].calls_callback = true;
  14370. }
  14371. static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
  14372. {
  14373. return env->insn_aux_data[insn_idx].calls_callback;
  14374. }
  14375. enum {
  14376. DONE_EXPLORING = 0,
  14377. KEEP_EXPLORING = 1,
  14378. };
  14379. /* t, w, e - match pseudo-code above:
  14380. * t - index of current instruction
  14381. * w - next instruction
  14382. * e - edge
  14383. */
  14384. static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
  14385. {
  14386. int *insn_stack = env->cfg.insn_stack;
  14387. int *insn_state = env->cfg.insn_state;
  14388. if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
  14389. return DONE_EXPLORING;
  14390. if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
  14391. return DONE_EXPLORING;
  14392. if (w < 0 || w >= env->prog->len) {
  14393. verbose_linfo(env, t, "%d: ", t);
  14394. verbose(env, "jump out of range from insn %d to %d\n", t, w);
  14395. return -EINVAL;
  14396. }
  14397. if (e == BRANCH) {
  14398. /* mark branch target for state pruning */
  14399. mark_prune_point(env, w);
  14400. mark_jmp_point(env, w);
  14401. }
  14402. if (insn_state[w] == 0) {
  14403. /* tree-edge */
  14404. insn_state[t] = DISCOVERED | e;
  14405. insn_state[w] = DISCOVERED;
  14406. if (env->cfg.cur_stack >= env->prog->len)
  14407. return -E2BIG;
  14408. insn_stack[env->cfg.cur_stack++] = w;
  14409. return KEEP_EXPLORING;
  14410. } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
  14411. if (env->bpf_capable)
  14412. return DONE_EXPLORING;
  14413. verbose_linfo(env, t, "%d: ", t);
  14414. verbose_linfo(env, w, "%d: ", w);
  14415. verbose(env, "back-edge from insn %d to %d\n", t, w);
  14416. return -EINVAL;
  14417. } else if (insn_state[w] == EXPLORED) {
  14418. /* forward- or cross-edge */
  14419. insn_state[t] = DISCOVERED | e;
  14420. } else {
  14421. verbose(env, "insn state internal bug\n");
  14422. return -EFAULT;
  14423. }
  14424. return DONE_EXPLORING;
  14425. }
  14426. static int visit_func_call_insn(int t, struct bpf_insn *insns,
  14427. struct bpf_verifier_env *env,
  14428. bool visit_callee)
  14429. {
  14430. int ret, insn_sz;
  14431. int w;
  14432. insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
  14433. ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
  14434. if (ret)
  14435. return ret;
  14436. mark_prune_point(env, t + insn_sz);
  14437. /* when we exit from subprog, we need to record non-linear history */
  14438. mark_jmp_point(env, t + insn_sz);
  14439. if (visit_callee) {
  14440. w = t + insns[t].imm + 1;
  14441. mark_prune_point(env, t);
  14442. merge_callee_effects(env, t, w);
  14443. ret = push_insn(t, w, BRANCH, env);
  14444. }
  14445. return ret;
  14446. }
  14447. /* Bitmask with 1s for all caller saved registers */
  14448. #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
  14449. /* Return a bitmask specifying which caller saved registers are
  14450. * clobbered by a call to a helper *as if* this helper follows
  14451. * bpf_fastcall contract:
  14452. * - includes R0 if function is non-void;
  14453. * - includes R1-R5 if corresponding parameter has is described
  14454. * in the function prototype.
  14455. */
  14456. static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn)
  14457. {
  14458. u32 mask;
  14459. int i;
  14460. mask = 0;
  14461. if (fn->ret_type != RET_VOID)
  14462. mask |= BIT(BPF_REG_0);
  14463. for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i)
  14464. if (fn->arg_type[i] != ARG_DONTCARE)
  14465. mask |= BIT(BPF_REG_1 + i);
  14466. return mask;
  14467. }
  14468. /* True if do_misc_fixups() replaces calls to helper number 'imm',
  14469. * replacement patch is presumed to follow bpf_fastcall contract
  14470. * (see mark_fastcall_pattern_for_call() below).
  14471. */
  14472. static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
  14473. {
  14474. switch (imm) {
  14475. #ifdef CONFIG_X86_64
  14476. case BPF_FUNC_get_smp_processor_id:
  14477. return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
  14478. #endif
  14479. default:
  14480. return false;
  14481. }
  14482. }
  14483. /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */
  14484. static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta)
  14485. {
  14486. u32 vlen, i, mask;
  14487. vlen = btf_type_vlen(meta->func_proto);
  14488. mask = 0;
  14489. if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type)))
  14490. mask |= BIT(BPF_REG_0);
  14491. for (i = 0; i < vlen; ++i)
  14492. mask |= BIT(BPF_REG_1 + i);
  14493. return mask;
  14494. }
  14495. /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */
  14496. static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta)
  14497. {
  14498. if (meta->btf == btf_vmlinux)
  14499. return meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
  14500. meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast];
  14501. return false;
  14502. }
  14503. /* LLVM define a bpf_fastcall function attribute.
  14504. * This attribute means that function scratches only some of
  14505. * the caller saved registers defined by ABI.
  14506. * For BPF the set of such registers could be defined as follows:
  14507. * - R0 is scratched only if function is non-void;
  14508. * - R1-R5 are scratched only if corresponding parameter type is defined
  14509. * in the function prototype.
  14510. *
  14511. * The contract between kernel and clang allows to simultaneously use
  14512. * such functions and maintain backwards compatibility with old
  14513. * kernels that don't understand bpf_fastcall calls:
  14514. *
  14515. * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
  14516. * registers are not scratched by the call;
  14517. *
  14518. * - as a post-processing step, clang visits each bpf_fastcall call and adds
  14519. * spill/fill for every live r0-r5;
  14520. *
  14521. * - stack offsets used for the spill/fill are allocated as lowest
  14522. * stack offsets in whole function and are not used for any other
  14523. * purposes;
  14524. *
  14525. * - when kernel loads a program, it looks for such patterns
  14526. * (bpf_fastcall function surrounded by spills/fills) and checks if
  14527. * spill/fill stack offsets are used exclusively in fastcall patterns;
  14528. *
  14529. * - if so, and if verifier or current JIT inlines the call to the
  14530. * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
  14531. * spill/fill pairs;
  14532. *
  14533. * - when old kernel loads a program, presence of spill/fill pairs
  14534. * keeps BPF program valid, albeit slightly less efficient.
  14535. *
  14536. * For example:
  14537. *
  14538. * r1 = 1;
  14539. * r2 = 2;
  14540. * *(u64 *)(r10 - 8) = r1; r1 = 1;
  14541. * *(u64 *)(r10 - 16) = r2; r2 = 2;
  14542. * call %[to_be_inlined] --> call %[to_be_inlined]
  14543. * r2 = *(u64 *)(r10 - 16); r0 = r1;
  14544. * r1 = *(u64 *)(r10 - 8); r0 += r2;
  14545. * r0 = r1; exit;
  14546. * r0 += r2;
  14547. * exit;
  14548. *
  14549. * The purpose of mark_fastcall_pattern_for_call is to:
  14550. * - look for such patterns;
  14551. * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
  14552. * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
  14553. * - update env->subprog_info[*]->fastcall_stack_off to find an offset
  14554. * at which bpf_fastcall spill/fill stack slots start;
  14555. * - update env->subprog_info[*]->keep_fastcall_stack.
  14556. *
  14557. * The .fastcall_pattern and .fastcall_stack_off are used by
  14558. * check_fastcall_stack_contract() to check if every stack access to
  14559. * fastcall spill/fill stack slot originates from spill/fill
  14560. * instructions, members of fastcall patterns.
  14561. *
  14562. * If such condition holds true for a subprogram, fastcall patterns could
  14563. * be rewritten by remove_fastcall_spills_fills().
  14564. * Otherwise bpf_fastcall patterns are not changed in the subprogram
  14565. * (code, presumably, generated by an older clang version).
  14566. *
  14567. * For example, it is *not* safe to remove spill/fill below:
  14568. *
  14569. * r1 = 1;
  14570. * *(u64 *)(r10 - 8) = r1; r1 = 1;
  14571. * call %[to_be_inlined] --> call %[to_be_inlined]
  14572. * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!!
  14573. * r0 = *(u64 *)(r10 - 8); r0 += r1;
  14574. * r0 += r1; exit;
  14575. * exit;
  14576. */
  14577. static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
  14578. struct bpf_subprog_info *subprog,
  14579. int insn_idx, s16 lowest_off)
  14580. {
  14581. struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
  14582. struct bpf_insn *call = &env->prog->insnsi[insn_idx];
  14583. const struct bpf_func_proto *fn;
  14584. u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS;
  14585. u32 expected_regs_mask;
  14586. bool can_be_inlined = false;
  14587. s16 off;
  14588. int i;
  14589. if (bpf_helper_call(call)) {
  14590. if (get_helper_proto(env, call->imm, &fn) < 0)
  14591. /* error would be reported later */
  14592. return;
  14593. clobbered_regs_mask = helper_fastcall_clobber_mask(fn);
  14594. can_be_inlined = fn->allow_fastcall &&
  14595. (verifier_inlines_helper_call(env, call->imm) ||
  14596. bpf_jit_inlines_helper_call(call->imm));
  14597. }
  14598. if (bpf_pseudo_kfunc_call(call)) {
  14599. struct bpf_kfunc_call_arg_meta meta;
  14600. int err;
  14601. err = fetch_kfunc_meta(env, call, &meta, NULL);
  14602. if (err < 0)
  14603. /* error would be reported later */
  14604. return;
  14605. clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta);
  14606. can_be_inlined = is_fastcall_kfunc_call(&meta);
  14607. }
  14608. if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS)
  14609. return;
  14610. /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
  14611. expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
  14612. /* match pairs of form:
  14613. *
  14614. * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0)
  14615. * ...
  14616. * call %[to_be_inlined]
  14617. * ...
  14618. * rX = *(u64 *)(r10 - Y)
  14619. */
  14620. for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
  14621. if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
  14622. break;
  14623. stx = &insns[insn_idx - i];
  14624. ldx = &insns[insn_idx + i];
  14625. /* must be a stack spill/fill pair */
  14626. if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
  14627. ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
  14628. stx->dst_reg != BPF_REG_10 ||
  14629. ldx->src_reg != BPF_REG_10)
  14630. break;
  14631. /* must be a spill/fill for the same reg */
  14632. if (stx->src_reg != ldx->dst_reg)
  14633. break;
  14634. /* must be one of the previously unseen registers */
  14635. if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
  14636. break;
  14637. /* must be a spill/fill for the same expected offset,
  14638. * no need to check offset alignment, BPF_DW stack access
  14639. * is always 8-byte aligned.
  14640. */
  14641. if (stx->off != off || ldx->off != off)
  14642. break;
  14643. expected_regs_mask &= ~BIT(stx->src_reg);
  14644. env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
  14645. env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
  14646. }
  14647. if (i == 1)
  14648. return;
  14649. /* Conditionally set 'fastcall_spills_num' to allow forward
  14650. * compatibility when more helper functions are marked as
  14651. * bpf_fastcall at compile time than current kernel supports, e.g:
  14652. *
  14653. * 1: *(u64 *)(r10 - 8) = r1
  14654. * 2: call A ;; assume A is bpf_fastcall for current kernel
  14655. * 3: r1 = *(u64 *)(r10 - 8)
  14656. * 4: *(u64 *)(r10 - 8) = r1
  14657. * 5: call B ;; assume B is not bpf_fastcall for current kernel
  14658. * 6: r1 = *(u64 *)(r10 - 8)
  14659. *
  14660. * There is no need to block bpf_fastcall rewrite for such program.
  14661. * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
  14662. * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
  14663. * does not remove spill/fill pair {4,6}.
  14664. */
  14665. if (can_be_inlined)
  14666. env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
  14667. else
  14668. subprog->keep_fastcall_stack = 1;
  14669. subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
  14670. }
  14671. static int mark_fastcall_patterns(struct bpf_verifier_env *env)
  14672. {
  14673. struct bpf_subprog_info *subprog = env->subprog_info;
  14674. struct bpf_insn *insn;
  14675. s16 lowest_off;
  14676. int s, i;
  14677. for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
  14678. /* find lowest stack spill offset used in this subprog */
  14679. lowest_off = 0;
  14680. for (i = subprog->start; i < (subprog + 1)->start; ++i) {
  14681. insn = env->prog->insnsi + i;
  14682. if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
  14683. insn->dst_reg != BPF_REG_10)
  14684. continue;
  14685. lowest_off = min(lowest_off, insn->off);
  14686. }
  14687. /* use this offset to find fastcall patterns */
  14688. for (i = subprog->start; i < (subprog + 1)->start; ++i) {
  14689. insn = env->prog->insnsi + i;
  14690. if (insn->code != (BPF_JMP | BPF_CALL))
  14691. continue;
  14692. mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
  14693. }
  14694. }
  14695. return 0;
  14696. }
  14697. /* Visits the instruction at index t and returns one of the following:
  14698. * < 0 - an error occurred
  14699. * DONE_EXPLORING - the instruction was fully explored
  14700. * KEEP_EXPLORING - there is still work to be done before it is fully explored
  14701. */
  14702. static int visit_insn(int t, struct bpf_verifier_env *env)
  14703. {
  14704. struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
  14705. int ret, off, insn_sz;
  14706. if (bpf_pseudo_func(insn))
  14707. return visit_func_call_insn(t, insns, env, true);
  14708. /* All non-branch instructions have a single fall-through edge. */
  14709. if (BPF_CLASS(insn->code) != BPF_JMP &&
  14710. BPF_CLASS(insn->code) != BPF_JMP32) {
  14711. insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
  14712. return push_insn(t, t + insn_sz, FALLTHROUGH, env);
  14713. }
  14714. switch (BPF_OP(insn->code)) {
  14715. case BPF_EXIT:
  14716. return DONE_EXPLORING;
  14717. case BPF_CALL:
  14718. if (is_async_callback_calling_insn(insn))
  14719. /* Mark this call insn as a prune point to trigger
  14720. * is_state_visited() check before call itself is
  14721. * processed by __check_func_call(). Otherwise new
  14722. * async state will be pushed for further exploration.
  14723. */
  14724. mark_prune_point(env, t);
  14725. /* For functions that invoke callbacks it is not known how many times
  14726. * callback would be called. Verifier models callback calling functions
  14727. * by repeatedly visiting callback bodies and returning to origin call
  14728. * instruction.
  14729. * In order to stop such iteration verifier needs to identify when a
  14730. * state identical some state from a previous iteration is reached.
  14731. * Check below forces creation of checkpoint before callback calling
  14732. * instruction to allow search for such identical states.
  14733. */
  14734. if (is_sync_callback_calling_insn(insn)) {
  14735. mark_calls_callback(env, t);
  14736. mark_force_checkpoint(env, t);
  14737. mark_prune_point(env, t);
  14738. mark_jmp_point(env, t);
  14739. }
  14740. if (bpf_helper_call(insn) && bpf_helper_changes_pkt_data(insn->imm))
  14741. mark_subprog_changes_pkt_data(env, t);
  14742. if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
  14743. struct bpf_kfunc_call_arg_meta meta;
  14744. ret = fetch_kfunc_meta(env, insn, &meta, NULL);
  14745. if (ret == 0 && is_iter_next_kfunc(&meta)) {
  14746. mark_prune_point(env, t);
  14747. /* Checking and saving state checkpoints at iter_next() call
  14748. * is crucial for fast convergence of open-coded iterator loop
  14749. * logic, so we need to force it. If we don't do that,
  14750. * is_state_visited() might skip saving a checkpoint, causing
  14751. * unnecessarily long sequence of not checkpointed
  14752. * instructions and jumps, leading to exhaustion of jump
  14753. * history buffer, and potentially other undesired outcomes.
  14754. * It is expected that with correct open-coded iterators
  14755. * convergence will happen quickly, so we don't run a risk of
  14756. * exhausting memory.
  14757. */
  14758. mark_force_checkpoint(env, t);
  14759. }
  14760. }
  14761. return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
  14762. case BPF_JA:
  14763. if (BPF_SRC(insn->code) != BPF_K)
  14764. return -EINVAL;
  14765. if (BPF_CLASS(insn->code) == BPF_JMP)
  14766. off = insn->off;
  14767. else
  14768. off = insn->imm;
  14769. /* unconditional jump with single edge */
  14770. ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
  14771. if (ret)
  14772. return ret;
  14773. mark_prune_point(env, t + off + 1);
  14774. mark_jmp_point(env, t + off + 1);
  14775. return ret;
  14776. default:
  14777. /* conditional jump with two edges */
  14778. mark_prune_point(env, t);
  14779. if (is_may_goto_insn(insn))
  14780. mark_force_checkpoint(env, t);
  14781. ret = push_insn(t, t + 1, FALLTHROUGH, env);
  14782. if (ret)
  14783. return ret;
  14784. return push_insn(t, t + insn->off + 1, BRANCH, env);
  14785. }
  14786. }
  14787. /* non-recursive depth-first-search to detect loops in BPF program
  14788. * loop == back-edge in directed graph
  14789. */
  14790. static int check_cfg(struct bpf_verifier_env *env)
  14791. {
  14792. int insn_cnt = env->prog->len;
  14793. int *insn_stack, *insn_state;
  14794. int ex_insn_beg, i, ret = 0;
  14795. bool ex_done = false;
  14796. insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  14797. if (!insn_state)
  14798. return -ENOMEM;
  14799. insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
  14800. if (!insn_stack) {
  14801. kvfree(insn_state);
  14802. return -ENOMEM;
  14803. }
  14804. insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
  14805. insn_stack[0] = 0; /* 0 is the first instruction */
  14806. env->cfg.cur_stack = 1;
  14807. walk_cfg:
  14808. while (env->cfg.cur_stack > 0) {
  14809. int t = insn_stack[env->cfg.cur_stack - 1];
  14810. ret = visit_insn(t, env);
  14811. switch (ret) {
  14812. case DONE_EXPLORING:
  14813. insn_state[t] = EXPLORED;
  14814. env->cfg.cur_stack--;
  14815. break;
  14816. case KEEP_EXPLORING:
  14817. break;
  14818. default:
  14819. if (ret > 0) {
  14820. verbose(env, "visit_insn internal bug\n");
  14821. ret = -EFAULT;
  14822. }
  14823. goto err_free;
  14824. }
  14825. }
  14826. if (env->cfg.cur_stack < 0) {
  14827. verbose(env, "pop stack internal bug\n");
  14828. ret = -EFAULT;
  14829. goto err_free;
  14830. }
  14831. if (env->exception_callback_subprog && !ex_done) {
  14832. ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
  14833. insn_state[ex_insn_beg] = DISCOVERED;
  14834. insn_stack[0] = ex_insn_beg;
  14835. env->cfg.cur_stack = 1;
  14836. ex_done = true;
  14837. goto walk_cfg;
  14838. }
  14839. for (i = 0; i < insn_cnt; i++) {
  14840. struct bpf_insn *insn = &env->prog->insnsi[i];
  14841. if (insn_state[i] != EXPLORED) {
  14842. verbose(env, "unreachable insn %d\n", i);
  14843. ret = -EINVAL;
  14844. goto err_free;
  14845. }
  14846. if (bpf_is_ldimm64(insn)) {
  14847. if (insn_state[i + 1] != 0) {
  14848. verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
  14849. ret = -EINVAL;
  14850. goto err_free;
  14851. }
  14852. i++; /* skip second half of ldimm64 */
  14853. }
  14854. }
  14855. ret = 0; /* cfg looks good */
  14856. env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
  14857. err_free:
  14858. kvfree(insn_state);
  14859. kvfree(insn_stack);
  14860. env->cfg.insn_state = env->cfg.insn_stack = NULL;
  14861. return ret;
  14862. }
  14863. static int check_abnormal_return(struct bpf_verifier_env *env)
  14864. {
  14865. int i;
  14866. for (i = 1; i < env->subprog_cnt; i++) {
  14867. if (env->subprog_info[i].has_ld_abs) {
  14868. verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
  14869. return -EINVAL;
  14870. }
  14871. if (env->subprog_info[i].has_tail_call) {
  14872. verbose(env, "tail_call is not allowed in subprogs without BTF\n");
  14873. return -EINVAL;
  14874. }
  14875. }
  14876. return 0;
  14877. }
  14878. /* The minimum supported BTF func info size */
  14879. #define MIN_BPF_FUNCINFO_SIZE 8
  14880. #define MAX_FUNCINFO_REC_SIZE 252
  14881. static int check_btf_func_early(struct bpf_verifier_env *env,
  14882. const union bpf_attr *attr,
  14883. bpfptr_t uattr)
  14884. {
  14885. u32 krec_size = sizeof(struct bpf_func_info);
  14886. const struct btf_type *type, *func_proto;
  14887. u32 i, nfuncs, urec_size, min_size;
  14888. struct bpf_func_info *krecord;
  14889. struct bpf_prog *prog;
  14890. const struct btf *btf;
  14891. u32 prev_offset = 0;
  14892. bpfptr_t urecord;
  14893. int ret = -ENOMEM;
  14894. nfuncs = attr->func_info_cnt;
  14895. if (!nfuncs) {
  14896. if (check_abnormal_return(env))
  14897. return -EINVAL;
  14898. return 0;
  14899. }
  14900. urec_size = attr->func_info_rec_size;
  14901. if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
  14902. urec_size > MAX_FUNCINFO_REC_SIZE ||
  14903. urec_size % sizeof(u32)) {
  14904. verbose(env, "invalid func info rec size %u\n", urec_size);
  14905. return -EINVAL;
  14906. }
  14907. prog = env->prog;
  14908. btf = prog->aux->btf;
  14909. urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
  14910. min_size = min_t(u32, krec_size, urec_size);
  14911. krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
  14912. if (!krecord)
  14913. return -ENOMEM;
  14914. for (i = 0; i < nfuncs; i++) {
  14915. ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
  14916. if (ret) {
  14917. if (ret == -E2BIG) {
  14918. verbose(env, "nonzero tailing record in func info");
  14919. /* set the size kernel expects so loader can zero
  14920. * out the rest of the record.
  14921. */
  14922. if (copy_to_bpfptr_offset(uattr,
  14923. offsetof(union bpf_attr, func_info_rec_size),
  14924. &min_size, sizeof(min_size)))
  14925. ret = -EFAULT;
  14926. }
  14927. goto err_free;
  14928. }
  14929. if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
  14930. ret = -EFAULT;
  14931. goto err_free;
  14932. }
  14933. /* check insn_off */
  14934. ret = -EINVAL;
  14935. if (i == 0) {
  14936. if (krecord[i].insn_off) {
  14937. verbose(env,
  14938. "nonzero insn_off %u for the first func info record",
  14939. krecord[i].insn_off);
  14940. goto err_free;
  14941. }
  14942. } else if (krecord[i].insn_off <= prev_offset) {
  14943. verbose(env,
  14944. "same or smaller insn offset (%u) than previous func info record (%u)",
  14945. krecord[i].insn_off, prev_offset);
  14946. goto err_free;
  14947. }
  14948. /* check type_id */
  14949. type = btf_type_by_id(btf, krecord[i].type_id);
  14950. if (!type || !btf_type_is_func(type)) {
  14951. verbose(env, "invalid type id %d in func info",
  14952. krecord[i].type_id);
  14953. goto err_free;
  14954. }
  14955. func_proto = btf_type_by_id(btf, type->type);
  14956. if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
  14957. /* btf_func_check() already verified it during BTF load */
  14958. goto err_free;
  14959. prev_offset = krecord[i].insn_off;
  14960. bpfptr_add(&urecord, urec_size);
  14961. }
  14962. prog->aux->func_info = krecord;
  14963. prog->aux->func_info_cnt = nfuncs;
  14964. return 0;
  14965. err_free:
  14966. kvfree(krecord);
  14967. return ret;
  14968. }
  14969. static int check_btf_func(struct bpf_verifier_env *env,
  14970. const union bpf_attr *attr,
  14971. bpfptr_t uattr)
  14972. {
  14973. const struct btf_type *type, *func_proto, *ret_type;
  14974. u32 i, nfuncs, urec_size;
  14975. struct bpf_func_info *krecord;
  14976. struct bpf_func_info_aux *info_aux = NULL;
  14977. struct bpf_prog *prog;
  14978. const struct btf *btf;
  14979. bpfptr_t urecord;
  14980. bool scalar_return;
  14981. int ret = -ENOMEM;
  14982. nfuncs = attr->func_info_cnt;
  14983. if (!nfuncs) {
  14984. if (check_abnormal_return(env))
  14985. return -EINVAL;
  14986. return 0;
  14987. }
  14988. if (nfuncs != env->subprog_cnt) {
  14989. verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
  14990. return -EINVAL;
  14991. }
  14992. urec_size = attr->func_info_rec_size;
  14993. prog = env->prog;
  14994. btf = prog->aux->btf;
  14995. urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
  14996. krecord = prog->aux->func_info;
  14997. info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
  14998. if (!info_aux)
  14999. return -ENOMEM;
  15000. for (i = 0; i < nfuncs; i++) {
  15001. /* check insn_off */
  15002. ret = -EINVAL;
  15003. if (env->subprog_info[i].start != krecord[i].insn_off) {
  15004. verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
  15005. goto err_free;
  15006. }
  15007. /* Already checked type_id */
  15008. type = btf_type_by_id(btf, krecord[i].type_id);
  15009. info_aux[i].linkage = BTF_INFO_VLEN(type->info);
  15010. /* Already checked func_proto */
  15011. func_proto = btf_type_by_id(btf, type->type);
  15012. ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
  15013. scalar_return =
  15014. btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
  15015. if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
  15016. verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
  15017. goto err_free;
  15018. }
  15019. if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
  15020. verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
  15021. goto err_free;
  15022. }
  15023. bpfptr_add(&urecord, urec_size);
  15024. }
  15025. prog->aux->func_info_aux = info_aux;
  15026. return 0;
  15027. err_free:
  15028. kfree(info_aux);
  15029. return ret;
  15030. }
  15031. static void adjust_btf_func(struct bpf_verifier_env *env)
  15032. {
  15033. struct bpf_prog_aux *aux = env->prog->aux;
  15034. int i;
  15035. if (!aux->func_info)
  15036. return;
  15037. /* func_info is not available for hidden subprogs */
  15038. for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
  15039. aux->func_info[i].insn_off = env->subprog_info[i].start;
  15040. }
  15041. #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
  15042. #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
  15043. static int check_btf_line(struct bpf_verifier_env *env,
  15044. const union bpf_attr *attr,
  15045. bpfptr_t uattr)
  15046. {
  15047. u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
  15048. struct bpf_subprog_info *sub;
  15049. struct bpf_line_info *linfo;
  15050. struct bpf_prog *prog;
  15051. const struct btf *btf;
  15052. bpfptr_t ulinfo;
  15053. int err;
  15054. nr_linfo = attr->line_info_cnt;
  15055. if (!nr_linfo)
  15056. return 0;
  15057. if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
  15058. return -EINVAL;
  15059. rec_size = attr->line_info_rec_size;
  15060. if (rec_size < MIN_BPF_LINEINFO_SIZE ||
  15061. rec_size > MAX_LINEINFO_REC_SIZE ||
  15062. rec_size & (sizeof(u32) - 1))
  15063. return -EINVAL;
  15064. /* Need to zero it in case the userspace may
  15065. * pass in a smaller bpf_line_info object.
  15066. */
  15067. linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
  15068. GFP_KERNEL | __GFP_NOWARN);
  15069. if (!linfo)
  15070. return -ENOMEM;
  15071. prog = env->prog;
  15072. btf = prog->aux->btf;
  15073. s = 0;
  15074. sub = env->subprog_info;
  15075. ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
  15076. expected_size = sizeof(struct bpf_line_info);
  15077. ncopy = min_t(u32, expected_size, rec_size);
  15078. for (i = 0; i < nr_linfo; i++) {
  15079. err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
  15080. if (err) {
  15081. if (err == -E2BIG) {
  15082. verbose(env, "nonzero tailing record in line_info");
  15083. if (copy_to_bpfptr_offset(uattr,
  15084. offsetof(union bpf_attr, line_info_rec_size),
  15085. &expected_size, sizeof(expected_size)))
  15086. err = -EFAULT;
  15087. }
  15088. goto err_free;
  15089. }
  15090. if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
  15091. err = -EFAULT;
  15092. goto err_free;
  15093. }
  15094. /*
  15095. * Check insn_off to ensure
  15096. * 1) strictly increasing AND
  15097. * 2) bounded by prog->len
  15098. *
  15099. * The linfo[0].insn_off == 0 check logically falls into
  15100. * the later "missing bpf_line_info for func..." case
  15101. * because the first linfo[0].insn_off must be the
  15102. * first sub also and the first sub must have
  15103. * subprog_info[0].start == 0.
  15104. */
  15105. if ((i && linfo[i].insn_off <= prev_offset) ||
  15106. linfo[i].insn_off >= prog->len) {
  15107. verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
  15108. i, linfo[i].insn_off, prev_offset,
  15109. prog->len);
  15110. err = -EINVAL;
  15111. goto err_free;
  15112. }
  15113. if (!prog->insnsi[linfo[i].insn_off].code) {
  15114. verbose(env,
  15115. "Invalid insn code at line_info[%u].insn_off\n",
  15116. i);
  15117. err = -EINVAL;
  15118. goto err_free;
  15119. }
  15120. if (!btf_name_by_offset(btf, linfo[i].line_off) ||
  15121. !btf_name_by_offset(btf, linfo[i].file_name_off)) {
  15122. verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
  15123. err = -EINVAL;
  15124. goto err_free;
  15125. }
  15126. if (s != env->subprog_cnt) {
  15127. if (linfo[i].insn_off == sub[s].start) {
  15128. sub[s].linfo_idx = i;
  15129. s++;
  15130. } else if (sub[s].start < linfo[i].insn_off) {
  15131. verbose(env, "missing bpf_line_info for func#%u\n", s);
  15132. err = -EINVAL;
  15133. goto err_free;
  15134. }
  15135. }
  15136. prev_offset = linfo[i].insn_off;
  15137. bpfptr_add(&ulinfo, rec_size);
  15138. }
  15139. if (s != env->subprog_cnt) {
  15140. verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
  15141. env->subprog_cnt - s, s);
  15142. err = -EINVAL;
  15143. goto err_free;
  15144. }
  15145. prog->aux->linfo = linfo;
  15146. prog->aux->nr_linfo = nr_linfo;
  15147. return 0;
  15148. err_free:
  15149. kvfree(linfo);
  15150. return err;
  15151. }
  15152. #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
  15153. #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
  15154. static int check_core_relo(struct bpf_verifier_env *env,
  15155. const union bpf_attr *attr,
  15156. bpfptr_t uattr)
  15157. {
  15158. u32 i, nr_core_relo, ncopy, expected_size, rec_size;
  15159. struct bpf_core_relo core_relo = {};
  15160. struct bpf_prog *prog = env->prog;
  15161. const struct btf *btf = prog->aux->btf;
  15162. struct bpf_core_ctx ctx = {
  15163. .log = &env->log,
  15164. .btf = btf,
  15165. };
  15166. bpfptr_t u_core_relo;
  15167. int err;
  15168. nr_core_relo = attr->core_relo_cnt;
  15169. if (!nr_core_relo)
  15170. return 0;
  15171. if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
  15172. return -EINVAL;
  15173. rec_size = attr->core_relo_rec_size;
  15174. if (rec_size < MIN_CORE_RELO_SIZE ||
  15175. rec_size > MAX_CORE_RELO_SIZE ||
  15176. rec_size % sizeof(u32))
  15177. return -EINVAL;
  15178. u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
  15179. expected_size = sizeof(struct bpf_core_relo);
  15180. ncopy = min_t(u32, expected_size, rec_size);
  15181. /* Unlike func_info and line_info, copy and apply each CO-RE
  15182. * relocation record one at a time.
  15183. */
  15184. for (i = 0; i < nr_core_relo; i++) {
  15185. /* future proofing when sizeof(bpf_core_relo) changes */
  15186. err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
  15187. if (err) {
  15188. if (err == -E2BIG) {
  15189. verbose(env, "nonzero tailing record in core_relo");
  15190. if (copy_to_bpfptr_offset(uattr,
  15191. offsetof(union bpf_attr, core_relo_rec_size),
  15192. &expected_size, sizeof(expected_size)))
  15193. err = -EFAULT;
  15194. }
  15195. break;
  15196. }
  15197. if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
  15198. err = -EFAULT;
  15199. break;
  15200. }
  15201. if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
  15202. verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
  15203. i, core_relo.insn_off, prog->len);
  15204. err = -EINVAL;
  15205. break;
  15206. }
  15207. err = bpf_core_apply(&ctx, &core_relo, i,
  15208. &prog->insnsi[core_relo.insn_off / 8]);
  15209. if (err)
  15210. break;
  15211. bpfptr_add(&u_core_relo, rec_size);
  15212. }
  15213. return err;
  15214. }
  15215. static int check_btf_info_early(struct bpf_verifier_env *env,
  15216. const union bpf_attr *attr,
  15217. bpfptr_t uattr)
  15218. {
  15219. struct btf *btf;
  15220. int err;
  15221. if (!attr->func_info_cnt && !attr->line_info_cnt) {
  15222. if (check_abnormal_return(env))
  15223. return -EINVAL;
  15224. return 0;
  15225. }
  15226. btf = btf_get_by_fd(attr->prog_btf_fd);
  15227. if (IS_ERR(btf))
  15228. return PTR_ERR(btf);
  15229. if (btf_is_kernel(btf)) {
  15230. btf_put(btf);
  15231. return -EACCES;
  15232. }
  15233. env->prog->aux->btf = btf;
  15234. err = check_btf_func_early(env, attr, uattr);
  15235. if (err)
  15236. return err;
  15237. return 0;
  15238. }
  15239. static int check_btf_info(struct bpf_verifier_env *env,
  15240. const union bpf_attr *attr,
  15241. bpfptr_t uattr)
  15242. {
  15243. int err;
  15244. if (!attr->func_info_cnt && !attr->line_info_cnt) {
  15245. if (check_abnormal_return(env))
  15246. return -EINVAL;
  15247. return 0;
  15248. }
  15249. err = check_btf_func(env, attr, uattr);
  15250. if (err)
  15251. return err;
  15252. err = check_btf_line(env, attr, uattr);
  15253. if (err)
  15254. return err;
  15255. err = check_core_relo(env, attr, uattr);
  15256. if (err)
  15257. return err;
  15258. return 0;
  15259. }
  15260. /* check %cur's range satisfies %old's */
  15261. static bool range_within(const struct bpf_reg_state *old,
  15262. const struct bpf_reg_state *cur)
  15263. {
  15264. return old->umin_value <= cur->umin_value &&
  15265. old->umax_value >= cur->umax_value &&
  15266. old->smin_value <= cur->smin_value &&
  15267. old->smax_value >= cur->smax_value &&
  15268. old->u32_min_value <= cur->u32_min_value &&
  15269. old->u32_max_value >= cur->u32_max_value &&
  15270. old->s32_min_value <= cur->s32_min_value &&
  15271. old->s32_max_value >= cur->s32_max_value;
  15272. }
  15273. /* If in the old state two registers had the same id, then they need to have
  15274. * the same id in the new state as well. But that id could be different from
  15275. * the old state, so we need to track the mapping from old to new ids.
  15276. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
  15277. * regs with old id 5 must also have new id 9 for the new state to be safe. But
  15278. * regs with a different old id could still have new id 9, we don't care about
  15279. * that.
  15280. * So we look through our idmap to see if this old id has been seen before. If
  15281. * so, we require the new id to match; otherwise, we add the id pair to the map.
  15282. */
  15283. static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
  15284. {
  15285. struct bpf_id_pair *map = idmap->map;
  15286. unsigned int i;
  15287. /* either both IDs should be set or both should be zero */
  15288. if (!!old_id != !!cur_id)
  15289. return false;
  15290. if (old_id == 0) /* cur_id == 0 as well */
  15291. return true;
  15292. for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
  15293. if (!map[i].old) {
  15294. /* Reached an empty slot; haven't seen this id before */
  15295. map[i].old = old_id;
  15296. map[i].cur = cur_id;
  15297. return true;
  15298. }
  15299. if (map[i].old == old_id)
  15300. return map[i].cur == cur_id;
  15301. if (map[i].cur == cur_id)
  15302. return false;
  15303. }
  15304. /* We ran out of idmap slots, which should be impossible */
  15305. WARN_ON_ONCE(1);
  15306. return false;
  15307. }
  15308. /* Similar to check_ids(), but allocate a unique temporary ID
  15309. * for 'old_id' or 'cur_id' of zero.
  15310. * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
  15311. */
  15312. static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
  15313. {
  15314. old_id = old_id ? old_id : ++idmap->tmp_id_gen;
  15315. cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
  15316. return check_ids(old_id, cur_id, idmap);
  15317. }
  15318. static void clean_func_state(struct bpf_verifier_env *env,
  15319. struct bpf_func_state *st)
  15320. {
  15321. enum bpf_reg_liveness live;
  15322. int i, j;
  15323. for (i = 0; i < BPF_REG_FP; i++) {
  15324. live = st->regs[i].live;
  15325. /* liveness must not touch this register anymore */
  15326. st->regs[i].live |= REG_LIVE_DONE;
  15327. if (!(live & REG_LIVE_READ))
  15328. /* since the register is unused, clear its state
  15329. * to make further comparison simpler
  15330. */
  15331. __mark_reg_not_init(env, &st->regs[i]);
  15332. }
  15333. for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
  15334. live = st->stack[i].spilled_ptr.live;
  15335. /* liveness must not touch this stack slot anymore */
  15336. st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
  15337. if (!(live & REG_LIVE_READ)) {
  15338. __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
  15339. for (j = 0; j < BPF_REG_SIZE; j++)
  15340. st->stack[i].slot_type[j] = STACK_INVALID;
  15341. }
  15342. }
  15343. }
  15344. static void clean_verifier_state(struct bpf_verifier_env *env,
  15345. struct bpf_verifier_state *st)
  15346. {
  15347. int i;
  15348. if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
  15349. /* all regs in this state in all frames were already marked */
  15350. return;
  15351. for (i = 0; i <= st->curframe; i++)
  15352. clean_func_state(env, st->frame[i]);
  15353. }
  15354. /* the parentage chains form a tree.
  15355. * the verifier states are added to state lists at given insn and
  15356. * pushed into state stack for future exploration.
  15357. * when the verifier reaches bpf_exit insn some of the verifer states
  15358. * stored in the state lists have their final liveness state already,
  15359. * but a lot of states will get revised from liveness point of view when
  15360. * the verifier explores other branches.
  15361. * Example:
  15362. * 1: r0 = 1
  15363. * 2: if r1 == 100 goto pc+1
  15364. * 3: r0 = 2
  15365. * 4: exit
  15366. * when the verifier reaches exit insn the register r0 in the state list of
  15367. * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
  15368. * of insn 2 and goes exploring further. At the insn 4 it will walk the
  15369. * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
  15370. *
  15371. * Since the verifier pushes the branch states as it sees them while exploring
  15372. * the program the condition of walking the branch instruction for the second
  15373. * time means that all states below this branch were already explored and
  15374. * their final liveness marks are already propagated.
  15375. * Hence when the verifier completes the search of state list in is_state_visited()
  15376. * we can call this clean_live_states() function to mark all liveness states
  15377. * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
  15378. * will not be used.
  15379. * This function also clears the registers and stack for states that !READ
  15380. * to simplify state merging.
  15381. *
  15382. * Important note here that walking the same branch instruction in the callee
  15383. * doesn't meant that the states are DONE. The verifier has to compare
  15384. * the callsites
  15385. */
  15386. static void clean_live_states(struct bpf_verifier_env *env, int insn,
  15387. struct bpf_verifier_state *cur)
  15388. {
  15389. struct bpf_verifier_state *loop_entry;
  15390. struct bpf_verifier_state_list *sl;
  15391. sl = *explored_state(env, insn);
  15392. while (sl) {
  15393. if (sl->state.branches)
  15394. goto next;
  15395. loop_entry = get_loop_entry(&sl->state);
  15396. if (loop_entry && loop_entry->branches)
  15397. goto next;
  15398. if (sl->state.insn_idx != insn ||
  15399. !same_callsites(&sl->state, cur))
  15400. goto next;
  15401. clean_verifier_state(env, &sl->state);
  15402. next:
  15403. sl = sl->next;
  15404. }
  15405. }
  15406. static bool regs_exact(const struct bpf_reg_state *rold,
  15407. const struct bpf_reg_state *rcur,
  15408. struct bpf_idmap *idmap)
  15409. {
  15410. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
  15411. check_ids(rold->id, rcur->id, idmap) &&
  15412. check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
  15413. }
  15414. enum exact_level {
  15415. NOT_EXACT,
  15416. EXACT,
  15417. RANGE_WITHIN
  15418. };
  15419. /* Returns true if (rold safe implies rcur safe) */
  15420. static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
  15421. struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
  15422. enum exact_level exact)
  15423. {
  15424. if (exact == EXACT)
  15425. return regs_exact(rold, rcur, idmap);
  15426. if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
  15427. /* explored state didn't use this */
  15428. return true;
  15429. if (rold->type == NOT_INIT) {
  15430. if (exact == NOT_EXACT || rcur->type == NOT_INIT)
  15431. /* explored state can't have used this */
  15432. return true;
  15433. }
  15434. /* Enforce that register types have to match exactly, including their
  15435. * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
  15436. * rule.
  15437. *
  15438. * One can make a point that using a pointer register as unbounded
  15439. * SCALAR would be technically acceptable, but this could lead to
  15440. * pointer leaks because scalars are allowed to leak while pointers
  15441. * are not. We could make this safe in special cases if root is
  15442. * calling us, but it's probably not worth the hassle.
  15443. *
  15444. * Also, register types that are *not* MAYBE_NULL could technically be
  15445. * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
  15446. * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
  15447. * to the same map).
  15448. * However, if the old MAYBE_NULL register then got NULL checked,
  15449. * doing so could have affected others with the same id, and we can't
  15450. * check for that because we lost the id when we converted to
  15451. * a non-MAYBE_NULL variant.
  15452. * So, as a general rule we don't allow mixing MAYBE_NULL and
  15453. * non-MAYBE_NULL registers as well.
  15454. */
  15455. if (rold->type != rcur->type)
  15456. return false;
  15457. switch (base_type(rold->type)) {
  15458. case SCALAR_VALUE:
  15459. if (env->explore_alu_limits) {
  15460. /* explore_alu_limits disables tnum_in() and range_within()
  15461. * logic and requires everything to be strict
  15462. */
  15463. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
  15464. check_scalar_ids(rold->id, rcur->id, idmap);
  15465. }
  15466. if (!rold->precise && exact == NOT_EXACT)
  15467. return true;
  15468. if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
  15469. return false;
  15470. if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
  15471. return false;
  15472. /* Why check_ids() for scalar registers?
  15473. *
  15474. * Consider the following BPF code:
  15475. * 1: r6 = ... unbound scalar, ID=a ...
  15476. * 2: r7 = ... unbound scalar, ID=b ...
  15477. * 3: if (r6 > r7) goto +1
  15478. * 4: r6 = r7
  15479. * 5: if (r6 > X) goto ...
  15480. * 6: ... memory operation using r7 ...
  15481. *
  15482. * First verification path is [1-6]:
  15483. * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
  15484. * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
  15485. * r7 <= X, because r6 and r7 share same id.
  15486. * Next verification path is [1-4, 6].
  15487. *
  15488. * Instruction (6) would be reached in two states:
  15489. * I. r6{.id=b}, r7{.id=b} via path 1-6;
  15490. * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
  15491. *
  15492. * Use check_ids() to distinguish these states.
  15493. * ---
  15494. * Also verify that new value satisfies old value range knowledge.
  15495. */
  15496. return range_within(rold, rcur) &&
  15497. tnum_in(rold->var_off, rcur->var_off) &&
  15498. check_scalar_ids(rold->id, rcur->id, idmap);
  15499. case PTR_TO_MAP_KEY:
  15500. case PTR_TO_MAP_VALUE:
  15501. case PTR_TO_MEM:
  15502. case PTR_TO_BUF:
  15503. case PTR_TO_TP_BUFFER:
  15504. /* If the new min/max/var_off satisfy the old ones and
  15505. * everything else matches, we are OK.
  15506. */
  15507. return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
  15508. range_within(rold, rcur) &&
  15509. tnum_in(rold->var_off, rcur->var_off) &&
  15510. check_ids(rold->id, rcur->id, idmap) &&
  15511. check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
  15512. case PTR_TO_PACKET_META:
  15513. case PTR_TO_PACKET:
  15514. /* We must have at least as much range as the old ptr
  15515. * did, so that any accesses which were safe before are
  15516. * still safe. This is true even if old range < old off,
  15517. * since someone could have accessed through (ptr - k), or
  15518. * even done ptr -= k in a register, to get a safe access.
  15519. */
  15520. if (rold->range > rcur->range)
  15521. return false;
  15522. /* If the offsets don't match, we can't trust our alignment;
  15523. * nor can we be sure that we won't fall out of range.
  15524. */
  15525. if (rold->off != rcur->off)
  15526. return false;
  15527. /* id relations must be preserved */
  15528. if (!check_ids(rold->id, rcur->id, idmap))
  15529. return false;
  15530. /* new val must satisfy old val knowledge */
  15531. return range_within(rold, rcur) &&
  15532. tnum_in(rold->var_off, rcur->var_off);
  15533. case PTR_TO_STACK:
  15534. /* two stack pointers are equal only if they're pointing to
  15535. * the same stack frame, since fp-8 in foo != fp-8 in bar
  15536. */
  15537. return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
  15538. case PTR_TO_ARENA:
  15539. return true;
  15540. default:
  15541. return regs_exact(rold, rcur, idmap);
  15542. }
  15543. }
  15544. static struct bpf_reg_state unbound_reg;
  15545. static __init int unbound_reg_init(void)
  15546. {
  15547. __mark_reg_unknown_imprecise(&unbound_reg);
  15548. unbound_reg.live |= REG_LIVE_READ;
  15549. return 0;
  15550. }
  15551. late_initcall(unbound_reg_init);
  15552. static bool is_stack_all_misc(struct bpf_verifier_env *env,
  15553. struct bpf_stack_state *stack)
  15554. {
  15555. u32 i;
  15556. for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
  15557. if ((stack->slot_type[i] == STACK_MISC) ||
  15558. (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
  15559. continue;
  15560. return false;
  15561. }
  15562. return true;
  15563. }
  15564. static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
  15565. struct bpf_stack_state *stack)
  15566. {
  15567. if (is_spilled_scalar_reg64(stack))
  15568. return &stack->spilled_ptr;
  15569. if (is_stack_all_misc(env, stack))
  15570. return &unbound_reg;
  15571. return NULL;
  15572. }
  15573. static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
  15574. struct bpf_func_state *cur, struct bpf_idmap *idmap,
  15575. enum exact_level exact)
  15576. {
  15577. int i, spi;
  15578. /* walk slots of the explored stack and ignore any additional
  15579. * slots in the current stack, since explored(safe) state
  15580. * didn't use them
  15581. */
  15582. for (i = 0; i < old->allocated_stack; i++) {
  15583. struct bpf_reg_state *old_reg, *cur_reg;
  15584. spi = i / BPF_REG_SIZE;
  15585. if (exact != NOT_EXACT &&
  15586. (i >= cur->allocated_stack ||
  15587. old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
  15588. cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
  15589. return false;
  15590. if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
  15591. && exact == NOT_EXACT) {
  15592. i += BPF_REG_SIZE - 1;
  15593. /* explored state didn't use this */
  15594. continue;
  15595. }
  15596. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
  15597. continue;
  15598. if (env->allow_uninit_stack &&
  15599. old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
  15600. continue;
  15601. /* explored stack has more populated slots than current stack
  15602. * and these slots were used
  15603. */
  15604. if (i >= cur->allocated_stack)
  15605. return false;
  15606. /* 64-bit scalar spill vs all slots MISC and vice versa.
  15607. * Load from all slots MISC produces unbound scalar.
  15608. * Construct a fake register for such stack and call
  15609. * regsafe() to ensure scalar ids are compared.
  15610. */
  15611. old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
  15612. cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
  15613. if (old_reg && cur_reg) {
  15614. if (!regsafe(env, old_reg, cur_reg, idmap, exact))
  15615. return false;
  15616. i += BPF_REG_SIZE - 1;
  15617. continue;
  15618. }
  15619. /* if old state was safe with misc data in the stack
  15620. * it will be safe with zero-initialized stack.
  15621. * The opposite is not true
  15622. */
  15623. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
  15624. cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
  15625. continue;
  15626. if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
  15627. cur->stack[spi].slot_type[i % BPF_REG_SIZE])
  15628. /* Ex: old explored (safe) state has STACK_SPILL in
  15629. * this stack slot, but current has STACK_MISC ->
  15630. * this verifier states are not equivalent,
  15631. * return false to continue verification of this path
  15632. */
  15633. return false;
  15634. if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
  15635. continue;
  15636. /* Both old and cur are having same slot_type */
  15637. switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
  15638. case STACK_SPILL:
  15639. /* when explored and current stack slot are both storing
  15640. * spilled registers, check that stored pointers types
  15641. * are the same as well.
  15642. * Ex: explored safe path could have stored
  15643. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
  15644. * but current path has stored:
  15645. * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
  15646. * such verifier states are not equivalent.
  15647. * return false to continue verification of this path
  15648. */
  15649. if (!regsafe(env, &old->stack[spi].spilled_ptr,
  15650. &cur->stack[spi].spilled_ptr, idmap, exact))
  15651. return false;
  15652. break;
  15653. case STACK_DYNPTR:
  15654. old_reg = &old->stack[spi].spilled_ptr;
  15655. cur_reg = &cur->stack[spi].spilled_ptr;
  15656. if (old_reg->dynptr.type != cur_reg->dynptr.type ||
  15657. old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
  15658. !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
  15659. return false;
  15660. break;
  15661. case STACK_ITER:
  15662. old_reg = &old->stack[spi].spilled_ptr;
  15663. cur_reg = &cur->stack[spi].spilled_ptr;
  15664. /* iter.depth is not compared between states as it
  15665. * doesn't matter for correctness and would otherwise
  15666. * prevent convergence; we maintain it only to prevent
  15667. * infinite loop check triggering, see
  15668. * iter_active_depths_differ()
  15669. */
  15670. if (old_reg->iter.btf != cur_reg->iter.btf ||
  15671. old_reg->iter.btf_id != cur_reg->iter.btf_id ||
  15672. old_reg->iter.state != cur_reg->iter.state ||
  15673. /* ignore {old_reg,cur_reg}->iter.depth, see above */
  15674. !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
  15675. return false;
  15676. break;
  15677. case STACK_MISC:
  15678. case STACK_ZERO:
  15679. case STACK_INVALID:
  15680. continue;
  15681. /* Ensure that new unhandled slot types return false by default */
  15682. default:
  15683. return false;
  15684. }
  15685. }
  15686. return true;
  15687. }
  15688. static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
  15689. struct bpf_idmap *idmap)
  15690. {
  15691. int i;
  15692. if (old->acquired_refs != cur->acquired_refs)
  15693. return false;
  15694. for (i = 0; i < old->acquired_refs; i++) {
  15695. if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
  15696. return false;
  15697. }
  15698. return true;
  15699. }
  15700. /* compare two verifier states
  15701. *
  15702. * all states stored in state_list are known to be valid, since
  15703. * verifier reached 'bpf_exit' instruction through them
  15704. *
  15705. * this function is called when verifier exploring different branches of
  15706. * execution popped from the state stack. If it sees an old state that has
  15707. * more strict register state and more strict stack state then this execution
  15708. * branch doesn't need to be explored further, since verifier already
  15709. * concluded that more strict state leads to valid finish.
  15710. *
  15711. * Therefore two states are equivalent if register state is more conservative
  15712. * and explored stack state is more conservative than the current one.
  15713. * Example:
  15714. * explored current
  15715. * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
  15716. * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
  15717. *
  15718. * In other words if current stack state (one being explored) has more
  15719. * valid slots than old one that already passed validation, it means
  15720. * the verifier can stop exploring and conclude that current state is valid too
  15721. *
  15722. * Similarly with registers. If explored state has register type as invalid
  15723. * whereas register type in current state is meaningful, it means that
  15724. * the current state will reach 'bpf_exit' instruction safely
  15725. */
  15726. static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
  15727. struct bpf_func_state *cur, enum exact_level exact)
  15728. {
  15729. int i;
  15730. if (old->callback_depth > cur->callback_depth)
  15731. return false;
  15732. for (i = 0; i < MAX_BPF_REG; i++)
  15733. if (!regsafe(env, &old->regs[i], &cur->regs[i],
  15734. &env->idmap_scratch, exact))
  15735. return false;
  15736. if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
  15737. return false;
  15738. if (!refsafe(old, cur, &env->idmap_scratch))
  15739. return false;
  15740. return true;
  15741. }
  15742. static void reset_idmap_scratch(struct bpf_verifier_env *env)
  15743. {
  15744. env->idmap_scratch.tmp_id_gen = env->id_gen;
  15745. memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
  15746. }
  15747. static bool states_equal(struct bpf_verifier_env *env,
  15748. struct bpf_verifier_state *old,
  15749. struct bpf_verifier_state *cur,
  15750. enum exact_level exact)
  15751. {
  15752. int i;
  15753. if (old->curframe != cur->curframe)
  15754. return false;
  15755. reset_idmap_scratch(env);
  15756. /* Verification state from speculative execution simulation
  15757. * must never prune a non-speculative execution one.
  15758. */
  15759. if (old->speculative && !cur->speculative)
  15760. return false;
  15761. if (old->active_lock.ptr != cur->active_lock.ptr)
  15762. return false;
  15763. /* Old and cur active_lock's have to be either both present
  15764. * or both absent.
  15765. */
  15766. if (!!old->active_lock.id != !!cur->active_lock.id)
  15767. return false;
  15768. if (old->active_lock.id &&
  15769. !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
  15770. return false;
  15771. if (old->active_rcu_lock != cur->active_rcu_lock)
  15772. return false;
  15773. if (old->active_preempt_lock != cur->active_preempt_lock)
  15774. return false;
  15775. if (old->in_sleepable != cur->in_sleepable)
  15776. return false;
  15777. /* for states to be equal callsites have to be the same
  15778. * and all frame states need to be equivalent
  15779. */
  15780. for (i = 0; i <= old->curframe; i++) {
  15781. if (old->frame[i]->callsite != cur->frame[i]->callsite)
  15782. return false;
  15783. if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
  15784. return false;
  15785. }
  15786. return true;
  15787. }
  15788. /* Return 0 if no propagation happened. Return negative error code if error
  15789. * happened. Otherwise, return the propagated bit.
  15790. */
  15791. static int propagate_liveness_reg(struct bpf_verifier_env *env,
  15792. struct bpf_reg_state *reg,
  15793. struct bpf_reg_state *parent_reg)
  15794. {
  15795. u8 parent_flag = parent_reg->live & REG_LIVE_READ;
  15796. u8 flag = reg->live & REG_LIVE_READ;
  15797. int err;
  15798. /* When comes here, read flags of PARENT_REG or REG could be any of
  15799. * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
  15800. * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
  15801. */
  15802. if (parent_flag == REG_LIVE_READ64 ||
  15803. /* Or if there is no read flag from REG. */
  15804. !flag ||
  15805. /* Or if the read flag from REG is the same as PARENT_REG. */
  15806. parent_flag == flag)
  15807. return 0;
  15808. err = mark_reg_read(env, reg, parent_reg, flag);
  15809. if (err)
  15810. return err;
  15811. return flag;
  15812. }
  15813. /* A write screens off any subsequent reads; but write marks come from the
  15814. * straight-line code between a state and its parent. When we arrive at an
  15815. * equivalent state (jump target or such) we didn't arrive by the straight-line
  15816. * code, so read marks in the state must propagate to the parent regardless
  15817. * of the state's write marks. That's what 'parent == state->parent' comparison
  15818. * in mark_reg_read() is for.
  15819. */
  15820. static int propagate_liveness(struct bpf_verifier_env *env,
  15821. const struct bpf_verifier_state *vstate,
  15822. struct bpf_verifier_state *vparent)
  15823. {
  15824. struct bpf_reg_state *state_reg, *parent_reg;
  15825. struct bpf_func_state *state, *parent;
  15826. int i, frame, err = 0;
  15827. if (vparent->curframe != vstate->curframe) {
  15828. WARN(1, "propagate_live: parent frame %d current frame %d\n",
  15829. vparent->curframe, vstate->curframe);
  15830. return -EFAULT;
  15831. }
  15832. /* Propagate read liveness of registers... */
  15833. BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
  15834. for (frame = 0; frame <= vstate->curframe; frame++) {
  15835. parent = vparent->frame[frame];
  15836. state = vstate->frame[frame];
  15837. parent_reg = parent->regs;
  15838. state_reg = state->regs;
  15839. /* We don't need to worry about FP liveness, it's read-only */
  15840. for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
  15841. err = propagate_liveness_reg(env, &state_reg[i],
  15842. &parent_reg[i]);
  15843. if (err < 0)
  15844. return err;
  15845. if (err == REG_LIVE_READ64)
  15846. mark_insn_zext(env, &parent_reg[i]);
  15847. }
  15848. /* Propagate stack slots. */
  15849. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
  15850. i < parent->allocated_stack / BPF_REG_SIZE; i++) {
  15851. parent_reg = &parent->stack[i].spilled_ptr;
  15852. state_reg = &state->stack[i].spilled_ptr;
  15853. err = propagate_liveness_reg(env, state_reg,
  15854. parent_reg);
  15855. if (err < 0)
  15856. return err;
  15857. }
  15858. }
  15859. return 0;
  15860. }
  15861. /* find precise scalars in the previous equivalent state and
  15862. * propagate them into the current state
  15863. */
  15864. static int propagate_precision(struct bpf_verifier_env *env,
  15865. const struct bpf_verifier_state *old)
  15866. {
  15867. struct bpf_reg_state *state_reg;
  15868. struct bpf_func_state *state;
  15869. int i, err = 0, fr;
  15870. bool first;
  15871. for (fr = old->curframe; fr >= 0; fr--) {
  15872. state = old->frame[fr];
  15873. state_reg = state->regs;
  15874. first = true;
  15875. for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
  15876. if (state_reg->type != SCALAR_VALUE ||
  15877. !state_reg->precise ||
  15878. !(state_reg->live & REG_LIVE_READ))
  15879. continue;
  15880. if (env->log.level & BPF_LOG_LEVEL2) {
  15881. if (first)
  15882. verbose(env, "frame %d: propagating r%d", fr, i);
  15883. else
  15884. verbose(env, ",r%d", i);
  15885. }
  15886. bt_set_frame_reg(&env->bt, fr, i);
  15887. first = false;
  15888. }
  15889. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  15890. if (!is_spilled_reg(&state->stack[i]))
  15891. continue;
  15892. state_reg = &state->stack[i].spilled_ptr;
  15893. if (state_reg->type != SCALAR_VALUE ||
  15894. !state_reg->precise ||
  15895. !(state_reg->live & REG_LIVE_READ))
  15896. continue;
  15897. if (env->log.level & BPF_LOG_LEVEL2) {
  15898. if (first)
  15899. verbose(env, "frame %d: propagating fp%d",
  15900. fr, (-i - 1) * BPF_REG_SIZE);
  15901. else
  15902. verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
  15903. }
  15904. bt_set_frame_slot(&env->bt, fr, i);
  15905. first = false;
  15906. }
  15907. if (!first)
  15908. verbose(env, "\n");
  15909. }
  15910. err = mark_chain_precision_batch(env);
  15911. if (err < 0)
  15912. return err;
  15913. return 0;
  15914. }
  15915. static bool states_maybe_looping(struct bpf_verifier_state *old,
  15916. struct bpf_verifier_state *cur)
  15917. {
  15918. struct bpf_func_state *fold, *fcur;
  15919. int i, fr = cur->curframe;
  15920. if (old->curframe != fr)
  15921. return false;
  15922. fold = old->frame[fr];
  15923. fcur = cur->frame[fr];
  15924. for (i = 0; i < MAX_BPF_REG; i++)
  15925. if (memcmp(&fold->regs[i], &fcur->regs[i],
  15926. offsetof(struct bpf_reg_state, parent)))
  15927. return false;
  15928. return true;
  15929. }
  15930. static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
  15931. {
  15932. return env->insn_aux_data[insn_idx].is_iter_next;
  15933. }
  15934. /* is_state_visited() handles iter_next() (see process_iter_next_call() for
  15935. * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
  15936. * states to match, which otherwise would look like an infinite loop. So while
  15937. * iter_next() calls are taken care of, we still need to be careful and
  15938. * prevent erroneous and too eager declaration of "ininite loop", when
  15939. * iterators are involved.
  15940. *
  15941. * Here's a situation in pseudo-BPF assembly form:
  15942. *
  15943. * 0: again: ; set up iter_next() call args
  15944. * 1: r1 = &it ; <CHECKPOINT HERE>
  15945. * 2: call bpf_iter_num_next ; this is iter_next() call
  15946. * 3: if r0 == 0 goto done
  15947. * 4: ... something useful here ...
  15948. * 5: goto again ; another iteration
  15949. * 6: done:
  15950. * 7: r1 = &it
  15951. * 8: call bpf_iter_num_destroy ; clean up iter state
  15952. * 9: exit
  15953. *
  15954. * This is a typical loop. Let's assume that we have a prune point at 1:,
  15955. * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
  15956. * again`, assuming other heuristics don't get in a way).
  15957. *
  15958. * When we first time come to 1:, let's say we have some state X. We proceed
  15959. * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
  15960. * Now we come back to validate that forked ACTIVE state. We proceed through
  15961. * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
  15962. * are converging. But the problem is that we don't know that yet, as this
  15963. * convergence has to happen at iter_next() call site only. So if nothing is
  15964. * done, at 1: verifier will use bounded loop logic and declare infinite
  15965. * looping (and would be *technically* correct, if not for iterator's
  15966. * "eventual sticky NULL" contract, see process_iter_next_call()). But we
  15967. * don't want that. So what we do in process_iter_next_call() when we go on
  15968. * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
  15969. * a different iteration. So when we suspect an infinite loop, we additionally
  15970. * check if any of the *ACTIVE* iterator states depths differ. If yes, we
  15971. * pretend we are not looping and wait for next iter_next() call.
  15972. *
  15973. * This only applies to ACTIVE state. In DRAINED state we don't expect to
  15974. * loop, because that would actually mean infinite loop, as DRAINED state is
  15975. * "sticky", and so we'll keep returning into the same instruction with the
  15976. * same state (at least in one of possible code paths).
  15977. *
  15978. * This approach allows to keep infinite loop heuristic even in the face of
  15979. * active iterator. E.g., C snippet below is and will be detected as
  15980. * inifintely looping:
  15981. *
  15982. * struct bpf_iter_num it;
  15983. * int *p, x;
  15984. *
  15985. * bpf_iter_num_new(&it, 0, 10);
  15986. * while ((p = bpf_iter_num_next(&t))) {
  15987. * x = p;
  15988. * while (x--) {} // <<-- infinite loop here
  15989. * }
  15990. *
  15991. */
  15992. static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
  15993. {
  15994. struct bpf_reg_state *slot, *cur_slot;
  15995. struct bpf_func_state *state;
  15996. int i, fr;
  15997. for (fr = old->curframe; fr >= 0; fr--) {
  15998. state = old->frame[fr];
  15999. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  16000. if (state->stack[i].slot_type[0] != STACK_ITER)
  16001. continue;
  16002. slot = &state->stack[i].spilled_ptr;
  16003. if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
  16004. continue;
  16005. cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
  16006. if (cur_slot->iter.depth != slot->iter.depth)
  16007. return true;
  16008. }
  16009. }
  16010. return false;
  16011. }
  16012. static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
  16013. {
  16014. struct bpf_verifier_state_list *new_sl;
  16015. struct bpf_verifier_state_list *sl, **pprev;
  16016. struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
  16017. int i, j, n, err, states_cnt = 0;
  16018. bool force_new_state, add_new_state, force_exact;
  16019. force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
  16020. /* Avoid accumulating infinitely long jmp history */
  16021. cur->insn_hist_end - cur->insn_hist_start > 40;
  16022. /* bpf progs typically have pruning point every 4 instructions
  16023. * http://vger.kernel.org/bpfconf2019.html#session-1
  16024. * Do not add new state for future pruning if the verifier hasn't seen
  16025. * at least 2 jumps and at least 8 instructions.
  16026. * This heuristics helps decrease 'total_states' and 'peak_states' metric.
  16027. * In tests that amounts to up to 50% reduction into total verifier
  16028. * memory consumption and 20% verifier time speedup.
  16029. */
  16030. add_new_state = force_new_state;
  16031. if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
  16032. env->insn_processed - env->prev_insn_processed >= 8)
  16033. add_new_state = true;
  16034. pprev = explored_state(env, insn_idx);
  16035. sl = *pprev;
  16036. clean_live_states(env, insn_idx, cur);
  16037. while (sl) {
  16038. states_cnt++;
  16039. if (sl->state.insn_idx != insn_idx)
  16040. goto next;
  16041. if (sl->state.branches) {
  16042. struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
  16043. if (frame->in_async_callback_fn &&
  16044. frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
  16045. /* Different async_entry_cnt means that the verifier is
  16046. * processing another entry into async callback.
  16047. * Seeing the same state is not an indication of infinite
  16048. * loop or infinite recursion.
  16049. * But finding the same state doesn't mean that it's safe
  16050. * to stop processing the current state. The previous state
  16051. * hasn't yet reached bpf_exit, since state.branches > 0.
  16052. * Checking in_async_callback_fn alone is not enough either.
  16053. * Since the verifier still needs to catch infinite loops
  16054. * inside async callbacks.
  16055. */
  16056. goto skip_inf_loop_check;
  16057. }
  16058. /* BPF open-coded iterators loop detection is special.
  16059. * states_maybe_looping() logic is too simplistic in detecting
  16060. * states that *might* be equivalent, because it doesn't know
  16061. * about ID remapping, so don't even perform it.
  16062. * See process_iter_next_call() and iter_active_depths_differ()
  16063. * for overview of the logic. When current and one of parent
  16064. * states are detected as equivalent, it's a good thing: we prove
  16065. * convergence and can stop simulating further iterations.
  16066. * It's safe to assume that iterator loop will finish, taking into
  16067. * account iter_next() contract of eventually returning
  16068. * sticky NULL result.
  16069. *
  16070. * Note, that states have to be compared exactly in this case because
  16071. * read and precision marks might not be finalized inside the loop.
  16072. * E.g. as in the program below:
  16073. *
  16074. * 1. r7 = -16
  16075. * 2. r6 = bpf_get_prandom_u32()
  16076. * 3. while (bpf_iter_num_next(&fp[-8])) {
  16077. * 4. if (r6 != 42) {
  16078. * 5. r7 = -32
  16079. * 6. r6 = bpf_get_prandom_u32()
  16080. * 7. continue
  16081. * 8. }
  16082. * 9. r0 = r10
  16083. * 10. r0 += r7
  16084. * 11. r8 = *(u64 *)(r0 + 0)
  16085. * 12. r6 = bpf_get_prandom_u32()
  16086. * 13. }
  16087. *
  16088. * Here verifier would first visit path 1-3, create a checkpoint at 3
  16089. * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
  16090. * not have read or precision mark for r7 yet, thus inexact states
  16091. * comparison would discard current state with r7=-32
  16092. * => unsafe memory access at 11 would not be caught.
  16093. */
  16094. if (is_iter_next_insn(env, insn_idx)) {
  16095. if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
  16096. struct bpf_func_state *cur_frame;
  16097. struct bpf_reg_state *iter_state, *iter_reg;
  16098. int spi;
  16099. cur_frame = cur->frame[cur->curframe];
  16100. /* btf_check_iter_kfuncs() enforces that
  16101. * iter state pointer is always the first arg
  16102. */
  16103. iter_reg = &cur_frame->regs[BPF_REG_1];
  16104. /* current state is valid due to states_equal(),
  16105. * so we can assume valid iter and reg state,
  16106. * no need for extra (re-)validations
  16107. */
  16108. spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
  16109. iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
  16110. if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
  16111. update_loop_entry(cur, &sl->state);
  16112. goto hit;
  16113. }
  16114. }
  16115. goto skip_inf_loop_check;
  16116. }
  16117. if (is_may_goto_insn_at(env, insn_idx)) {
  16118. if (sl->state.may_goto_depth != cur->may_goto_depth &&
  16119. states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
  16120. update_loop_entry(cur, &sl->state);
  16121. goto hit;
  16122. }
  16123. }
  16124. if (calls_callback(env, insn_idx)) {
  16125. if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
  16126. goto hit;
  16127. goto skip_inf_loop_check;
  16128. }
  16129. /* attempt to detect infinite loop to avoid unnecessary doomed work */
  16130. if (states_maybe_looping(&sl->state, cur) &&
  16131. states_equal(env, &sl->state, cur, EXACT) &&
  16132. !iter_active_depths_differ(&sl->state, cur) &&
  16133. sl->state.may_goto_depth == cur->may_goto_depth &&
  16134. sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
  16135. verbose_linfo(env, insn_idx, "; ");
  16136. verbose(env, "infinite loop detected at insn %d\n", insn_idx);
  16137. verbose(env, "cur state:");
  16138. print_verifier_state(env, cur->frame[cur->curframe], true);
  16139. verbose(env, "old state:");
  16140. print_verifier_state(env, sl->state.frame[cur->curframe], true);
  16141. return -EINVAL;
  16142. }
  16143. /* if the verifier is processing a loop, avoid adding new state
  16144. * too often, since different loop iterations have distinct
  16145. * states and may not help future pruning.
  16146. * This threshold shouldn't be too low to make sure that
  16147. * a loop with large bound will be rejected quickly.
  16148. * The most abusive loop will be:
  16149. * r1 += 1
  16150. * if r1 < 1000000 goto pc-2
  16151. * 1M insn_procssed limit / 100 == 10k peak states.
  16152. * This threshold shouldn't be too high either, since states
  16153. * at the end of the loop are likely to be useful in pruning.
  16154. */
  16155. skip_inf_loop_check:
  16156. if (!force_new_state &&
  16157. env->jmps_processed - env->prev_jmps_processed < 20 &&
  16158. env->insn_processed - env->prev_insn_processed < 100)
  16159. add_new_state = false;
  16160. goto miss;
  16161. }
  16162. /* If sl->state is a part of a loop and this loop's entry is a part of
  16163. * current verification path then states have to be compared exactly.
  16164. * 'force_exact' is needed to catch the following case:
  16165. *
  16166. * initial Here state 'succ' was processed first,
  16167. * | it was eventually tracked to produce a
  16168. * V state identical to 'hdr'.
  16169. * .---------> hdr All branches from 'succ' had been explored
  16170. * | | and thus 'succ' has its .branches == 0.
  16171. * | V
  16172. * | .------... Suppose states 'cur' and 'succ' correspond
  16173. * | | | to the same instruction + callsites.
  16174. * | V V In such case it is necessary to check
  16175. * | ... ... if 'succ' and 'cur' are states_equal().
  16176. * | | | If 'succ' and 'cur' are a part of the
  16177. * | V V same loop exact flag has to be set.
  16178. * | succ <- cur To check if that is the case, verify
  16179. * | | if loop entry of 'succ' is in current
  16180. * | V DFS path.
  16181. * | ...
  16182. * | |
  16183. * '----'
  16184. *
  16185. * Additional details are in the comment before get_loop_entry().
  16186. */
  16187. loop_entry = get_loop_entry(&sl->state);
  16188. force_exact = loop_entry && loop_entry->branches > 0;
  16189. if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
  16190. if (force_exact)
  16191. update_loop_entry(cur, loop_entry);
  16192. hit:
  16193. sl->hit_cnt++;
  16194. /* reached equivalent register/stack state,
  16195. * prune the search.
  16196. * Registers read by the continuation are read by us.
  16197. * If we have any write marks in env->cur_state, they
  16198. * will prevent corresponding reads in the continuation
  16199. * from reaching our parent (an explored_state). Our
  16200. * own state will get the read marks recorded, but
  16201. * they'll be immediately forgotten as we're pruning
  16202. * this state and will pop a new one.
  16203. */
  16204. err = propagate_liveness(env, &sl->state, cur);
  16205. /* if previous state reached the exit with precision and
  16206. * current state is equivalent to it (except precision marks)
  16207. * the precision needs to be propagated back in
  16208. * the current state.
  16209. */
  16210. if (is_jmp_point(env, env->insn_idx))
  16211. err = err ? : push_insn_history(env, cur, 0, 0);
  16212. err = err ? : propagate_precision(env, &sl->state);
  16213. if (err)
  16214. return err;
  16215. return 1;
  16216. }
  16217. miss:
  16218. /* when new state is not going to be added do not increase miss count.
  16219. * Otherwise several loop iterations will remove the state
  16220. * recorded earlier. The goal of these heuristics is to have
  16221. * states from some iterations of the loop (some in the beginning
  16222. * and some at the end) to help pruning.
  16223. */
  16224. if (add_new_state)
  16225. sl->miss_cnt++;
  16226. /* heuristic to determine whether this state is beneficial
  16227. * to keep checking from state equivalence point of view.
  16228. * Higher numbers increase max_states_per_insn and verification time,
  16229. * but do not meaningfully decrease insn_processed.
  16230. * 'n' controls how many times state could miss before eviction.
  16231. * Use bigger 'n' for checkpoints because evicting checkpoint states
  16232. * too early would hinder iterator convergence.
  16233. */
  16234. n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
  16235. if (sl->miss_cnt > sl->hit_cnt * n + n) {
  16236. /* the state is unlikely to be useful. Remove it to
  16237. * speed up verification
  16238. */
  16239. *pprev = sl->next;
  16240. if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
  16241. !sl->state.used_as_loop_entry) {
  16242. u32 br = sl->state.branches;
  16243. WARN_ONCE(br,
  16244. "BUG live_done but branches_to_explore %d\n",
  16245. br);
  16246. free_verifier_state(&sl->state, false);
  16247. kfree(sl);
  16248. env->peak_states--;
  16249. } else {
  16250. /* cannot free this state, since parentage chain may
  16251. * walk it later. Add it for free_list instead to
  16252. * be freed at the end of verification
  16253. */
  16254. sl->next = env->free_list;
  16255. env->free_list = sl;
  16256. }
  16257. sl = *pprev;
  16258. continue;
  16259. }
  16260. next:
  16261. pprev = &sl->next;
  16262. sl = *pprev;
  16263. }
  16264. if (env->max_states_per_insn < states_cnt)
  16265. env->max_states_per_insn = states_cnt;
  16266. if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
  16267. return 0;
  16268. if (!add_new_state)
  16269. return 0;
  16270. /* There were no equivalent states, remember the current one.
  16271. * Technically the current state is not proven to be safe yet,
  16272. * but it will either reach outer most bpf_exit (which means it's safe)
  16273. * or it will be rejected. When there are no loops the verifier won't be
  16274. * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
  16275. * again on the way to bpf_exit.
  16276. * When looping the sl->state.branches will be > 0 and this state
  16277. * will not be considered for equivalence until branches == 0.
  16278. */
  16279. new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
  16280. if (!new_sl)
  16281. return -ENOMEM;
  16282. env->total_states++;
  16283. env->peak_states++;
  16284. env->prev_jmps_processed = env->jmps_processed;
  16285. env->prev_insn_processed = env->insn_processed;
  16286. /* forget precise markings we inherited, see __mark_chain_precision */
  16287. if (env->bpf_capable)
  16288. mark_all_scalars_imprecise(env, cur);
  16289. /* add new state to the head of linked list */
  16290. new = &new_sl->state;
  16291. err = copy_verifier_state(new, cur);
  16292. if (err) {
  16293. free_verifier_state(new, false);
  16294. kfree(new_sl);
  16295. return err;
  16296. }
  16297. new->insn_idx = insn_idx;
  16298. WARN_ONCE(new->branches != 1,
  16299. "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
  16300. cur->parent = new;
  16301. cur->first_insn_idx = insn_idx;
  16302. cur->insn_hist_start = cur->insn_hist_end;
  16303. cur->dfs_depth = new->dfs_depth + 1;
  16304. new_sl->next = *explored_state(env, insn_idx);
  16305. *explored_state(env, insn_idx) = new_sl;
  16306. /* connect new state to parentage chain. Current frame needs all
  16307. * registers connected. Only r6 - r9 of the callers are alive (pushed
  16308. * to the stack implicitly by JITs) so in callers' frames connect just
  16309. * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
  16310. * the state of the call instruction (with WRITTEN set), and r0 comes
  16311. * from callee with its full parentage chain, anyway.
  16312. */
  16313. /* clear write marks in current state: the writes we did are not writes
  16314. * our child did, so they don't screen off its reads from us.
  16315. * (There are no read marks in current state, because reads always mark
  16316. * their parent and current state never has children yet. Only
  16317. * explored_states can get read marks.)
  16318. */
  16319. for (j = 0; j <= cur->curframe; j++) {
  16320. for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
  16321. cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
  16322. for (i = 0; i < BPF_REG_FP; i++)
  16323. cur->frame[j]->regs[i].live = REG_LIVE_NONE;
  16324. }
  16325. /* all stack frames are accessible from callee, clear them all */
  16326. for (j = 0; j <= cur->curframe; j++) {
  16327. struct bpf_func_state *frame = cur->frame[j];
  16328. struct bpf_func_state *newframe = new->frame[j];
  16329. for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
  16330. frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
  16331. frame->stack[i].spilled_ptr.parent =
  16332. &newframe->stack[i].spilled_ptr;
  16333. }
  16334. }
  16335. return 0;
  16336. }
  16337. /* Return true if it's OK to have the same insn return a different type. */
  16338. static bool reg_type_mismatch_ok(enum bpf_reg_type type)
  16339. {
  16340. switch (base_type(type)) {
  16341. case PTR_TO_CTX:
  16342. case PTR_TO_SOCKET:
  16343. case PTR_TO_SOCK_COMMON:
  16344. case PTR_TO_TCP_SOCK:
  16345. case PTR_TO_XDP_SOCK:
  16346. case PTR_TO_BTF_ID:
  16347. case PTR_TO_ARENA:
  16348. return false;
  16349. default:
  16350. return true;
  16351. }
  16352. }
  16353. /* If an instruction was previously used with particular pointer types, then we
  16354. * need to be careful to avoid cases such as the below, where it may be ok
  16355. * for one branch accessing the pointer, but not ok for the other branch:
  16356. *
  16357. * R1 = sock_ptr
  16358. * goto X;
  16359. * ...
  16360. * R1 = some_other_valid_ptr;
  16361. * goto X;
  16362. * ...
  16363. * R2 = *(u32 *)(R1 + 0);
  16364. */
  16365. static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
  16366. {
  16367. return src != prev && (!reg_type_mismatch_ok(src) ||
  16368. !reg_type_mismatch_ok(prev));
  16369. }
  16370. static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
  16371. bool allow_trust_mismatch)
  16372. {
  16373. enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
  16374. if (*prev_type == NOT_INIT) {
  16375. /* Saw a valid insn
  16376. * dst_reg = *(u32 *)(src_reg + off)
  16377. * save type to validate intersecting paths
  16378. */
  16379. *prev_type = type;
  16380. } else if (reg_type_mismatch(type, *prev_type)) {
  16381. /* Abuser program is trying to use the same insn
  16382. * dst_reg = *(u32*) (src_reg + off)
  16383. * with different pointer types:
  16384. * src_reg == ctx in one branch and
  16385. * src_reg == stack|map in some other branch.
  16386. * Reject it.
  16387. */
  16388. if (allow_trust_mismatch &&
  16389. base_type(type) == PTR_TO_BTF_ID &&
  16390. base_type(*prev_type) == PTR_TO_BTF_ID) {
  16391. /*
  16392. * Have to support a use case when one path through
  16393. * the program yields TRUSTED pointer while another
  16394. * is UNTRUSTED. Fallback to UNTRUSTED to generate
  16395. * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
  16396. */
  16397. *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
  16398. } else {
  16399. verbose(env, "same insn cannot be used with different pointers\n");
  16400. return -EINVAL;
  16401. }
  16402. }
  16403. return 0;
  16404. }
  16405. static int do_check(struct bpf_verifier_env *env)
  16406. {
  16407. bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
  16408. struct bpf_verifier_state *state = env->cur_state;
  16409. struct bpf_insn *insns = env->prog->insnsi;
  16410. struct bpf_reg_state *regs;
  16411. int insn_cnt = env->prog->len;
  16412. bool do_print_state = false;
  16413. int prev_insn_idx = -1;
  16414. for (;;) {
  16415. bool exception_exit = false;
  16416. struct bpf_insn *insn;
  16417. u8 class;
  16418. int err;
  16419. /* reset current history entry on each new instruction */
  16420. env->cur_hist_ent = NULL;
  16421. env->prev_insn_idx = prev_insn_idx;
  16422. if (env->insn_idx >= insn_cnt) {
  16423. verbose(env, "invalid insn idx %d insn_cnt %d\n",
  16424. env->insn_idx, insn_cnt);
  16425. return -EFAULT;
  16426. }
  16427. insn = &insns[env->insn_idx];
  16428. class = BPF_CLASS(insn->code);
  16429. if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
  16430. verbose(env,
  16431. "BPF program is too large. Processed %d insn\n",
  16432. env->insn_processed);
  16433. return -E2BIG;
  16434. }
  16435. state->last_insn_idx = env->prev_insn_idx;
  16436. if (is_prune_point(env, env->insn_idx)) {
  16437. err = is_state_visited(env, env->insn_idx);
  16438. if (err < 0)
  16439. return err;
  16440. if (err == 1) {
  16441. /* found equivalent state, can prune the search */
  16442. if (env->log.level & BPF_LOG_LEVEL) {
  16443. if (do_print_state)
  16444. verbose(env, "\nfrom %d to %d%s: safe\n",
  16445. env->prev_insn_idx, env->insn_idx,
  16446. env->cur_state->speculative ?
  16447. " (speculative execution)" : "");
  16448. else
  16449. verbose(env, "%d: safe\n", env->insn_idx);
  16450. }
  16451. goto process_bpf_exit;
  16452. }
  16453. }
  16454. if (is_jmp_point(env, env->insn_idx)) {
  16455. err = push_insn_history(env, state, 0, 0);
  16456. if (err)
  16457. return err;
  16458. }
  16459. if (signal_pending(current))
  16460. return -EAGAIN;
  16461. if (need_resched())
  16462. cond_resched();
  16463. if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
  16464. verbose(env, "\nfrom %d to %d%s:",
  16465. env->prev_insn_idx, env->insn_idx,
  16466. env->cur_state->speculative ?
  16467. " (speculative execution)" : "");
  16468. print_verifier_state(env, state->frame[state->curframe], true);
  16469. do_print_state = false;
  16470. }
  16471. if (env->log.level & BPF_LOG_LEVEL) {
  16472. const struct bpf_insn_cbs cbs = {
  16473. .cb_call = disasm_kfunc_name,
  16474. .cb_print = verbose,
  16475. .private_data = env,
  16476. };
  16477. if (verifier_state_scratched(env))
  16478. print_insn_state(env, state->frame[state->curframe]);
  16479. verbose_linfo(env, env->insn_idx, "; ");
  16480. env->prev_log_pos = env->log.end_pos;
  16481. verbose(env, "%d: ", env->insn_idx);
  16482. print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
  16483. env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
  16484. env->prev_log_pos = env->log.end_pos;
  16485. }
  16486. if (bpf_prog_is_offloaded(env->prog->aux)) {
  16487. err = bpf_prog_offload_verify_insn(env, env->insn_idx,
  16488. env->prev_insn_idx);
  16489. if (err)
  16490. return err;
  16491. }
  16492. regs = cur_regs(env);
  16493. sanitize_mark_insn_seen(env);
  16494. prev_insn_idx = env->insn_idx;
  16495. if (class == BPF_ALU || class == BPF_ALU64) {
  16496. err = check_alu_op(env, insn);
  16497. if (err)
  16498. return err;
  16499. } else if (class == BPF_LDX) {
  16500. enum bpf_reg_type src_reg_type;
  16501. /* check for reserved fields is already done */
  16502. /* check src operand */
  16503. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  16504. if (err)
  16505. return err;
  16506. err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
  16507. if (err)
  16508. return err;
  16509. src_reg_type = regs[insn->src_reg].type;
  16510. /* check that memory (src_reg + off) is readable,
  16511. * the state of dst_reg will be updated by this func
  16512. */
  16513. err = check_mem_access(env, env->insn_idx, insn->src_reg,
  16514. insn->off, BPF_SIZE(insn->code),
  16515. BPF_READ, insn->dst_reg, false,
  16516. BPF_MODE(insn->code) == BPF_MEMSX);
  16517. err = err ?: save_aux_ptr_type(env, src_reg_type, true);
  16518. err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
  16519. if (err)
  16520. return err;
  16521. } else if (class == BPF_STX) {
  16522. enum bpf_reg_type dst_reg_type;
  16523. if (BPF_MODE(insn->code) == BPF_ATOMIC) {
  16524. err = check_atomic(env, env->insn_idx, insn);
  16525. if (err)
  16526. return err;
  16527. env->insn_idx++;
  16528. continue;
  16529. }
  16530. if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
  16531. verbose(env, "BPF_STX uses reserved fields\n");
  16532. return -EINVAL;
  16533. }
  16534. /* check src1 operand */
  16535. err = check_reg_arg(env, insn->src_reg, SRC_OP);
  16536. if (err)
  16537. return err;
  16538. /* check src2 operand */
  16539. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  16540. if (err)
  16541. return err;
  16542. dst_reg_type = regs[insn->dst_reg].type;
  16543. /* check that memory (dst_reg + off) is writeable */
  16544. err = check_mem_access(env, env->insn_idx, insn->dst_reg,
  16545. insn->off, BPF_SIZE(insn->code),
  16546. BPF_WRITE, insn->src_reg, false, false);
  16547. if (err)
  16548. return err;
  16549. err = save_aux_ptr_type(env, dst_reg_type, false);
  16550. if (err)
  16551. return err;
  16552. } else if (class == BPF_ST) {
  16553. enum bpf_reg_type dst_reg_type;
  16554. if (BPF_MODE(insn->code) != BPF_MEM ||
  16555. insn->src_reg != BPF_REG_0) {
  16556. verbose(env, "BPF_ST uses reserved fields\n");
  16557. return -EINVAL;
  16558. }
  16559. /* check src operand */
  16560. err = check_reg_arg(env, insn->dst_reg, SRC_OP);
  16561. if (err)
  16562. return err;
  16563. dst_reg_type = regs[insn->dst_reg].type;
  16564. /* check that memory (dst_reg + off) is writeable */
  16565. err = check_mem_access(env, env->insn_idx, insn->dst_reg,
  16566. insn->off, BPF_SIZE(insn->code),
  16567. BPF_WRITE, -1, false, false);
  16568. if (err)
  16569. return err;
  16570. err = save_aux_ptr_type(env, dst_reg_type, false);
  16571. if (err)
  16572. return err;
  16573. } else if (class == BPF_JMP || class == BPF_JMP32) {
  16574. u8 opcode = BPF_OP(insn->code);
  16575. env->jmps_processed++;
  16576. if (opcode == BPF_CALL) {
  16577. if (BPF_SRC(insn->code) != BPF_K ||
  16578. (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
  16579. && insn->off != 0) ||
  16580. (insn->src_reg != BPF_REG_0 &&
  16581. insn->src_reg != BPF_PSEUDO_CALL &&
  16582. insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
  16583. insn->dst_reg != BPF_REG_0 ||
  16584. class == BPF_JMP32) {
  16585. verbose(env, "BPF_CALL uses reserved fields\n");
  16586. return -EINVAL;
  16587. }
  16588. if (env->cur_state->active_lock.ptr) {
  16589. if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
  16590. (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
  16591. (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
  16592. verbose(env, "function calls are not allowed while holding a lock\n");
  16593. return -EINVAL;
  16594. }
  16595. }
  16596. if (insn->src_reg == BPF_PSEUDO_CALL) {
  16597. err = check_func_call(env, insn, &env->insn_idx);
  16598. } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
  16599. err = check_kfunc_call(env, insn, &env->insn_idx);
  16600. if (!err && is_bpf_throw_kfunc(insn)) {
  16601. exception_exit = true;
  16602. goto process_bpf_exit_full;
  16603. }
  16604. } else {
  16605. err = check_helper_call(env, insn, &env->insn_idx);
  16606. }
  16607. if (err)
  16608. return err;
  16609. mark_reg_scratched(env, BPF_REG_0);
  16610. } else if (opcode == BPF_JA) {
  16611. if (BPF_SRC(insn->code) != BPF_K ||
  16612. insn->src_reg != BPF_REG_0 ||
  16613. insn->dst_reg != BPF_REG_0 ||
  16614. (class == BPF_JMP && insn->imm != 0) ||
  16615. (class == BPF_JMP32 && insn->off != 0)) {
  16616. verbose(env, "BPF_JA uses reserved fields\n");
  16617. return -EINVAL;
  16618. }
  16619. if (class == BPF_JMP)
  16620. env->insn_idx += insn->off + 1;
  16621. else
  16622. env->insn_idx += insn->imm + 1;
  16623. continue;
  16624. } else if (opcode == BPF_EXIT) {
  16625. if (BPF_SRC(insn->code) != BPF_K ||
  16626. insn->imm != 0 ||
  16627. insn->src_reg != BPF_REG_0 ||
  16628. insn->dst_reg != BPF_REG_0 ||
  16629. class == BPF_JMP32) {
  16630. verbose(env, "BPF_EXIT uses reserved fields\n");
  16631. return -EINVAL;
  16632. }
  16633. process_bpf_exit_full:
  16634. if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
  16635. verbose(env, "bpf_spin_unlock is missing\n");
  16636. return -EINVAL;
  16637. }
  16638. if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
  16639. verbose(env, "bpf_rcu_read_unlock is missing\n");
  16640. return -EINVAL;
  16641. }
  16642. if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) {
  16643. verbose(env, "%d bpf_preempt_enable%s missing\n",
  16644. env->cur_state->active_preempt_lock,
  16645. env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are");
  16646. return -EINVAL;
  16647. }
  16648. /* We must do check_reference_leak here before
  16649. * prepare_func_exit to handle the case when
  16650. * state->curframe > 0, it may be a callback
  16651. * function, for which reference_state must
  16652. * match caller reference state when it exits.
  16653. */
  16654. err = check_reference_leak(env, exception_exit);
  16655. if (err)
  16656. return err;
  16657. /* The side effect of the prepare_func_exit
  16658. * which is being skipped is that it frees
  16659. * bpf_func_state. Typically, process_bpf_exit
  16660. * will only be hit with outermost exit.
  16661. * copy_verifier_state in pop_stack will handle
  16662. * freeing of any extra bpf_func_state left over
  16663. * from not processing all nested function
  16664. * exits. We also skip return code checks as
  16665. * they are not needed for exceptional exits.
  16666. */
  16667. if (exception_exit)
  16668. goto process_bpf_exit;
  16669. if (state->curframe) {
  16670. /* exit from nested function */
  16671. err = prepare_func_exit(env, &env->insn_idx);
  16672. if (err)
  16673. return err;
  16674. do_print_state = true;
  16675. continue;
  16676. }
  16677. err = check_return_code(env, BPF_REG_0, "R0");
  16678. if (err)
  16679. return err;
  16680. process_bpf_exit:
  16681. mark_verifier_state_scratched(env);
  16682. update_branch_counts(env, env->cur_state);
  16683. err = pop_stack(env, &prev_insn_idx,
  16684. &env->insn_idx, pop_log);
  16685. if (err < 0) {
  16686. if (err != -ENOENT)
  16687. return err;
  16688. break;
  16689. } else {
  16690. if (WARN_ON_ONCE(env->cur_state->loop_entry)) {
  16691. verbose(env, "verifier bug: env->cur_state->loop_entry != NULL\n");
  16692. return -EFAULT;
  16693. }
  16694. do_print_state = true;
  16695. continue;
  16696. }
  16697. } else {
  16698. err = check_cond_jmp_op(env, insn, &env->insn_idx);
  16699. if (err)
  16700. return err;
  16701. }
  16702. } else if (class == BPF_LD) {
  16703. u8 mode = BPF_MODE(insn->code);
  16704. if (mode == BPF_ABS || mode == BPF_IND) {
  16705. err = check_ld_abs(env, insn);
  16706. if (err)
  16707. return err;
  16708. } else if (mode == BPF_IMM) {
  16709. err = check_ld_imm(env, insn);
  16710. if (err)
  16711. return err;
  16712. env->insn_idx++;
  16713. sanitize_mark_insn_seen(env);
  16714. } else {
  16715. verbose(env, "invalid BPF_LD mode\n");
  16716. return -EINVAL;
  16717. }
  16718. } else {
  16719. verbose(env, "unknown insn class %d\n", class);
  16720. return -EINVAL;
  16721. }
  16722. env->insn_idx++;
  16723. }
  16724. return 0;
  16725. }
  16726. static int find_btf_percpu_datasec(struct btf *btf)
  16727. {
  16728. const struct btf_type *t;
  16729. const char *tname;
  16730. int i, n;
  16731. /*
  16732. * Both vmlinux and module each have their own ".data..percpu"
  16733. * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
  16734. * types to look at only module's own BTF types.
  16735. */
  16736. n = btf_nr_types(btf);
  16737. if (btf_is_module(btf))
  16738. i = btf_nr_types(btf_vmlinux);
  16739. else
  16740. i = 1;
  16741. for(; i < n; i++) {
  16742. t = btf_type_by_id(btf, i);
  16743. if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
  16744. continue;
  16745. tname = btf_name_by_offset(btf, t->name_off);
  16746. if (!strcmp(tname, ".data..percpu"))
  16747. return i;
  16748. }
  16749. return -ENOENT;
  16750. }
  16751. /* replace pseudo btf_id with kernel symbol address */
  16752. static int check_pseudo_btf_id(struct bpf_verifier_env *env,
  16753. struct bpf_insn *insn,
  16754. struct bpf_insn_aux_data *aux)
  16755. {
  16756. const struct btf_var_secinfo *vsi;
  16757. const struct btf_type *datasec;
  16758. struct btf_mod_pair *btf_mod;
  16759. const struct btf_type *t;
  16760. const char *sym_name;
  16761. bool percpu = false;
  16762. u32 type, id = insn->imm;
  16763. struct btf *btf;
  16764. s32 datasec_id;
  16765. u64 addr;
  16766. int i, btf_fd, err;
  16767. btf_fd = insn[1].imm;
  16768. if (btf_fd) {
  16769. btf = btf_get_by_fd(btf_fd);
  16770. if (IS_ERR(btf)) {
  16771. verbose(env, "invalid module BTF object FD specified.\n");
  16772. return -EINVAL;
  16773. }
  16774. } else {
  16775. if (!btf_vmlinux) {
  16776. verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
  16777. return -EINVAL;
  16778. }
  16779. btf = btf_vmlinux;
  16780. btf_get(btf);
  16781. }
  16782. t = btf_type_by_id(btf, id);
  16783. if (!t) {
  16784. verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
  16785. err = -ENOENT;
  16786. goto err_put;
  16787. }
  16788. if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
  16789. verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
  16790. err = -EINVAL;
  16791. goto err_put;
  16792. }
  16793. sym_name = btf_name_by_offset(btf, t->name_off);
  16794. addr = kallsyms_lookup_name(sym_name);
  16795. if (!addr) {
  16796. verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
  16797. sym_name);
  16798. err = -ENOENT;
  16799. goto err_put;
  16800. }
  16801. insn[0].imm = (u32)addr;
  16802. insn[1].imm = addr >> 32;
  16803. if (btf_type_is_func(t)) {
  16804. aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
  16805. aux->btf_var.mem_size = 0;
  16806. goto check_btf;
  16807. }
  16808. datasec_id = find_btf_percpu_datasec(btf);
  16809. if (datasec_id > 0) {
  16810. datasec = btf_type_by_id(btf, datasec_id);
  16811. for_each_vsi(i, datasec, vsi) {
  16812. if (vsi->type == id) {
  16813. percpu = true;
  16814. break;
  16815. }
  16816. }
  16817. }
  16818. type = t->type;
  16819. t = btf_type_skip_modifiers(btf, type, NULL);
  16820. if (percpu) {
  16821. aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
  16822. aux->btf_var.btf = btf;
  16823. aux->btf_var.btf_id = type;
  16824. } else if (!btf_type_is_struct(t)) {
  16825. const struct btf_type *ret;
  16826. const char *tname;
  16827. u32 tsize;
  16828. /* resolve the type size of ksym. */
  16829. ret = btf_resolve_size(btf, t, &tsize);
  16830. if (IS_ERR(ret)) {
  16831. tname = btf_name_by_offset(btf, t->name_off);
  16832. verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
  16833. tname, PTR_ERR(ret));
  16834. err = -EINVAL;
  16835. goto err_put;
  16836. }
  16837. aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
  16838. aux->btf_var.mem_size = tsize;
  16839. } else {
  16840. aux->btf_var.reg_type = PTR_TO_BTF_ID;
  16841. aux->btf_var.btf = btf;
  16842. aux->btf_var.btf_id = type;
  16843. }
  16844. check_btf:
  16845. /* check whether we recorded this BTF (and maybe module) already */
  16846. for (i = 0; i < env->used_btf_cnt; i++) {
  16847. if (env->used_btfs[i].btf == btf) {
  16848. btf_put(btf);
  16849. return 0;
  16850. }
  16851. }
  16852. if (env->used_btf_cnt >= MAX_USED_BTFS) {
  16853. err = -E2BIG;
  16854. goto err_put;
  16855. }
  16856. btf_mod = &env->used_btfs[env->used_btf_cnt];
  16857. btf_mod->btf = btf;
  16858. btf_mod->module = NULL;
  16859. /* if we reference variables from kernel module, bump its refcount */
  16860. if (btf_is_module(btf)) {
  16861. btf_mod->module = btf_try_get_module(btf);
  16862. if (!btf_mod->module) {
  16863. err = -ENXIO;
  16864. goto err_put;
  16865. }
  16866. }
  16867. env->used_btf_cnt++;
  16868. return 0;
  16869. err_put:
  16870. btf_put(btf);
  16871. return err;
  16872. }
  16873. static bool is_tracing_prog_type(enum bpf_prog_type type)
  16874. {
  16875. switch (type) {
  16876. case BPF_PROG_TYPE_KPROBE:
  16877. case BPF_PROG_TYPE_TRACEPOINT:
  16878. case BPF_PROG_TYPE_PERF_EVENT:
  16879. case BPF_PROG_TYPE_RAW_TRACEPOINT:
  16880. case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
  16881. return true;
  16882. default:
  16883. return false;
  16884. }
  16885. }
  16886. static int check_map_prog_compatibility(struct bpf_verifier_env *env,
  16887. struct bpf_map *map,
  16888. struct bpf_prog *prog)
  16889. {
  16890. enum bpf_prog_type prog_type = resolve_prog_type(prog);
  16891. if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
  16892. btf_record_has_field(map->record, BPF_RB_ROOT)) {
  16893. if (is_tracing_prog_type(prog_type)) {
  16894. verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
  16895. return -EINVAL;
  16896. }
  16897. }
  16898. if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
  16899. if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
  16900. verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
  16901. return -EINVAL;
  16902. }
  16903. if (is_tracing_prog_type(prog_type)) {
  16904. verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
  16905. return -EINVAL;
  16906. }
  16907. }
  16908. if (btf_record_has_field(map->record, BPF_TIMER)) {
  16909. if (is_tracing_prog_type(prog_type)) {
  16910. verbose(env, "tracing progs cannot use bpf_timer yet\n");
  16911. return -EINVAL;
  16912. }
  16913. }
  16914. if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
  16915. if (is_tracing_prog_type(prog_type)) {
  16916. verbose(env, "tracing progs cannot use bpf_wq yet\n");
  16917. return -EINVAL;
  16918. }
  16919. }
  16920. if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
  16921. !bpf_offload_prog_map_match(prog, map)) {
  16922. verbose(env, "offload device mismatch between prog and map\n");
  16923. return -EINVAL;
  16924. }
  16925. if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
  16926. verbose(env, "bpf_struct_ops map cannot be used in prog\n");
  16927. return -EINVAL;
  16928. }
  16929. if (prog->sleepable)
  16930. switch (map->map_type) {
  16931. case BPF_MAP_TYPE_HASH:
  16932. case BPF_MAP_TYPE_LRU_HASH:
  16933. case BPF_MAP_TYPE_ARRAY:
  16934. case BPF_MAP_TYPE_PERCPU_HASH:
  16935. case BPF_MAP_TYPE_PERCPU_ARRAY:
  16936. case BPF_MAP_TYPE_LRU_PERCPU_HASH:
  16937. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  16938. case BPF_MAP_TYPE_HASH_OF_MAPS:
  16939. case BPF_MAP_TYPE_RINGBUF:
  16940. case BPF_MAP_TYPE_USER_RINGBUF:
  16941. case BPF_MAP_TYPE_INODE_STORAGE:
  16942. case BPF_MAP_TYPE_SK_STORAGE:
  16943. case BPF_MAP_TYPE_TASK_STORAGE:
  16944. case BPF_MAP_TYPE_CGRP_STORAGE:
  16945. case BPF_MAP_TYPE_QUEUE:
  16946. case BPF_MAP_TYPE_STACK:
  16947. case BPF_MAP_TYPE_ARENA:
  16948. break;
  16949. default:
  16950. verbose(env,
  16951. "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
  16952. return -EINVAL;
  16953. }
  16954. return 0;
  16955. }
  16956. static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
  16957. {
  16958. return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
  16959. map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
  16960. }
  16961. /* Add map behind fd to used maps list, if it's not already there, and return
  16962. * its index. Also set *reused to true if this map was already in the list of
  16963. * used maps.
  16964. * Returns <0 on error, or >= 0 index, on success.
  16965. */
  16966. static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused)
  16967. {
  16968. CLASS(fd, f)(fd);
  16969. struct bpf_map *map;
  16970. int i;
  16971. map = __bpf_map_get(f);
  16972. if (IS_ERR(map)) {
  16973. verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
  16974. return PTR_ERR(map);
  16975. }
  16976. /* check whether we recorded this map already */
  16977. for (i = 0; i < env->used_map_cnt; i++) {
  16978. if (env->used_maps[i] == map) {
  16979. *reused = true;
  16980. return i;
  16981. }
  16982. }
  16983. if (env->used_map_cnt >= MAX_USED_MAPS) {
  16984. verbose(env, "The total number of maps per program has reached the limit of %u\n",
  16985. MAX_USED_MAPS);
  16986. return -E2BIG;
  16987. }
  16988. if (env->prog->sleepable)
  16989. atomic64_inc(&map->sleepable_refcnt);
  16990. /* hold the map. If the program is rejected by verifier,
  16991. * the map will be released by release_maps() or it
  16992. * will be used by the valid program until it's unloaded
  16993. * and all maps are released in bpf_free_used_maps()
  16994. */
  16995. bpf_map_inc(map);
  16996. *reused = false;
  16997. env->used_maps[env->used_map_cnt++] = map;
  16998. return env->used_map_cnt - 1;
  16999. }
  17000. /* find and rewrite pseudo imm in ld_imm64 instructions:
  17001. *
  17002. * 1. if it accesses map FD, replace it with actual map pointer.
  17003. * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
  17004. *
  17005. * NOTE: btf_vmlinux is required for converting pseudo btf_id.
  17006. */
  17007. static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
  17008. {
  17009. struct bpf_insn *insn = env->prog->insnsi;
  17010. int insn_cnt = env->prog->len;
  17011. int i, err;
  17012. err = bpf_prog_calc_tag(env->prog);
  17013. if (err)
  17014. return err;
  17015. for (i = 0; i < insn_cnt; i++, insn++) {
  17016. if (BPF_CLASS(insn->code) == BPF_LDX &&
  17017. ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
  17018. insn->imm != 0)) {
  17019. verbose(env, "BPF_LDX uses reserved fields\n");
  17020. return -EINVAL;
  17021. }
  17022. if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
  17023. struct bpf_insn_aux_data *aux;
  17024. struct bpf_map *map;
  17025. int map_idx;
  17026. u64 addr;
  17027. u32 fd;
  17028. bool reused;
  17029. if (i == insn_cnt - 1 || insn[1].code != 0 ||
  17030. insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
  17031. insn[1].off != 0) {
  17032. verbose(env, "invalid bpf_ld_imm64 insn\n");
  17033. return -EINVAL;
  17034. }
  17035. if (insn[0].src_reg == 0)
  17036. /* valid generic load 64-bit imm */
  17037. goto next_insn;
  17038. if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
  17039. aux = &env->insn_aux_data[i];
  17040. err = check_pseudo_btf_id(env, insn, aux);
  17041. if (err)
  17042. return err;
  17043. goto next_insn;
  17044. }
  17045. if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
  17046. aux = &env->insn_aux_data[i];
  17047. aux->ptr_type = PTR_TO_FUNC;
  17048. goto next_insn;
  17049. }
  17050. /* In final convert_pseudo_ld_imm64() step, this is
  17051. * converted into regular 64-bit imm load insn.
  17052. */
  17053. switch (insn[0].src_reg) {
  17054. case BPF_PSEUDO_MAP_VALUE:
  17055. case BPF_PSEUDO_MAP_IDX_VALUE:
  17056. break;
  17057. case BPF_PSEUDO_MAP_FD:
  17058. case BPF_PSEUDO_MAP_IDX:
  17059. if (insn[1].imm == 0)
  17060. break;
  17061. fallthrough;
  17062. default:
  17063. verbose(env, "unrecognized bpf_ld_imm64 insn\n");
  17064. return -EINVAL;
  17065. }
  17066. switch (insn[0].src_reg) {
  17067. case BPF_PSEUDO_MAP_IDX_VALUE:
  17068. case BPF_PSEUDO_MAP_IDX:
  17069. if (bpfptr_is_null(env->fd_array)) {
  17070. verbose(env, "fd_idx without fd_array is invalid\n");
  17071. return -EPROTO;
  17072. }
  17073. if (copy_from_bpfptr_offset(&fd, env->fd_array,
  17074. insn[0].imm * sizeof(fd),
  17075. sizeof(fd)))
  17076. return -EFAULT;
  17077. break;
  17078. default:
  17079. fd = insn[0].imm;
  17080. break;
  17081. }
  17082. map_idx = add_used_map_from_fd(env, fd, &reused);
  17083. if (map_idx < 0)
  17084. return map_idx;
  17085. map = env->used_maps[map_idx];
  17086. aux = &env->insn_aux_data[i];
  17087. aux->map_index = map_idx;
  17088. err = check_map_prog_compatibility(env, map, env->prog);
  17089. if (err)
  17090. return err;
  17091. if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
  17092. insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
  17093. addr = (unsigned long)map;
  17094. } else {
  17095. u32 off = insn[1].imm;
  17096. if (off >= BPF_MAX_VAR_OFF) {
  17097. verbose(env, "direct value offset of %u is not allowed\n", off);
  17098. return -EINVAL;
  17099. }
  17100. if (!map->ops->map_direct_value_addr) {
  17101. verbose(env, "no direct value access support for this map type\n");
  17102. return -EINVAL;
  17103. }
  17104. err = map->ops->map_direct_value_addr(map, &addr, off);
  17105. if (err) {
  17106. verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
  17107. map->value_size, off);
  17108. return err;
  17109. }
  17110. aux->map_off = off;
  17111. addr += off;
  17112. }
  17113. insn[0].imm = (u32)addr;
  17114. insn[1].imm = addr >> 32;
  17115. /* proceed with extra checks only if its newly added used map */
  17116. if (reused)
  17117. goto next_insn;
  17118. if (bpf_map_is_cgroup_storage(map) &&
  17119. bpf_cgroup_storage_assign(env->prog->aux, map)) {
  17120. verbose(env, "only one cgroup storage of each type is allowed\n");
  17121. return -EBUSY;
  17122. }
  17123. if (map->map_type == BPF_MAP_TYPE_ARENA) {
  17124. if (env->prog->aux->arena) {
  17125. verbose(env, "Only one arena per program\n");
  17126. return -EBUSY;
  17127. }
  17128. if (!env->allow_ptr_leaks || !env->bpf_capable) {
  17129. verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
  17130. return -EPERM;
  17131. }
  17132. if (!env->prog->jit_requested) {
  17133. verbose(env, "JIT is required to use arena\n");
  17134. return -EOPNOTSUPP;
  17135. }
  17136. if (!bpf_jit_supports_arena()) {
  17137. verbose(env, "JIT doesn't support arena\n");
  17138. return -EOPNOTSUPP;
  17139. }
  17140. env->prog->aux->arena = (void *)map;
  17141. if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
  17142. verbose(env, "arena's user address must be set via map_extra or mmap()\n");
  17143. return -EINVAL;
  17144. }
  17145. }
  17146. next_insn:
  17147. insn++;
  17148. i++;
  17149. continue;
  17150. }
  17151. /* Basic sanity check before we invest more work here. */
  17152. if (!bpf_opcode_in_insntable(insn->code)) {
  17153. verbose(env, "unknown opcode %02x\n", insn->code);
  17154. return -EINVAL;
  17155. }
  17156. }
  17157. /* now all pseudo BPF_LD_IMM64 instructions load valid
  17158. * 'struct bpf_map *' into a register instead of user map_fd.
  17159. * These pointers will be used later by verifier to validate map access.
  17160. */
  17161. return 0;
  17162. }
  17163. /* drop refcnt of maps used by the rejected program */
  17164. static void release_maps(struct bpf_verifier_env *env)
  17165. {
  17166. __bpf_free_used_maps(env->prog->aux, env->used_maps,
  17167. env->used_map_cnt);
  17168. }
  17169. /* drop refcnt of maps used by the rejected program */
  17170. static void release_btfs(struct bpf_verifier_env *env)
  17171. {
  17172. __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
  17173. }
  17174. /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
  17175. static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
  17176. {
  17177. struct bpf_insn *insn = env->prog->insnsi;
  17178. int insn_cnt = env->prog->len;
  17179. int i;
  17180. for (i = 0; i < insn_cnt; i++, insn++) {
  17181. if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
  17182. continue;
  17183. if (insn->src_reg == BPF_PSEUDO_FUNC)
  17184. continue;
  17185. insn->src_reg = 0;
  17186. }
  17187. }
  17188. /* single env->prog->insni[off] instruction was replaced with the range
  17189. * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
  17190. * [0, off) and [off, end) to new locations, so the patched range stays zero
  17191. */
  17192. static void adjust_insn_aux_data(struct bpf_verifier_env *env,
  17193. struct bpf_insn_aux_data *new_data,
  17194. struct bpf_prog *new_prog, u32 off, u32 cnt)
  17195. {
  17196. struct bpf_insn_aux_data *old_data = env->insn_aux_data;
  17197. struct bpf_insn *insn = new_prog->insnsi;
  17198. u32 old_seen = old_data[off].seen;
  17199. u32 prog_len;
  17200. int i;
  17201. /* aux info at OFF always needs adjustment, no matter fast path
  17202. * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
  17203. * original insn at old prog.
  17204. */
  17205. old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
  17206. if (cnt == 1)
  17207. return;
  17208. prog_len = new_prog->len;
  17209. memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
  17210. memcpy(new_data + off + cnt - 1, old_data + off,
  17211. sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
  17212. for (i = off; i < off + cnt - 1; i++) {
  17213. /* Expand insni[off]'s seen count to the patched range. */
  17214. new_data[i].seen = old_seen;
  17215. new_data[i].zext_dst = insn_has_def32(env, insn + i);
  17216. }
  17217. env->insn_aux_data = new_data;
  17218. vfree(old_data);
  17219. }
  17220. static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
  17221. {
  17222. int i;
  17223. if (len == 1)
  17224. return;
  17225. /* NOTE: fake 'exit' subprog should be updated as well. */
  17226. for (i = 0; i <= env->subprog_cnt; i++) {
  17227. if (env->subprog_info[i].start <= off)
  17228. continue;
  17229. env->subprog_info[i].start += len - 1;
  17230. }
  17231. }
  17232. static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
  17233. {
  17234. struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
  17235. int i, sz = prog->aux->size_poke_tab;
  17236. struct bpf_jit_poke_descriptor *desc;
  17237. for (i = 0; i < sz; i++) {
  17238. desc = &tab[i];
  17239. if (desc->insn_idx <= off)
  17240. continue;
  17241. desc->insn_idx += len - 1;
  17242. }
  17243. }
  17244. static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
  17245. const struct bpf_insn *patch, u32 len)
  17246. {
  17247. struct bpf_prog *new_prog;
  17248. struct bpf_insn_aux_data *new_data = NULL;
  17249. if (len > 1) {
  17250. new_data = vzalloc(array_size(env->prog->len + len - 1,
  17251. sizeof(struct bpf_insn_aux_data)));
  17252. if (!new_data)
  17253. return NULL;
  17254. }
  17255. new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
  17256. if (IS_ERR(new_prog)) {
  17257. if (PTR_ERR(new_prog) == -ERANGE)
  17258. verbose(env,
  17259. "insn %d cannot be patched due to 16-bit range\n",
  17260. env->insn_aux_data[off].orig_idx);
  17261. vfree(new_data);
  17262. return NULL;
  17263. }
  17264. adjust_insn_aux_data(env, new_data, new_prog, off, len);
  17265. adjust_subprog_starts(env, off, len);
  17266. adjust_poke_descs(new_prog, off, len);
  17267. return new_prog;
  17268. }
  17269. /*
  17270. * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
  17271. * jump offset by 'delta'.
  17272. */
  17273. static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
  17274. {
  17275. struct bpf_insn *insn = prog->insnsi;
  17276. u32 insn_cnt = prog->len, i;
  17277. s32 imm;
  17278. s16 off;
  17279. for (i = 0; i < insn_cnt; i++, insn++) {
  17280. u8 code = insn->code;
  17281. if (tgt_idx <= i && i < tgt_idx + delta)
  17282. continue;
  17283. if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
  17284. BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
  17285. continue;
  17286. if (insn->code == (BPF_JMP32 | BPF_JA)) {
  17287. if (i + 1 + insn->imm != tgt_idx)
  17288. continue;
  17289. if (check_add_overflow(insn->imm, delta, &imm))
  17290. return -ERANGE;
  17291. insn->imm = imm;
  17292. } else {
  17293. if (i + 1 + insn->off != tgt_idx)
  17294. continue;
  17295. if (check_add_overflow(insn->off, delta, &off))
  17296. return -ERANGE;
  17297. insn->off = off;
  17298. }
  17299. }
  17300. return 0;
  17301. }
  17302. static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
  17303. u32 off, u32 cnt)
  17304. {
  17305. int i, j;
  17306. /* find first prog starting at or after off (first to remove) */
  17307. for (i = 0; i < env->subprog_cnt; i++)
  17308. if (env->subprog_info[i].start >= off)
  17309. break;
  17310. /* find first prog starting at or after off + cnt (first to stay) */
  17311. for (j = i; j < env->subprog_cnt; j++)
  17312. if (env->subprog_info[j].start >= off + cnt)
  17313. break;
  17314. /* if j doesn't start exactly at off + cnt, we are just removing
  17315. * the front of previous prog
  17316. */
  17317. if (env->subprog_info[j].start != off + cnt)
  17318. j--;
  17319. if (j > i) {
  17320. struct bpf_prog_aux *aux = env->prog->aux;
  17321. int move;
  17322. /* move fake 'exit' subprog as well */
  17323. move = env->subprog_cnt + 1 - j;
  17324. memmove(env->subprog_info + i,
  17325. env->subprog_info + j,
  17326. sizeof(*env->subprog_info) * move);
  17327. env->subprog_cnt -= j - i;
  17328. /* remove func_info */
  17329. if (aux->func_info) {
  17330. move = aux->func_info_cnt - j;
  17331. memmove(aux->func_info + i,
  17332. aux->func_info + j,
  17333. sizeof(*aux->func_info) * move);
  17334. aux->func_info_cnt -= j - i;
  17335. /* func_info->insn_off is set after all code rewrites,
  17336. * in adjust_btf_func() - no need to adjust
  17337. */
  17338. }
  17339. } else {
  17340. /* convert i from "first prog to remove" to "first to adjust" */
  17341. if (env->subprog_info[i].start == off)
  17342. i++;
  17343. }
  17344. /* update fake 'exit' subprog as well */
  17345. for (; i <= env->subprog_cnt; i++)
  17346. env->subprog_info[i].start -= cnt;
  17347. return 0;
  17348. }
  17349. static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
  17350. u32 cnt)
  17351. {
  17352. struct bpf_prog *prog = env->prog;
  17353. u32 i, l_off, l_cnt, nr_linfo;
  17354. struct bpf_line_info *linfo;
  17355. nr_linfo = prog->aux->nr_linfo;
  17356. if (!nr_linfo)
  17357. return 0;
  17358. linfo = prog->aux->linfo;
  17359. /* find first line info to remove, count lines to be removed */
  17360. for (i = 0; i < nr_linfo; i++)
  17361. if (linfo[i].insn_off >= off)
  17362. break;
  17363. l_off = i;
  17364. l_cnt = 0;
  17365. for (; i < nr_linfo; i++)
  17366. if (linfo[i].insn_off < off + cnt)
  17367. l_cnt++;
  17368. else
  17369. break;
  17370. /* First live insn doesn't match first live linfo, it needs to "inherit"
  17371. * last removed linfo. prog is already modified, so prog->len == off
  17372. * means no live instructions after (tail of the program was removed).
  17373. */
  17374. if (prog->len != off && l_cnt &&
  17375. (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
  17376. l_cnt--;
  17377. linfo[--i].insn_off = off + cnt;
  17378. }
  17379. /* remove the line info which refer to the removed instructions */
  17380. if (l_cnt) {
  17381. memmove(linfo + l_off, linfo + i,
  17382. sizeof(*linfo) * (nr_linfo - i));
  17383. prog->aux->nr_linfo -= l_cnt;
  17384. nr_linfo = prog->aux->nr_linfo;
  17385. }
  17386. /* pull all linfo[i].insn_off >= off + cnt in by cnt */
  17387. for (i = l_off; i < nr_linfo; i++)
  17388. linfo[i].insn_off -= cnt;
  17389. /* fix up all subprogs (incl. 'exit') which start >= off */
  17390. for (i = 0; i <= env->subprog_cnt; i++)
  17391. if (env->subprog_info[i].linfo_idx > l_off) {
  17392. /* program may have started in the removed region but
  17393. * may not be fully removed
  17394. */
  17395. if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
  17396. env->subprog_info[i].linfo_idx -= l_cnt;
  17397. else
  17398. env->subprog_info[i].linfo_idx = l_off;
  17399. }
  17400. return 0;
  17401. }
  17402. static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
  17403. {
  17404. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  17405. unsigned int orig_prog_len = env->prog->len;
  17406. int err;
  17407. if (bpf_prog_is_offloaded(env->prog->aux))
  17408. bpf_prog_offload_remove_insns(env, off, cnt);
  17409. err = bpf_remove_insns(env->prog, off, cnt);
  17410. if (err)
  17411. return err;
  17412. err = adjust_subprog_starts_after_remove(env, off, cnt);
  17413. if (err)
  17414. return err;
  17415. err = bpf_adj_linfo_after_remove(env, off, cnt);
  17416. if (err)
  17417. return err;
  17418. memmove(aux_data + off, aux_data + off + cnt,
  17419. sizeof(*aux_data) * (orig_prog_len - off - cnt));
  17420. return 0;
  17421. }
  17422. /* The verifier does more data flow analysis than llvm and will not
  17423. * explore branches that are dead at run time. Malicious programs can
  17424. * have dead code too. Therefore replace all dead at-run-time code
  17425. * with 'ja -1'.
  17426. *
  17427. * Just nops are not optimal, e.g. if they would sit at the end of the
  17428. * program and through another bug we would manage to jump there, then
  17429. * we'd execute beyond program memory otherwise. Returning exception
  17430. * code also wouldn't work since we can have subprogs where the dead
  17431. * code could be located.
  17432. */
  17433. static void sanitize_dead_code(struct bpf_verifier_env *env)
  17434. {
  17435. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  17436. struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
  17437. struct bpf_insn *insn = env->prog->insnsi;
  17438. const int insn_cnt = env->prog->len;
  17439. int i;
  17440. for (i = 0; i < insn_cnt; i++) {
  17441. if (aux_data[i].seen)
  17442. continue;
  17443. memcpy(insn + i, &trap, sizeof(trap));
  17444. aux_data[i].zext_dst = false;
  17445. }
  17446. }
  17447. static bool insn_is_cond_jump(u8 code)
  17448. {
  17449. u8 op;
  17450. op = BPF_OP(code);
  17451. if (BPF_CLASS(code) == BPF_JMP32)
  17452. return op != BPF_JA;
  17453. if (BPF_CLASS(code) != BPF_JMP)
  17454. return false;
  17455. return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
  17456. }
  17457. static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
  17458. {
  17459. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  17460. struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
  17461. struct bpf_insn *insn = env->prog->insnsi;
  17462. const int insn_cnt = env->prog->len;
  17463. int i;
  17464. for (i = 0; i < insn_cnt; i++, insn++) {
  17465. if (!insn_is_cond_jump(insn->code))
  17466. continue;
  17467. if (!aux_data[i + 1].seen)
  17468. ja.off = insn->off;
  17469. else if (!aux_data[i + 1 + insn->off].seen)
  17470. ja.off = 0;
  17471. else
  17472. continue;
  17473. if (bpf_prog_is_offloaded(env->prog->aux))
  17474. bpf_prog_offload_replace_insn(env, i, &ja);
  17475. memcpy(insn, &ja, sizeof(ja));
  17476. }
  17477. }
  17478. static int opt_remove_dead_code(struct bpf_verifier_env *env)
  17479. {
  17480. struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
  17481. int insn_cnt = env->prog->len;
  17482. int i, err;
  17483. for (i = 0; i < insn_cnt; i++) {
  17484. int j;
  17485. j = 0;
  17486. while (i + j < insn_cnt && !aux_data[i + j].seen)
  17487. j++;
  17488. if (!j)
  17489. continue;
  17490. err = verifier_remove_insns(env, i, j);
  17491. if (err)
  17492. return err;
  17493. insn_cnt = env->prog->len;
  17494. }
  17495. return 0;
  17496. }
  17497. static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
  17498. static int opt_remove_nops(struct bpf_verifier_env *env)
  17499. {
  17500. const struct bpf_insn ja = NOP;
  17501. struct bpf_insn *insn = env->prog->insnsi;
  17502. int insn_cnt = env->prog->len;
  17503. int i, err;
  17504. for (i = 0; i < insn_cnt; i++) {
  17505. if (memcmp(&insn[i], &ja, sizeof(ja)))
  17506. continue;
  17507. err = verifier_remove_insns(env, i, 1);
  17508. if (err)
  17509. return err;
  17510. insn_cnt--;
  17511. i--;
  17512. }
  17513. return 0;
  17514. }
  17515. static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
  17516. const union bpf_attr *attr)
  17517. {
  17518. struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
  17519. struct bpf_insn_aux_data *aux = env->insn_aux_data;
  17520. int i, patch_len, delta = 0, len = env->prog->len;
  17521. struct bpf_insn *insns = env->prog->insnsi;
  17522. struct bpf_prog *new_prog;
  17523. bool rnd_hi32;
  17524. rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
  17525. zext_patch[1] = BPF_ZEXT_REG(0);
  17526. rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
  17527. rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
  17528. rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
  17529. for (i = 0; i < len; i++) {
  17530. int adj_idx = i + delta;
  17531. struct bpf_insn insn;
  17532. int load_reg;
  17533. insn = insns[adj_idx];
  17534. load_reg = insn_def_regno(&insn);
  17535. if (!aux[adj_idx].zext_dst) {
  17536. u8 code, class;
  17537. u32 imm_rnd;
  17538. if (!rnd_hi32)
  17539. continue;
  17540. code = insn.code;
  17541. class = BPF_CLASS(code);
  17542. if (load_reg == -1)
  17543. continue;
  17544. /* NOTE: arg "reg" (the fourth one) is only used for
  17545. * BPF_STX + SRC_OP, so it is safe to pass NULL
  17546. * here.
  17547. */
  17548. if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
  17549. if (class == BPF_LD &&
  17550. BPF_MODE(code) == BPF_IMM)
  17551. i++;
  17552. continue;
  17553. }
  17554. /* ctx load could be transformed into wider load. */
  17555. if (class == BPF_LDX &&
  17556. aux[adj_idx].ptr_type == PTR_TO_CTX)
  17557. continue;
  17558. imm_rnd = get_random_u32();
  17559. rnd_hi32_patch[0] = insn;
  17560. rnd_hi32_patch[1].imm = imm_rnd;
  17561. rnd_hi32_patch[3].dst_reg = load_reg;
  17562. patch = rnd_hi32_patch;
  17563. patch_len = 4;
  17564. goto apply_patch_buffer;
  17565. }
  17566. /* Add in an zero-extend instruction if a) the JIT has requested
  17567. * it or b) it's a CMPXCHG.
  17568. *
  17569. * The latter is because: BPF_CMPXCHG always loads a value into
  17570. * R0, therefore always zero-extends. However some archs'
  17571. * equivalent instruction only does this load when the
  17572. * comparison is successful. This detail of CMPXCHG is
  17573. * orthogonal to the general zero-extension behaviour of the
  17574. * CPU, so it's treated independently of bpf_jit_needs_zext.
  17575. */
  17576. if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
  17577. continue;
  17578. /* Zero-extension is done by the caller. */
  17579. if (bpf_pseudo_kfunc_call(&insn))
  17580. continue;
  17581. if (WARN_ON(load_reg == -1)) {
  17582. verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
  17583. return -EFAULT;
  17584. }
  17585. zext_patch[0] = insn;
  17586. zext_patch[1].dst_reg = load_reg;
  17587. zext_patch[1].src_reg = load_reg;
  17588. patch = zext_patch;
  17589. patch_len = 2;
  17590. apply_patch_buffer:
  17591. new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
  17592. if (!new_prog)
  17593. return -ENOMEM;
  17594. env->prog = new_prog;
  17595. insns = new_prog->insnsi;
  17596. aux = env->insn_aux_data;
  17597. delta += patch_len - 1;
  17598. }
  17599. return 0;
  17600. }
  17601. /* convert load instructions that access fields of a context type into a
  17602. * sequence of instructions that access fields of the underlying structure:
  17603. * struct __sk_buff -> struct sk_buff
  17604. * struct bpf_sock_ops -> struct sock
  17605. */
  17606. static int convert_ctx_accesses(struct bpf_verifier_env *env)
  17607. {
  17608. struct bpf_subprog_info *subprogs = env->subprog_info;
  17609. const struct bpf_verifier_ops *ops = env->ops;
  17610. int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
  17611. const int insn_cnt = env->prog->len;
  17612. struct bpf_insn *epilogue_buf = env->epilogue_buf;
  17613. struct bpf_insn *insn_buf = env->insn_buf;
  17614. struct bpf_insn *insn;
  17615. u32 target_size, size_default, off;
  17616. struct bpf_prog *new_prog;
  17617. enum bpf_access_type type;
  17618. bool is_narrower_load;
  17619. int epilogue_idx = 0;
  17620. if (ops->gen_epilogue) {
  17621. epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
  17622. -(subprogs[0].stack_depth + 8));
  17623. if (epilogue_cnt >= INSN_BUF_SIZE) {
  17624. verbose(env, "bpf verifier is misconfigured\n");
  17625. return -EINVAL;
  17626. } else if (epilogue_cnt) {
  17627. /* Save the ARG_PTR_TO_CTX for the epilogue to use */
  17628. cnt = 0;
  17629. subprogs[0].stack_depth += 8;
  17630. insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
  17631. -subprogs[0].stack_depth);
  17632. insn_buf[cnt++] = env->prog->insnsi[0];
  17633. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  17634. if (!new_prog)
  17635. return -ENOMEM;
  17636. env->prog = new_prog;
  17637. delta += cnt - 1;
  17638. ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
  17639. if (ret < 0)
  17640. return ret;
  17641. }
  17642. }
  17643. if (ops->gen_prologue || env->seen_direct_write) {
  17644. if (!ops->gen_prologue) {
  17645. verbose(env, "bpf verifier is misconfigured\n");
  17646. return -EINVAL;
  17647. }
  17648. cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
  17649. env->prog);
  17650. if (cnt >= INSN_BUF_SIZE) {
  17651. verbose(env, "bpf verifier is misconfigured\n");
  17652. return -EINVAL;
  17653. } else if (cnt) {
  17654. new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
  17655. if (!new_prog)
  17656. return -ENOMEM;
  17657. env->prog = new_prog;
  17658. delta += cnt - 1;
  17659. ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
  17660. if (ret < 0)
  17661. return ret;
  17662. }
  17663. }
  17664. if (delta)
  17665. WARN_ON(adjust_jmp_off(env->prog, 0, delta));
  17666. if (bpf_prog_is_offloaded(env->prog->aux))
  17667. return 0;
  17668. insn = env->prog->insnsi + delta;
  17669. for (i = 0; i < insn_cnt; i++, insn++) {
  17670. bpf_convert_ctx_access_t convert_ctx_access;
  17671. u8 mode;
  17672. if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
  17673. insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
  17674. insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
  17675. insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
  17676. insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
  17677. insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
  17678. insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
  17679. type = BPF_READ;
  17680. } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
  17681. insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
  17682. insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
  17683. insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
  17684. insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
  17685. insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
  17686. insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
  17687. insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
  17688. type = BPF_WRITE;
  17689. } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
  17690. insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
  17691. env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
  17692. insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
  17693. env->prog->aux->num_exentries++;
  17694. continue;
  17695. } else if (insn->code == (BPF_JMP | BPF_EXIT) &&
  17696. epilogue_cnt &&
  17697. i + delta < subprogs[1].start) {
  17698. /* Generate epilogue for the main prog */
  17699. if (epilogue_idx) {
  17700. /* jump back to the earlier generated epilogue */
  17701. insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
  17702. cnt = 1;
  17703. } else {
  17704. memcpy(insn_buf, epilogue_buf,
  17705. epilogue_cnt * sizeof(*epilogue_buf));
  17706. cnt = epilogue_cnt;
  17707. /* epilogue_idx cannot be 0. It must have at
  17708. * least one ctx ptr saving insn before the
  17709. * epilogue.
  17710. */
  17711. epilogue_idx = i + delta;
  17712. }
  17713. goto patch_insn_buf;
  17714. } else {
  17715. continue;
  17716. }
  17717. if (type == BPF_WRITE &&
  17718. env->insn_aux_data[i + delta].sanitize_stack_spill) {
  17719. struct bpf_insn patch[] = {
  17720. *insn,
  17721. BPF_ST_NOSPEC(),
  17722. };
  17723. cnt = ARRAY_SIZE(patch);
  17724. new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
  17725. if (!new_prog)
  17726. return -ENOMEM;
  17727. delta += cnt - 1;
  17728. env->prog = new_prog;
  17729. insn = new_prog->insnsi + i + delta;
  17730. continue;
  17731. }
  17732. switch ((int)env->insn_aux_data[i + delta].ptr_type) {
  17733. case PTR_TO_CTX:
  17734. if (!ops->convert_ctx_access)
  17735. continue;
  17736. convert_ctx_access = ops->convert_ctx_access;
  17737. break;
  17738. case PTR_TO_SOCKET:
  17739. case PTR_TO_SOCK_COMMON:
  17740. convert_ctx_access = bpf_sock_convert_ctx_access;
  17741. break;
  17742. case PTR_TO_TCP_SOCK:
  17743. convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
  17744. break;
  17745. case PTR_TO_XDP_SOCK:
  17746. convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
  17747. break;
  17748. case PTR_TO_BTF_ID:
  17749. case PTR_TO_BTF_ID | PTR_UNTRUSTED:
  17750. /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
  17751. * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
  17752. * be said once it is marked PTR_UNTRUSTED, hence we must handle
  17753. * any faults for loads into such types. BPF_WRITE is disallowed
  17754. * for this case.
  17755. */
  17756. case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
  17757. if (type == BPF_READ) {
  17758. if (BPF_MODE(insn->code) == BPF_MEM)
  17759. insn->code = BPF_LDX | BPF_PROBE_MEM |
  17760. BPF_SIZE((insn)->code);
  17761. else
  17762. insn->code = BPF_LDX | BPF_PROBE_MEMSX |
  17763. BPF_SIZE((insn)->code);
  17764. env->prog->aux->num_exentries++;
  17765. }
  17766. continue;
  17767. case PTR_TO_ARENA:
  17768. if (BPF_MODE(insn->code) == BPF_MEMSX) {
  17769. verbose(env, "sign extending loads from arena are not supported yet\n");
  17770. return -EOPNOTSUPP;
  17771. }
  17772. insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
  17773. env->prog->aux->num_exentries++;
  17774. continue;
  17775. default:
  17776. continue;
  17777. }
  17778. ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
  17779. size = BPF_LDST_BYTES(insn);
  17780. mode = BPF_MODE(insn->code);
  17781. /* If the read access is a narrower load of the field,
  17782. * convert to a 4/8-byte load, to minimum program type specific
  17783. * convert_ctx_access changes. If conversion is successful,
  17784. * we will apply proper mask to the result.
  17785. */
  17786. is_narrower_load = size < ctx_field_size;
  17787. size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
  17788. off = insn->off;
  17789. if (is_narrower_load) {
  17790. u8 size_code;
  17791. if (type == BPF_WRITE) {
  17792. verbose(env, "bpf verifier narrow ctx access misconfigured\n");
  17793. return -EINVAL;
  17794. }
  17795. size_code = BPF_H;
  17796. if (ctx_field_size == 4)
  17797. size_code = BPF_W;
  17798. else if (ctx_field_size == 8)
  17799. size_code = BPF_DW;
  17800. insn->off = off & ~(size_default - 1);
  17801. insn->code = BPF_LDX | BPF_MEM | size_code;
  17802. }
  17803. target_size = 0;
  17804. cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
  17805. &target_size);
  17806. if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
  17807. (ctx_field_size && !target_size)) {
  17808. verbose(env, "bpf verifier is misconfigured\n");
  17809. return -EINVAL;
  17810. }
  17811. if (is_narrower_load && size < target_size) {
  17812. u8 shift = bpf_ctx_narrow_access_offset(
  17813. off, size, size_default) * 8;
  17814. if (shift && cnt + 1 >= INSN_BUF_SIZE) {
  17815. verbose(env, "bpf verifier narrow ctx load misconfigured\n");
  17816. return -EINVAL;
  17817. }
  17818. if (ctx_field_size <= 4) {
  17819. if (shift)
  17820. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
  17821. insn->dst_reg,
  17822. shift);
  17823. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
  17824. (1 << size * 8) - 1);
  17825. } else {
  17826. if (shift)
  17827. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
  17828. insn->dst_reg,
  17829. shift);
  17830. insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
  17831. (1ULL << size * 8) - 1);
  17832. }
  17833. }
  17834. if (mode == BPF_MEMSX)
  17835. insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
  17836. insn->dst_reg, insn->dst_reg,
  17837. size * 8, 0);
  17838. patch_insn_buf:
  17839. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  17840. if (!new_prog)
  17841. return -ENOMEM;
  17842. delta += cnt - 1;
  17843. /* keep walking new program and skip insns we just inserted */
  17844. env->prog = new_prog;
  17845. insn = new_prog->insnsi + i + delta;
  17846. }
  17847. return 0;
  17848. }
  17849. static int jit_subprogs(struct bpf_verifier_env *env)
  17850. {
  17851. struct bpf_prog *prog = env->prog, **func, *tmp;
  17852. int i, j, subprog_start, subprog_end = 0, len, subprog;
  17853. struct bpf_map *map_ptr;
  17854. struct bpf_insn *insn;
  17855. void *old_bpf_func;
  17856. int err, num_exentries;
  17857. if (env->subprog_cnt <= 1)
  17858. return 0;
  17859. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  17860. if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
  17861. continue;
  17862. /* Upon error here we cannot fall back to interpreter but
  17863. * need a hard reject of the program. Thus -EFAULT is
  17864. * propagated in any case.
  17865. */
  17866. subprog = find_subprog(env, i + insn->imm + 1);
  17867. if (subprog < 0) {
  17868. WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
  17869. i + insn->imm + 1);
  17870. return -EFAULT;
  17871. }
  17872. /* temporarily remember subprog id inside insn instead of
  17873. * aux_data, since next loop will split up all insns into funcs
  17874. */
  17875. insn->off = subprog;
  17876. /* remember original imm in case JIT fails and fallback
  17877. * to interpreter will be needed
  17878. */
  17879. env->insn_aux_data[i].call_imm = insn->imm;
  17880. /* point imm to __bpf_call_base+1 from JITs point of view */
  17881. insn->imm = 1;
  17882. if (bpf_pseudo_func(insn)) {
  17883. #if defined(MODULES_VADDR)
  17884. u64 addr = MODULES_VADDR;
  17885. #else
  17886. u64 addr = VMALLOC_START;
  17887. #endif
  17888. /* jit (e.g. x86_64) may emit fewer instructions
  17889. * if it learns a u32 imm is the same as a u64 imm.
  17890. * Set close enough to possible prog address.
  17891. */
  17892. insn[0].imm = (u32)addr;
  17893. insn[1].imm = addr >> 32;
  17894. }
  17895. }
  17896. err = bpf_prog_alloc_jited_linfo(prog);
  17897. if (err)
  17898. goto out_undo_insn;
  17899. err = -ENOMEM;
  17900. func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
  17901. if (!func)
  17902. goto out_undo_insn;
  17903. for (i = 0; i < env->subprog_cnt; i++) {
  17904. subprog_start = subprog_end;
  17905. subprog_end = env->subprog_info[i + 1].start;
  17906. len = subprog_end - subprog_start;
  17907. /* bpf_prog_run() doesn't call subprogs directly,
  17908. * hence main prog stats include the runtime of subprogs.
  17909. * subprogs don't have IDs and not reachable via prog_get_next_id
  17910. * func[i]->stats will never be accessed and stays NULL
  17911. */
  17912. func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
  17913. if (!func[i])
  17914. goto out_free;
  17915. memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
  17916. len * sizeof(struct bpf_insn));
  17917. func[i]->type = prog->type;
  17918. func[i]->len = len;
  17919. if (bpf_prog_calc_tag(func[i]))
  17920. goto out_free;
  17921. func[i]->is_func = 1;
  17922. func[i]->sleepable = prog->sleepable;
  17923. func[i]->aux->func_idx = i;
  17924. /* Below members will be freed only at prog->aux */
  17925. func[i]->aux->btf = prog->aux->btf;
  17926. func[i]->aux->func_info = prog->aux->func_info;
  17927. func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
  17928. func[i]->aux->poke_tab = prog->aux->poke_tab;
  17929. func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
  17930. for (j = 0; j < prog->aux->size_poke_tab; j++) {
  17931. struct bpf_jit_poke_descriptor *poke;
  17932. poke = &prog->aux->poke_tab[j];
  17933. if (poke->insn_idx < subprog_end &&
  17934. poke->insn_idx >= subprog_start)
  17935. poke->aux = func[i]->aux;
  17936. }
  17937. func[i]->aux->name[0] = 'F';
  17938. func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
  17939. func[i]->jit_requested = 1;
  17940. func[i]->blinding_requested = prog->blinding_requested;
  17941. func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
  17942. func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
  17943. func[i]->aux->linfo = prog->aux->linfo;
  17944. func[i]->aux->nr_linfo = prog->aux->nr_linfo;
  17945. func[i]->aux->jited_linfo = prog->aux->jited_linfo;
  17946. func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
  17947. func[i]->aux->arena = prog->aux->arena;
  17948. num_exentries = 0;
  17949. insn = func[i]->insnsi;
  17950. for (j = 0; j < func[i]->len; j++, insn++) {
  17951. if (BPF_CLASS(insn->code) == BPF_LDX &&
  17952. (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
  17953. BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
  17954. BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
  17955. num_exentries++;
  17956. if ((BPF_CLASS(insn->code) == BPF_STX ||
  17957. BPF_CLASS(insn->code) == BPF_ST) &&
  17958. BPF_MODE(insn->code) == BPF_PROBE_MEM32)
  17959. num_exentries++;
  17960. if (BPF_CLASS(insn->code) == BPF_STX &&
  17961. BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
  17962. num_exentries++;
  17963. }
  17964. func[i]->aux->num_exentries = num_exentries;
  17965. func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
  17966. func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
  17967. func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
  17968. if (!i)
  17969. func[i]->aux->exception_boundary = env->seen_exception;
  17970. func[i] = bpf_int_jit_compile(func[i]);
  17971. if (!func[i]->jited) {
  17972. err = -ENOTSUPP;
  17973. goto out_free;
  17974. }
  17975. cond_resched();
  17976. }
  17977. /* at this point all bpf functions were successfully JITed
  17978. * now populate all bpf_calls with correct addresses and
  17979. * run last pass of JIT
  17980. */
  17981. for (i = 0; i < env->subprog_cnt; i++) {
  17982. insn = func[i]->insnsi;
  17983. for (j = 0; j < func[i]->len; j++, insn++) {
  17984. if (bpf_pseudo_func(insn)) {
  17985. subprog = insn->off;
  17986. insn[0].imm = (u32)(long)func[subprog]->bpf_func;
  17987. insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
  17988. continue;
  17989. }
  17990. if (!bpf_pseudo_call(insn))
  17991. continue;
  17992. subprog = insn->off;
  17993. insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
  17994. }
  17995. /* we use the aux data to keep a list of the start addresses
  17996. * of the JITed images for each function in the program
  17997. *
  17998. * for some architectures, such as powerpc64, the imm field
  17999. * might not be large enough to hold the offset of the start
  18000. * address of the callee's JITed image from __bpf_call_base
  18001. *
  18002. * in such cases, we can lookup the start address of a callee
  18003. * by using its subprog id, available from the off field of
  18004. * the call instruction, as an index for this list
  18005. */
  18006. func[i]->aux->func = func;
  18007. func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
  18008. func[i]->aux->real_func_cnt = env->subprog_cnt;
  18009. }
  18010. for (i = 0; i < env->subprog_cnt; i++) {
  18011. old_bpf_func = func[i]->bpf_func;
  18012. tmp = bpf_int_jit_compile(func[i]);
  18013. if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
  18014. verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
  18015. err = -ENOTSUPP;
  18016. goto out_free;
  18017. }
  18018. cond_resched();
  18019. }
  18020. /* finally lock prog and jit images for all functions and
  18021. * populate kallsysm. Begin at the first subprogram, since
  18022. * bpf_prog_load will add the kallsyms for the main program.
  18023. */
  18024. for (i = 1; i < env->subprog_cnt; i++) {
  18025. err = bpf_prog_lock_ro(func[i]);
  18026. if (err)
  18027. goto out_free;
  18028. }
  18029. for (i = 1; i < env->subprog_cnt; i++)
  18030. bpf_prog_kallsyms_add(func[i]);
  18031. /* Last step: make now unused interpreter insns from main
  18032. * prog consistent for later dump requests, so they can
  18033. * later look the same as if they were interpreted only.
  18034. */
  18035. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  18036. if (bpf_pseudo_func(insn)) {
  18037. insn[0].imm = env->insn_aux_data[i].call_imm;
  18038. insn[1].imm = insn->off;
  18039. insn->off = 0;
  18040. continue;
  18041. }
  18042. if (!bpf_pseudo_call(insn))
  18043. continue;
  18044. insn->off = env->insn_aux_data[i].call_imm;
  18045. subprog = find_subprog(env, i + insn->off + 1);
  18046. insn->imm = subprog;
  18047. }
  18048. prog->jited = 1;
  18049. prog->bpf_func = func[0]->bpf_func;
  18050. prog->jited_len = func[0]->jited_len;
  18051. prog->aux->extable = func[0]->aux->extable;
  18052. prog->aux->num_exentries = func[0]->aux->num_exentries;
  18053. prog->aux->func = func;
  18054. prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
  18055. prog->aux->real_func_cnt = env->subprog_cnt;
  18056. prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
  18057. prog->aux->exception_boundary = func[0]->aux->exception_boundary;
  18058. bpf_prog_jit_attempt_done(prog);
  18059. return 0;
  18060. out_free:
  18061. /* We failed JIT'ing, so at this point we need to unregister poke
  18062. * descriptors from subprogs, so that kernel is not attempting to
  18063. * patch it anymore as we're freeing the subprog JIT memory.
  18064. */
  18065. for (i = 0; i < prog->aux->size_poke_tab; i++) {
  18066. map_ptr = prog->aux->poke_tab[i].tail_call.map;
  18067. map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
  18068. }
  18069. /* At this point we're guaranteed that poke descriptors are not
  18070. * live anymore. We can just unlink its descriptor table as it's
  18071. * released with the main prog.
  18072. */
  18073. for (i = 0; i < env->subprog_cnt; i++) {
  18074. if (!func[i])
  18075. continue;
  18076. func[i]->aux->poke_tab = NULL;
  18077. bpf_jit_free(func[i]);
  18078. }
  18079. kfree(func);
  18080. out_undo_insn:
  18081. /* cleanup main prog to be interpreted */
  18082. prog->jit_requested = 0;
  18083. prog->blinding_requested = 0;
  18084. for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
  18085. if (!bpf_pseudo_call(insn))
  18086. continue;
  18087. insn->off = 0;
  18088. insn->imm = env->insn_aux_data[i].call_imm;
  18089. }
  18090. bpf_prog_jit_attempt_done(prog);
  18091. return err;
  18092. }
  18093. static int fixup_call_args(struct bpf_verifier_env *env)
  18094. {
  18095. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  18096. struct bpf_prog *prog = env->prog;
  18097. struct bpf_insn *insn = prog->insnsi;
  18098. bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
  18099. int i, depth;
  18100. #endif
  18101. int err = 0;
  18102. if (env->prog->jit_requested &&
  18103. !bpf_prog_is_offloaded(env->prog->aux)) {
  18104. err = jit_subprogs(env);
  18105. if (err == 0)
  18106. return 0;
  18107. if (err == -EFAULT)
  18108. return err;
  18109. }
  18110. #ifndef CONFIG_BPF_JIT_ALWAYS_ON
  18111. if (has_kfunc_call) {
  18112. verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
  18113. return -EINVAL;
  18114. }
  18115. if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
  18116. /* When JIT fails the progs with bpf2bpf calls and tail_calls
  18117. * have to be rejected, since interpreter doesn't support them yet.
  18118. */
  18119. verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
  18120. return -EINVAL;
  18121. }
  18122. for (i = 0; i < prog->len; i++, insn++) {
  18123. if (bpf_pseudo_func(insn)) {
  18124. /* When JIT fails the progs with callback calls
  18125. * have to be rejected, since interpreter doesn't support them yet.
  18126. */
  18127. verbose(env, "callbacks are not allowed in non-JITed programs\n");
  18128. return -EINVAL;
  18129. }
  18130. if (!bpf_pseudo_call(insn))
  18131. continue;
  18132. depth = get_callee_stack_depth(env, insn, i);
  18133. if (depth < 0)
  18134. return depth;
  18135. bpf_patch_call_args(insn, depth);
  18136. }
  18137. err = 0;
  18138. #endif
  18139. return err;
  18140. }
  18141. /* replace a generic kfunc with a specialized version if necessary */
  18142. static void specialize_kfunc(struct bpf_verifier_env *env,
  18143. u32 func_id, u16 offset, unsigned long *addr)
  18144. {
  18145. struct bpf_prog *prog = env->prog;
  18146. bool seen_direct_write;
  18147. void *xdp_kfunc;
  18148. bool is_rdonly;
  18149. if (bpf_dev_bound_kfunc_id(func_id)) {
  18150. xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
  18151. if (xdp_kfunc) {
  18152. *addr = (unsigned long)xdp_kfunc;
  18153. return;
  18154. }
  18155. /* fallback to default kfunc when not supported by netdev */
  18156. }
  18157. if (offset)
  18158. return;
  18159. if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
  18160. seen_direct_write = env->seen_direct_write;
  18161. is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
  18162. if (is_rdonly)
  18163. *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
  18164. /* restore env->seen_direct_write to its original value, since
  18165. * may_access_direct_pkt_data mutates it
  18166. */
  18167. env->seen_direct_write = seen_direct_write;
  18168. }
  18169. }
  18170. static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
  18171. u16 struct_meta_reg,
  18172. u16 node_offset_reg,
  18173. struct bpf_insn *insn,
  18174. struct bpf_insn *insn_buf,
  18175. int *cnt)
  18176. {
  18177. struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
  18178. struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
  18179. insn_buf[0] = addr[0];
  18180. insn_buf[1] = addr[1];
  18181. insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
  18182. insn_buf[3] = *insn;
  18183. *cnt = 4;
  18184. }
  18185. static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
  18186. struct bpf_insn *insn_buf, int insn_idx, int *cnt)
  18187. {
  18188. const struct bpf_kfunc_desc *desc;
  18189. if (!insn->imm) {
  18190. verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
  18191. return -EINVAL;
  18192. }
  18193. *cnt = 0;
  18194. /* insn->imm has the btf func_id. Replace it with an offset relative to
  18195. * __bpf_call_base, unless the JIT needs to call functions that are
  18196. * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
  18197. */
  18198. desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
  18199. if (!desc) {
  18200. verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
  18201. insn->imm);
  18202. return -EFAULT;
  18203. }
  18204. if (!bpf_jit_supports_far_kfunc_call())
  18205. insn->imm = BPF_CALL_IMM(desc->addr);
  18206. if (insn->off)
  18207. return 0;
  18208. if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
  18209. desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
  18210. struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
  18211. struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
  18212. u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
  18213. if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
  18214. verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
  18215. insn_idx);
  18216. return -EFAULT;
  18217. }
  18218. insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
  18219. insn_buf[1] = addr[0];
  18220. insn_buf[2] = addr[1];
  18221. insn_buf[3] = *insn;
  18222. *cnt = 4;
  18223. } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
  18224. desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
  18225. desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
  18226. struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
  18227. struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
  18228. if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
  18229. verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
  18230. insn_idx);
  18231. return -EFAULT;
  18232. }
  18233. if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
  18234. !kptr_struct_meta) {
  18235. verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
  18236. insn_idx);
  18237. return -EFAULT;
  18238. }
  18239. insn_buf[0] = addr[0];
  18240. insn_buf[1] = addr[1];
  18241. insn_buf[2] = *insn;
  18242. *cnt = 3;
  18243. } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
  18244. desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
  18245. desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
  18246. struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
  18247. int struct_meta_reg = BPF_REG_3;
  18248. int node_offset_reg = BPF_REG_4;
  18249. /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
  18250. if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
  18251. struct_meta_reg = BPF_REG_4;
  18252. node_offset_reg = BPF_REG_5;
  18253. }
  18254. if (!kptr_struct_meta) {
  18255. verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
  18256. insn_idx);
  18257. return -EFAULT;
  18258. }
  18259. __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
  18260. node_offset_reg, insn, insn_buf, cnt);
  18261. } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
  18262. desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
  18263. insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
  18264. *cnt = 1;
  18265. } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
  18266. struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
  18267. insn_buf[0] = ld_addrs[0];
  18268. insn_buf[1] = ld_addrs[1];
  18269. insn_buf[2] = *insn;
  18270. *cnt = 3;
  18271. }
  18272. return 0;
  18273. }
  18274. /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
  18275. static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
  18276. {
  18277. struct bpf_subprog_info *info = env->subprog_info;
  18278. int cnt = env->subprog_cnt;
  18279. struct bpf_prog *prog;
  18280. /* We only reserve one slot for hidden subprogs in subprog_info. */
  18281. if (env->hidden_subprog_cnt) {
  18282. verbose(env, "verifier internal error: only one hidden subprog supported\n");
  18283. return -EFAULT;
  18284. }
  18285. /* We're not patching any existing instruction, just appending the new
  18286. * ones for the hidden subprog. Hence all of the adjustment operations
  18287. * in bpf_patch_insn_data are no-ops.
  18288. */
  18289. prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
  18290. if (!prog)
  18291. return -ENOMEM;
  18292. env->prog = prog;
  18293. info[cnt + 1].start = info[cnt].start;
  18294. info[cnt].start = prog->len - len + 1;
  18295. env->subprog_cnt++;
  18296. env->hidden_subprog_cnt++;
  18297. return 0;
  18298. }
  18299. /* Do various post-verification rewrites in a single program pass.
  18300. * These rewrites simplify JIT and interpreter implementations.
  18301. */
  18302. static int do_misc_fixups(struct bpf_verifier_env *env)
  18303. {
  18304. struct bpf_prog *prog = env->prog;
  18305. enum bpf_attach_type eatype = prog->expected_attach_type;
  18306. enum bpf_prog_type prog_type = resolve_prog_type(prog);
  18307. struct bpf_insn *insn = prog->insnsi;
  18308. const struct bpf_func_proto *fn;
  18309. const int insn_cnt = prog->len;
  18310. const struct bpf_map_ops *ops;
  18311. struct bpf_insn_aux_data *aux;
  18312. struct bpf_insn *insn_buf = env->insn_buf;
  18313. struct bpf_prog *new_prog;
  18314. struct bpf_map *map_ptr;
  18315. int i, ret, cnt, delta = 0, cur_subprog = 0;
  18316. struct bpf_subprog_info *subprogs = env->subprog_info;
  18317. u16 stack_depth = subprogs[cur_subprog].stack_depth;
  18318. u16 stack_depth_extra = 0;
  18319. if (env->seen_exception && !env->exception_callback_subprog) {
  18320. struct bpf_insn patch[] = {
  18321. env->prog->insnsi[insn_cnt - 1],
  18322. BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
  18323. BPF_EXIT_INSN(),
  18324. };
  18325. ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
  18326. if (ret < 0)
  18327. return ret;
  18328. prog = env->prog;
  18329. insn = prog->insnsi;
  18330. env->exception_callback_subprog = env->subprog_cnt - 1;
  18331. /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
  18332. mark_subprog_exc_cb(env, env->exception_callback_subprog);
  18333. }
  18334. for (i = 0; i < insn_cnt;) {
  18335. if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
  18336. if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
  18337. (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
  18338. /* convert to 32-bit mov that clears upper 32-bit */
  18339. insn->code = BPF_ALU | BPF_MOV | BPF_X;
  18340. /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
  18341. insn->off = 0;
  18342. insn->imm = 0;
  18343. } /* cast from as(0) to as(1) should be handled by JIT */
  18344. goto next_insn;
  18345. }
  18346. if (env->insn_aux_data[i + delta].needs_zext)
  18347. /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
  18348. insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
  18349. /* Make sdiv/smod divide-by-minus-one exceptions impossible. */
  18350. if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
  18351. insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
  18352. insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
  18353. insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
  18354. insn->off == 1 && insn->imm == -1) {
  18355. bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
  18356. bool isdiv = BPF_OP(insn->code) == BPF_DIV;
  18357. struct bpf_insn *patchlet;
  18358. struct bpf_insn chk_and_sdiv[] = {
  18359. BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
  18360. BPF_NEG | BPF_K, insn->dst_reg,
  18361. 0, 0, 0),
  18362. };
  18363. struct bpf_insn chk_and_smod[] = {
  18364. BPF_MOV32_IMM(insn->dst_reg, 0),
  18365. };
  18366. patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
  18367. cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
  18368. new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
  18369. if (!new_prog)
  18370. return -ENOMEM;
  18371. delta += cnt - 1;
  18372. env->prog = prog = new_prog;
  18373. insn = new_prog->insnsi + i + delta;
  18374. goto next_insn;
  18375. }
  18376. /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
  18377. if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
  18378. insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
  18379. insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
  18380. insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
  18381. bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
  18382. bool isdiv = BPF_OP(insn->code) == BPF_DIV;
  18383. bool is_sdiv = isdiv && insn->off == 1;
  18384. bool is_smod = !isdiv && insn->off == 1;
  18385. struct bpf_insn *patchlet;
  18386. struct bpf_insn chk_and_div[] = {
  18387. /* [R,W]x div 0 -> 0 */
  18388. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  18389. BPF_JNE | BPF_K, insn->src_reg,
  18390. 0, 2, 0),
  18391. BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
  18392. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  18393. *insn,
  18394. };
  18395. struct bpf_insn chk_and_mod[] = {
  18396. /* [R,W]x mod 0 -> [R,W]x */
  18397. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  18398. BPF_JEQ | BPF_K, insn->src_reg,
  18399. 0, 1 + (is64 ? 0 : 1), 0),
  18400. *insn,
  18401. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  18402. BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
  18403. };
  18404. struct bpf_insn chk_and_sdiv[] = {
  18405. /* [R,W]x sdiv 0 -> 0
  18406. * LLONG_MIN sdiv -1 -> LLONG_MIN
  18407. * INT_MIN sdiv -1 -> INT_MIN
  18408. */
  18409. BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
  18410. BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
  18411. BPF_ADD | BPF_K, BPF_REG_AX,
  18412. 0, 0, 1),
  18413. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  18414. BPF_JGT | BPF_K, BPF_REG_AX,
  18415. 0, 4, 1),
  18416. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  18417. BPF_JEQ | BPF_K, BPF_REG_AX,
  18418. 0, 1, 0),
  18419. BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
  18420. BPF_MOV | BPF_K, insn->dst_reg,
  18421. 0, 0, 0),
  18422. /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
  18423. BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
  18424. BPF_NEG | BPF_K, insn->dst_reg,
  18425. 0, 0, 0),
  18426. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  18427. *insn,
  18428. };
  18429. struct bpf_insn chk_and_smod[] = {
  18430. /* [R,W]x mod 0 -> [R,W]x */
  18431. /* [R,W]x mod -1 -> 0 */
  18432. BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
  18433. BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
  18434. BPF_ADD | BPF_K, BPF_REG_AX,
  18435. 0, 0, 1),
  18436. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  18437. BPF_JGT | BPF_K, BPF_REG_AX,
  18438. 0, 3, 1),
  18439. BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
  18440. BPF_JEQ | BPF_K, BPF_REG_AX,
  18441. 0, 3 + (is64 ? 0 : 1), 1),
  18442. BPF_MOV32_IMM(insn->dst_reg, 0),
  18443. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  18444. *insn,
  18445. BPF_JMP_IMM(BPF_JA, 0, 0, 1),
  18446. BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
  18447. };
  18448. if (is_sdiv) {
  18449. patchlet = chk_and_sdiv;
  18450. cnt = ARRAY_SIZE(chk_and_sdiv);
  18451. } else if (is_smod) {
  18452. patchlet = chk_and_smod;
  18453. cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
  18454. } else {
  18455. patchlet = isdiv ? chk_and_div : chk_and_mod;
  18456. cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
  18457. ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
  18458. }
  18459. new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
  18460. if (!new_prog)
  18461. return -ENOMEM;
  18462. delta += cnt - 1;
  18463. env->prog = prog = new_prog;
  18464. insn = new_prog->insnsi + i + delta;
  18465. goto next_insn;
  18466. }
  18467. /* Make it impossible to de-reference a userspace address */
  18468. if (BPF_CLASS(insn->code) == BPF_LDX &&
  18469. (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
  18470. BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
  18471. struct bpf_insn *patch = &insn_buf[0];
  18472. u64 uaddress_limit = bpf_arch_uaddress_limit();
  18473. if (!uaddress_limit)
  18474. goto next_insn;
  18475. *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
  18476. if (insn->off)
  18477. *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
  18478. *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
  18479. *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
  18480. *patch++ = *insn;
  18481. *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
  18482. *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
  18483. cnt = patch - insn_buf;
  18484. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18485. if (!new_prog)
  18486. return -ENOMEM;
  18487. delta += cnt - 1;
  18488. env->prog = prog = new_prog;
  18489. insn = new_prog->insnsi + i + delta;
  18490. goto next_insn;
  18491. }
  18492. /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
  18493. if (BPF_CLASS(insn->code) == BPF_LD &&
  18494. (BPF_MODE(insn->code) == BPF_ABS ||
  18495. BPF_MODE(insn->code) == BPF_IND)) {
  18496. cnt = env->ops->gen_ld_abs(insn, insn_buf);
  18497. if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
  18498. verbose(env, "bpf verifier is misconfigured\n");
  18499. return -EINVAL;
  18500. }
  18501. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18502. if (!new_prog)
  18503. return -ENOMEM;
  18504. delta += cnt - 1;
  18505. env->prog = prog = new_prog;
  18506. insn = new_prog->insnsi + i + delta;
  18507. goto next_insn;
  18508. }
  18509. /* Rewrite pointer arithmetic to mitigate speculation attacks. */
  18510. if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
  18511. insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
  18512. const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
  18513. const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
  18514. struct bpf_insn *patch = &insn_buf[0];
  18515. bool issrc, isneg, isimm;
  18516. u32 off_reg;
  18517. aux = &env->insn_aux_data[i + delta];
  18518. if (!aux->alu_state ||
  18519. aux->alu_state == BPF_ALU_NON_POINTER)
  18520. goto next_insn;
  18521. isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
  18522. issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
  18523. BPF_ALU_SANITIZE_SRC;
  18524. isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
  18525. off_reg = issrc ? insn->src_reg : insn->dst_reg;
  18526. if (isimm) {
  18527. *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
  18528. } else {
  18529. if (isneg)
  18530. *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
  18531. *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
  18532. *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
  18533. *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
  18534. *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
  18535. *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
  18536. *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
  18537. }
  18538. if (!issrc)
  18539. *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
  18540. insn->src_reg = BPF_REG_AX;
  18541. if (isneg)
  18542. insn->code = insn->code == code_add ?
  18543. code_sub : code_add;
  18544. *patch++ = *insn;
  18545. if (issrc && isneg && !isimm)
  18546. *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
  18547. cnt = patch - insn_buf;
  18548. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18549. if (!new_prog)
  18550. return -ENOMEM;
  18551. delta += cnt - 1;
  18552. env->prog = prog = new_prog;
  18553. insn = new_prog->insnsi + i + delta;
  18554. goto next_insn;
  18555. }
  18556. if (is_may_goto_insn(insn)) {
  18557. int stack_off = -stack_depth - 8;
  18558. stack_depth_extra = 8;
  18559. insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
  18560. if (insn->off >= 0)
  18561. insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
  18562. else
  18563. insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
  18564. insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
  18565. insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
  18566. cnt = 4;
  18567. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18568. if (!new_prog)
  18569. return -ENOMEM;
  18570. delta += cnt - 1;
  18571. env->prog = prog = new_prog;
  18572. insn = new_prog->insnsi + i + delta;
  18573. goto next_insn;
  18574. }
  18575. if (insn->code != (BPF_JMP | BPF_CALL))
  18576. goto next_insn;
  18577. if (insn->src_reg == BPF_PSEUDO_CALL)
  18578. goto next_insn;
  18579. if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
  18580. ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
  18581. if (ret)
  18582. return ret;
  18583. if (cnt == 0)
  18584. goto next_insn;
  18585. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18586. if (!new_prog)
  18587. return -ENOMEM;
  18588. delta += cnt - 1;
  18589. env->prog = prog = new_prog;
  18590. insn = new_prog->insnsi + i + delta;
  18591. goto next_insn;
  18592. }
  18593. /* Skip inlining the helper call if the JIT does it. */
  18594. if (bpf_jit_inlines_helper_call(insn->imm))
  18595. goto next_insn;
  18596. if (insn->imm == BPF_FUNC_get_route_realm)
  18597. prog->dst_needed = 1;
  18598. if (insn->imm == BPF_FUNC_get_prandom_u32)
  18599. bpf_user_rnd_init_once();
  18600. if (insn->imm == BPF_FUNC_override_return)
  18601. prog->kprobe_override = 1;
  18602. if (insn->imm == BPF_FUNC_tail_call) {
  18603. /* If we tail call into other programs, we
  18604. * cannot make any assumptions since they can
  18605. * be replaced dynamically during runtime in
  18606. * the program array.
  18607. */
  18608. prog->cb_access = 1;
  18609. if (!allow_tail_call_in_subprogs(env))
  18610. prog->aux->stack_depth = MAX_BPF_STACK;
  18611. prog->aux->max_pkt_offset = MAX_PACKET_OFF;
  18612. /* mark bpf_tail_call as different opcode to avoid
  18613. * conditional branch in the interpreter for every normal
  18614. * call and to prevent accidental JITing by JIT compiler
  18615. * that doesn't support bpf_tail_call yet
  18616. */
  18617. insn->imm = 0;
  18618. insn->code = BPF_JMP | BPF_TAIL_CALL;
  18619. aux = &env->insn_aux_data[i + delta];
  18620. if (env->bpf_capable && !prog->blinding_requested &&
  18621. prog->jit_requested &&
  18622. !bpf_map_key_poisoned(aux) &&
  18623. !bpf_map_ptr_poisoned(aux) &&
  18624. !bpf_map_ptr_unpriv(aux)) {
  18625. struct bpf_jit_poke_descriptor desc = {
  18626. .reason = BPF_POKE_REASON_TAIL_CALL,
  18627. .tail_call.map = aux->map_ptr_state.map_ptr,
  18628. .tail_call.key = bpf_map_key_immediate(aux),
  18629. .insn_idx = i + delta,
  18630. };
  18631. ret = bpf_jit_add_poke_descriptor(prog, &desc);
  18632. if (ret < 0) {
  18633. verbose(env, "adding tail call poke descriptor failed\n");
  18634. return ret;
  18635. }
  18636. insn->imm = ret + 1;
  18637. goto next_insn;
  18638. }
  18639. if (!bpf_map_ptr_unpriv(aux))
  18640. goto next_insn;
  18641. /* instead of changing every JIT dealing with tail_call
  18642. * emit two extra insns:
  18643. * if (index >= max_entries) goto out;
  18644. * index &= array->index_mask;
  18645. * to avoid out-of-bounds cpu speculation
  18646. */
  18647. if (bpf_map_ptr_poisoned(aux)) {
  18648. verbose(env, "tail_call abusing map_ptr\n");
  18649. return -EINVAL;
  18650. }
  18651. map_ptr = aux->map_ptr_state.map_ptr;
  18652. insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
  18653. map_ptr->max_entries, 2);
  18654. insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
  18655. container_of(map_ptr,
  18656. struct bpf_array,
  18657. map)->index_mask);
  18658. insn_buf[2] = *insn;
  18659. cnt = 3;
  18660. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18661. if (!new_prog)
  18662. return -ENOMEM;
  18663. delta += cnt - 1;
  18664. env->prog = prog = new_prog;
  18665. insn = new_prog->insnsi + i + delta;
  18666. goto next_insn;
  18667. }
  18668. if (insn->imm == BPF_FUNC_timer_set_callback) {
  18669. /* The verifier will process callback_fn as many times as necessary
  18670. * with different maps and the register states prepared by
  18671. * set_timer_callback_state will be accurate.
  18672. *
  18673. * The following use case is valid:
  18674. * map1 is shared by prog1, prog2, prog3.
  18675. * prog1 calls bpf_timer_init for some map1 elements
  18676. * prog2 calls bpf_timer_set_callback for some map1 elements.
  18677. * Those that were not bpf_timer_init-ed will return -EINVAL.
  18678. * prog3 calls bpf_timer_start for some map1 elements.
  18679. * Those that were not both bpf_timer_init-ed and
  18680. * bpf_timer_set_callback-ed will return -EINVAL.
  18681. */
  18682. struct bpf_insn ld_addrs[2] = {
  18683. BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
  18684. };
  18685. insn_buf[0] = ld_addrs[0];
  18686. insn_buf[1] = ld_addrs[1];
  18687. insn_buf[2] = *insn;
  18688. cnt = 3;
  18689. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18690. if (!new_prog)
  18691. return -ENOMEM;
  18692. delta += cnt - 1;
  18693. env->prog = prog = new_prog;
  18694. insn = new_prog->insnsi + i + delta;
  18695. goto patch_call_imm;
  18696. }
  18697. if (is_storage_get_function(insn->imm)) {
  18698. if (!in_sleepable(env) ||
  18699. env->insn_aux_data[i + delta].storage_get_func_atomic)
  18700. insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
  18701. else
  18702. insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
  18703. insn_buf[1] = *insn;
  18704. cnt = 2;
  18705. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18706. if (!new_prog)
  18707. return -ENOMEM;
  18708. delta += cnt - 1;
  18709. env->prog = prog = new_prog;
  18710. insn = new_prog->insnsi + i + delta;
  18711. goto patch_call_imm;
  18712. }
  18713. /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
  18714. if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
  18715. /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
  18716. * bpf_mem_alloc() returns a ptr to the percpu data ptr.
  18717. */
  18718. insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
  18719. insn_buf[1] = *insn;
  18720. cnt = 2;
  18721. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18722. if (!new_prog)
  18723. return -ENOMEM;
  18724. delta += cnt - 1;
  18725. env->prog = prog = new_prog;
  18726. insn = new_prog->insnsi + i + delta;
  18727. goto patch_call_imm;
  18728. }
  18729. /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
  18730. * and other inlining handlers are currently limited to 64 bit
  18731. * only.
  18732. */
  18733. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  18734. (insn->imm == BPF_FUNC_map_lookup_elem ||
  18735. insn->imm == BPF_FUNC_map_update_elem ||
  18736. insn->imm == BPF_FUNC_map_delete_elem ||
  18737. insn->imm == BPF_FUNC_map_push_elem ||
  18738. insn->imm == BPF_FUNC_map_pop_elem ||
  18739. insn->imm == BPF_FUNC_map_peek_elem ||
  18740. insn->imm == BPF_FUNC_redirect_map ||
  18741. insn->imm == BPF_FUNC_for_each_map_elem ||
  18742. insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
  18743. aux = &env->insn_aux_data[i + delta];
  18744. if (bpf_map_ptr_poisoned(aux))
  18745. goto patch_call_imm;
  18746. map_ptr = aux->map_ptr_state.map_ptr;
  18747. ops = map_ptr->ops;
  18748. if (insn->imm == BPF_FUNC_map_lookup_elem &&
  18749. ops->map_gen_lookup) {
  18750. cnt = ops->map_gen_lookup(map_ptr, insn_buf);
  18751. if (cnt == -EOPNOTSUPP)
  18752. goto patch_map_ops_generic;
  18753. if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
  18754. verbose(env, "bpf verifier is misconfigured\n");
  18755. return -EINVAL;
  18756. }
  18757. new_prog = bpf_patch_insn_data(env, i + delta,
  18758. insn_buf, cnt);
  18759. if (!new_prog)
  18760. return -ENOMEM;
  18761. delta += cnt - 1;
  18762. env->prog = prog = new_prog;
  18763. insn = new_prog->insnsi + i + delta;
  18764. goto next_insn;
  18765. }
  18766. BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
  18767. (void *(*)(struct bpf_map *map, void *key))NULL));
  18768. BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
  18769. (long (*)(struct bpf_map *map, void *key))NULL));
  18770. BUILD_BUG_ON(!__same_type(ops->map_update_elem,
  18771. (long (*)(struct bpf_map *map, void *key, void *value,
  18772. u64 flags))NULL));
  18773. BUILD_BUG_ON(!__same_type(ops->map_push_elem,
  18774. (long (*)(struct bpf_map *map, void *value,
  18775. u64 flags))NULL));
  18776. BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
  18777. (long (*)(struct bpf_map *map, void *value))NULL));
  18778. BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
  18779. (long (*)(struct bpf_map *map, void *value))NULL));
  18780. BUILD_BUG_ON(!__same_type(ops->map_redirect,
  18781. (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
  18782. BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
  18783. (long (*)(struct bpf_map *map,
  18784. bpf_callback_t callback_fn,
  18785. void *callback_ctx,
  18786. u64 flags))NULL));
  18787. BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
  18788. (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
  18789. patch_map_ops_generic:
  18790. switch (insn->imm) {
  18791. case BPF_FUNC_map_lookup_elem:
  18792. insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
  18793. goto next_insn;
  18794. case BPF_FUNC_map_update_elem:
  18795. insn->imm = BPF_CALL_IMM(ops->map_update_elem);
  18796. goto next_insn;
  18797. case BPF_FUNC_map_delete_elem:
  18798. insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
  18799. goto next_insn;
  18800. case BPF_FUNC_map_push_elem:
  18801. insn->imm = BPF_CALL_IMM(ops->map_push_elem);
  18802. goto next_insn;
  18803. case BPF_FUNC_map_pop_elem:
  18804. insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
  18805. goto next_insn;
  18806. case BPF_FUNC_map_peek_elem:
  18807. insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
  18808. goto next_insn;
  18809. case BPF_FUNC_redirect_map:
  18810. insn->imm = BPF_CALL_IMM(ops->map_redirect);
  18811. goto next_insn;
  18812. case BPF_FUNC_for_each_map_elem:
  18813. insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
  18814. goto next_insn;
  18815. case BPF_FUNC_map_lookup_percpu_elem:
  18816. insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
  18817. goto next_insn;
  18818. }
  18819. goto patch_call_imm;
  18820. }
  18821. /* Implement bpf_jiffies64 inline. */
  18822. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  18823. insn->imm == BPF_FUNC_jiffies64) {
  18824. struct bpf_insn ld_jiffies_addr[2] = {
  18825. BPF_LD_IMM64(BPF_REG_0,
  18826. (unsigned long)&jiffies),
  18827. };
  18828. insn_buf[0] = ld_jiffies_addr[0];
  18829. insn_buf[1] = ld_jiffies_addr[1];
  18830. insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
  18831. BPF_REG_0, 0);
  18832. cnt = 3;
  18833. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
  18834. cnt);
  18835. if (!new_prog)
  18836. return -ENOMEM;
  18837. delta += cnt - 1;
  18838. env->prog = prog = new_prog;
  18839. insn = new_prog->insnsi + i + delta;
  18840. goto next_insn;
  18841. }
  18842. #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
  18843. /* Implement bpf_get_smp_processor_id() inline. */
  18844. if (insn->imm == BPF_FUNC_get_smp_processor_id &&
  18845. verifier_inlines_helper_call(env, insn->imm)) {
  18846. /* BPF_FUNC_get_smp_processor_id inlining is an
  18847. * optimization, so if pcpu_hot.cpu_number is ever
  18848. * changed in some incompatible and hard to support
  18849. * way, it's fine to back out this inlining logic
  18850. */
  18851. #ifdef CONFIG_SMP
  18852. insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
  18853. insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
  18854. insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
  18855. cnt = 3;
  18856. #else
  18857. insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
  18858. cnt = 1;
  18859. #endif
  18860. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18861. if (!new_prog)
  18862. return -ENOMEM;
  18863. delta += cnt - 1;
  18864. env->prog = prog = new_prog;
  18865. insn = new_prog->insnsi + i + delta;
  18866. goto next_insn;
  18867. }
  18868. #endif
  18869. /* Implement bpf_get_func_arg inline. */
  18870. if (prog_type == BPF_PROG_TYPE_TRACING &&
  18871. insn->imm == BPF_FUNC_get_func_arg) {
  18872. /* Load nr_args from ctx - 8 */
  18873. insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
  18874. insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
  18875. insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
  18876. insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
  18877. insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
  18878. insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
  18879. insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
  18880. insn_buf[7] = BPF_JMP_A(1);
  18881. insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
  18882. cnt = 9;
  18883. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18884. if (!new_prog)
  18885. return -ENOMEM;
  18886. delta += cnt - 1;
  18887. env->prog = prog = new_prog;
  18888. insn = new_prog->insnsi + i + delta;
  18889. goto next_insn;
  18890. }
  18891. /* Implement bpf_get_func_ret inline. */
  18892. if (prog_type == BPF_PROG_TYPE_TRACING &&
  18893. insn->imm == BPF_FUNC_get_func_ret) {
  18894. if (eatype == BPF_TRACE_FEXIT ||
  18895. eatype == BPF_MODIFY_RETURN) {
  18896. /* Load nr_args from ctx - 8 */
  18897. insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
  18898. insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
  18899. insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
  18900. insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
  18901. insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
  18902. insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
  18903. cnt = 6;
  18904. } else {
  18905. insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
  18906. cnt = 1;
  18907. }
  18908. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18909. if (!new_prog)
  18910. return -ENOMEM;
  18911. delta += cnt - 1;
  18912. env->prog = prog = new_prog;
  18913. insn = new_prog->insnsi + i + delta;
  18914. goto next_insn;
  18915. }
  18916. /* Implement get_func_arg_cnt inline. */
  18917. if (prog_type == BPF_PROG_TYPE_TRACING &&
  18918. insn->imm == BPF_FUNC_get_func_arg_cnt) {
  18919. /* Load nr_args from ctx - 8 */
  18920. insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
  18921. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
  18922. if (!new_prog)
  18923. return -ENOMEM;
  18924. env->prog = prog = new_prog;
  18925. insn = new_prog->insnsi + i + delta;
  18926. goto next_insn;
  18927. }
  18928. /* Implement bpf_get_func_ip inline. */
  18929. if (prog_type == BPF_PROG_TYPE_TRACING &&
  18930. insn->imm == BPF_FUNC_get_func_ip) {
  18931. /* Load IP address from ctx - 16 */
  18932. insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
  18933. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
  18934. if (!new_prog)
  18935. return -ENOMEM;
  18936. env->prog = prog = new_prog;
  18937. insn = new_prog->insnsi + i + delta;
  18938. goto next_insn;
  18939. }
  18940. /* Implement bpf_get_branch_snapshot inline. */
  18941. if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
  18942. prog->jit_requested && BITS_PER_LONG == 64 &&
  18943. insn->imm == BPF_FUNC_get_branch_snapshot) {
  18944. /* We are dealing with the following func protos:
  18945. * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
  18946. * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
  18947. */
  18948. const u32 br_entry_size = sizeof(struct perf_branch_entry);
  18949. /* struct perf_branch_entry is part of UAPI and is
  18950. * used as an array element, so extremely unlikely to
  18951. * ever grow or shrink
  18952. */
  18953. BUILD_BUG_ON(br_entry_size != 24);
  18954. /* if (unlikely(flags)) return -EINVAL */
  18955. insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
  18956. /* Transform size (bytes) into number of entries (cnt = size / 24).
  18957. * But to avoid expensive division instruction, we implement
  18958. * divide-by-3 through multiplication, followed by further
  18959. * division by 8 through 3-bit right shift.
  18960. * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
  18961. * p. 227, chapter "Unsigned Division by 3" for details and proofs.
  18962. *
  18963. * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
  18964. */
  18965. insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
  18966. insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
  18967. insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
  18968. /* call perf_snapshot_branch_stack implementation */
  18969. insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
  18970. /* if (entry_cnt == 0) return -ENOENT */
  18971. insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
  18972. /* return entry_cnt * sizeof(struct perf_branch_entry) */
  18973. insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
  18974. insn_buf[7] = BPF_JMP_A(3);
  18975. /* return -EINVAL; */
  18976. insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
  18977. insn_buf[9] = BPF_JMP_A(1);
  18978. /* return -ENOENT; */
  18979. insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
  18980. cnt = 11;
  18981. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18982. if (!new_prog)
  18983. return -ENOMEM;
  18984. delta += cnt - 1;
  18985. env->prog = prog = new_prog;
  18986. insn = new_prog->insnsi + i + delta;
  18987. goto next_insn;
  18988. }
  18989. /* Implement bpf_kptr_xchg inline */
  18990. if (prog->jit_requested && BITS_PER_LONG == 64 &&
  18991. insn->imm == BPF_FUNC_kptr_xchg &&
  18992. bpf_jit_supports_ptr_xchg()) {
  18993. insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
  18994. insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
  18995. cnt = 2;
  18996. new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
  18997. if (!new_prog)
  18998. return -ENOMEM;
  18999. delta += cnt - 1;
  19000. env->prog = prog = new_prog;
  19001. insn = new_prog->insnsi + i + delta;
  19002. goto next_insn;
  19003. }
  19004. patch_call_imm:
  19005. fn = env->ops->get_func_proto(insn->imm, env->prog);
  19006. /* all functions that have prototype and verifier allowed
  19007. * programs to call them, must be real in-kernel functions
  19008. */
  19009. if (!fn->func) {
  19010. verbose(env,
  19011. "kernel subsystem misconfigured func %s#%d\n",
  19012. func_id_name(insn->imm), insn->imm);
  19013. return -EFAULT;
  19014. }
  19015. insn->imm = fn->func - __bpf_call_base;
  19016. next_insn:
  19017. if (subprogs[cur_subprog + 1].start == i + delta + 1) {
  19018. subprogs[cur_subprog].stack_depth += stack_depth_extra;
  19019. subprogs[cur_subprog].stack_extra = stack_depth_extra;
  19020. stack_depth = subprogs[cur_subprog].stack_depth;
  19021. if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
  19022. verbose(env, "stack size %d(extra %d) is too large\n",
  19023. stack_depth, stack_depth_extra);
  19024. return -EINVAL;
  19025. }
  19026. cur_subprog++;
  19027. stack_depth = subprogs[cur_subprog].stack_depth;
  19028. stack_depth_extra = 0;
  19029. }
  19030. i++;
  19031. insn++;
  19032. }
  19033. env->prog->aux->stack_depth = subprogs[0].stack_depth;
  19034. for (i = 0; i < env->subprog_cnt; i++) {
  19035. int subprog_start = subprogs[i].start;
  19036. int stack_slots = subprogs[i].stack_extra / 8;
  19037. if (!stack_slots)
  19038. continue;
  19039. if (stack_slots > 1) {
  19040. verbose(env, "verifier bug: stack_slots supports may_goto only\n");
  19041. return -EFAULT;
  19042. }
  19043. /* Add ST insn to subprog prologue to init extra stack */
  19044. insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
  19045. -subprogs[i].stack_depth, BPF_MAX_LOOPS);
  19046. /* Copy first actual insn to preserve it */
  19047. insn_buf[1] = env->prog->insnsi[subprog_start];
  19048. new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
  19049. if (!new_prog)
  19050. return -ENOMEM;
  19051. env->prog = prog = new_prog;
  19052. /*
  19053. * If may_goto is a first insn of a prog there could be a jmp
  19054. * insn that points to it, hence adjust all such jmps to point
  19055. * to insn after BPF_ST that inits may_goto count.
  19056. * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
  19057. */
  19058. WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
  19059. }
  19060. /* Since poke tab is now finalized, publish aux to tracker. */
  19061. for (i = 0; i < prog->aux->size_poke_tab; i++) {
  19062. map_ptr = prog->aux->poke_tab[i].tail_call.map;
  19063. if (!map_ptr->ops->map_poke_track ||
  19064. !map_ptr->ops->map_poke_untrack ||
  19065. !map_ptr->ops->map_poke_run) {
  19066. verbose(env, "bpf verifier is misconfigured\n");
  19067. return -EINVAL;
  19068. }
  19069. ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
  19070. if (ret < 0) {
  19071. verbose(env, "tracking tail call prog failed\n");
  19072. return ret;
  19073. }
  19074. }
  19075. sort_kfunc_descs_by_imm_off(env->prog);
  19076. return 0;
  19077. }
  19078. static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
  19079. int position,
  19080. s32 stack_base,
  19081. u32 callback_subprogno,
  19082. u32 *total_cnt)
  19083. {
  19084. s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
  19085. s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
  19086. s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
  19087. int reg_loop_max = BPF_REG_6;
  19088. int reg_loop_cnt = BPF_REG_7;
  19089. int reg_loop_ctx = BPF_REG_8;
  19090. struct bpf_insn *insn_buf = env->insn_buf;
  19091. struct bpf_prog *new_prog;
  19092. u32 callback_start;
  19093. u32 call_insn_offset;
  19094. s32 callback_offset;
  19095. u32 cnt = 0;
  19096. /* This represents an inlined version of bpf_iter.c:bpf_loop,
  19097. * be careful to modify this code in sync.
  19098. */
  19099. /* Return error and jump to the end of the patch if
  19100. * expected number of iterations is too big.
  19101. */
  19102. insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
  19103. insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
  19104. insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
  19105. /* spill R6, R7, R8 to use these as loop vars */
  19106. insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
  19107. insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
  19108. insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
  19109. /* initialize loop vars */
  19110. insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
  19111. insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
  19112. insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
  19113. /* loop header,
  19114. * if reg_loop_cnt >= reg_loop_max skip the loop body
  19115. */
  19116. insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
  19117. /* callback call,
  19118. * correct callback offset would be set after patching
  19119. */
  19120. insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
  19121. insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
  19122. insn_buf[cnt++] = BPF_CALL_REL(0);
  19123. /* increment loop counter */
  19124. insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
  19125. /* jump to loop header if callback returned 0 */
  19126. insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
  19127. /* return value of bpf_loop,
  19128. * set R0 to the number of iterations
  19129. */
  19130. insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
  19131. /* restore original values of R6, R7, R8 */
  19132. insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
  19133. insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
  19134. insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
  19135. *total_cnt = cnt;
  19136. new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
  19137. if (!new_prog)
  19138. return new_prog;
  19139. /* callback start is known only after patching */
  19140. callback_start = env->subprog_info[callback_subprogno].start;
  19141. /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
  19142. call_insn_offset = position + 12;
  19143. callback_offset = callback_start - call_insn_offset - 1;
  19144. new_prog->insnsi[call_insn_offset].imm = callback_offset;
  19145. return new_prog;
  19146. }
  19147. static bool is_bpf_loop_call(struct bpf_insn *insn)
  19148. {
  19149. return insn->code == (BPF_JMP | BPF_CALL) &&
  19150. insn->src_reg == 0 &&
  19151. insn->imm == BPF_FUNC_loop;
  19152. }
  19153. /* For all sub-programs in the program (including main) check
  19154. * insn_aux_data to see if there are bpf_loop calls that require
  19155. * inlining. If such calls are found the calls are replaced with a
  19156. * sequence of instructions produced by `inline_bpf_loop` function and
  19157. * subprog stack_depth is increased by the size of 3 registers.
  19158. * This stack space is used to spill values of the R6, R7, R8. These
  19159. * registers are used to store the loop bound, counter and context
  19160. * variables.
  19161. */
  19162. static int optimize_bpf_loop(struct bpf_verifier_env *env)
  19163. {
  19164. struct bpf_subprog_info *subprogs = env->subprog_info;
  19165. int i, cur_subprog = 0, cnt, delta = 0;
  19166. struct bpf_insn *insn = env->prog->insnsi;
  19167. int insn_cnt = env->prog->len;
  19168. u16 stack_depth = subprogs[cur_subprog].stack_depth;
  19169. u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
  19170. u16 stack_depth_extra = 0;
  19171. for (i = 0; i < insn_cnt; i++, insn++) {
  19172. struct bpf_loop_inline_state *inline_state =
  19173. &env->insn_aux_data[i + delta].loop_inline_state;
  19174. if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
  19175. struct bpf_prog *new_prog;
  19176. stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
  19177. new_prog = inline_bpf_loop(env,
  19178. i + delta,
  19179. -(stack_depth + stack_depth_extra),
  19180. inline_state->callback_subprogno,
  19181. &cnt);
  19182. if (!new_prog)
  19183. return -ENOMEM;
  19184. delta += cnt - 1;
  19185. env->prog = new_prog;
  19186. insn = new_prog->insnsi + i + delta;
  19187. }
  19188. if (subprogs[cur_subprog + 1].start == i + delta + 1) {
  19189. subprogs[cur_subprog].stack_depth += stack_depth_extra;
  19190. cur_subprog++;
  19191. stack_depth = subprogs[cur_subprog].stack_depth;
  19192. stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
  19193. stack_depth_extra = 0;
  19194. }
  19195. }
  19196. env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
  19197. return 0;
  19198. }
  19199. /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
  19200. * adjust subprograms stack depth when possible.
  19201. */
  19202. static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
  19203. {
  19204. struct bpf_subprog_info *subprog = env->subprog_info;
  19205. struct bpf_insn_aux_data *aux = env->insn_aux_data;
  19206. struct bpf_insn *insn = env->prog->insnsi;
  19207. int insn_cnt = env->prog->len;
  19208. u32 spills_num;
  19209. bool modified = false;
  19210. int i, j;
  19211. for (i = 0; i < insn_cnt; i++, insn++) {
  19212. if (aux[i].fastcall_spills_num > 0) {
  19213. spills_num = aux[i].fastcall_spills_num;
  19214. /* NOPs would be removed by opt_remove_nops() */
  19215. for (j = 1; j <= spills_num; ++j) {
  19216. *(insn - j) = NOP;
  19217. *(insn + j) = NOP;
  19218. }
  19219. modified = true;
  19220. }
  19221. if ((subprog + 1)->start == i + 1) {
  19222. if (modified && !subprog->keep_fastcall_stack)
  19223. subprog->stack_depth = -subprog->fastcall_stack_off;
  19224. subprog++;
  19225. modified = false;
  19226. }
  19227. }
  19228. return 0;
  19229. }
  19230. static void free_states(struct bpf_verifier_env *env)
  19231. {
  19232. struct bpf_verifier_state_list *sl, *sln;
  19233. int i;
  19234. sl = env->free_list;
  19235. while (sl) {
  19236. sln = sl->next;
  19237. free_verifier_state(&sl->state, false);
  19238. kfree(sl);
  19239. sl = sln;
  19240. }
  19241. env->free_list = NULL;
  19242. if (!env->explored_states)
  19243. return;
  19244. for (i = 0; i < state_htab_size(env); i++) {
  19245. sl = env->explored_states[i];
  19246. while (sl) {
  19247. sln = sl->next;
  19248. free_verifier_state(&sl->state, false);
  19249. kfree(sl);
  19250. sl = sln;
  19251. }
  19252. env->explored_states[i] = NULL;
  19253. }
  19254. }
  19255. static int do_check_common(struct bpf_verifier_env *env, int subprog)
  19256. {
  19257. bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
  19258. struct bpf_subprog_info *sub = subprog_info(env, subprog);
  19259. struct bpf_verifier_state *state;
  19260. struct bpf_reg_state *regs;
  19261. int ret, i;
  19262. env->prev_linfo = NULL;
  19263. env->pass_cnt++;
  19264. state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
  19265. if (!state)
  19266. return -ENOMEM;
  19267. state->curframe = 0;
  19268. state->speculative = false;
  19269. state->branches = 1;
  19270. state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
  19271. if (!state->frame[0]) {
  19272. kfree(state);
  19273. return -ENOMEM;
  19274. }
  19275. env->cur_state = state;
  19276. init_func_state(env, state->frame[0],
  19277. BPF_MAIN_FUNC /* callsite */,
  19278. 0 /* frameno */,
  19279. subprog);
  19280. state->first_insn_idx = env->subprog_info[subprog].start;
  19281. state->last_insn_idx = -1;
  19282. regs = state->frame[state->curframe]->regs;
  19283. if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
  19284. const char *sub_name = subprog_name(env, subprog);
  19285. struct bpf_subprog_arg_info *arg;
  19286. struct bpf_reg_state *reg;
  19287. verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
  19288. ret = btf_prepare_func_args(env, subprog);
  19289. if (ret)
  19290. goto out;
  19291. if (subprog_is_exc_cb(env, subprog)) {
  19292. state->frame[0]->in_exception_callback_fn = true;
  19293. /* We have already ensured that the callback returns an integer, just
  19294. * like all global subprogs. We need to determine it only has a single
  19295. * scalar argument.
  19296. */
  19297. if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
  19298. verbose(env, "exception cb only supports single integer argument\n");
  19299. ret = -EINVAL;
  19300. goto out;
  19301. }
  19302. }
  19303. for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
  19304. arg = &sub->args[i - BPF_REG_1];
  19305. reg = &regs[i];
  19306. if (arg->arg_type == ARG_PTR_TO_CTX) {
  19307. reg->type = PTR_TO_CTX;
  19308. mark_reg_known_zero(env, regs, i);
  19309. } else if (arg->arg_type == ARG_ANYTHING) {
  19310. reg->type = SCALAR_VALUE;
  19311. mark_reg_unknown(env, regs, i);
  19312. } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
  19313. /* assume unspecial LOCAL dynptr type */
  19314. __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
  19315. } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
  19316. reg->type = PTR_TO_MEM;
  19317. if (arg->arg_type & PTR_MAYBE_NULL)
  19318. reg->type |= PTR_MAYBE_NULL;
  19319. mark_reg_known_zero(env, regs, i);
  19320. reg->mem_size = arg->mem_size;
  19321. reg->id = ++env->id_gen;
  19322. } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
  19323. reg->type = PTR_TO_BTF_ID;
  19324. if (arg->arg_type & PTR_MAYBE_NULL)
  19325. reg->type |= PTR_MAYBE_NULL;
  19326. if (arg->arg_type & PTR_UNTRUSTED)
  19327. reg->type |= PTR_UNTRUSTED;
  19328. if (arg->arg_type & PTR_TRUSTED)
  19329. reg->type |= PTR_TRUSTED;
  19330. mark_reg_known_zero(env, regs, i);
  19331. reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
  19332. reg->btf_id = arg->btf_id;
  19333. reg->id = ++env->id_gen;
  19334. } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
  19335. /* caller can pass either PTR_TO_ARENA or SCALAR */
  19336. mark_reg_unknown(env, regs, i);
  19337. } else {
  19338. WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
  19339. i - BPF_REG_1, arg->arg_type);
  19340. ret = -EFAULT;
  19341. goto out;
  19342. }
  19343. }
  19344. } else {
  19345. /* if main BPF program has associated BTF info, validate that
  19346. * it's matching expected signature, and otherwise mark BTF
  19347. * info for main program as unreliable
  19348. */
  19349. if (env->prog->aux->func_info_aux) {
  19350. ret = btf_prepare_func_args(env, 0);
  19351. if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
  19352. env->prog->aux->func_info_aux[0].unreliable = true;
  19353. }
  19354. /* 1st arg to a function */
  19355. regs[BPF_REG_1].type = PTR_TO_CTX;
  19356. mark_reg_known_zero(env, regs, BPF_REG_1);
  19357. }
  19358. ret = do_check(env);
  19359. out:
  19360. /* check for NULL is necessary, since cur_state can be freed inside
  19361. * do_check() under memory pressure.
  19362. */
  19363. if (env->cur_state) {
  19364. free_verifier_state(env->cur_state, true);
  19365. env->cur_state = NULL;
  19366. }
  19367. while (!pop_stack(env, NULL, NULL, false));
  19368. if (!ret && pop_log)
  19369. bpf_vlog_reset(&env->log, 0);
  19370. free_states(env);
  19371. return ret;
  19372. }
  19373. /* Lazily verify all global functions based on their BTF, if they are called
  19374. * from main BPF program or any of subprograms transitively.
  19375. * BPF global subprogs called from dead code are not validated.
  19376. * All callable global functions must pass verification.
  19377. * Otherwise the whole program is rejected.
  19378. * Consider:
  19379. * int bar(int);
  19380. * int foo(int f)
  19381. * {
  19382. * return bar(f);
  19383. * }
  19384. * int bar(int b)
  19385. * {
  19386. * ...
  19387. * }
  19388. * foo() will be verified first for R1=any_scalar_value. During verification it
  19389. * will be assumed that bar() already verified successfully and call to bar()
  19390. * from foo() will be checked for type match only. Later bar() will be verified
  19391. * independently to check that it's safe for R1=any_scalar_value.
  19392. */
  19393. static int do_check_subprogs(struct bpf_verifier_env *env)
  19394. {
  19395. struct bpf_prog_aux *aux = env->prog->aux;
  19396. struct bpf_func_info_aux *sub_aux;
  19397. int i, ret, new_cnt;
  19398. if (!aux->func_info)
  19399. return 0;
  19400. /* exception callback is presumed to be always called */
  19401. if (env->exception_callback_subprog)
  19402. subprog_aux(env, env->exception_callback_subprog)->called = true;
  19403. again:
  19404. new_cnt = 0;
  19405. for (i = 1; i < env->subprog_cnt; i++) {
  19406. if (!subprog_is_global(env, i))
  19407. continue;
  19408. sub_aux = subprog_aux(env, i);
  19409. if (!sub_aux->called || sub_aux->verified)
  19410. continue;
  19411. env->insn_idx = env->subprog_info[i].start;
  19412. WARN_ON_ONCE(env->insn_idx == 0);
  19413. ret = do_check_common(env, i);
  19414. if (ret) {
  19415. return ret;
  19416. } else if (env->log.level & BPF_LOG_LEVEL) {
  19417. verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
  19418. i, subprog_name(env, i));
  19419. }
  19420. /* We verified new global subprog, it might have called some
  19421. * more global subprogs that we haven't verified yet, so we
  19422. * need to do another pass over subprogs to verify those.
  19423. */
  19424. sub_aux->verified = true;
  19425. new_cnt++;
  19426. }
  19427. /* We can't loop forever as we verify at least one global subprog on
  19428. * each pass.
  19429. */
  19430. if (new_cnt)
  19431. goto again;
  19432. return 0;
  19433. }
  19434. static int do_check_main(struct bpf_verifier_env *env)
  19435. {
  19436. int ret;
  19437. env->insn_idx = 0;
  19438. ret = do_check_common(env, 0);
  19439. if (!ret)
  19440. env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
  19441. return ret;
  19442. }
  19443. static void print_verification_stats(struct bpf_verifier_env *env)
  19444. {
  19445. int i;
  19446. if (env->log.level & BPF_LOG_STATS) {
  19447. verbose(env, "verification time %lld usec\n",
  19448. div_u64(env->verification_time, 1000));
  19449. verbose(env, "stack depth ");
  19450. for (i = 0; i < env->subprog_cnt; i++) {
  19451. u32 depth = env->subprog_info[i].stack_depth;
  19452. verbose(env, "%d", depth);
  19453. if (i + 1 < env->subprog_cnt)
  19454. verbose(env, "+");
  19455. }
  19456. verbose(env, "\n");
  19457. }
  19458. verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
  19459. "total_states %d peak_states %d mark_read %d\n",
  19460. env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
  19461. env->max_states_per_insn, env->total_states,
  19462. env->peak_states, env->longest_mark_read_walk);
  19463. }
  19464. static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
  19465. {
  19466. const struct btf_type *t, *func_proto;
  19467. const struct bpf_struct_ops_desc *st_ops_desc;
  19468. const struct bpf_struct_ops *st_ops;
  19469. const struct btf_member *member;
  19470. struct bpf_prog *prog = env->prog;
  19471. u32 btf_id, member_idx;
  19472. struct btf *btf;
  19473. const char *mname;
  19474. int err;
  19475. if (!prog->gpl_compatible) {
  19476. verbose(env, "struct ops programs must have a GPL compatible license\n");
  19477. return -EINVAL;
  19478. }
  19479. if (!prog->aux->attach_btf_id)
  19480. return -ENOTSUPP;
  19481. btf = prog->aux->attach_btf;
  19482. if (btf_is_module(btf)) {
  19483. /* Make sure st_ops is valid through the lifetime of env */
  19484. env->attach_btf_mod = btf_try_get_module(btf);
  19485. if (!env->attach_btf_mod) {
  19486. verbose(env, "struct_ops module %s is not found\n",
  19487. btf_get_name(btf));
  19488. return -ENOTSUPP;
  19489. }
  19490. }
  19491. btf_id = prog->aux->attach_btf_id;
  19492. st_ops_desc = bpf_struct_ops_find(btf, btf_id);
  19493. if (!st_ops_desc) {
  19494. verbose(env, "attach_btf_id %u is not a supported struct\n",
  19495. btf_id);
  19496. return -ENOTSUPP;
  19497. }
  19498. st_ops = st_ops_desc->st_ops;
  19499. t = st_ops_desc->type;
  19500. member_idx = prog->expected_attach_type;
  19501. if (member_idx >= btf_type_vlen(t)) {
  19502. verbose(env, "attach to invalid member idx %u of struct %s\n",
  19503. member_idx, st_ops->name);
  19504. return -EINVAL;
  19505. }
  19506. member = &btf_type_member(t)[member_idx];
  19507. mname = btf_name_by_offset(btf, member->name_off);
  19508. func_proto = btf_type_resolve_func_ptr(btf, member->type,
  19509. NULL);
  19510. if (!func_proto) {
  19511. verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
  19512. mname, member_idx, st_ops->name);
  19513. return -EINVAL;
  19514. }
  19515. err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8);
  19516. if (err) {
  19517. verbose(env, "attach to unsupported member %s of struct %s\n",
  19518. mname, st_ops->name);
  19519. return err;
  19520. }
  19521. if (st_ops->check_member) {
  19522. err = st_ops->check_member(t, member, prog);
  19523. if (err) {
  19524. verbose(env, "attach to unsupported member %s of struct %s\n",
  19525. mname, st_ops->name);
  19526. return err;
  19527. }
  19528. }
  19529. /* btf_ctx_access() used this to provide argument type info */
  19530. prog->aux->ctx_arg_info =
  19531. st_ops_desc->arg_info[member_idx].info;
  19532. prog->aux->ctx_arg_info_size =
  19533. st_ops_desc->arg_info[member_idx].cnt;
  19534. prog->aux->attach_func_proto = func_proto;
  19535. prog->aux->attach_func_name = mname;
  19536. env->ops = st_ops->verifier_ops;
  19537. return 0;
  19538. }
  19539. #define SECURITY_PREFIX "security_"
  19540. static int check_attach_modify_return(unsigned long addr, const char *func_name)
  19541. {
  19542. if (within_error_injection_list(addr) ||
  19543. !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
  19544. return 0;
  19545. return -EINVAL;
  19546. }
  19547. /* list of non-sleepable functions that are otherwise on
  19548. * ALLOW_ERROR_INJECTION list
  19549. */
  19550. BTF_SET_START(btf_non_sleepable_error_inject)
  19551. /* Three functions below can be called from sleepable and non-sleepable context.
  19552. * Assume non-sleepable from bpf safety point of view.
  19553. */
  19554. BTF_ID(func, __filemap_add_folio)
  19555. #ifdef CONFIG_FAIL_PAGE_ALLOC
  19556. BTF_ID(func, should_fail_alloc_page)
  19557. #endif
  19558. #ifdef CONFIG_FAILSLAB
  19559. BTF_ID(func, should_failslab)
  19560. #endif
  19561. BTF_SET_END(btf_non_sleepable_error_inject)
  19562. static int check_non_sleepable_error_inject(u32 btf_id)
  19563. {
  19564. return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
  19565. }
  19566. int bpf_check_attach_target(struct bpf_verifier_log *log,
  19567. const struct bpf_prog *prog,
  19568. const struct bpf_prog *tgt_prog,
  19569. u32 btf_id,
  19570. struct bpf_attach_target_info *tgt_info)
  19571. {
  19572. bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
  19573. bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
  19574. char trace_symbol[KSYM_SYMBOL_LEN];
  19575. const char prefix[] = "btf_trace_";
  19576. struct bpf_raw_event_map *btp;
  19577. int ret = 0, subprog = -1, i;
  19578. const struct btf_type *t;
  19579. bool conservative = true;
  19580. const char *tname, *fname;
  19581. struct btf *btf;
  19582. long addr = 0;
  19583. struct module *mod = NULL;
  19584. if (!btf_id) {
  19585. bpf_log(log, "Tracing programs must provide btf_id\n");
  19586. return -EINVAL;
  19587. }
  19588. btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
  19589. if (!btf) {
  19590. bpf_log(log,
  19591. "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
  19592. return -EINVAL;
  19593. }
  19594. t = btf_type_by_id(btf, btf_id);
  19595. if (!t) {
  19596. bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
  19597. return -EINVAL;
  19598. }
  19599. tname = btf_name_by_offset(btf, t->name_off);
  19600. if (!tname) {
  19601. bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
  19602. return -EINVAL;
  19603. }
  19604. if (tgt_prog) {
  19605. struct bpf_prog_aux *aux = tgt_prog->aux;
  19606. bool tgt_changes_pkt_data;
  19607. if (bpf_prog_is_dev_bound(prog->aux) &&
  19608. !bpf_prog_dev_bound_match(prog, tgt_prog)) {
  19609. bpf_log(log, "Target program bound device mismatch");
  19610. return -EINVAL;
  19611. }
  19612. for (i = 0; i < aux->func_info_cnt; i++)
  19613. if (aux->func_info[i].type_id == btf_id) {
  19614. subprog = i;
  19615. break;
  19616. }
  19617. if (subprog == -1) {
  19618. bpf_log(log, "Subprog %s doesn't exist\n", tname);
  19619. return -EINVAL;
  19620. }
  19621. if (aux->func && aux->func[subprog]->aux->exception_cb) {
  19622. bpf_log(log,
  19623. "%s programs cannot attach to exception callback\n",
  19624. prog_extension ? "Extension" : "FENTRY/FEXIT");
  19625. return -EINVAL;
  19626. }
  19627. conservative = aux->func_info_aux[subprog].unreliable;
  19628. if (prog_extension) {
  19629. if (conservative) {
  19630. bpf_log(log,
  19631. "Cannot replace static functions\n");
  19632. return -EINVAL;
  19633. }
  19634. if (!prog->jit_requested) {
  19635. bpf_log(log,
  19636. "Extension programs should be JITed\n");
  19637. return -EINVAL;
  19638. }
  19639. tgt_changes_pkt_data = aux->func
  19640. ? aux->func[subprog]->aux->changes_pkt_data
  19641. : aux->changes_pkt_data;
  19642. if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
  19643. bpf_log(log,
  19644. "Extension program changes packet data, while original does not\n");
  19645. return -EINVAL;
  19646. }
  19647. }
  19648. if (!tgt_prog->jited) {
  19649. bpf_log(log, "Can attach to only JITed progs\n");
  19650. return -EINVAL;
  19651. }
  19652. if (prog_tracing) {
  19653. if (aux->attach_tracing_prog) {
  19654. /*
  19655. * Target program is an fentry/fexit which is already attached
  19656. * to another tracing program. More levels of nesting
  19657. * attachment are not allowed.
  19658. */
  19659. bpf_log(log, "Cannot nest tracing program attach more than once\n");
  19660. return -EINVAL;
  19661. }
  19662. } else if (tgt_prog->type == prog->type) {
  19663. /*
  19664. * To avoid potential call chain cycles, prevent attaching of a
  19665. * program extension to another extension. It's ok to attach
  19666. * fentry/fexit to extension program.
  19667. */
  19668. bpf_log(log, "Cannot recursively attach\n");
  19669. return -EINVAL;
  19670. }
  19671. if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
  19672. prog_extension &&
  19673. (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
  19674. tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
  19675. /* Program extensions can extend all program types
  19676. * except fentry/fexit. The reason is the following.
  19677. * The fentry/fexit programs are used for performance
  19678. * analysis, stats and can be attached to any program
  19679. * type. When extension program is replacing XDP function
  19680. * it is necessary to allow performance analysis of all
  19681. * functions. Both original XDP program and its program
  19682. * extension. Hence attaching fentry/fexit to
  19683. * BPF_PROG_TYPE_EXT is allowed. If extending of
  19684. * fentry/fexit was allowed it would be possible to create
  19685. * long call chain fentry->extension->fentry->extension
  19686. * beyond reasonable stack size. Hence extending fentry
  19687. * is not allowed.
  19688. */
  19689. bpf_log(log, "Cannot extend fentry/fexit\n");
  19690. return -EINVAL;
  19691. }
  19692. } else {
  19693. if (prog_extension) {
  19694. bpf_log(log, "Cannot replace kernel functions\n");
  19695. return -EINVAL;
  19696. }
  19697. }
  19698. switch (prog->expected_attach_type) {
  19699. case BPF_TRACE_RAW_TP:
  19700. if (tgt_prog) {
  19701. bpf_log(log,
  19702. "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
  19703. return -EINVAL;
  19704. }
  19705. if (!btf_type_is_typedef(t)) {
  19706. bpf_log(log, "attach_btf_id %u is not a typedef\n",
  19707. btf_id);
  19708. return -EINVAL;
  19709. }
  19710. if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
  19711. bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
  19712. btf_id, tname);
  19713. return -EINVAL;
  19714. }
  19715. tname += sizeof(prefix) - 1;
  19716. /* The func_proto of "btf_trace_##tname" is generated from typedef without argument
  19717. * names. Thus using bpf_raw_event_map to get argument names.
  19718. */
  19719. btp = bpf_get_raw_tracepoint(tname);
  19720. if (!btp)
  19721. return -EINVAL;
  19722. fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
  19723. trace_symbol);
  19724. bpf_put_raw_tracepoint(btp);
  19725. if (fname)
  19726. ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
  19727. if (!fname || ret < 0) {
  19728. bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
  19729. prefix, tname);
  19730. t = btf_type_by_id(btf, t->type);
  19731. if (!btf_type_is_ptr(t))
  19732. /* should never happen in valid vmlinux build */
  19733. return -EINVAL;
  19734. } else {
  19735. t = btf_type_by_id(btf, ret);
  19736. if (!btf_type_is_func(t))
  19737. /* should never happen in valid vmlinux build */
  19738. return -EINVAL;
  19739. }
  19740. t = btf_type_by_id(btf, t->type);
  19741. if (!btf_type_is_func_proto(t))
  19742. /* should never happen in valid vmlinux build */
  19743. return -EINVAL;
  19744. break;
  19745. case BPF_TRACE_ITER:
  19746. if (!btf_type_is_func(t)) {
  19747. bpf_log(log, "attach_btf_id %u is not a function\n",
  19748. btf_id);
  19749. return -EINVAL;
  19750. }
  19751. t = btf_type_by_id(btf, t->type);
  19752. if (!btf_type_is_func_proto(t))
  19753. return -EINVAL;
  19754. ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
  19755. if (ret)
  19756. return ret;
  19757. break;
  19758. default:
  19759. if (!prog_extension)
  19760. return -EINVAL;
  19761. fallthrough;
  19762. case BPF_MODIFY_RETURN:
  19763. case BPF_LSM_MAC:
  19764. case BPF_LSM_CGROUP:
  19765. case BPF_TRACE_FENTRY:
  19766. case BPF_TRACE_FEXIT:
  19767. if (!btf_type_is_func(t)) {
  19768. bpf_log(log, "attach_btf_id %u is not a function\n",
  19769. btf_id);
  19770. return -EINVAL;
  19771. }
  19772. if (prog_extension &&
  19773. btf_check_type_match(log, prog, btf, t))
  19774. return -EINVAL;
  19775. t = btf_type_by_id(btf, t->type);
  19776. if (!btf_type_is_func_proto(t))
  19777. return -EINVAL;
  19778. if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
  19779. (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
  19780. prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
  19781. return -EINVAL;
  19782. if (tgt_prog && conservative)
  19783. t = NULL;
  19784. ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
  19785. if (ret < 0)
  19786. return ret;
  19787. if (tgt_prog) {
  19788. if (subprog == 0)
  19789. addr = (long) tgt_prog->bpf_func;
  19790. else
  19791. addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
  19792. } else {
  19793. if (btf_is_module(btf)) {
  19794. mod = btf_try_get_module(btf);
  19795. if (mod)
  19796. addr = find_kallsyms_symbol_value(mod, tname);
  19797. else
  19798. addr = 0;
  19799. } else {
  19800. addr = kallsyms_lookup_name(tname);
  19801. }
  19802. if (!addr) {
  19803. module_put(mod);
  19804. bpf_log(log,
  19805. "The address of function %s cannot be found\n",
  19806. tname);
  19807. return -ENOENT;
  19808. }
  19809. }
  19810. if (prog->sleepable) {
  19811. ret = -EINVAL;
  19812. switch (prog->type) {
  19813. case BPF_PROG_TYPE_TRACING:
  19814. /* fentry/fexit/fmod_ret progs can be sleepable if they are
  19815. * attached to ALLOW_ERROR_INJECTION and are not in denylist.
  19816. */
  19817. if (!check_non_sleepable_error_inject(btf_id) &&
  19818. within_error_injection_list(addr))
  19819. ret = 0;
  19820. /* fentry/fexit/fmod_ret progs can also be sleepable if they are
  19821. * in the fmodret id set with the KF_SLEEPABLE flag.
  19822. */
  19823. else {
  19824. u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
  19825. prog);
  19826. if (flags && (*flags & KF_SLEEPABLE))
  19827. ret = 0;
  19828. }
  19829. break;
  19830. case BPF_PROG_TYPE_LSM:
  19831. /* LSM progs check that they are attached to bpf_lsm_*() funcs.
  19832. * Only some of them are sleepable.
  19833. */
  19834. if (bpf_lsm_is_sleepable_hook(btf_id))
  19835. ret = 0;
  19836. break;
  19837. default:
  19838. break;
  19839. }
  19840. if (ret) {
  19841. module_put(mod);
  19842. bpf_log(log, "%s is not sleepable\n", tname);
  19843. return ret;
  19844. }
  19845. } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
  19846. if (tgt_prog) {
  19847. module_put(mod);
  19848. bpf_log(log, "can't modify return codes of BPF programs\n");
  19849. return -EINVAL;
  19850. }
  19851. ret = -EINVAL;
  19852. if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
  19853. !check_attach_modify_return(addr, tname))
  19854. ret = 0;
  19855. if (ret) {
  19856. module_put(mod);
  19857. bpf_log(log, "%s() is not modifiable\n", tname);
  19858. return ret;
  19859. }
  19860. }
  19861. break;
  19862. }
  19863. tgt_info->tgt_addr = addr;
  19864. tgt_info->tgt_name = tname;
  19865. tgt_info->tgt_type = t;
  19866. tgt_info->tgt_mod = mod;
  19867. return 0;
  19868. }
  19869. BTF_SET_START(btf_id_deny)
  19870. BTF_ID_UNUSED
  19871. #ifdef CONFIG_SMP
  19872. BTF_ID(func, migrate_disable)
  19873. BTF_ID(func, migrate_enable)
  19874. #endif
  19875. #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
  19876. BTF_ID(func, rcu_read_unlock_strict)
  19877. #endif
  19878. #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
  19879. BTF_ID(func, preempt_count_add)
  19880. BTF_ID(func, preempt_count_sub)
  19881. #endif
  19882. #ifdef CONFIG_PREEMPT_RCU
  19883. BTF_ID(func, __rcu_read_lock)
  19884. BTF_ID(func, __rcu_read_unlock)
  19885. #endif
  19886. BTF_SET_END(btf_id_deny)
  19887. /* fexit and fmod_ret can't be used to attach to __noreturn functions.
  19888. * Currently, we must manually list all __noreturn functions here. Once a more
  19889. * robust solution is implemented, this workaround can be removed.
  19890. */
  19891. BTF_SET_START(noreturn_deny)
  19892. #ifdef CONFIG_IA32_EMULATION
  19893. BTF_ID(func, __ia32_sys_exit)
  19894. BTF_ID(func, __ia32_sys_exit_group)
  19895. #endif
  19896. #ifdef CONFIG_KUNIT
  19897. BTF_ID(func, __kunit_abort)
  19898. BTF_ID(func, kunit_try_catch_throw)
  19899. #endif
  19900. #ifdef CONFIG_MODULES
  19901. BTF_ID(func, __module_put_and_kthread_exit)
  19902. #endif
  19903. #ifdef CONFIG_X86_64
  19904. BTF_ID(func, __x64_sys_exit)
  19905. BTF_ID(func, __x64_sys_exit_group)
  19906. #endif
  19907. BTF_ID(func, do_exit)
  19908. BTF_ID(func, do_group_exit)
  19909. BTF_ID(func, kthread_complete_and_exit)
  19910. BTF_ID(func, kthread_exit)
  19911. BTF_ID(func, make_task_dead)
  19912. BTF_SET_END(noreturn_deny)
  19913. static bool can_be_sleepable(struct bpf_prog *prog)
  19914. {
  19915. if (prog->type == BPF_PROG_TYPE_TRACING) {
  19916. switch (prog->expected_attach_type) {
  19917. case BPF_TRACE_FENTRY:
  19918. case BPF_TRACE_FEXIT:
  19919. case BPF_MODIFY_RETURN:
  19920. case BPF_TRACE_ITER:
  19921. return true;
  19922. default:
  19923. return false;
  19924. }
  19925. }
  19926. return prog->type == BPF_PROG_TYPE_LSM ||
  19927. prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
  19928. prog->type == BPF_PROG_TYPE_STRUCT_OPS;
  19929. }
  19930. static int check_attach_btf_id(struct bpf_verifier_env *env)
  19931. {
  19932. struct bpf_prog *prog = env->prog;
  19933. struct bpf_prog *tgt_prog = prog->aux->dst_prog;
  19934. struct bpf_attach_target_info tgt_info = {};
  19935. u32 btf_id = prog->aux->attach_btf_id;
  19936. struct bpf_trampoline *tr;
  19937. int ret;
  19938. u64 key;
  19939. if (prog->type == BPF_PROG_TYPE_SYSCALL) {
  19940. if (prog->sleepable)
  19941. /* attach_btf_id checked to be zero already */
  19942. return 0;
  19943. verbose(env, "Syscall programs can only be sleepable\n");
  19944. return -EINVAL;
  19945. }
  19946. if (prog->sleepable && !can_be_sleepable(prog)) {
  19947. verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
  19948. return -EINVAL;
  19949. }
  19950. if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
  19951. return check_struct_ops_btf_id(env);
  19952. if (prog->type != BPF_PROG_TYPE_TRACING &&
  19953. prog->type != BPF_PROG_TYPE_LSM &&
  19954. prog->type != BPF_PROG_TYPE_EXT)
  19955. return 0;
  19956. ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
  19957. if (ret)
  19958. return ret;
  19959. if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
  19960. /* to make freplace equivalent to their targets, they need to
  19961. * inherit env->ops and expected_attach_type for the rest of the
  19962. * verification
  19963. */
  19964. env->ops = bpf_verifier_ops[tgt_prog->type];
  19965. prog->expected_attach_type = tgt_prog->expected_attach_type;
  19966. }
  19967. /* store info about the attachment target that will be used later */
  19968. prog->aux->attach_func_proto = tgt_info.tgt_type;
  19969. prog->aux->attach_func_name = tgt_info.tgt_name;
  19970. prog->aux->mod = tgt_info.tgt_mod;
  19971. if (tgt_prog) {
  19972. prog->aux->saved_dst_prog_type = tgt_prog->type;
  19973. prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
  19974. }
  19975. if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
  19976. prog->aux->attach_btf_trace = true;
  19977. return 0;
  19978. } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
  19979. if (!bpf_iter_prog_supported(prog))
  19980. return -EINVAL;
  19981. return 0;
  19982. }
  19983. if (prog->type == BPF_PROG_TYPE_LSM) {
  19984. ret = bpf_lsm_verify_prog(&env->log, prog);
  19985. if (ret < 0)
  19986. return ret;
  19987. } else if (prog->type == BPF_PROG_TYPE_TRACING &&
  19988. btf_id_set_contains(&btf_id_deny, btf_id)) {
  19989. return -EINVAL;
  19990. } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
  19991. prog->expected_attach_type == BPF_MODIFY_RETURN) &&
  19992. btf_id_set_contains(&noreturn_deny, btf_id)) {
  19993. verbose(env, "Attaching fexit/fmod_ret to __noreturn functions is rejected.\n");
  19994. return -EINVAL;
  19995. }
  19996. key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
  19997. tr = bpf_trampoline_get(key, &tgt_info);
  19998. if (!tr)
  19999. return -ENOMEM;
  20000. if (tgt_prog && tgt_prog->aux->tail_call_reachable)
  20001. tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
  20002. prog->aux->dst_trampoline = tr;
  20003. return 0;
  20004. }
  20005. struct btf *bpf_get_btf_vmlinux(void)
  20006. {
  20007. if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
  20008. mutex_lock(&bpf_verifier_lock);
  20009. if (!btf_vmlinux)
  20010. btf_vmlinux = btf_parse_vmlinux();
  20011. mutex_unlock(&bpf_verifier_lock);
  20012. }
  20013. return btf_vmlinux;
  20014. }
  20015. int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
  20016. {
  20017. u64 start_time = ktime_get_ns();
  20018. struct bpf_verifier_env *env;
  20019. int i, len, ret = -EINVAL, err;
  20020. u32 log_true_size;
  20021. bool is_priv;
  20022. /* no program is valid */
  20023. if (ARRAY_SIZE(bpf_verifier_ops) == 0)
  20024. return -EINVAL;
  20025. /* 'struct bpf_verifier_env' can be global, but since it's not small,
  20026. * allocate/free it every time bpf_check() is called
  20027. */
  20028. env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
  20029. if (!env)
  20030. return -ENOMEM;
  20031. env->bt.env = env;
  20032. len = (*prog)->len;
  20033. env->insn_aux_data =
  20034. vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
  20035. ret = -ENOMEM;
  20036. if (!env->insn_aux_data)
  20037. goto err_free_env;
  20038. for (i = 0; i < len; i++)
  20039. env->insn_aux_data[i].orig_idx = i;
  20040. env->prog = *prog;
  20041. env->ops = bpf_verifier_ops[env->prog->type];
  20042. env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
  20043. env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
  20044. env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
  20045. env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
  20046. env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
  20047. env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
  20048. bpf_get_btf_vmlinux();
  20049. /* grab the mutex to protect few globals used by verifier */
  20050. if (!is_priv)
  20051. mutex_lock(&bpf_verifier_lock);
  20052. /* user could have requested verbose verifier output
  20053. * and supplied buffer to store the verification trace
  20054. */
  20055. ret = bpf_vlog_init(&env->log, attr->log_level,
  20056. (char __user *) (unsigned long) attr->log_buf,
  20057. attr->log_size);
  20058. if (ret)
  20059. goto err_unlock;
  20060. mark_verifier_state_clean(env);
  20061. if (IS_ERR(btf_vmlinux)) {
  20062. /* Either gcc or pahole or kernel are broken. */
  20063. verbose(env, "in-kernel BTF is malformed\n");
  20064. ret = PTR_ERR(btf_vmlinux);
  20065. goto skip_full_check;
  20066. }
  20067. env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
  20068. if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
  20069. env->strict_alignment = true;
  20070. if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
  20071. env->strict_alignment = false;
  20072. if (is_priv)
  20073. env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
  20074. env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
  20075. env->explored_states = kvcalloc(state_htab_size(env),
  20076. sizeof(struct bpf_verifier_state_list *),
  20077. GFP_USER);
  20078. ret = -ENOMEM;
  20079. if (!env->explored_states)
  20080. goto skip_full_check;
  20081. ret = check_btf_info_early(env, attr, uattr);
  20082. if (ret < 0)
  20083. goto skip_full_check;
  20084. ret = add_subprog_and_kfunc(env);
  20085. if (ret < 0)
  20086. goto skip_full_check;
  20087. ret = check_subprogs(env);
  20088. if (ret < 0)
  20089. goto skip_full_check;
  20090. ret = check_btf_info(env, attr, uattr);
  20091. if (ret < 0)
  20092. goto skip_full_check;
  20093. ret = resolve_pseudo_ldimm64(env);
  20094. if (ret < 0)
  20095. goto skip_full_check;
  20096. if (bpf_prog_is_offloaded(env->prog->aux)) {
  20097. ret = bpf_prog_offload_verifier_prep(env->prog);
  20098. if (ret)
  20099. goto skip_full_check;
  20100. }
  20101. ret = check_cfg(env);
  20102. if (ret < 0)
  20103. goto skip_full_check;
  20104. ret = check_attach_btf_id(env);
  20105. if (ret)
  20106. goto skip_full_check;
  20107. ret = mark_fastcall_patterns(env);
  20108. if (ret < 0)
  20109. goto skip_full_check;
  20110. ret = do_check_main(env);
  20111. ret = ret ?: do_check_subprogs(env);
  20112. if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
  20113. ret = bpf_prog_offload_finalize(env);
  20114. skip_full_check:
  20115. kvfree(env->explored_states);
  20116. /* might decrease stack depth, keep it before passes that
  20117. * allocate additional slots.
  20118. */
  20119. if (ret == 0)
  20120. ret = remove_fastcall_spills_fills(env);
  20121. if (ret == 0)
  20122. ret = check_max_stack_depth(env);
  20123. /* instruction rewrites happen after this point */
  20124. if (ret == 0)
  20125. ret = optimize_bpf_loop(env);
  20126. if (is_priv) {
  20127. if (ret == 0)
  20128. opt_hard_wire_dead_code_branches(env);
  20129. if (ret == 0)
  20130. ret = opt_remove_dead_code(env);
  20131. if (ret == 0)
  20132. ret = opt_remove_nops(env);
  20133. } else {
  20134. if (ret == 0)
  20135. sanitize_dead_code(env);
  20136. }
  20137. if (ret == 0)
  20138. /* program is valid, convert *(u32*)(ctx + off) accesses */
  20139. ret = convert_ctx_accesses(env);
  20140. if (ret == 0)
  20141. ret = do_misc_fixups(env);
  20142. /* do 32-bit optimization after insn patching has done so those patched
  20143. * insns could be handled correctly.
  20144. */
  20145. if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
  20146. ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
  20147. env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
  20148. : false;
  20149. }
  20150. if (ret == 0)
  20151. ret = fixup_call_args(env);
  20152. env->verification_time = ktime_get_ns() - start_time;
  20153. print_verification_stats(env);
  20154. env->prog->aux->verified_insns = env->insn_processed;
  20155. /* preserve original error even if log finalization is successful */
  20156. err = bpf_vlog_finalize(&env->log, &log_true_size);
  20157. if (err)
  20158. ret = err;
  20159. if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
  20160. copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
  20161. &log_true_size, sizeof(log_true_size))) {
  20162. ret = -EFAULT;
  20163. goto err_release_maps;
  20164. }
  20165. if (ret)
  20166. goto err_release_maps;
  20167. if (env->used_map_cnt) {
  20168. /* if program passed verifier, update used_maps in bpf_prog_info */
  20169. env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
  20170. sizeof(env->used_maps[0]),
  20171. GFP_KERNEL);
  20172. if (!env->prog->aux->used_maps) {
  20173. ret = -ENOMEM;
  20174. goto err_release_maps;
  20175. }
  20176. memcpy(env->prog->aux->used_maps, env->used_maps,
  20177. sizeof(env->used_maps[0]) * env->used_map_cnt);
  20178. env->prog->aux->used_map_cnt = env->used_map_cnt;
  20179. }
  20180. if (env->used_btf_cnt) {
  20181. /* if program passed verifier, update used_btfs in bpf_prog_aux */
  20182. env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
  20183. sizeof(env->used_btfs[0]),
  20184. GFP_KERNEL);
  20185. if (!env->prog->aux->used_btfs) {
  20186. ret = -ENOMEM;
  20187. goto err_release_maps;
  20188. }
  20189. memcpy(env->prog->aux->used_btfs, env->used_btfs,
  20190. sizeof(env->used_btfs[0]) * env->used_btf_cnt);
  20191. env->prog->aux->used_btf_cnt = env->used_btf_cnt;
  20192. }
  20193. if (env->used_map_cnt || env->used_btf_cnt) {
  20194. /* program is valid. Convert pseudo bpf_ld_imm64 into generic
  20195. * bpf_ld_imm64 instructions
  20196. */
  20197. convert_pseudo_ld_imm64(env);
  20198. }
  20199. adjust_btf_func(env);
  20200. err_release_maps:
  20201. if (!env->prog->aux->used_maps)
  20202. /* if we didn't copy map pointers into bpf_prog_info, release
  20203. * them now. Otherwise free_used_maps() will release them.
  20204. */
  20205. release_maps(env);
  20206. if (!env->prog->aux->used_btfs)
  20207. release_btfs(env);
  20208. /* extension progs temporarily inherit the attach_type of their targets
  20209. for verification purposes, so set it back to zero before returning
  20210. */
  20211. if (env->prog->type == BPF_PROG_TYPE_EXT)
  20212. env->prog->expected_attach_type = 0;
  20213. *prog = env->prog;
  20214. module_put(env->attach_btf_mod);
  20215. err_unlock:
  20216. if (!is_priv)
  20217. mutex_unlock(&bpf_verifier_lock);
  20218. vfree(env->insn_aux_data);
  20219. kvfree(env->insn_hist);
  20220. err_free_env:
  20221. kvfree(env);
  20222. return ret;
  20223. }