brintos

brintos / linux-shallow public Read only

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