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