relo_core.c 51 KB

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