|
3 | 3 | #include <stdio.h>
|
4 | 4 | #include <errno.h>
|
5 | 5 | #include <bpf/btf.h>
|
| 6 | +#include <bpf/libbpf.h> |
| 7 | +#include "test_progs.h" |
6 | 8 |
|
7 | 9 | static const char * const btf_kind_str_mapping[] = {
|
8 | 10 | [BTF_KIND_UNKN] = "UNKNOWN",
|
@@ -198,3 +200,60 @@ const char *btf_type_raw_dump(const struct btf *btf, int type_id)
|
198 | 200 |
|
199 | 201 | return buf;
|
200 | 202 | }
|
| 203 | + |
| 204 | +int btf_validate_raw(struct btf *btf, int nr_types, const char *exp_types[]) |
| 205 | +{ |
| 206 | + int i; |
| 207 | + bool ok = true; |
| 208 | + |
| 209 | + ASSERT_EQ(btf__get_nr_types(btf), nr_types, "btf_nr_types"); |
| 210 | + |
| 211 | + for (i = 1; i <= nr_types; i++) { |
| 212 | + if (!ASSERT_STREQ(btf_type_raw_dump(btf, i), exp_types[i - 1], "raw_dump")) |
| 213 | + ok = false; |
| 214 | + } |
| 215 | + |
| 216 | + return ok; |
| 217 | +} |
| 218 | + |
| 219 | +static void btf_dump_printf(void *ctx, const char *fmt, va_list args) |
| 220 | +{ |
| 221 | + vfprintf(ctx, fmt, args); |
| 222 | +} |
| 223 | + |
| 224 | +/* Print BTF-to-C dump into a local buffer and return string pointer back. |
| 225 | + * Buffer *will* be overwritten by subsequent btf_type_raw_dump() calls |
| 226 | + */ |
| 227 | +const char *btf_type_c_dump(const struct btf *btf) |
| 228 | +{ |
| 229 | + static char buf[16 * 1024]; |
| 230 | + FILE *buf_file; |
| 231 | + struct btf_dump *d = NULL; |
| 232 | + struct btf_dump_opts opts = {}; |
| 233 | + int err, i; |
| 234 | + |
| 235 | + buf_file = fmemopen(buf, sizeof(buf) - 1, "w"); |
| 236 | + if (!buf_file) { |
| 237 | + fprintf(stderr, "Failed to open memstream: %d\n", errno); |
| 238 | + return NULL; |
| 239 | + } |
| 240 | + |
| 241 | + opts.ctx = buf_file; |
| 242 | + d = btf_dump__new(btf, NULL, &opts, btf_dump_printf); |
| 243 | + if (libbpf_get_error(d)) { |
| 244 | + fprintf(stderr, "Failed to create btf_dump instance: %ld\n", libbpf_get_error(d)); |
| 245 | + return NULL; |
| 246 | + } |
| 247 | + |
| 248 | + for (i = 1; i <= btf__get_nr_types(btf); i++) { |
| 249 | + err = btf_dump__dump_type(d, i); |
| 250 | + if (err) { |
| 251 | + fprintf(stderr, "Failed to dump type [%d]: %d\n", i, err); |
| 252 | + return NULL; |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + fflush(buf_file); |
| 257 | + fclose(buf_file); |
| 258 | + return buf; |
| 259 | +} |
0 commit comments