xref: /openbmc/linux/tools/bpf/bpftool/gen.c (revision 827beb77)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2019 Facebook */
3 
4 #ifndef _GNU_SOURCE
5 #define _GNU_SOURCE
6 #endif
7 #include <ctype.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <linux/err.h>
11 #include <stdbool.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <bpf/bpf.h>
16 #include <bpf/libbpf.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/mman.h>
20 #include <bpf/btf.h>
21 
22 #include "json_writer.h"
23 #include "main.h"
24 
25 #define MAX_OBJ_NAME_LEN 64
26 
27 static void sanitize_identifier(char *name)
28 {
29 	int i;
30 
31 	for (i = 0; name[i]; i++)
32 		if (!isalnum(name[i]) && name[i] != '_')
33 			name[i] = '_';
34 }
35 
36 static bool str_has_prefix(const char *str, const char *prefix)
37 {
38 	return strncmp(str, prefix, strlen(prefix)) == 0;
39 }
40 
41 static bool str_has_suffix(const char *str, const char *suffix)
42 {
43 	size_t i, n1 = strlen(str), n2 = strlen(suffix);
44 
45 	if (n1 < n2)
46 		return false;
47 
48 	for (i = 0; i < n2; i++) {
49 		if (str[n1 - i - 1] != suffix[n2 - i - 1])
50 			return false;
51 	}
52 
53 	return true;
54 }
55 
56 static void get_obj_name(char *name, const char *file)
57 {
58 	/* Using basename() GNU version which doesn't modify arg. */
59 	strncpy(name, basename(file), MAX_OBJ_NAME_LEN - 1);
60 	name[MAX_OBJ_NAME_LEN - 1] = '\0';
61 	if (str_has_suffix(name, ".o"))
62 		name[strlen(name) - 2] = '\0';
63 	sanitize_identifier(name);
64 }
65 
66 static void get_header_guard(char *guard, const char *obj_name)
67 {
68 	int i;
69 
70 	sprintf(guard, "__%s_SKEL_H__", obj_name);
71 	for (i = 0; guard[i]; i++)
72 		guard[i] = toupper(guard[i]);
73 }
74 
75 static bool get_map_ident(const struct bpf_map *map, char *buf, size_t buf_sz)
76 {
77 	static const char *sfxs[] = { ".data", ".rodata", ".bss", ".kconfig" };
78 	const char *name = bpf_map__name(map);
79 	int i, n;
80 
81 	if (!bpf_map__is_internal(map)) {
82 		snprintf(buf, buf_sz, "%s", name);
83 		return true;
84 	}
85 
86 	for  (i = 0, n = ARRAY_SIZE(sfxs); i < n; i++) {
87 		const char *sfx = sfxs[i], *p;
88 
89 		p = strstr(name, sfx);
90 		if (p) {
91 			snprintf(buf, buf_sz, "%s", p + 1);
92 			sanitize_identifier(buf);
93 			return true;
94 		}
95 	}
96 
97 	return false;
98 }
99 
100 static bool get_datasec_ident(const char *sec_name, char *buf, size_t buf_sz)
101 {
102 	static const char *pfxs[] = { ".data", ".rodata", ".bss", ".kconfig" };
103 	int i, n;
104 
105 	for  (i = 0, n = ARRAY_SIZE(pfxs); i < n; i++) {
106 		const char *pfx = pfxs[i];
107 
108 		if (str_has_prefix(sec_name, pfx)) {
109 			snprintf(buf, buf_sz, "%s", sec_name + 1);
110 			sanitize_identifier(buf);
111 			return true;
112 		}
113 	}
114 
115 	return false;
116 }
117 
118 static void codegen_btf_dump_printf(void *ctx, const char *fmt, va_list args)
119 {
120 	vprintf(fmt, args);
121 }
122 
123 static int codegen_datasec_def(struct bpf_object *obj,
124 			       struct btf *btf,
125 			       struct btf_dump *d,
126 			       const struct btf_type *sec,
127 			       const char *obj_name)
128 {
129 	const char *sec_name = btf__name_by_offset(btf, sec->name_off);
130 	const struct btf_var_secinfo *sec_var = btf_var_secinfos(sec);
131 	int i, err, off = 0, pad_cnt = 0, vlen = btf_vlen(sec);
132 	char var_ident[256], sec_ident[256];
133 	bool strip_mods = false;
134 
135 	if (!get_datasec_ident(sec_name, sec_ident, sizeof(sec_ident)))
136 		return 0;
137 
138 	if (strcmp(sec_name, ".kconfig") != 0)
139 		strip_mods = true;
140 
141 	printf("	struct %s__%s {\n", obj_name, sec_ident);
142 	for (i = 0; i < vlen; i++, sec_var++) {
143 		const struct btf_type *var = btf__type_by_id(btf, sec_var->type);
144 		const char *var_name = btf__name_by_offset(btf, var->name_off);
145 		DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts, opts,
146 			.field_name = var_ident,
147 			.indent_level = 2,
148 			.strip_mods = strip_mods,
149 		);
150 		int need_off = sec_var->offset, align_off, align;
151 		__u32 var_type_id = var->type;
152 
153 		/* static variables are not exposed through BPF skeleton */
154 		if (btf_var(var)->linkage == BTF_VAR_STATIC)
155 			continue;
156 
157 		if (off > need_off) {
158 			p_err("Something is wrong for %s's variable #%d: need offset %d, already at %d.\n",
159 			      sec_name, i, need_off, off);
160 			return -EINVAL;
161 		}
162 
163 		align = btf__align_of(btf, var->type);
164 		if (align <= 0) {
165 			p_err("Failed to determine alignment of variable '%s': %d",
166 			      var_name, align);
167 			return -EINVAL;
168 		}
169 		/* Assume 32-bit architectures when generating data section
170 		 * struct memory layout. Given bpftool can't know which target
171 		 * host architecture it's emitting skeleton for, we need to be
172 		 * conservative and assume 32-bit one to ensure enough padding
173 		 * bytes are generated for pointer and long types. This will
174 		 * still work correctly for 64-bit architectures, because in
175 		 * the worst case we'll generate unnecessary padding field,
176 		 * which on 64-bit architectures is not strictly necessary and
177 		 * would be handled by natural 8-byte alignment. But it still
178 		 * will be a correct memory layout, based on recorded offsets
179 		 * in BTF.
180 		 */
181 		if (align > 4)
182 			align = 4;
183 
184 		align_off = (off + align - 1) / align * align;
185 		if (align_off != need_off) {
186 			printf("\t\tchar __pad%d[%d];\n",
187 			       pad_cnt, need_off - off);
188 			pad_cnt++;
189 		}
190 
191 		/* sanitize variable name, e.g., for static vars inside
192 		 * a function, it's name is '<function name>.<variable name>',
193 		 * which we'll turn into a '<function name>_<variable name>'
194 		 */
195 		var_ident[0] = '\0';
196 		strncat(var_ident, var_name, sizeof(var_ident) - 1);
197 		sanitize_identifier(var_ident);
198 
199 		printf("\t\t");
200 		err = btf_dump__emit_type_decl(d, var_type_id, &opts);
201 		if (err)
202 			return err;
203 		printf(";\n");
204 
205 		off = sec_var->offset + sec_var->size;
206 	}
207 	printf("	} *%s;\n", sec_ident);
208 	return 0;
209 }
210 
211 static int codegen_datasecs(struct bpf_object *obj, const char *obj_name)
212 {
213 	struct btf *btf = bpf_object__btf(obj);
214 	int n = btf__type_cnt(btf);
215 	struct btf_dump *d;
216 	struct bpf_map *map;
217 	const struct btf_type *sec;
218 	char sec_ident[256], map_ident[256];
219 	int i, err = 0;
220 
221 	d = btf_dump__new(btf, NULL, NULL, codegen_btf_dump_printf);
222 	if (IS_ERR(d))
223 		return PTR_ERR(d);
224 
225 	bpf_object__for_each_map(map, obj) {
226 		/* only generate definitions for memory-mapped internal maps */
227 		if (!bpf_map__is_internal(map))
228 			continue;
229 		if (!(bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
230 			continue;
231 
232 		if (!get_map_ident(map, map_ident, sizeof(map_ident)))
233 			continue;
234 
235 		sec = NULL;
236 		for (i = 1; i < n; i++) {
237 			const struct btf_type *t = btf__type_by_id(btf, i);
238 			const char *name;
239 
240 			if (!btf_is_datasec(t))
241 				continue;
242 
243 			name = btf__str_by_offset(btf, t->name_off);
244 			if (!get_datasec_ident(name, sec_ident, sizeof(sec_ident)))
245 				continue;
246 
247 			if (strcmp(sec_ident, map_ident) == 0) {
248 				sec = t;
249 				break;
250 			}
251 		}
252 
253 		/* In some cases (e.g., sections like .rodata.cst16 containing
254 		 * compiler allocated string constants only) there will be
255 		 * special internal maps with no corresponding DATASEC BTF
256 		 * type. In such case, generate empty structs for each such
257 		 * map. It will still be memory-mapped and its contents
258 		 * accessible from user-space through BPF skeleton.
259 		 */
260 		if (!sec) {
261 			printf("	struct %s__%s {\n", obj_name, map_ident);
262 			printf("	} *%s;\n", map_ident);
263 		} else {
264 			err = codegen_datasec_def(obj, btf, d, sec, obj_name);
265 			if (err)
266 				goto out;
267 		}
268 	}
269 
270 
271 out:
272 	btf_dump__free(d);
273 	return err;
274 }
275 
276 static void codegen(const char *template, ...)
277 {
278 	const char *src, *end;
279 	int skip_tabs = 0, n;
280 	char *s, *dst;
281 	va_list args;
282 	char c;
283 
284 	n = strlen(template);
285 	s = malloc(n + 1);
286 	if (!s)
287 		exit(-1);
288 	src = template;
289 	dst = s;
290 
291 	/* find out "baseline" indentation to skip */
292 	while ((c = *src++)) {
293 		if (c == '\t') {
294 			skip_tabs++;
295 		} else if (c == '\n') {
296 			break;
297 		} else {
298 			p_err("unrecognized character at pos %td in template '%s': '%c'",
299 			      src - template - 1, template, c);
300 			free(s);
301 			exit(-1);
302 		}
303 	}
304 
305 	while (*src) {
306 		/* skip baseline indentation tabs */
307 		for (n = skip_tabs; n > 0; n--, src++) {
308 			if (*src != '\t') {
309 				p_err("not enough tabs at pos %td in template '%s'",
310 				      src - template - 1, template);
311 				free(s);
312 				exit(-1);
313 			}
314 		}
315 		/* trim trailing whitespace */
316 		end = strchrnul(src, '\n');
317 		for (n = end - src; n > 0 && isspace(src[n - 1]); n--)
318 			;
319 		memcpy(dst, src, n);
320 		dst += n;
321 		if (*end)
322 			*dst++ = '\n';
323 		src = *end ? end + 1 : end;
324 	}
325 	*dst++ = '\0';
326 
327 	/* print out using adjusted template */
328 	va_start(args, template);
329 	n = vprintf(s, args);
330 	va_end(args);
331 
332 	free(s);
333 }
334 
335 static void print_hex(const char *data, int data_sz)
336 {
337 	int i, len;
338 
339 	for (i = 0, len = 0; i < data_sz; i++) {
340 		int w = data[i] ? 4 : 2;
341 
342 		len += w;
343 		if (len > 78) {
344 			printf("\\\n");
345 			len = w;
346 		}
347 		if (!data[i])
348 			printf("\\0");
349 		else
350 			printf("\\x%02x", (unsigned char)data[i]);
351 	}
352 }
353 
354 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
355 {
356 	long page_sz = sysconf(_SC_PAGE_SIZE);
357 	size_t map_sz;
358 
359 	map_sz = (size_t)roundup(bpf_map__value_size(map), 8) * bpf_map__max_entries(map);
360 	map_sz = roundup(map_sz, page_sz);
361 	return map_sz;
362 }
363 
364 static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
365 {
366 	struct bpf_program *prog;
367 
368 	bpf_object__for_each_program(prog, obj) {
369 		const char *tp_name;
370 
371 		codegen("\
372 			\n\
373 			\n\
374 			static inline int					    \n\
375 			%1$s__%2$s__attach(struct %1$s *skel)			    \n\
376 			{							    \n\
377 				int prog_fd = skel->progs.%2$s.prog_fd;		    \n\
378 			", obj_name, bpf_program__name(prog));
379 
380 		switch (bpf_program__get_type(prog)) {
381 		case BPF_PROG_TYPE_RAW_TRACEPOINT:
382 			tp_name = strchr(bpf_program__section_name(prog), '/') + 1;
383 			printf("\tint fd = bpf_raw_tracepoint_open(\"%s\", prog_fd);\n", tp_name);
384 			break;
385 		case BPF_PROG_TYPE_TRACING:
386 			printf("\tint fd = bpf_raw_tracepoint_open(NULL, prog_fd);\n");
387 			break;
388 		default:
389 			printf("\tint fd = ((void)prog_fd, 0); /* auto-attach not supported */\n");
390 			break;
391 		}
392 		codegen("\
393 			\n\
394 										    \n\
395 				if (fd > 0)					    \n\
396 					skel->links.%1$s_fd = fd;		    \n\
397 				return fd;					    \n\
398 			}							    \n\
399 			", bpf_program__name(prog));
400 	}
401 
402 	codegen("\
403 		\n\
404 									    \n\
405 		static inline int					    \n\
406 		%1$s__attach(struct %1$s *skel)				    \n\
407 		{							    \n\
408 			int ret = 0;					    \n\
409 									    \n\
410 		", obj_name);
411 
412 	bpf_object__for_each_program(prog, obj) {
413 		codegen("\
414 			\n\
415 				ret = ret < 0 ? ret : %1$s__%2$s__attach(skel);   \n\
416 			", obj_name, bpf_program__name(prog));
417 	}
418 
419 	codegen("\
420 		\n\
421 			return ret < 0 ? ret : 0;			    \n\
422 		}							    \n\
423 									    \n\
424 		static inline void					    \n\
425 		%1$s__detach(struct %1$s *skel)				    \n\
426 		{							    \n\
427 		", obj_name);
428 
429 	bpf_object__for_each_program(prog, obj) {
430 		codegen("\
431 			\n\
432 				skel_closenz(skel->links.%1$s_fd);	    \n\
433 			", bpf_program__name(prog));
434 	}
435 
436 	codegen("\
437 		\n\
438 		}							    \n\
439 		");
440 }
441 
442 static void codegen_destroy(struct bpf_object *obj, const char *obj_name)
443 {
444 	struct bpf_program *prog;
445 	struct bpf_map *map;
446 	char ident[256];
447 
448 	codegen("\
449 		\n\
450 		static void						    \n\
451 		%1$s__destroy(struct %1$s *skel)			    \n\
452 		{							    \n\
453 			if (!skel)					    \n\
454 				return;					    \n\
455 			%1$s__detach(skel);				    \n\
456 		",
457 		obj_name);
458 
459 	bpf_object__for_each_program(prog, obj) {
460 		codegen("\
461 			\n\
462 				skel_closenz(skel->progs.%1$s.prog_fd);	    \n\
463 			", bpf_program__name(prog));
464 	}
465 
466 	bpf_object__for_each_map(map, obj) {
467 		if (!get_map_ident(map, ident, sizeof(ident)))
468 			continue;
469 		if (bpf_map__is_internal(map) &&
470 		    (bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
471 			printf("\tmunmap(skel->%1$s, %2$zd);\n",
472 			       ident, bpf_map_mmap_sz(map));
473 		codegen("\
474 			\n\
475 				skel_closenz(skel->maps.%1$s.map_fd);	    \n\
476 			", ident);
477 	}
478 	codegen("\
479 		\n\
480 			free(skel);					    \n\
481 		}							    \n\
482 		",
483 		obj_name);
484 }
485 
486 static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *header_guard)
487 {
488 	struct bpf_object_load_attr load_attr = {};
489 	DECLARE_LIBBPF_OPTS(gen_loader_opts, opts);
490 	struct bpf_map *map;
491 	char ident[256];
492 	int err = 0;
493 
494 	err = bpf_object__gen_loader(obj, &opts);
495 	if (err)
496 		return err;
497 
498 	load_attr.obj = obj;
499 	if (verifier_logs)
500 		/* log_level1 + log_level2 + stats, but not stable UAPI */
501 		load_attr.log_level = 1 + 2 + 4;
502 
503 	err = bpf_object__load_xattr(&load_attr);
504 	if (err) {
505 		p_err("failed to load object file");
506 		goto out;
507 	}
508 	/* If there was no error during load then gen_loader_opts
509 	 * are populated with the loader program.
510 	 */
511 
512 	/* finish generating 'struct skel' */
513 	codegen("\
514 		\n\
515 		};							    \n\
516 		", obj_name);
517 
518 
519 	codegen_attach_detach(obj, obj_name);
520 
521 	codegen_destroy(obj, obj_name);
522 
523 	codegen("\
524 		\n\
525 		static inline struct %1$s *				    \n\
526 		%1$s__open(void)					    \n\
527 		{							    \n\
528 			struct %1$s *skel;				    \n\
529 									    \n\
530 			skel = calloc(sizeof(*skel), 1);		    \n\
531 			if (!skel)					    \n\
532 				goto cleanup;				    \n\
533 			skel->ctx.sz = (void *)&skel->links - (void *)skel; \n\
534 		",
535 		obj_name, opts.data_sz);
536 	bpf_object__for_each_map(map, obj) {
537 		const void *mmap_data = NULL;
538 		size_t mmap_size = 0;
539 
540 		if (!get_map_ident(map, ident, sizeof(ident)))
541 			continue;
542 
543 		if (!bpf_map__is_internal(map) ||
544 		    !(bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
545 			continue;
546 
547 		codegen("\
548 			\n\
549 				skel->%1$s =					 \n\
550 					mmap(NULL, %2$zd, PROT_READ | PROT_WRITE,\n\
551 					     MAP_SHARED | MAP_ANONYMOUS, -1, 0); \n\
552 				if (skel->%1$s == (void *) -1)			 \n\
553 					goto cleanup;				 \n\
554 				memcpy(skel->%1$s, (void *)\"\\			 \n\
555 			", ident, bpf_map_mmap_sz(map));
556 		mmap_data = bpf_map__initial_value(map, &mmap_size);
557 		print_hex(mmap_data, mmap_size);
558 		printf("\", %2$zd);\n"
559 		       "\tskel->maps.%1$s.initial_value = (__u64)(long)skel->%1$s;\n",
560 		       ident, mmap_size);
561 	}
562 	codegen("\
563 		\n\
564 			return skel;					    \n\
565 		cleanup:						    \n\
566 			%1$s__destroy(skel);				    \n\
567 			return NULL;					    \n\
568 		}							    \n\
569 									    \n\
570 		static inline int					    \n\
571 		%1$s__load(struct %1$s *skel)				    \n\
572 		{							    \n\
573 			struct bpf_load_and_run_opts opts = {};		    \n\
574 			int err;					    \n\
575 									    \n\
576 			opts.ctx = (struct bpf_loader_ctx *)skel;	    \n\
577 			opts.data_sz = %2$d;				    \n\
578 			opts.data = (void *)\"\\			    \n\
579 		",
580 		obj_name, opts.data_sz);
581 	print_hex(opts.data, opts.data_sz);
582 	codegen("\
583 		\n\
584 		\";							    \n\
585 		");
586 
587 	codegen("\
588 		\n\
589 			opts.insns_sz = %d;				    \n\
590 			opts.insns = (void *)\"\\			    \n\
591 		",
592 		opts.insns_sz);
593 	print_hex(opts.insns, opts.insns_sz);
594 	codegen("\
595 		\n\
596 		\";							    \n\
597 			err = bpf_load_and_run(&opts);			    \n\
598 			if (err < 0)					    \n\
599 				return err;				    \n\
600 		", obj_name);
601 	bpf_object__for_each_map(map, obj) {
602 		const char *mmap_flags;
603 
604 		if (!get_map_ident(map, ident, sizeof(ident)))
605 			continue;
606 
607 		if (!bpf_map__is_internal(map) ||
608 		    !(bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
609 			continue;
610 
611 		if (bpf_map__def(map)->map_flags & BPF_F_RDONLY_PROG)
612 			mmap_flags = "PROT_READ";
613 		else
614 			mmap_flags = "PROT_READ | PROT_WRITE";
615 
616 		printf("\tskel->%1$s =\n"
617 		       "\t\tmmap(skel->%1$s, %2$zd, %3$s, MAP_SHARED | MAP_FIXED,\n"
618 		       "\t\t\tskel->maps.%1$s.map_fd, 0);\n",
619 		       ident, bpf_map_mmap_sz(map), mmap_flags);
620 	}
621 	codegen("\
622 		\n\
623 			return 0;					    \n\
624 		}							    \n\
625 									    \n\
626 		static inline struct %1$s *				    \n\
627 		%1$s__open_and_load(void)				    \n\
628 		{							    \n\
629 			struct %1$s *skel;				    \n\
630 									    \n\
631 			skel = %1$s__open();				    \n\
632 			if (!skel)					    \n\
633 				return NULL;				    \n\
634 			if (%1$s__load(skel)) {				    \n\
635 				%1$s__destroy(skel);			    \n\
636 				return NULL;				    \n\
637 			}						    \n\
638 			return skel;					    \n\
639 		}							    \n\
640 		", obj_name);
641 
642 	codegen("\
643 		\n\
644 									    \n\
645 		#endif /* %s */						    \n\
646 		",
647 		header_guard);
648 	err = 0;
649 out:
650 	return err;
651 }
652 
653 static int do_skeleton(int argc, char **argv)
654 {
655 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SKEL_H__")];
656 	size_t i, map_cnt = 0, prog_cnt = 0, file_sz, mmap_sz;
657 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
658 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
659 	struct bpf_object *obj = NULL;
660 	const char *file;
661 	char ident[256];
662 	struct bpf_program *prog;
663 	int fd, err = -1;
664 	struct bpf_map *map;
665 	struct btf *btf;
666 	struct stat st;
667 
668 	if (!REQ_ARGS(1)) {
669 		usage();
670 		return -1;
671 	}
672 	file = GET_ARG();
673 
674 	while (argc) {
675 		if (!REQ_ARGS(2))
676 			return -1;
677 
678 		if (is_prefix(*argv, "name")) {
679 			NEXT_ARG();
680 
681 			if (obj_name[0] != '\0') {
682 				p_err("object name already specified");
683 				return -1;
684 			}
685 
686 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
687 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
688 		} else {
689 			p_err("unknown arg %s", *argv);
690 			return -1;
691 		}
692 
693 		NEXT_ARG();
694 	}
695 
696 	if (argc) {
697 		p_err("extra unknown arguments");
698 		return -1;
699 	}
700 
701 	if (stat(file, &st)) {
702 		p_err("failed to stat() %s: %s", file, strerror(errno));
703 		return -1;
704 	}
705 	file_sz = st.st_size;
706 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
707 	fd = open(file, O_RDONLY);
708 	if (fd < 0) {
709 		p_err("failed to open() %s: %s", file, strerror(errno));
710 		return -1;
711 	}
712 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
713 	if (obj_data == MAP_FAILED) {
714 		obj_data = NULL;
715 		p_err("failed to mmap() %s: %s", file, strerror(errno));
716 		goto out;
717 	}
718 	if (obj_name[0] == '\0')
719 		get_obj_name(obj_name, file);
720 	opts.object_name = obj_name;
721 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
722 	if (IS_ERR(obj)) {
723 		char err_buf[256];
724 
725 		libbpf_strerror(PTR_ERR(obj), err_buf, sizeof(err_buf));
726 		p_err("failed to open BPF object file: %s", err_buf);
727 		obj = NULL;
728 		goto out;
729 	}
730 
731 	bpf_object__for_each_map(map, obj) {
732 		if (!get_map_ident(map, ident, sizeof(ident))) {
733 			p_err("ignoring unrecognized internal map '%s'...",
734 			      bpf_map__name(map));
735 			continue;
736 		}
737 		map_cnt++;
738 	}
739 	bpf_object__for_each_program(prog, obj) {
740 		prog_cnt++;
741 	}
742 
743 	get_header_guard(header_guard, obj_name);
744 	if (use_loader) {
745 		codegen("\
746 		\n\
747 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
748 		/* THIS FILE IS AUTOGENERATED! */			    \n\
749 		#ifndef %2$s						    \n\
750 		#define %2$s						    \n\
751 									    \n\
752 		#include <stdlib.h>					    \n\
753 		#include <bpf/bpf.h>					    \n\
754 		#include <bpf/skel_internal.h>				    \n\
755 									    \n\
756 		struct %1$s {						    \n\
757 			struct bpf_loader_ctx ctx;			    \n\
758 		",
759 		obj_name, header_guard
760 		);
761 	} else {
762 		codegen("\
763 		\n\
764 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
765 									    \n\
766 		/* THIS FILE IS AUTOGENERATED! */			    \n\
767 		#ifndef %2$s						    \n\
768 		#define %2$s						    \n\
769 									    \n\
770 		#include <errno.h>					    \n\
771 		#include <stdlib.h>					    \n\
772 		#include <bpf/libbpf.h>					    \n\
773 									    \n\
774 		struct %1$s {						    \n\
775 			struct bpf_object_skeleton *skeleton;		    \n\
776 			struct bpf_object *obj;				    \n\
777 		",
778 		obj_name, header_guard
779 		);
780 	}
781 
782 	if (map_cnt) {
783 		printf("\tstruct {\n");
784 		bpf_object__for_each_map(map, obj) {
785 			if (!get_map_ident(map, ident, sizeof(ident)))
786 				continue;
787 			if (use_loader)
788 				printf("\t\tstruct bpf_map_desc %s;\n", ident);
789 			else
790 				printf("\t\tstruct bpf_map *%s;\n", ident);
791 		}
792 		printf("\t} maps;\n");
793 	}
794 
795 	if (prog_cnt) {
796 		printf("\tstruct {\n");
797 		bpf_object__for_each_program(prog, obj) {
798 			if (use_loader)
799 				printf("\t\tstruct bpf_prog_desc %s;\n",
800 				       bpf_program__name(prog));
801 			else
802 				printf("\t\tstruct bpf_program *%s;\n",
803 				       bpf_program__name(prog));
804 		}
805 		printf("\t} progs;\n");
806 		printf("\tstruct {\n");
807 		bpf_object__for_each_program(prog, obj) {
808 			if (use_loader)
809 				printf("\t\tint %s_fd;\n",
810 				       bpf_program__name(prog));
811 			else
812 				printf("\t\tstruct bpf_link *%s;\n",
813 				       bpf_program__name(prog));
814 		}
815 		printf("\t} links;\n");
816 	}
817 
818 	btf = bpf_object__btf(obj);
819 	if (btf) {
820 		err = codegen_datasecs(obj, obj_name);
821 		if (err)
822 			goto out;
823 	}
824 	if (use_loader) {
825 		err = gen_trace(obj, obj_name, header_guard);
826 		goto out;
827 	}
828 
829 	codegen("\
830 		\n\
831 		};							    \n\
832 									    \n\
833 		static void						    \n\
834 		%1$s__destroy(struct %1$s *obj)				    \n\
835 		{							    \n\
836 			if (!obj)					    \n\
837 				return;					    \n\
838 			if (obj->skeleton)				    \n\
839 				bpf_object__destroy_skeleton(obj->skeleton);\n\
840 			free(obj);					    \n\
841 		}							    \n\
842 									    \n\
843 		static inline int					    \n\
844 		%1$s__create_skeleton(struct %1$s *obj);		    \n\
845 									    \n\
846 		static inline struct %1$s *				    \n\
847 		%1$s__open_opts(const struct bpf_object_open_opts *opts)    \n\
848 		{							    \n\
849 			struct %1$s *obj;				    \n\
850 			int err;					    \n\
851 									    \n\
852 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
853 			if (!obj) {					    \n\
854 				errno = ENOMEM;				    \n\
855 				return NULL;				    \n\
856 			}						    \n\
857 									    \n\
858 			err = %1$s__create_skeleton(obj);		    \n\
859 			if (err)					    \n\
860 				goto err_out;				    \n\
861 									    \n\
862 			err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
863 			if (err)					    \n\
864 				goto err_out;				    \n\
865 									    \n\
866 			return obj;					    \n\
867 		err_out:						    \n\
868 			%1$s__destroy(obj);				    \n\
869 			errno = -err;					    \n\
870 			return NULL;					    \n\
871 		}							    \n\
872 									    \n\
873 		static inline struct %1$s *				    \n\
874 		%1$s__open(void)					    \n\
875 		{							    \n\
876 			return %1$s__open_opts(NULL);			    \n\
877 		}							    \n\
878 									    \n\
879 		static inline int					    \n\
880 		%1$s__load(struct %1$s *obj)				    \n\
881 		{							    \n\
882 			return bpf_object__load_skeleton(obj->skeleton);    \n\
883 		}							    \n\
884 									    \n\
885 		static inline struct %1$s *				    \n\
886 		%1$s__open_and_load(void)				    \n\
887 		{							    \n\
888 			struct %1$s *obj;				    \n\
889 			int err;					    \n\
890 									    \n\
891 			obj = %1$s__open();				    \n\
892 			if (!obj)					    \n\
893 				return NULL;				    \n\
894 			err = %1$s__load(obj);				    \n\
895 			if (err) {					    \n\
896 				%1$s__destroy(obj);			    \n\
897 				errno = -err;				    \n\
898 				return NULL;				    \n\
899 			}						    \n\
900 			return obj;					    \n\
901 		}							    \n\
902 									    \n\
903 		static inline int					    \n\
904 		%1$s__attach(struct %1$s *obj)				    \n\
905 		{							    \n\
906 			return bpf_object__attach_skeleton(obj->skeleton);  \n\
907 		}							    \n\
908 									    \n\
909 		static inline void					    \n\
910 		%1$s__detach(struct %1$s *obj)				    \n\
911 		{							    \n\
912 			return bpf_object__detach_skeleton(obj->skeleton);  \n\
913 		}							    \n\
914 		",
915 		obj_name
916 	);
917 
918 	codegen("\
919 		\n\
920 									    \n\
921 		static inline const void *%1$s__elf_bytes(size_t *sz);	    \n\
922 									    \n\
923 		static inline int					    \n\
924 		%1$s__create_skeleton(struct %1$s *obj)			    \n\
925 		{							    \n\
926 			struct bpf_object_skeleton *s;			    \n\
927 									    \n\
928 			s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
929 			if (!s)						    \n\
930 				goto err;				    \n\
931 			obj->skeleton = s;				    \n\
932 									    \n\
933 			s->sz = sizeof(*s);				    \n\
934 			s->name = \"%1$s\";				    \n\
935 			s->obj = &obj->obj;				    \n\
936 		",
937 		obj_name
938 	);
939 	if (map_cnt) {
940 		codegen("\
941 			\n\
942 									    \n\
943 				/* maps */				    \n\
944 				s->map_cnt = %zu;			    \n\
945 				s->map_skel_sz = sizeof(*s->maps);	    \n\
946 				s->maps = (struct bpf_map_skeleton *)calloc(s->map_cnt, s->map_skel_sz);\n\
947 				if (!s->maps)				    \n\
948 					goto err;			    \n\
949 			",
950 			map_cnt
951 		);
952 		i = 0;
953 		bpf_object__for_each_map(map, obj) {
954 			if (!get_map_ident(map, ident, sizeof(ident)))
955 				continue;
956 
957 			codegen("\
958 				\n\
959 									    \n\
960 					s->maps[%zu].name = \"%s\";	    \n\
961 					s->maps[%zu].map = &obj->maps.%s;   \n\
962 				",
963 				i, bpf_map__name(map), i, ident);
964 			/* memory-mapped internal maps */
965 			if (bpf_map__is_internal(map) &&
966 			    (bpf_map__def(map)->map_flags & BPF_F_MMAPABLE)) {
967 				printf("\ts->maps[%zu].mmaped = (void **)&obj->%s;\n",
968 				       i, ident);
969 			}
970 			i++;
971 		}
972 	}
973 	if (prog_cnt) {
974 		codegen("\
975 			\n\
976 									    \n\
977 				/* programs */				    \n\
978 				s->prog_cnt = %zu;			    \n\
979 				s->prog_skel_sz = sizeof(*s->progs);	    \n\
980 				s->progs = (struct bpf_prog_skeleton *)calloc(s->prog_cnt, s->prog_skel_sz);\n\
981 				if (!s->progs)				    \n\
982 					goto err;			    \n\
983 			",
984 			prog_cnt
985 		);
986 		i = 0;
987 		bpf_object__for_each_program(prog, obj) {
988 			codegen("\
989 				\n\
990 									    \n\
991 					s->progs[%1$zu].name = \"%2$s\";    \n\
992 					s->progs[%1$zu].prog = &obj->progs.%2$s;\n\
993 					s->progs[%1$zu].link = &obj->links.%2$s;\n\
994 				",
995 				i, bpf_program__name(prog));
996 			i++;
997 		}
998 	}
999 	codegen("\
1000 		\n\
1001 									    \n\
1002 			s->data = (void *)%2$s__elf_bytes(&s->data_sz);	    \n\
1003 									    \n\
1004 			return 0;					    \n\
1005 		err:							    \n\
1006 			bpf_object__destroy_skeleton(s);		    \n\
1007 			return -ENOMEM;					    \n\
1008 		}							    \n\
1009 									    \n\
1010 		static inline const void *%2$s__elf_bytes(size_t *sz)	    \n\
1011 		{							    \n\
1012 			*sz = %1$d;					    \n\
1013 			return (const void *)\"\\			    \n\
1014 		"
1015 		, file_sz, obj_name);
1016 
1017 	/* embed contents of BPF object file */
1018 	print_hex(obj_data, file_sz);
1019 
1020 	codegen("\
1021 		\n\
1022 		\";							    \n\
1023 		}							    \n\
1024 									    \n\
1025 		#endif /* %s */						    \n\
1026 		",
1027 		header_guard);
1028 	err = 0;
1029 out:
1030 	bpf_object__close(obj);
1031 	if (obj_data)
1032 		munmap(obj_data, mmap_sz);
1033 	close(fd);
1034 	return err;
1035 }
1036 
1037 static int do_object(int argc, char **argv)
1038 {
1039 	struct bpf_linker *linker;
1040 	const char *output_file, *file;
1041 	int err = 0;
1042 
1043 	if (!REQ_ARGS(2)) {
1044 		usage();
1045 		return -1;
1046 	}
1047 
1048 	output_file = GET_ARG();
1049 
1050 	linker = bpf_linker__new(output_file, NULL);
1051 	if (!linker) {
1052 		p_err("failed to create BPF linker instance");
1053 		return -1;
1054 	}
1055 
1056 	while (argc) {
1057 		file = GET_ARG();
1058 
1059 		err = bpf_linker__add_file(linker, file, NULL);
1060 		if (err) {
1061 			p_err("failed to link '%s': %s (%d)", file, strerror(err), err);
1062 			goto out;
1063 		}
1064 	}
1065 
1066 	err = bpf_linker__finalize(linker);
1067 	if (err) {
1068 		p_err("failed to finalize ELF file: %s (%d)", strerror(err), err);
1069 		goto out;
1070 	}
1071 
1072 	err = 0;
1073 out:
1074 	bpf_linker__free(linker);
1075 	return err;
1076 }
1077 
1078 static int do_help(int argc, char **argv)
1079 {
1080 	if (json_output) {
1081 		jsonw_null(json_wtr);
1082 		return 0;
1083 	}
1084 
1085 	fprintf(stderr,
1086 		"Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
1087 		"       %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
1088 		"       %1$s %2$s help\n"
1089 		"\n"
1090 		"       " HELP_SPEC_OPTIONS " |\n"
1091 		"                    {-L|--use-loader} }\n"
1092 		"",
1093 		bin_name, "gen");
1094 
1095 	return 0;
1096 }
1097 
1098 static const struct cmd cmds[] = {
1099 	{ "object",	do_object },
1100 	{ "skeleton",	do_skeleton },
1101 	{ "help",	do_help },
1102 	{ 0 }
1103 };
1104 
1105 int do_gen(int argc, char **argv)
1106 {
1107 	return cmd_select(cmds, argc, argv, do_help);
1108 }
1109