1 // SPDX-License-Identifier: GPL-2.0 2 /* Copyright (c) 2020 Facebook */ 3 #include <test_progs.h> 4 #include <bpf/btf.h> 5 6 static char *dump_buf; 7 static size_t dump_buf_sz; 8 static FILE *dump_buf_file; 9 10 static void btf_dump_printf(void *ctx, const char *fmt, va_list args) 11 { 12 vfprintf(ctx, fmt, args); 13 } 14 15 void test_btf_split() { 16 struct btf_dump_opts opts; 17 struct btf_dump *d = NULL; 18 const struct btf_type *t; 19 struct btf *btf1, *btf2; 20 int str_off, i, err; 21 22 btf1 = btf__new_empty(); 23 if (!ASSERT_OK_PTR(btf1, "empty_main_btf")) 24 return; 25 26 btf__set_pointer_size(btf1, 8); /* enforce 64-bit arch */ 27 28 btf__add_int(btf1, "int", 4, BTF_INT_SIGNED); /* [1] int */ 29 btf__add_ptr(btf1, 1); /* [2] ptr to int */ 30 31 btf__add_struct(btf1, "s1", 4); /* [3] struct s1 { */ 32 btf__add_field(btf1, "f1", 1, 0, 0); /* int f1; */ 33 /* } */ 34 35 btf2 = btf__new_empty_split(btf1); 36 if (!ASSERT_OK_PTR(btf2, "empty_split_btf")) 37 goto cleanup; 38 39 /* pointer size should be "inherited" from main BTF */ 40 ASSERT_EQ(btf__pointer_size(btf2), 8, "inherit_ptr_sz"); 41 42 str_off = btf__find_str(btf2, "int"); 43 ASSERT_NEQ(str_off, -ENOENT, "str_int_missing"); 44 45 t = btf__type_by_id(btf2, 1); 46 if (!ASSERT_OK_PTR(t, "int_type")) 47 goto cleanup; 48 ASSERT_EQ(btf_is_int(t), true, "int_kind"); 49 ASSERT_STREQ(btf__str_by_offset(btf2, t->name_off), "int", "int_name"); 50 51 btf__add_struct(btf2, "s2", 16); /* [4] struct s2 { */ 52 btf__add_field(btf2, "f1", 3, 0, 0); /* struct s1 f1; */ 53 btf__add_field(btf2, "f2", 1, 32, 0); /* int f2; */ 54 btf__add_field(btf2, "f3", 2, 64, 0); /* int *f3; */ 55 /* } */ 56 57 t = btf__type_by_id(btf1, 4); 58 ASSERT_NULL(t, "split_type_in_main"); 59 60 t = btf__type_by_id(btf2, 4); 61 if (!ASSERT_OK_PTR(t, "split_struct_type")) 62 goto cleanup; 63 ASSERT_EQ(btf_is_struct(t), true, "split_struct_kind"); 64 ASSERT_EQ(btf_vlen(t), 3, "split_struct_vlen"); 65 ASSERT_STREQ(btf__str_by_offset(btf2, t->name_off), "s2", "split_struct_name"); 66 67 /* BTF-to-C dump of split BTF */ 68 dump_buf_file = open_memstream(&dump_buf, &dump_buf_sz); 69 if (!ASSERT_OK_PTR(dump_buf_file, "dump_memstream")) 70 return; 71 opts.ctx = dump_buf_file; 72 d = btf_dump__new(btf2, NULL, &opts, btf_dump_printf); 73 if (!ASSERT_OK_PTR(d, "btf_dump__new")) 74 goto cleanup; 75 for (i = 1; i <= btf__get_nr_types(btf2); i++) { 76 err = btf_dump__dump_type(d, i); 77 ASSERT_OK(err, "dump_type_ok"); 78 } 79 fflush(dump_buf_file); 80 dump_buf[dump_buf_sz] = 0; /* some libc implementations don't do this */ 81 ASSERT_STREQ(dump_buf, 82 "struct s1 {\n" 83 " int f1;\n" 84 "};\n" 85 "\n" 86 "struct s2 {\n" 87 " struct s1 f1;\n" 88 " int f2;\n" 89 " int *f3;\n" 90 "};\n\n", "c_dump"); 91 92 cleanup: 93 if (dump_buf_file) 94 fclose(dump_buf_file); 95 free(dump_buf); 96 btf_dump__free(d); 97 btf__free(btf1); 98 btf__free(btf2); 99 } 100