relo_core.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. /* Copyright (c) 2019 Facebook */
  3. #ifdef __KERNEL__
  4. #include <linux/bpf.h>
  5. #include <linux/btf.h>
  6. #include <linux/string.h>
  7. #include <linux/bpf_verifier.h>
  8. #include "relo_core.h"
  9. static const char *btf_kind_str(const struct btf_type *t)
  10. {
  11. return btf_type_str(t);
  12. }
  13. static bool is_ldimm64_insn(struct bpf_insn *insn)
  14. {
  15. return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
  16. }
  17. static const struct btf_type *
  18. skip_mods_and_typedefs(const struct btf *btf, u32 id, u32 *res_id)
  19. {
  20. return btf_type_skip_modifiers(btf, id, res_id);
  21. }
  22. static const char *btf__name_by_offset(const struct btf *btf, u32 offset)
  23. {
  24. return btf_name_by_offset(btf, offset);
  25. }
  26. static s64 btf__resolve_size(const struct btf *btf, u32 type_id)
  27. {
  28. const struct btf_type *t;
  29. int size;
  30. t = btf_type_by_id(btf, type_id);
  31. t = btf_resolve_size(btf, t, &size);
  32. if (IS_ERR(t))
  33. return PTR_ERR(t);
  34. return size;
  35. }
  36. enum libbpf_print_level {
  37. LIBBPF_WARN,
  38. LIBBPF_INFO,
  39. LIBBPF_DEBUG,
  40. };
  41. #undef pr_warn
  42. #undef pr_info
  43. #undef pr_debug
  44. #define pr_warn(fmt, log, ...) bpf_log((void *)log, fmt, "", ##__VA_ARGS__)
  45. #define pr_info(fmt, log, ...) bpf_log((void *)log, fmt, "", ##__VA_ARGS__)
  46. #define pr_debug(fmt, log, ...) bpf_log((void *)log, fmt, "", ##__VA_ARGS__)
  47. #define libbpf_print(level, fmt, ...) bpf_log((void *)prog_name, fmt, ##__VA_ARGS__)
  48. #else
  49. #include <stdio.h>
  50. #include <string.h>
  51. #include <errno.h>
  52. #include <ctype.h>
  53. #include <linux/err.h>
  54. #include "libbpf.h"
  55. #include "bpf.h"
  56. #include "btf.h"
  57. #include "libbpf_internal.h"
  58. #endif
  59. static bool is_flex_arr(const struct btf *btf,
  60. const struct bpf_core_accessor *acc,
  61. const struct btf_array *arr)
  62. {
  63. const struct btf_type *t;
  64. /* not a flexible array, if not inside a struct or has non-zero size */
  65. if (!acc->name || arr->nelems > 0)
  66. return false;
  67. /* has to be the last member of enclosing struct */
  68. t = btf_type_by_id(btf, acc->type_id);
  69. return acc->idx == btf_vlen(t) - 1;
  70. }
  71. static const char *core_relo_kind_str(enum bpf_core_relo_kind kind)
  72. {
  73. switch (kind) {
  74. case BPF_CORE_FIELD_BYTE_OFFSET: return "byte_off";
  75. case BPF_CORE_FIELD_BYTE_SIZE: return "byte_sz";
  76. case BPF_CORE_FIELD_EXISTS: return "field_exists";
  77. case BPF_CORE_FIELD_SIGNED: return "signed";
  78. case BPF_CORE_FIELD_LSHIFT_U64: return "lshift_u64";
  79. case BPF_CORE_FIELD_RSHIFT_U64: return "rshift_u64";
  80. case BPF_CORE_TYPE_ID_LOCAL: return "local_type_id";
  81. case BPF_CORE_TYPE_ID_TARGET: return "target_type_id";
  82. case BPF_CORE_TYPE_EXISTS: return "type_exists";
  83. case BPF_CORE_TYPE_MATCHES: return "type_matches";
  84. case BPF_CORE_TYPE_SIZE: return "type_size";
  85. case BPF_CORE_ENUMVAL_EXISTS: return "enumval_exists";
  86. case BPF_CORE_ENUMVAL_VALUE: return "enumval_value";
  87. default: return "unknown";
  88. }
  89. }
  90. static bool core_relo_is_field_based(enum bpf_core_relo_kind kind)
  91. {
  92. switch (kind) {
  93. case BPF_CORE_FIELD_BYTE_OFFSET:
  94. case BPF_CORE_FIELD_BYTE_SIZE:
  95. case BPF_CORE_FIELD_EXISTS:
  96. case BPF_CORE_FIELD_SIGNED:
  97. case BPF_CORE_FIELD_LSHIFT_U64:
  98. case BPF_CORE_FIELD_RSHIFT_U64:
  99. return true;
  100. default:
  101. return false;
  102. }
  103. }
  104. static bool core_relo_is_type_based(enum bpf_core_relo_kind kind)
  105. {
  106. switch (kind) {
  107. case BPF_CORE_TYPE_ID_LOCAL:
  108. case BPF_CORE_TYPE_ID_TARGET:
  109. case BPF_CORE_TYPE_EXISTS:
  110. case BPF_CORE_TYPE_MATCHES:
  111. case BPF_CORE_TYPE_SIZE:
  112. return true;
  113. default:
  114. return false;
  115. }
  116. }
  117. static bool core_relo_is_enumval_based(enum bpf_core_relo_kind kind)
  118. {
  119. switch (kind) {
  120. case BPF_CORE_ENUMVAL_EXISTS:
  121. case BPF_CORE_ENUMVAL_VALUE:
  122. return true;
  123. default:
  124. return false;
  125. }
  126. }
  127. int __bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
  128. const struct btf *targ_btf, __u32 targ_id, int level)
  129. {
  130. const struct btf_type *local_type, *targ_type;
  131. int depth = 32; /* max recursion depth */
  132. /* caller made sure that names match (ignoring flavor suffix) */
  133. local_type = btf_type_by_id(local_btf, local_id);
  134. targ_type = btf_type_by_id(targ_btf, targ_id);
  135. if (!btf_kind_core_compat(local_type, targ_type))
  136. return 0;
  137. recur:
  138. depth--;
  139. if (depth < 0)
  140. return -EINVAL;
  141. local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
  142. targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
  143. if (!local_type || !targ_type)
  144. return -EINVAL;
  145. if (!btf_kind_core_compat(local_type, targ_type))
  146. return 0;
  147. switch (btf_kind(local_type)) {
  148. case BTF_KIND_UNKN:
  149. case BTF_KIND_STRUCT:
  150. case BTF_KIND_UNION:
  151. case BTF_KIND_ENUM:
  152. case BTF_KIND_FWD:
  153. case BTF_KIND_ENUM64:
  154. return 1;
  155. case BTF_KIND_INT:
  156. /* just reject deprecated bitfield-like integers; all other
  157. * integers are by default compatible between each other
  158. */
  159. return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
  160. case BTF_KIND_PTR:
  161. local_id = local_type->type;
  162. targ_id = targ_type->type;
  163. goto recur;
  164. case BTF_KIND_ARRAY:
  165. local_id = btf_array(local_type)->type;
  166. targ_id = btf_array(targ_type)->type;
  167. goto recur;
  168. case BTF_KIND_FUNC_PROTO: {
  169. struct btf_param *local_p = btf_params(local_type);
  170. struct btf_param *targ_p = btf_params(targ_type);
  171. __u16 local_vlen = btf_vlen(local_type);
  172. __u16 targ_vlen = btf_vlen(targ_type);
  173. int i, err;
  174. if (local_vlen != targ_vlen)
  175. return 0;
  176. for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
  177. if (level <= 0)
  178. return -EINVAL;
  179. skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
  180. skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
  181. err = __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
  182. level - 1);
  183. if (err <= 0)
  184. return err;
  185. }
  186. /* tail recurse for return type check */
  187. skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
  188. skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
  189. goto recur;
  190. }
  191. default:
  192. pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
  193. btf_kind_str(local_type), local_id, targ_id);
  194. return 0;
  195. }
  196. }
  197. /*
  198. * Turn bpf_core_relo into a low- and high-level spec representation,
  199. * validating correctness along the way, as well as calculating resulting
  200. * field bit offset, specified by accessor string. Low-level spec captures
  201. * every single level of nestedness, including traversing anonymous
  202. * struct/union members. High-level one only captures semantically meaningful
  203. * "turning points": named fields and array indicies.
  204. * E.g., for this case:
  205. *
  206. * struct sample {
  207. * int __unimportant;
  208. * struct {
  209. * int __1;
  210. * int __2;
  211. * int a[7];
  212. * };
  213. * };
  214. *
  215. * struct sample *s = ...;
  216. *
  217. * int x = &s->a[3]; // access string = '0:1:2:3'
  218. *
  219. * Low-level spec has 1:1 mapping with each element of access string (it's
  220. * just a parsed access string representation): [0, 1, 2, 3].
  221. *
  222. * High-level spec will capture only 3 points:
  223. * - initial zero-index access by pointer (&s->... is the same as &s[0]...);
  224. * - field 'a' access (corresponds to '2' in low-level spec);
  225. * - array element #3 access (corresponds to '3' in low-level spec).
  226. *
  227. * Type-based relocations (TYPE_EXISTS/TYPE_MATCHES/TYPE_SIZE,
  228. * TYPE_ID_LOCAL/TYPE_ID_TARGET) don't capture any field information. Their
  229. * spec and raw_spec are kept empty.
  230. *
  231. * Enum value-based relocations (ENUMVAL_EXISTS/ENUMVAL_VALUE) use access
  232. * string to specify enumerator's value index that need to be relocated.
  233. */
  234. int bpf_core_parse_spec(const char *prog_name, const struct btf *btf,
  235. const struct bpf_core_relo *relo,
  236. struct bpf_core_spec *spec)
  237. {
  238. int access_idx, parsed_len, i;
  239. struct bpf_core_accessor *acc;
  240. const struct btf_type *t;
  241. const char *name, *spec_str;
  242. __u32 id, name_off;
  243. __s64 sz;
  244. spec_str = btf__name_by_offset(btf, relo->access_str_off);
  245. if (str_is_empty(spec_str) || *spec_str == ':')
  246. return -EINVAL;
  247. memset(spec, 0, sizeof(*spec));
  248. spec->btf = btf;
  249. spec->root_type_id = relo->type_id;
  250. spec->relo_kind = relo->kind;
  251. /* type-based relocations don't have a field access string */
  252. if (core_relo_is_type_based(relo->kind)) {
  253. if (strcmp(spec_str, "0"))
  254. return -EINVAL;
  255. return 0;
  256. }
  257. /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
  258. while (*spec_str) {
  259. if (*spec_str == ':')
  260. ++spec_str;
  261. if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
  262. return -EINVAL;
  263. if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
  264. return -E2BIG;
  265. spec_str += parsed_len;
  266. spec->raw_spec[spec->raw_len++] = access_idx;
  267. }
  268. if (spec->raw_len == 0)
  269. return -EINVAL;
  270. t = skip_mods_and_typedefs(btf, relo->type_id, &id);
  271. if (!t)
  272. return -EINVAL;
  273. access_idx = spec->raw_spec[0];
  274. acc = &spec->spec[0];
  275. acc->type_id = id;
  276. acc->idx = access_idx;
  277. spec->len++;
  278. if (core_relo_is_enumval_based(relo->kind)) {
  279. if (!btf_is_any_enum(t) || spec->raw_len > 1 || access_idx >= btf_vlen(t))
  280. return -EINVAL;
  281. /* record enumerator name in a first accessor */
  282. name_off = btf_is_enum(t) ? btf_enum(t)[access_idx].name_off
  283. : btf_enum64(t)[access_idx].name_off;
  284. acc->name = btf__name_by_offset(btf, name_off);
  285. return 0;
  286. }
  287. if (!core_relo_is_field_based(relo->kind))
  288. return -EINVAL;
  289. sz = btf__resolve_size(btf, id);
  290. if (sz < 0)
  291. return sz;
  292. spec->bit_offset = access_idx * sz * 8;
  293. for (i = 1; i < spec->raw_len; i++) {
  294. t = skip_mods_and_typedefs(btf, id, &id);
  295. if (!t)
  296. return -EINVAL;
  297. access_idx = spec->raw_spec[i];
  298. acc = &spec->spec[spec->len];
  299. if (btf_is_composite(t)) {
  300. const struct btf_member *m;
  301. __u32 bit_offset;
  302. if (access_idx >= btf_vlen(t))
  303. return -EINVAL;
  304. bit_offset = btf_member_bit_offset(t, access_idx);
  305. spec->bit_offset += bit_offset;
  306. m = btf_members(t) + access_idx;
  307. if (m->name_off) {
  308. name = btf__name_by_offset(btf, m->name_off);
  309. if (str_is_empty(name))
  310. return -EINVAL;
  311. acc->type_id = id;
  312. acc->idx = access_idx;
  313. acc->name = name;
  314. spec->len++;
  315. }
  316. id = m->type;
  317. } else if (btf_is_array(t)) {
  318. const struct btf_array *a = btf_array(t);
  319. bool flex;
  320. t = skip_mods_and_typedefs(btf, a->type, &id);
  321. if (!t)
  322. return -EINVAL;
  323. flex = is_flex_arr(btf, acc - 1, a);
  324. if (!flex && access_idx >= a->nelems)
  325. return -EINVAL;
  326. spec->spec[spec->len].type_id = id;
  327. spec->spec[spec->len].idx = access_idx;
  328. spec->len++;
  329. sz = btf__resolve_size(btf, id);
  330. if (sz < 0)
  331. return sz;
  332. spec->bit_offset += access_idx * sz * 8;
  333. } else {
  334. pr_warn("prog '%s': relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %s\n",
  335. prog_name, relo->type_id, spec_str, i, id, btf_kind_str(t));
  336. return -EINVAL;
  337. }
  338. }
  339. return 0;
  340. }
  341. /* Check two types for compatibility for the purpose of field access
  342. * relocation. const/volatile/restrict and typedefs are skipped to ensure we
  343. * are relocating semantically compatible entities:
  344. * - any two STRUCTs/UNIONs are compatible and can be mixed;
  345. * - any two FWDs are compatible, if their names match (modulo flavor suffix);
  346. * - any two PTRs are always compatible;
  347. * - for ENUMs, names should be the same (ignoring flavor suffix) or at
  348. * least one of enums should be anonymous;
  349. * - for ENUMs, check sizes, names are ignored;
  350. * - for INT, size and signedness are ignored;
  351. * - any two FLOATs are always compatible;
  352. * - for ARRAY, dimensionality is ignored, element types are checked for
  353. * compatibility recursively;
  354. * - everything else shouldn't be ever a target of relocation.
  355. * These rules are not set in stone and probably will be adjusted as we get
  356. * more experience with using BPF CO-RE relocations.
  357. */
  358. static int bpf_core_fields_are_compat(const struct btf *local_btf,
  359. __u32 local_id,
  360. const struct btf *targ_btf,
  361. __u32 targ_id)
  362. {
  363. const struct btf_type *local_type, *targ_type;
  364. recur:
  365. local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
  366. targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
  367. if (!local_type || !targ_type)
  368. return -EINVAL;
  369. if (btf_is_composite(local_type) && btf_is_composite(targ_type))
  370. return 1;
  371. if (!btf_kind_core_compat(local_type, targ_type))
  372. return 0;
  373. switch (btf_kind(local_type)) {
  374. case BTF_KIND_PTR:
  375. case BTF_KIND_FLOAT:
  376. return 1;
  377. case BTF_KIND_FWD:
  378. case BTF_KIND_ENUM64:
  379. case BTF_KIND_ENUM: {
  380. const char *local_name, *targ_name;
  381. size_t local_len, targ_len;
  382. local_name = btf__name_by_offset(local_btf,
  383. local_type->name_off);
  384. targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
  385. local_len = bpf_core_essential_name_len(local_name);
  386. targ_len = bpf_core_essential_name_len(targ_name);
  387. /* one of them is anonymous or both w/ same flavor-less names */
  388. return local_len == 0 || targ_len == 0 ||
  389. (local_len == targ_len &&
  390. strncmp(local_name, targ_name, local_len) == 0);
  391. }
  392. case BTF_KIND_INT:
  393. /* just reject deprecated bitfield-like integers; all other
  394. * integers are by default compatible between each other
  395. */
  396. return btf_int_offset(local_type) == 0 &&
  397. btf_int_offset(targ_type) == 0;
  398. case BTF_KIND_ARRAY:
  399. local_id = btf_array(local_type)->type;
  400. targ_id = btf_array(targ_type)->type;
  401. goto recur;
  402. default:
  403. return 0;
  404. }
  405. }
  406. /*
  407. * Given single high-level named field accessor in local type, find
  408. * corresponding high-level accessor for a target type. Along the way,
  409. * maintain low-level spec for target as well. Also keep updating target
  410. * bit offset.
  411. *
  412. * Searching is performed through recursive exhaustive enumeration of all
  413. * fields of a struct/union. If there are any anonymous (embedded)
  414. * structs/unions, they are recursively searched as well. If field with
  415. * desired name is found, check compatibility between local and target types,
  416. * before returning result.
  417. *
  418. * 1 is returned, if field is found.
  419. * 0 is returned if no compatible field is found.
  420. * <0 is returned on error.
  421. */
  422. static int bpf_core_match_member(const struct btf *local_btf,
  423. const struct bpf_core_accessor *local_acc,
  424. const struct btf *targ_btf,
  425. __u32 targ_id,
  426. struct bpf_core_spec *spec,
  427. __u32 *next_targ_id)
  428. {
  429. const struct btf_type *local_type, *targ_type;
  430. const struct btf_member *local_member, *m;
  431. const char *local_name, *targ_name;
  432. __u32 local_id;
  433. int i, n, found;
  434. targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
  435. if (!targ_type)
  436. return -EINVAL;
  437. if (!btf_is_composite(targ_type))
  438. return 0;
  439. local_id = local_acc->type_id;
  440. local_type = btf_type_by_id(local_btf, local_id);
  441. local_member = btf_members(local_type) + local_acc->idx;
  442. local_name = btf__name_by_offset(local_btf, local_member->name_off);
  443. n = btf_vlen(targ_type);
  444. m = btf_members(targ_type);
  445. for (i = 0; i < n; i++, m++) {
  446. __u32 bit_offset;
  447. bit_offset = btf_member_bit_offset(targ_type, i);
  448. /* too deep struct/union/array nesting */
  449. if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
  450. return -E2BIG;
  451. /* speculate this member will be the good one */
  452. spec->bit_offset += bit_offset;
  453. spec->raw_spec[spec->raw_len++] = i;
  454. targ_name = btf__name_by_offset(targ_btf, m->name_off);
  455. if (str_is_empty(targ_name)) {
  456. /* embedded struct/union, we need to go deeper */
  457. found = bpf_core_match_member(local_btf, local_acc,
  458. targ_btf, m->type,
  459. spec, next_targ_id);
  460. if (found) /* either found or error */
  461. return found;
  462. } else if (strcmp(local_name, targ_name) == 0) {
  463. /* matching named field */
  464. struct bpf_core_accessor *targ_acc;
  465. targ_acc = &spec->spec[spec->len++];
  466. targ_acc->type_id = targ_id;
  467. targ_acc->idx = i;
  468. targ_acc->name = targ_name;
  469. *next_targ_id = m->type;
  470. found = bpf_core_fields_are_compat(local_btf,
  471. local_member->type,
  472. targ_btf, m->type);
  473. if (!found)
  474. spec->len--; /* pop accessor */
  475. return found;
  476. }
  477. /* member turned out not to be what we looked for */
  478. spec->bit_offset -= bit_offset;
  479. spec->raw_len--;
  480. }
  481. return 0;
  482. }
  483. /*
  484. * Try to match local spec to a target type and, if successful, produce full
  485. * target spec (high-level, low-level + bit offset).
  486. */
  487. static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
  488. const struct btf *targ_btf, __u32 targ_id,
  489. struct bpf_core_spec *targ_spec)
  490. {
  491. const struct btf_type *targ_type;
  492. const struct bpf_core_accessor *local_acc;
  493. struct bpf_core_accessor *targ_acc;
  494. int i, sz, matched;
  495. __u32 name_off;
  496. memset(targ_spec, 0, sizeof(*targ_spec));
  497. targ_spec->btf = targ_btf;
  498. targ_spec->root_type_id = targ_id;
  499. targ_spec->relo_kind = local_spec->relo_kind;
  500. if (core_relo_is_type_based(local_spec->relo_kind)) {
  501. if (local_spec->relo_kind == BPF_CORE_TYPE_MATCHES)
  502. return bpf_core_types_match(local_spec->btf,
  503. local_spec->root_type_id,
  504. targ_btf, targ_id);
  505. else
  506. return bpf_core_types_are_compat(local_spec->btf,
  507. local_spec->root_type_id,
  508. targ_btf, targ_id);
  509. }
  510. local_acc = &local_spec->spec[0];
  511. targ_acc = &targ_spec->spec[0];
  512. if (core_relo_is_enumval_based(local_spec->relo_kind)) {
  513. size_t local_essent_len, targ_essent_len;
  514. const char *targ_name;
  515. /* has to resolve to an enum */
  516. targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id, &targ_id);
  517. if (!btf_is_any_enum(targ_type))
  518. return 0;
  519. local_essent_len = bpf_core_essential_name_len(local_acc->name);
  520. for (i = 0; i < btf_vlen(targ_type); i++) {
  521. if (btf_is_enum(targ_type))
  522. name_off = btf_enum(targ_type)[i].name_off;
  523. else
  524. name_off = btf_enum64(targ_type)[i].name_off;
  525. targ_name = btf__name_by_offset(targ_spec->btf, name_off);
  526. targ_essent_len = bpf_core_essential_name_len(targ_name);
  527. if (targ_essent_len != local_essent_len)
  528. continue;
  529. if (strncmp(local_acc->name, targ_name, local_essent_len) == 0) {
  530. targ_acc->type_id = targ_id;
  531. targ_acc->idx = i;
  532. targ_acc->name = targ_name;
  533. targ_spec->len++;
  534. targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
  535. targ_spec->raw_len++;
  536. return 1;
  537. }
  538. }
  539. return 0;
  540. }
  541. if (!core_relo_is_field_based(local_spec->relo_kind))
  542. return -EINVAL;
  543. for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
  544. targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
  545. &targ_id);
  546. if (!targ_type)
  547. return -EINVAL;
  548. if (local_acc->name) {
  549. matched = bpf_core_match_member(local_spec->btf,
  550. local_acc,
  551. targ_btf, targ_id,
  552. targ_spec, &targ_id);
  553. if (matched <= 0)
  554. return matched;
  555. } else {
  556. /* for i=0, targ_id is already treated as array element
  557. * type (because it's the original struct), for others
  558. * we should find array element type first
  559. */
  560. if (i > 0) {
  561. const struct btf_array *a;
  562. bool flex;
  563. if (!btf_is_array(targ_type))
  564. return 0;
  565. a = btf_array(targ_type);
  566. flex = is_flex_arr(targ_btf, targ_acc - 1, a);
  567. if (!flex && local_acc->idx >= a->nelems)
  568. return 0;
  569. if (!skip_mods_and_typedefs(targ_btf, a->type,
  570. &targ_id))
  571. return -EINVAL;
  572. }
  573. /* too deep struct/union/array nesting */
  574. if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
  575. return -E2BIG;
  576. targ_acc->type_id = targ_id;
  577. targ_acc->idx = local_acc->idx;
  578. targ_acc->name = NULL;
  579. targ_spec->len++;
  580. targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
  581. targ_spec->raw_len++;
  582. sz = btf__resolve_size(targ_btf, targ_id);
  583. if (sz < 0)
  584. return sz;
  585. targ_spec->bit_offset += local_acc->idx * sz * 8;
  586. }
  587. }
  588. return 1;
  589. }
  590. static int bpf_core_calc_field_relo(const char *prog_name,
  591. const struct bpf_core_relo *relo,
  592. const struct bpf_core_spec *spec,
  593. __u64 *val, __u32 *field_sz, __u32 *type_id,
  594. bool *validate)
  595. {
  596. const struct bpf_core_accessor *acc;
  597. const struct btf_type *t;
  598. __u32 byte_off, byte_sz, bit_off, bit_sz, field_type_id, elem_id;
  599. const struct btf_member *m;
  600. const struct btf_type *mt;
  601. bool bitfield;
  602. __s64 sz;
  603. *field_sz = 0;
  604. if (relo->kind == BPF_CORE_FIELD_EXISTS) {
  605. *val = spec ? 1 : 0;
  606. return 0;
  607. }
  608. if (!spec)
  609. return -EUCLEAN; /* request instruction poisoning */
  610. acc = &spec->spec[spec->len - 1];
  611. t = btf_type_by_id(spec->btf, acc->type_id);
  612. /* a[n] accessor needs special handling */
  613. if (!acc->name) {
  614. if (relo->kind == BPF_CORE_FIELD_BYTE_OFFSET) {
  615. *val = spec->bit_offset / 8;
  616. /* remember field size for load/store mem size;
  617. * note, for arrays we care about individual element
  618. * sizes, not the overall array size
  619. */
  620. t = skip_mods_and_typedefs(spec->btf, acc->type_id, &elem_id);
  621. while (btf_is_array(t))
  622. t = skip_mods_and_typedefs(spec->btf, btf_array(t)->type, &elem_id);
  623. sz = btf__resolve_size(spec->btf, elem_id);
  624. if (sz < 0)
  625. return -EINVAL;
  626. *field_sz = sz;
  627. *type_id = acc->type_id;
  628. } else if (relo->kind == BPF_CORE_FIELD_BYTE_SIZE) {
  629. sz = btf__resolve_size(spec->btf, acc->type_id);
  630. if (sz < 0)
  631. return -EINVAL;
  632. *val = sz;
  633. } else {
  634. pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
  635. prog_name, relo->kind, relo->insn_off / 8);
  636. return -EINVAL;
  637. }
  638. if (validate)
  639. *validate = true;
  640. return 0;
  641. }
  642. m = btf_members(t) + acc->idx;
  643. mt = skip_mods_and_typedefs(spec->btf, m->type, &field_type_id);
  644. bit_off = spec->bit_offset;
  645. bit_sz = btf_member_bitfield_size(t, acc->idx);
  646. bitfield = bit_sz > 0;
  647. if (bitfield) {
  648. byte_sz = mt->size;
  649. byte_off = bit_off / 8 / byte_sz * byte_sz;
  650. /* figure out smallest int size necessary for bitfield load */
  651. while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
  652. if (byte_sz >= 8) {
  653. /* bitfield can't be read with 64-bit read */
  654. pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
  655. prog_name, relo->kind, relo->insn_off / 8);
  656. return -E2BIG;
  657. }
  658. byte_sz *= 2;
  659. byte_off = bit_off / 8 / byte_sz * byte_sz;
  660. }
  661. } else {
  662. sz = btf__resolve_size(spec->btf, field_type_id);
  663. if (sz < 0)
  664. return -EINVAL;
  665. byte_sz = sz;
  666. byte_off = spec->bit_offset / 8;
  667. bit_sz = byte_sz * 8;
  668. }
  669. /* for bitfields, all the relocatable aspects are ambiguous and we
  670. * might disagree with compiler, so turn off validation of expected
  671. * value, except for signedness
  672. */
  673. if (validate)
  674. *validate = !bitfield;
  675. switch (relo->kind) {
  676. case BPF_CORE_FIELD_BYTE_OFFSET:
  677. *val = byte_off;
  678. if (!bitfield) {
  679. /* remember field size for load/store mem size;
  680. * note, for arrays we care about individual element
  681. * sizes, not the overall array size
  682. */
  683. t = skip_mods_and_typedefs(spec->btf, field_type_id, &elem_id);
  684. while (btf_is_array(t))
  685. t = skip_mods_and_typedefs(spec->btf, btf_array(t)->type, &elem_id);
  686. sz = btf__resolve_size(spec->btf, elem_id);
  687. if (sz < 0)
  688. return -EINVAL;
  689. *field_sz = sz;
  690. *type_id = field_type_id;
  691. }
  692. break;
  693. case BPF_CORE_FIELD_BYTE_SIZE:
  694. *val = byte_sz;
  695. break;
  696. case BPF_CORE_FIELD_SIGNED:
  697. *val = (btf_is_any_enum(mt) && BTF_INFO_KFLAG(mt->info)) ||
  698. (btf_is_int(mt) && (btf_int_encoding(mt) & BTF_INT_SIGNED));
  699. if (validate)
  700. *validate = true; /* signedness is never ambiguous */
  701. break;
  702. case BPF_CORE_FIELD_LSHIFT_U64:
  703. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  704. *val = 64 - (bit_off + bit_sz - byte_off * 8);
  705. #else
  706. *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
  707. #endif
  708. break;
  709. case BPF_CORE_FIELD_RSHIFT_U64:
  710. *val = 64 - bit_sz;
  711. if (validate)
  712. *validate = true; /* right shift is never ambiguous */
  713. break;
  714. case BPF_CORE_FIELD_EXISTS:
  715. default:
  716. return -EOPNOTSUPP;
  717. }
  718. return 0;
  719. }
  720. static int bpf_core_calc_type_relo(const struct bpf_core_relo *relo,
  721. const struct bpf_core_spec *spec,
  722. __u64 *val, bool *validate)
  723. {
  724. __s64 sz;
  725. /* by default, always check expected value in bpf_insn */
  726. if (validate)
  727. *validate = true;
  728. /* type-based relos return zero when target type is not found */
  729. if (!spec) {
  730. *val = 0;
  731. return 0;
  732. }
  733. switch (relo->kind) {
  734. case BPF_CORE_TYPE_ID_TARGET:
  735. *val = spec->root_type_id;
  736. /* type ID, embedded in bpf_insn, might change during linking,
  737. * so enforcing it is pointless
  738. */
  739. if (validate)
  740. *validate = false;
  741. break;
  742. case BPF_CORE_TYPE_EXISTS:
  743. case BPF_CORE_TYPE_MATCHES:
  744. *val = 1;
  745. break;
  746. case BPF_CORE_TYPE_SIZE:
  747. sz = btf__resolve_size(spec->btf, spec->root_type_id);
  748. if (sz < 0)
  749. return -EINVAL;
  750. *val = sz;
  751. break;
  752. case BPF_CORE_TYPE_ID_LOCAL:
  753. /* BPF_CORE_TYPE_ID_LOCAL is handled specially and shouldn't get here */
  754. default:
  755. return -EOPNOTSUPP;
  756. }
  757. return 0;
  758. }
  759. static int bpf_core_calc_enumval_relo(const struct bpf_core_relo *relo,
  760. const struct bpf_core_spec *spec,
  761. __u64 *val)
  762. {
  763. const struct btf_type *t;
  764. switch (relo->kind) {
  765. case BPF_CORE_ENUMVAL_EXISTS:
  766. *val = spec ? 1 : 0;
  767. break;
  768. case BPF_CORE_ENUMVAL_VALUE:
  769. if (!spec)
  770. return -EUCLEAN; /* request instruction poisoning */
  771. t = btf_type_by_id(spec->btf, spec->spec[0].type_id);
  772. if (btf_is_enum(t))
  773. *val = btf_enum(t)[spec->spec[0].idx].val;
  774. else
  775. *val = btf_enum64_value(btf_enum64(t) + spec->spec[0].idx);
  776. break;
  777. default:
  778. return -EOPNOTSUPP;
  779. }
  780. return 0;
  781. }
  782. /* Calculate original and target relocation values, given local and target
  783. * specs and relocation kind. These values are calculated for each candidate.
  784. * If there are multiple candidates, resulting values should all be consistent
  785. * with each other. Otherwise, libbpf will refuse to proceed due to ambiguity.
  786. * If instruction has to be poisoned, *poison will be set to true.
  787. */
  788. static int bpf_core_calc_relo(const char *prog_name,
  789. const struct bpf_core_relo *relo,
  790. int relo_idx,
  791. const struct bpf_core_spec *local_spec,
  792. const struct bpf_core_spec *targ_spec,
  793. struct bpf_core_relo_res *res)
  794. {
  795. int err = -EOPNOTSUPP;
  796. res->orig_val = 0;
  797. res->new_val = 0;
  798. res->poison = false;
  799. res->validate = true;
  800. res->fail_memsz_adjust = false;
  801. res->orig_sz = res->new_sz = 0;
  802. res->orig_type_id = res->new_type_id = 0;
  803. if (core_relo_is_field_based(relo->kind)) {
  804. err = bpf_core_calc_field_relo(prog_name, relo, local_spec,
  805. &res->orig_val, &res->orig_sz,
  806. &res->orig_type_id, &res->validate);
  807. err = err ?: bpf_core_calc_field_relo(prog_name, relo, targ_spec,
  808. &res->new_val, &res->new_sz,
  809. &res->new_type_id, NULL);
  810. if (err)
  811. goto done;
  812. /* Validate if it's safe to adjust load/store memory size.
  813. * Adjustments are performed only if original and new memory
  814. * sizes differ.
  815. */
  816. res->fail_memsz_adjust = false;
  817. if (res->orig_sz != res->new_sz) {
  818. const struct btf_type *orig_t, *new_t;
  819. orig_t = btf_type_by_id(local_spec->btf, res->orig_type_id);
  820. new_t = btf_type_by_id(targ_spec->btf, res->new_type_id);
  821. /* There are two use cases in which it's safe to
  822. * adjust load/store's mem size:
  823. * - reading a 32-bit kernel pointer, while on BPF
  824. * size pointers are always 64-bit; in this case
  825. * it's safe to "downsize" instruction size due to
  826. * pointer being treated as unsigned integer with
  827. * zero-extended upper 32-bits;
  828. * - reading unsigned integers, again due to
  829. * zero-extension is preserving the value correctly.
  830. *
  831. * In all other cases it's incorrect to attempt to
  832. * load/store field because read value will be
  833. * incorrect, so we poison relocated instruction.
  834. */
  835. if (btf_is_ptr(orig_t) && btf_is_ptr(new_t))
  836. goto done;
  837. if (btf_is_int(orig_t) && btf_is_int(new_t) &&
  838. btf_int_encoding(orig_t) != BTF_INT_SIGNED &&
  839. btf_int_encoding(new_t) != BTF_INT_SIGNED)
  840. goto done;
  841. /* mark as invalid mem size adjustment, but this will
  842. * only be checked for LDX/STX/ST insns
  843. */
  844. res->fail_memsz_adjust = true;
  845. }
  846. } else if (core_relo_is_type_based(relo->kind)) {
  847. err = bpf_core_calc_type_relo(relo, local_spec, &res->orig_val, &res->validate);
  848. err = err ?: bpf_core_calc_type_relo(relo, targ_spec, &res->new_val, NULL);
  849. } else if (core_relo_is_enumval_based(relo->kind)) {
  850. err = bpf_core_calc_enumval_relo(relo, local_spec, &res->orig_val);
  851. err = err ?: bpf_core_calc_enumval_relo(relo, targ_spec, &res->new_val);
  852. }
  853. done:
  854. if (err == -EUCLEAN) {
  855. /* EUCLEAN is used to signal instruction poisoning request */
  856. res->poison = true;
  857. err = 0;
  858. } else if (err == -EOPNOTSUPP) {
  859. /* EOPNOTSUPP means unknown/unsupported relocation */
  860. pr_warn("prog '%s': relo #%d: unrecognized CO-RE relocation %s (%d) at insn #%d\n",
  861. prog_name, relo_idx, core_relo_kind_str(relo->kind),
  862. relo->kind, relo->insn_off / 8);
  863. }
  864. return err;
  865. }
  866. /*
  867. * Turn instruction for which CO_RE relocation failed into invalid one with
  868. * distinct signature.
  869. */
  870. static void bpf_core_poison_insn(const char *prog_name, int relo_idx,
  871. int insn_idx, struct bpf_insn *insn)
  872. {
  873. pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
  874. prog_name, relo_idx, insn_idx);
  875. insn->code = BPF_JMP | BPF_CALL;
  876. insn->dst_reg = 0;
  877. insn->src_reg = 0;
  878. insn->off = 0;
  879. /* if this instruction is reachable (not a dead code),
  880. * verifier will complain with the following message:
  881. * invalid func unknown#195896080
  882. */
  883. insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
  884. }
  885. static int insn_bpf_size_to_bytes(struct bpf_insn *insn)
  886. {
  887. switch (BPF_SIZE(insn->code)) {
  888. case BPF_DW: return 8;
  889. case BPF_W: return 4;
  890. case BPF_H: return 2;
  891. case BPF_B: return 1;
  892. default: return -1;
  893. }
  894. }
  895. static int insn_bytes_to_bpf_size(__u32 sz)
  896. {
  897. switch (sz) {
  898. case 8: return BPF_DW;
  899. case 4: return BPF_W;
  900. case 2: return BPF_H;
  901. case 1: return BPF_B;
  902. default: return -1;
  903. }
  904. }
  905. /*
  906. * Patch relocatable BPF instruction.
  907. *
  908. * Patched value is determined by relocation kind and target specification.
  909. * For existence relocations target spec will be NULL if field/type is not found.
  910. * Expected insn->imm value is determined using relocation kind and local
  911. * spec, and is checked before patching instruction. If actual insn->imm value
  912. * is wrong, bail out with error.
  913. *
  914. * Currently supported classes of BPF instruction are:
  915. * 1. rX = <imm> (assignment with immediate operand);
  916. * 2. rX += <imm> (arithmetic operations with immediate operand);
  917. * 3. rX = <imm64> (load with 64-bit immediate value);
  918. * 4. rX = *(T *)(rY + <off>), where T is one of {u8, u16, u32, u64};
  919. * 5. *(T *)(rX + <off>) = rY, where T is one of {u8, u16, u32, u64};
  920. * 6. *(T *)(rX + <off>) = <imm>, where T is one of {u8, u16, u32, u64}.
  921. */
  922. int bpf_core_patch_insn(const char *prog_name, struct bpf_insn *insn,
  923. int insn_idx, const struct bpf_core_relo *relo,
  924. int relo_idx, const struct bpf_core_relo_res *res)
  925. {
  926. __u64 orig_val, new_val;
  927. __u8 class;
  928. class = BPF_CLASS(insn->code);
  929. if (res->poison) {
  930. poison:
  931. /* poison second part of ldimm64 to avoid confusing error from
  932. * verifier about "unknown opcode 00"
  933. */
  934. if (is_ldimm64_insn(insn))
  935. bpf_core_poison_insn(prog_name, relo_idx, insn_idx + 1, insn + 1);
  936. bpf_core_poison_insn(prog_name, relo_idx, insn_idx, insn);
  937. return 0;
  938. }
  939. orig_val = res->orig_val;
  940. new_val = res->new_val;
  941. switch (class) {
  942. case BPF_ALU:
  943. case BPF_ALU64:
  944. if (BPF_SRC(insn->code) != BPF_K)
  945. return -EINVAL;
  946. if (res->validate && insn->imm != orig_val) {
  947. pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %llu -> %llu\n",
  948. prog_name, relo_idx,
  949. insn_idx, insn->imm, (unsigned long long)orig_val,
  950. (unsigned long long)new_val);
  951. return -EINVAL;
  952. }
  953. orig_val = insn->imm;
  954. insn->imm = new_val;
  955. pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %llu -> %llu\n",
  956. prog_name, relo_idx, insn_idx,
  957. (unsigned long long)orig_val, (unsigned long long)new_val);
  958. break;
  959. case BPF_LDX:
  960. case BPF_ST:
  961. case BPF_STX:
  962. if (res->validate && insn->off != orig_val) {
  963. pr_warn("prog '%s': relo #%d: unexpected insn #%d (LDX/ST/STX) value: got %u, exp %llu -> %llu\n",
  964. prog_name, relo_idx, insn_idx, insn->off, (unsigned long long)orig_val,
  965. (unsigned long long)new_val);
  966. return -EINVAL;
  967. }
  968. if (new_val > SHRT_MAX) {
  969. pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %llu\n",
  970. prog_name, relo_idx, insn_idx, (unsigned long long)new_val);
  971. return -ERANGE;
  972. }
  973. if (res->fail_memsz_adjust) {
  974. pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) accesses field incorrectly. "
  975. "Make sure you are accessing pointers, unsigned integers, or fields of matching type and size.\n",
  976. prog_name, relo_idx, insn_idx);
  977. goto poison;
  978. }
  979. orig_val = insn->off;
  980. insn->off = new_val;
  981. pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %llu -> %llu\n",
  982. prog_name, relo_idx, insn_idx, (unsigned long long)orig_val,
  983. (unsigned long long)new_val);
  984. if (res->new_sz != res->orig_sz) {
  985. int insn_bytes_sz, insn_bpf_sz;
  986. insn_bytes_sz = insn_bpf_size_to_bytes(insn);
  987. if (insn_bytes_sz != res->orig_sz) {
  988. pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) unexpected mem size: got %d, exp %u\n",
  989. prog_name, relo_idx, insn_idx, insn_bytes_sz, res->orig_sz);
  990. return -EINVAL;
  991. }
  992. insn_bpf_sz = insn_bytes_to_bpf_size(res->new_sz);
  993. if (insn_bpf_sz < 0) {
  994. pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) invalid new mem size: %u\n",
  995. prog_name, relo_idx, insn_idx, res->new_sz);
  996. return -EINVAL;
  997. }
  998. insn->code = BPF_MODE(insn->code) | insn_bpf_sz | BPF_CLASS(insn->code);
  999. pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) mem_sz %u -> %u\n",
  1000. prog_name, relo_idx, insn_idx, res->orig_sz, res->new_sz);
  1001. }
  1002. break;
  1003. case BPF_LD: {
  1004. __u64 imm;
  1005. if (!is_ldimm64_insn(insn) ||
  1006. insn[0].src_reg != 0 || insn[0].off != 0 ||
  1007. insn[1].code != 0 || insn[1].dst_reg != 0 ||
  1008. insn[1].src_reg != 0 || insn[1].off != 0) {
  1009. pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) has unexpected form\n",
  1010. prog_name, relo_idx, insn_idx);
  1011. return -EINVAL;
  1012. }
  1013. imm = (__u32)insn[0].imm | ((__u64)insn[1].imm << 32);
  1014. if (res->validate && imm != orig_val) {
  1015. pr_warn("prog '%s': relo #%d: unexpected insn #%d (LDIMM64) value: got %llu, exp %llu -> %llu\n",
  1016. prog_name, relo_idx,
  1017. insn_idx, (unsigned long long)imm,
  1018. (unsigned long long)orig_val, (unsigned long long)new_val);
  1019. return -EINVAL;
  1020. }
  1021. insn[0].imm = new_val;
  1022. insn[1].imm = new_val >> 32;
  1023. pr_debug("prog '%s': relo #%d: patched insn #%d (LDIMM64) imm64 %llu -> %llu\n",
  1024. prog_name, relo_idx, insn_idx,
  1025. (unsigned long long)imm, (unsigned long long)new_val);
  1026. break;
  1027. }
  1028. default:
  1029. pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:0x%x, src:0x%x, dst:0x%x, off:0x%x, imm:0x%x\n",
  1030. prog_name, relo_idx, insn_idx, insn->code,
  1031. insn->src_reg, insn->dst_reg, insn->off, insn->imm);
  1032. return -EINVAL;
  1033. }
  1034. return 0;
  1035. }
  1036. /* Output spec definition in the format:
  1037. * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
  1038. * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
  1039. */
  1040. int bpf_core_format_spec(char *buf, size_t buf_sz, const struct bpf_core_spec *spec)
  1041. {
  1042. const struct btf_type *t;
  1043. const char *s;
  1044. __u32 type_id;
  1045. int i, len = 0;
  1046. #define append_buf(fmt, args...) \
  1047. ({ \
  1048. int r; \
  1049. r = snprintf(buf, buf_sz, fmt, ##args); \
  1050. len += r; \
  1051. if (r >= buf_sz) \
  1052. r = buf_sz; \
  1053. buf += r; \
  1054. buf_sz -= r; \
  1055. })
  1056. type_id = spec->root_type_id;
  1057. t = btf_type_by_id(spec->btf, type_id);
  1058. s = btf__name_by_offset(spec->btf, t->name_off);
  1059. append_buf("<%s> [%u] %s %s",
  1060. core_relo_kind_str(spec->relo_kind),
  1061. type_id, btf_kind_str(t), str_is_empty(s) ? "<anon>" : s);
  1062. if (core_relo_is_type_based(spec->relo_kind))
  1063. return len;
  1064. if (core_relo_is_enumval_based(spec->relo_kind)) {
  1065. t = skip_mods_and_typedefs(spec->btf, type_id, NULL);
  1066. if (btf_is_enum(t)) {
  1067. const struct btf_enum *e;
  1068. const char *fmt_str;
  1069. e = btf_enum(t) + spec->raw_spec[0];
  1070. s = btf__name_by_offset(spec->btf, e->name_off);
  1071. fmt_str = BTF_INFO_KFLAG(t->info) ? "::%s = %d" : "::%s = %u";
  1072. append_buf(fmt_str, s, e->val);
  1073. } else {
  1074. const struct btf_enum64 *e;
  1075. const char *fmt_str;
  1076. e = btf_enum64(t) + spec->raw_spec[0];
  1077. s = btf__name_by_offset(spec->btf, e->name_off);
  1078. fmt_str = BTF_INFO_KFLAG(t->info) ? "::%s = %lld" : "::%s = %llu";
  1079. append_buf(fmt_str, s, (unsigned long long)btf_enum64_value(e));
  1080. }
  1081. return len;
  1082. }
  1083. if (core_relo_is_field_based(spec->relo_kind)) {
  1084. for (i = 0; i < spec->len; i++) {
  1085. if (spec->spec[i].name)
  1086. append_buf(".%s", spec->spec[i].name);
  1087. else if (i > 0 || spec->spec[i].idx > 0)
  1088. append_buf("[%u]", spec->spec[i].idx);
  1089. }
  1090. append_buf(" (");
  1091. for (i = 0; i < spec->raw_len; i++)
  1092. append_buf("%s%d", i == 0 ? "" : ":", spec->raw_spec[i]);
  1093. if (spec->bit_offset % 8)
  1094. append_buf(" @ offset %u.%u)", spec->bit_offset / 8, spec->bit_offset % 8);
  1095. else
  1096. append_buf(" @ offset %u)", spec->bit_offset / 8);
  1097. return len;
  1098. }
  1099. return len;
  1100. #undef append_buf
  1101. }
  1102. /*
  1103. * Calculate CO-RE relocation target result.
  1104. *
  1105. * The outline and important points of the algorithm:
  1106. * 1. For given local type, find corresponding candidate target types.
  1107. * Candidate type is a type with the same "essential" name, ignoring
  1108. * everything after last triple underscore (___). E.g., `sample`,
  1109. * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
  1110. * for each other. Names with triple underscore are referred to as
  1111. * "flavors" and are useful, among other things, to allow to
  1112. * specify/support incompatible variations of the same kernel struct, which
  1113. * might differ between different kernel versions and/or build
  1114. * configurations.
  1115. *
  1116. * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
  1117. * converter, when deduplicated BTF of a kernel still contains more than
  1118. * one different types with the same name. In that case, ___2, ___3, etc
  1119. * are appended starting from second name conflict. But start flavors are
  1120. * also useful to be defined "locally", in BPF program, to extract same
  1121. * data from incompatible changes between different kernel
  1122. * versions/configurations. For instance, to handle field renames between
  1123. * kernel versions, one can use two flavors of the struct name with the
  1124. * same common name and use conditional relocations to extract that field,
  1125. * depending on target kernel version.
  1126. * 2. For each candidate type, try to match local specification to this
  1127. * candidate target type. Matching involves finding corresponding
  1128. * high-level spec accessors, meaning that all named fields should match,
  1129. * as well as all array accesses should be within the actual bounds. Also,
  1130. * types should be compatible (see bpf_core_fields_are_compat for details).
  1131. * 3. It is supported and expected that there might be multiple flavors
  1132. * matching the spec. As long as all the specs resolve to the same set of
  1133. * offsets across all candidates, there is no error. If there is any
  1134. * ambiguity, CO-RE relocation will fail. This is necessary to accommodate
  1135. * imperfection of BTF deduplication, which can cause slight duplication of
  1136. * the same BTF type, if some directly or indirectly referenced (by
  1137. * pointer) type gets resolved to different actual types in different
  1138. * object files. If such a situation occurs, deduplicated BTF will end up
  1139. * with two (or more) structurally identical types, which differ only in
  1140. * types they refer to through pointer. This should be OK in most cases and
  1141. * is not an error.
  1142. * 4. Candidate types search is performed by linearly scanning through all
  1143. * types in target BTF. It is anticipated that this is overall more
  1144. * efficient memory-wise and not significantly worse (if not better)
  1145. * CPU-wise compared to prebuilding a map from all local type names to
  1146. * a list of candidate type names. It's also sped up by caching resolved
  1147. * list of matching candidates per each local "root" type ID, that has at
  1148. * least one bpf_core_relo associated with it. This list is shared
  1149. * between multiple relocations for the same type ID and is updated as some
  1150. * of the candidates are pruned due to structural incompatibility.
  1151. */
  1152. int bpf_core_calc_relo_insn(const char *prog_name,
  1153. const struct bpf_core_relo *relo,
  1154. int relo_idx,
  1155. const struct btf *local_btf,
  1156. struct bpf_core_cand_list *cands,
  1157. struct bpf_core_spec *specs_scratch,
  1158. struct bpf_core_relo_res *targ_res)
  1159. {
  1160. struct bpf_core_spec *local_spec = &specs_scratch[0];
  1161. struct bpf_core_spec *cand_spec = &specs_scratch[1];
  1162. struct bpf_core_spec *targ_spec = &specs_scratch[2];
  1163. struct bpf_core_relo_res cand_res;
  1164. const struct btf_type *local_type;
  1165. const char *local_name;
  1166. __u32 local_id;
  1167. char spec_buf[256];
  1168. int i, j, err;
  1169. local_id = relo->type_id;
  1170. local_type = btf_type_by_id(local_btf, local_id);
  1171. local_name = btf__name_by_offset(local_btf, local_type->name_off);
  1172. if (!local_name)
  1173. return -EINVAL;
  1174. err = bpf_core_parse_spec(prog_name, local_btf, relo, local_spec);
  1175. if (err) {
  1176. const char *spec_str;
  1177. spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
  1178. pr_warn("prog '%s': relo #%d: parsing [%d] %s %s + %s failed: %d\n",
  1179. prog_name, relo_idx, local_id, btf_kind_str(local_type),
  1180. str_is_empty(local_name) ? "<anon>" : local_name,
  1181. spec_str ?: "<?>", err);
  1182. return -EINVAL;
  1183. }
  1184. bpf_core_format_spec(spec_buf, sizeof(spec_buf), local_spec);
  1185. pr_debug("prog '%s': relo #%d: %s\n", prog_name, relo_idx, spec_buf);
  1186. /* TYPE_ID_LOCAL relo is special and doesn't need candidate search */
  1187. if (relo->kind == BPF_CORE_TYPE_ID_LOCAL) {
  1188. /* bpf_insn's imm value could get out of sync during linking */
  1189. memset(targ_res, 0, sizeof(*targ_res));
  1190. targ_res->validate = false;
  1191. targ_res->poison = false;
  1192. targ_res->orig_val = local_spec->root_type_id;
  1193. targ_res->new_val = local_spec->root_type_id;
  1194. return 0;
  1195. }
  1196. /* libbpf doesn't support candidate search for anonymous types */
  1197. if (str_is_empty(local_name)) {
  1198. pr_warn("prog '%s': relo #%d: <%s> (%d) relocation doesn't support anonymous types\n",
  1199. prog_name, relo_idx, core_relo_kind_str(relo->kind), relo->kind);
  1200. return -EOPNOTSUPP;
  1201. }
  1202. for (i = 0, j = 0; i < cands->len; i++) {
  1203. err = bpf_core_spec_match(local_spec, cands->cands[i].btf,
  1204. cands->cands[i].id, cand_spec);
  1205. if (err < 0) {
  1206. bpf_core_format_spec(spec_buf, sizeof(spec_buf), cand_spec);
  1207. pr_warn("prog '%s': relo #%d: error matching candidate #%d %s: %d\n",
  1208. prog_name, relo_idx, i, spec_buf, err);
  1209. return err;
  1210. }
  1211. bpf_core_format_spec(spec_buf, sizeof(spec_buf), cand_spec);
  1212. pr_debug("prog '%s': relo #%d: %s candidate #%d %s\n", prog_name,
  1213. relo_idx, err == 0 ? "non-matching" : "matching", i, spec_buf);
  1214. if (err == 0)
  1215. continue;
  1216. err = bpf_core_calc_relo(prog_name, relo, relo_idx, local_spec, cand_spec, &cand_res);
  1217. if (err)
  1218. return err;
  1219. if (j == 0) {
  1220. *targ_res = cand_res;
  1221. *targ_spec = *cand_spec;
  1222. } else if (cand_spec->bit_offset != targ_spec->bit_offset) {
  1223. /* if there are many field relo candidates, they
  1224. * should all resolve to the same bit offset
  1225. */
  1226. pr_warn("prog '%s': relo #%d: field offset ambiguity: %u != %u\n",
  1227. prog_name, relo_idx, cand_spec->bit_offset,
  1228. targ_spec->bit_offset);
  1229. return -EINVAL;
  1230. } else if (cand_res.poison != targ_res->poison ||
  1231. cand_res.new_val != targ_res->new_val) {
  1232. /* all candidates should result in the same relocation
  1233. * decision and value, otherwise it's dangerous to
  1234. * proceed due to ambiguity
  1235. */
  1236. pr_warn("prog '%s': relo #%d: relocation decision ambiguity: %s %llu != %s %llu\n",
  1237. prog_name, relo_idx,
  1238. cand_res.poison ? "failure" : "success",
  1239. (unsigned long long)cand_res.new_val,
  1240. targ_res->poison ? "failure" : "success",
  1241. (unsigned long long)targ_res->new_val);
  1242. return -EINVAL;
  1243. }
  1244. cands->cands[j++] = cands->cands[i];
  1245. }
  1246. /*
  1247. * For BPF_CORE_FIELD_EXISTS relo or when used BPF program has field
  1248. * existence checks or kernel version/config checks, it's expected
  1249. * that we might not find any candidates. In this case, if field
  1250. * wasn't found in any candidate, the list of candidates shouldn't
  1251. * change at all, we'll just handle relocating appropriately,
  1252. * depending on relo's kind.
  1253. */
  1254. if (j > 0)
  1255. cands->len = j;
  1256. /*
  1257. * If no candidates were found, it might be both a programmer error,
  1258. * as well as expected case, depending whether instruction w/
  1259. * relocation is guarded in some way that makes it unreachable (dead
  1260. * code) if relocation can't be resolved. This is handled in
  1261. * bpf_core_patch_insn() uniformly by replacing that instruction with
  1262. * BPF helper call insn (using invalid helper ID). If that instruction
  1263. * is indeed unreachable, then it will be ignored and eliminated by
  1264. * verifier. If it was an error, then verifier will complain and point
  1265. * to a specific instruction number in its log.
  1266. */
  1267. if (j == 0) {
  1268. pr_debug("prog '%s': relo #%d: no matching targets found\n",
  1269. prog_name, relo_idx);
  1270. /* calculate single target relo result explicitly */
  1271. err = bpf_core_calc_relo(prog_name, relo, relo_idx, local_spec, NULL, targ_res);
  1272. if (err)
  1273. return err;
  1274. }
  1275. return 0;
  1276. }
  1277. static bool bpf_core_names_match(const struct btf *local_btf, size_t local_name_off,
  1278. const struct btf *targ_btf, size_t targ_name_off)
  1279. {
  1280. const char *local_n, *targ_n;
  1281. size_t local_len, targ_len;
  1282. local_n = btf__name_by_offset(local_btf, local_name_off);
  1283. targ_n = btf__name_by_offset(targ_btf, targ_name_off);
  1284. if (str_is_empty(targ_n))
  1285. return str_is_empty(local_n);
  1286. targ_len = bpf_core_essential_name_len(targ_n);
  1287. local_len = bpf_core_essential_name_len(local_n);
  1288. return targ_len == local_len && strncmp(local_n, targ_n, local_len) == 0;
  1289. }
  1290. static int bpf_core_enums_match(const struct btf *local_btf, const struct btf_type *local_t,
  1291. const struct btf *targ_btf, const struct btf_type *targ_t)
  1292. {
  1293. __u16 local_vlen = btf_vlen(local_t);
  1294. __u16 targ_vlen = btf_vlen(targ_t);
  1295. int i, j;
  1296. if (local_t->size != targ_t->size)
  1297. return 0;
  1298. if (local_vlen > targ_vlen)
  1299. return 0;
  1300. /* iterate over the local enum's variants and make sure each has
  1301. * a symbolic name correspondent in the target
  1302. */
  1303. for (i = 0; i < local_vlen; i++) {
  1304. bool matched = false;
  1305. __u32 local_n_off, targ_n_off;
  1306. local_n_off = btf_is_enum(local_t) ? btf_enum(local_t)[i].name_off :
  1307. btf_enum64(local_t)[i].name_off;
  1308. for (j = 0; j < targ_vlen; j++) {
  1309. targ_n_off = btf_is_enum(targ_t) ? btf_enum(targ_t)[j].name_off :
  1310. btf_enum64(targ_t)[j].name_off;
  1311. if (bpf_core_names_match(local_btf, local_n_off, targ_btf, targ_n_off)) {
  1312. matched = true;
  1313. break;
  1314. }
  1315. }
  1316. if (!matched)
  1317. return 0;
  1318. }
  1319. return 1;
  1320. }
  1321. static int bpf_core_composites_match(const struct btf *local_btf, const struct btf_type *local_t,
  1322. const struct btf *targ_btf, const struct btf_type *targ_t,
  1323. bool behind_ptr, int level)
  1324. {
  1325. const struct btf_member *local_m = btf_members(local_t);
  1326. __u16 local_vlen = btf_vlen(local_t);
  1327. __u16 targ_vlen = btf_vlen(targ_t);
  1328. int i, j, err;
  1329. if (local_vlen > targ_vlen)
  1330. return 0;
  1331. /* check that all local members have a match in the target */
  1332. for (i = 0; i < local_vlen; i++, local_m++) {
  1333. const struct btf_member *targ_m = btf_members(targ_t);
  1334. bool matched = false;
  1335. for (j = 0; j < targ_vlen; j++, targ_m++) {
  1336. if (!bpf_core_names_match(local_btf, local_m->name_off,
  1337. targ_btf, targ_m->name_off))
  1338. continue;
  1339. err = __bpf_core_types_match(local_btf, local_m->type, targ_btf,
  1340. targ_m->type, behind_ptr, level - 1);
  1341. if (err < 0)
  1342. return err;
  1343. if (err > 0) {
  1344. matched = true;
  1345. break;
  1346. }
  1347. }
  1348. if (!matched)
  1349. return 0;
  1350. }
  1351. return 1;
  1352. }
  1353. /* Check that two types "match". This function assumes that root types were
  1354. * already checked for name match.
  1355. *
  1356. * The matching relation is defined as follows:
  1357. * - modifiers and typedefs are stripped (and, hence, effectively ignored)
  1358. * - generally speaking types need to be of same kind (struct vs. struct, union
  1359. * vs. union, etc.)
  1360. * - exceptions are struct/union behind a pointer which could also match a
  1361. * forward declaration of a struct or union, respectively, and enum vs.
  1362. * enum64 (see below)
  1363. * Then, depending on type:
  1364. * - integers:
  1365. * - match if size and signedness match
  1366. * - arrays & pointers:
  1367. * - target types are recursively matched
  1368. * - structs & unions:
  1369. * - local members need to exist in target with the same name
  1370. * - for each member we recursively check match unless it is already behind a
  1371. * pointer, in which case we only check matching names and compatible kind
  1372. * - enums:
  1373. * - local variants have to have a match in target by symbolic name (but not
  1374. * numeric value)
  1375. * - size has to match (but enum may match enum64 and vice versa)
  1376. * - function pointers:
  1377. * - number and position of arguments in local type has to match target
  1378. * - for each argument and the return value we recursively check match
  1379. */
  1380. int __bpf_core_types_match(const struct btf *local_btf, __u32 local_id, const struct btf *targ_btf,
  1381. __u32 targ_id, bool behind_ptr, int level)
  1382. {
  1383. const struct btf_type *local_t, *targ_t;
  1384. int depth = 32; /* max recursion depth */
  1385. __u16 local_k, targ_k;
  1386. if (level <= 0)
  1387. return -EINVAL;
  1388. recur:
  1389. depth--;
  1390. if (depth < 0)
  1391. return -EINVAL;
  1392. local_t = skip_mods_and_typedefs(local_btf, local_id, &local_id);
  1393. targ_t = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
  1394. if (!local_t || !targ_t)
  1395. return -EINVAL;
  1396. /* While the name check happens after typedefs are skipped, root-level
  1397. * typedefs would still be name-matched as that's the contract with
  1398. * callers.
  1399. */
  1400. if (!bpf_core_names_match(local_btf, local_t->name_off, targ_btf, targ_t->name_off))
  1401. return 0;
  1402. local_k = btf_kind(local_t);
  1403. targ_k = btf_kind(targ_t);
  1404. switch (local_k) {
  1405. case BTF_KIND_UNKN:
  1406. return local_k == targ_k;
  1407. case BTF_KIND_FWD: {
  1408. bool local_f = BTF_INFO_KFLAG(local_t->info);
  1409. if (behind_ptr) {
  1410. if (local_k == targ_k)
  1411. return local_f == BTF_INFO_KFLAG(targ_t->info);
  1412. /* for forward declarations kflag dictates whether the
  1413. * target is a struct (0) or union (1)
  1414. */
  1415. return (targ_k == BTF_KIND_STRUCT && !local_f) ||
  1416. (targ_k == BTF_KIND_UNION && local_f);
  1417. } else {
  1418. if (local_k != targ_k)
  1419. return 0;
  1420. /* match if the forward declaration is for the same kind */
  1421. return local_f == BTF_INFO_KFLAG(targ_t->info);
  1422. }
  1423. }
  1424. case BTF_KIND_ENUM:
  1425. case BTF_KIND_ENUM64:
  1426. if (!btf_is_any_enum(targ_t))
  1427. return 0;
  1428. return bpf_core_enums_match(local_btf, local_t, targ_btf, targ_t);
  1429. case BTF_KIND_STRUCT:
  1430. case BTF_KIND_UNION:
  1431. if (behind_ptr) {
  1432. bool targ_f = BTF_INFO_KFLAG(targ_t->info);
  1433. if (local_k == targ_k)
  1434. return 1;
  1435. if (targ_k != BTF_KIND_FWD)
  1436. return 0;
  1437. return (local_k == BTF_KIND_UNION) == targ_f;
  1438. } else {
  1439. if (local_k != targ_k)
  1440. return 0;
  1441. return bpf_core_composites_match(local_btf, local_t, targ_btf, targ_t,
  1442. behind_ptr, level);
  1443. }
  1444. case BTF_KIND_INT: {
  1445. __u8 local_sgn;
  1446. __u8 targ_sgn;
  1447. if (local_k != targ_k)
  1448. return 0;
  1449. local_sgn = btf_int_encoding(local_t) & BTF_INT_SIGNED;
  1450. targ_sgn = btf_int_encoding(targ_t) & BTF_INT_SIGNED;
  1451. return local_t->size == targ_t->size && local_sgn == targ_sgn;
  1452. }
  1453. case BTF_KIND_PTR:
  1454. if (local_k != targ_k)
  1455. return 0;
  1456. behind_ptr = true;
  1457. local_id = local_t->type;
  1458. targ_id = targ_t->type;
  1459. goto recur;
  1460. case BTF_KIND_ARRAY: {
  1461. const struct btf_array *local_array = btf_array(local_t);
  1462. const struct btf_array *targ_array = btf_array(targ_t);
  1463. if (local_k != targ_k)
  1464. return 0;
  1465. if (local_array->nelems != targ_array->nelems)
  1466. return 0;
  1467. local_id = local_array->type;
  1468. targ_id = targ_array->type;
  1469. goto recur;
  1470. }
  1471. case BTF_KIND_FUNC_PROTO: {
  1472. struct btf_param *local_p = btf_params(local_t);
  1473. struct btf_param *targ_p = btf_params(targ_t);
  1474. __u16 local_vlen = btf_vlen(local_t);
  1475. __u16 targ_vlen = btf_vlen(targ_t);
  1476. int i, err;
  1477. if (local_k != targ_k)
  1478. return 0;
  1479. if (local_vlen != targ_vlen)
  1480. return 0;
  1481. for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
  1482. err = __bpf_core_types_match(local_btf, local_p->type, targ_btf,
  1483. targ_p->type, behind_ptr, level - 1);
  1484. if (err <= 0)
  1485. return err;
  1486. }
  1487. /* tail recurse for return type check */
  1488. local_id = local_t->type;
  1489. targ_id = targ_t->type;
  1490. goto recur;
  1491. }
  1492. default:
  1493. pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
  1494. btf_kind_str(local_t), local_id, targ_id);
  1495. return 0;
  1496. }
  1497. }