xref: /openbmc/linux/tools/bpf/bpftool/gen.c (revision 2cf1c348)
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, codegen_btf_dump_printf, NULL, NULL);
222 	err = libbpf_get_error(d);
223 	if (err)
224 		return err;
225 
226 	bpf_object__for_each_map(map, obj) {
227 		/* only generate definitions for memory-mapped internal maps */
228 		if (!bpf_map__is_internal(map))
229 			continue;
230 		if (!(bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
231 			continue;
232 
233 		if (!get_map_ident(map, map_ident, sizeof(map_ident)))
234 			continue;
235 
236 		sec = NULL;
237 		for (i = 1; i < n; i++) {
238 			const struct btf_type *t = btf__type_by_id(btf, i);
239 			const char *name;
240 
241 			if (!btf_is_datasec(t))
242 				continue;
243 
244 			name = btf__str_by_offset(btf, t->name_off);
245 			if (!get_datasec_ident(name, sec_ident, sizeof(sec_ident)))
246 				continue;
247 
248 			if (strcmp(sec_ident, map_ident) == 0) {
249 				sec = t;
250 				break;
251 			}
252 		}
253 
254 		/* In some cases (e.g., sections like .rodata.cst16 containing
255 		 * compiler allocated string constants only) there will be
256 		 * special internal maps with no corresponding DATASEC BTF
257 		 * type. In such case, generate empty structs for each such
258 		 * map. It will still be memory-mapped and its contents
259 		 * accessible from user-space through BPF skeleton.
260 		 */
261 		if (!sec) {
262 			printf("	struct %s__%s {\n", obj_name, map_ident);
263 			printf("	} *%s;\n", map_ident);
264 		} else {
265 			err = codegen_datasec_def(obj, btf, d, sec, obj_name);
266 			if (err)
267 				goto out;
268 		}
269 	}
270 
271 
272 out:
273 	btf_dump__free(d);
274 	return err;
275 }
276 
277 static void codegen(const char *template, ...)
278 {
279 	const char *src, *end;
280 	int skip_tabs = 0, n;
281 	char *s, *dst;
282 	va_list args;
283 	char c;
284 
285 	n = strlen(template);
286 	s = malloc(n + 1);
287 	if (!s)
288 		exit(-1);
289 	src = template;
290 	dst = s;
291 
292 	/* find out "baseline" indentation to skip */
293 	while ((c = *src++)) {
294 		if (c == '\t') {
295 			skip_tabs++;
296 		} else if (c == '\n') {
297 			break;
298 		} else {
299 			p_err("unrecognized character at pos %td in template '%s': '%c'",
300 			      src - template - 1, template, c);
301 			free(s);
302 			exit(-1);
303 		}
304 	}
305 
306 	while (*src) {
307 		/* skip baseline indentation tabs */
308 		for (n = skip_tabs; n > 0; n--, src++) {
309 			if (*src != '\t') {
310 				p_err("not enough tabs at pos %td in template '%s'",
311 				      src - template - 1, template);
312 				free(s);
313 				exit(-1);
314 			}
315 		}
316 		/* trim trailing whitespace */
317 		end = strchrnul(src, '\n');
318 		for (n = end - src; n > 0 && isspace(src[n - 1]); n--)
319 			;
320 		memcpy(dst, src, n);
321 		dst += n;
322 		if (*end)
323 			*dst++ = '\n';
324 		src = *end ? end + 1 : end;
325 	}
326 	*dst++ = '\0';
327 
328 	/* print out using adjusted template */
329 	va_start(args, template);
330 	n = vprintf(s, args);
331 	va_end(args);
332 
333 	free(s);
334 }
335 
336 static void print_hex(const char *data, int data_sz)
337 {
338 	int i, len;
339 
340 	for (i = 0, len = 0; i < data_sz; i++) {
341 		int w = data[i] ? 4 : 2;
342 
343 		len += w;
344 		if (len > 78) {
345 			printf("\\\n");
346 			len = w;
347 		}
348 		if (!data[i])
349 			printf("\\0");
350 		else
351 			printf("\\x%02x", (unsigned char)data[i]);
352 	}
353 }
354 
355 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
356 {
357 	long page_sz = sysconf(_SC_PAGE_SIZE);
358 	size_t map_sz;
359 
360 	map_sz = (size_t)roundup(bpf_map__value_size(map), 8) * bpf_map__max_entries(map);
361 	map_sz = roundup(map_sz, page_sz);
362 	return map_sz;
363 }
364 
365 static void codegen_attach_detach(struct bpf_object *obj, const char *obj_name)
366 {
367 	struct bpf_program *prog;
368 
369 	bpf_object__for_each_program(prog, obj) {
370 		const char *tp_name;
371 
372 		codegen("\
373 			\n\
374 			\n\
375 			static inline int					    \n\
376 			%1$s__%2$s__attach(struct %1$s *skel)			    \n\
377 			{							    \n\
378 				int prog_fd = skel->progs.%2$s.prog_fd;		    \n\
379 			", obj_name, bpf_program__name(prog));
380 
381 		switch (bpf_program__get_type(prog)) {
382 		case BPF_PROG_TYPE_RAW_TRACEPOINT:
383 			tp_name = strchr(bpf_program__section_name(prog), '/') + 1;
384 			printf("\tint fd = bpf_raw_tracepoint_open(\"%s\", prog_fd);\n", tp_name);
385 			break;
386 		case BPF_PROG_TYPE_TRACING:
387 			printf("\tint fd = bpf_raw_tracepoint_open(NULL, prog_fd);\n");
388 			break;
389 		default:
390 			printf("\tint fd = ((void)prog_fd, 0); /* auto-attach not supported */\n");
391 			break;
392 		}
393 		codegen("\
394 			\n\
395 										    \n\
396 				if (fd > 0)					    \n\
397 					skel->links.%1$s_fd = fd;		    \n\
398 				return fd;					    \n\
399 			}							    \n\
400 			", bpf_program__name(prog));
401 	}
402 
403 	codegen("\
404 		\n\
405 									    \n\
406 		static inline int					    \n\
407 		%1$s__attach(struct %1$s *skel)				    \n\
408 		{							    \n\
409 			int ret = 0;					    \n\
410 									    \n\
411 		", obj_name);
412 
413 	bpf_object__for_each_program(prog, obj) {
414 		codegen("\
415 			\n\
416 				ret = ret < 0 ? ret : %1$s__%2$s__attach(skel);   \n\
417 			", obj_name, bpf_program__name(prog));
418 	}
419 
420 	codegen("\
421 		\n\
422 			return ret < 0 ? ret : 0;			    \n\
423 		}							    \n\
424 									    \n\
425 		static inline void					    \n\
426 		%1$s__detach(struct %1$s *skel)				    \n\
427 		{							    \n\
428 		", obj_name);
429 
430 	bpf_object__for_each_program(prog, obj) {
431 		codegen("\
432 			\n\
433 				skel_closenz(skel->links.%1$s_fd);	    \n\
434 			", bpf_program__name(prog));
435 	}
436 
437 	codegen("\
438 		\n\
439 		}							    \n\
440 		");
441 }
442 
443 static void codegen_destroy(struct bpf_object *obj, const char *obj_name)
444 {
445 	struct bpf_program *prog;
446 	struct bpf_map *map;
447 	char ident[256];
448 
449 	codegen("\
450 		\n\
451 		static void						    \n\
452 		%1$s__destroy(struct %1$s *skel)			    \n\
453 		{							    \n\
454 			if (!skel)					    \n\
455 				return;					    \n\
456 			%1$s__detach(skel);				    \n\
457 		",
458 		obj_name);
459 
460 	bpf_object__for_each_program(prog, obj) {
461 		codegen("\
462 			\n\
463 				skel_closenz(skel->progs.%1$s.prog_fd);	    \n\
464 			", bpf_program__name(prog));
465 	}
466 
467 	bpf_object__for_each_map(map, obj) {
468 		if (!get_map_ident(map, ident, sizeof(ident)))
469 			continue;
470 		if (bpf_map__is_internal(map) &&
471 		    (bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
472 			printf("\tmunmap(skel->%1$s, %2$zd);\n",
473 			       ident, bpf_map_mmap_sz(map));
474 		codegen("\
475 			\n\
476 				skel_closenz(skel->maps.%1$s.map_fd);	    \n\
477 			", ident);
478 	}
479 	codegen("\
480 		\n\
481 			free(skel);					    \n\
482 		}							    \n\
483 		",
484 		obj_name);
485 }
486 
487 static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *header_guard)
488 {
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 	err = bpf_object__load(obj);
499 	if (err) {
500 		p_err("failed to load object file");
501 		goto out;
502 	}
503 	/* If there was no error during load then gen_loader_opts
504 	 * are populated with the loader program.
505 	 */
506 
507 	/* finish generating 'struct skel' */
508 	codegen("\
509 		\n\
510 		};							    \n\
511 		", obj_name);
512 
513 
514 	codegen_attach_detach(obj, obj_name);
515 
516 	codegen_destroy(obj, obj_name);
517 
518 	codegen("\
519 		\n\
520 		static inline struct %1$s *				    \n\
521 		%1$s__open(void)					    \n\
522 		{							    \n\
523 			struct %1$s *skel;				    \n\
524 									    \n\
525 			skel = calloc(sizeof(*skel), 1);		    \n\
526 			if (!skel)					    \n\
527 				goto cleanup;				    \n\
528 			skel->ctx.sz = (void *)&skel->links - (void *)skel; \n\
529 		",
530 		obj_name, opts.data_sz);
531 	bpf_object__for_each_map(map, obj) {
532 		const void *mmap_data = NULL;
533 		size_t mmap_size = 0;
534 
535 		if (!get_map_ident(map, ident, sizeof(ident)))
536 			continue;
537 
538 		if (!bpf_map__is_internal(map) ||
539 		    !(bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
540 			continue;
541 
542 		codegen("\
543 			\n\
544 				skel->%1$s =					 \n\
545 					mmap(NULL, %2$zd, PROT_READ | PROT_WRITE,\n\
546 					     MAP_SHARED | MAP_ANONYMOUS, -1, 0); \n\
547 				if (skel->%1$s == (void *) -1)			 \n\
548 					goto cleanup;				 \n\
549 				memcpy(skel->%1$s, (void *)\"\\			 \n\
550 			", ident, bpf_map_mmap_sz(map));
551 		mmap_data = bpf_map__initial_value(map, &mmap_size);
552 		print_hex(mmap_data, mmap_size);
553 		printf("\", %2$zd);\n"
554 		       "\tskel->maps.%1$s.initial_value = (__u64)(long)skel->%1$s;\n",
555 		       ident, mmap_size);
556 	}
557 	codegen("\
558 		\n\
559 			return skel;					    \n\
560 		cleanup:						    \n\
561 			%1$s__destroy(skel);				    \n\
562 			return NULL;					    \n\
563 		}							    \n\
564 									    \n\
565 		static inline int					    \n\
566 		%1$s__load(struct %1$s *skel)				    \n\
567 		{							    \n\
568 			struct bpf_load_and_run_opts opts = {};		    \n\
569 			int err;					    \n\
570 									    \n\
571 			opts.ctx = (struct bpf_loader_ctx *)skel;	    \n\
572 			opts.data_sz = %2$d;				    \n\
573 			opts.data = (void *)\"\\			    \n\
574 		",
575 		obj_name, opts.data_sz);
576 	print_hex(opts.data, opts.data_sz);
577 	codegen("\
578 		\n\
579 		\";							    \n\
580 		");
581 
582 	codegen("\
583 		\n\
584 			opts.insns_sz = %d;				    \n\
585 			opts.insns = (void *)\"\\			    \n\
586 		",
587 		opts.insns_sz);
588 	print_hex(opts.insns, opts.insns_sz);
589 	codegen("\
590 		\n\
591 		\";							    \n\
592 			err = bpf_load_and_run(&opts);			    \n\
593 			if (err < 0)					    \n\
594 				return err;				    \n\
595 		", obj_name);
596 	bpf_object__for_each_map(map, obj) {
597 		const char *mmap_flags;
598 
599 		if (!get_map_ident(map, ident, sizeof(ident)))
600 			continue;
601 
602 		if (!bpf_map__is_internal(map) ||
603 		    !(bpf_map__def(map)->map_flags & BPF_F_MMAPABLE))
604 			continue;
605 
606 		if (bpf_map__def(map)->map_flags & BPF_F_RDONLY_PROG)
607 			mmap_flags = "PROT_READ";
608 		else
609 			mmap_flags = "PROT_READ | PROT_WRITE";
610 
611 		printf("\tskel->%1$s =\n"
612 		       "\t\tmmap(skel->%1$s, %2$zd, %3$s, MAP_SHARED | MAP_FIXED,\n"
613 		       "\t\t\tskel->maps.%1$s.map_fd, 0);\n",
614 		       ident, bpf_map_mmap_sz(map), mmap_flags);
615 	}
616 	codegen("\
617 		\n\
618 			return 0;					    \n\
619 		}							    \n\
620 									    \n\
621 		static inline struct %1$s *				    \n\
622 		%1$s__open_and_load(void)				    \n\
623 		{							    \n\
624 			struct %1$s *skel;				    \n\
625 									    \n\
626 			skel = %1$s__open();				    \n\
627 			if (!skel)					    \n\
628 				return NULL;				    \n\
629 			if (%1$s__load(skel)) {				    \n\
630 				%1$s__destroy(skel);			    \n\
631 				return NULL;				    \n\
632 			}						    \n\
633 			return skel;					    \n\
634 		}							    \n\
635 		", obj_name);
636 
637 	codegen("\
638 		\n\
639 									    \n\
640 		#endif /* %s */						    \n\
641 		",
642 		header_guard);
643 	err = 0;
644 out:
645 	return err;
646 }
647 
648 static int do_skeleton(int argc, char **argv)
649 {
650 	char header_guard[MAX_OBJ_NAME_LEN + sizeof("__SKEL_H__")];
651 	size_t i, map_cnt = 0, prog_cnt = 0, file_sz, mmap_sz;
652 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
653 	char obj_name[MAX_OBJ_NAME_LEN] = "", *obj_data;
654 	struct bpf_object *obj = NULL;
655 	const char *file;
656 	char ident[256];
657 	struct bpf_program *prog;
658 	int fd, err = -1;
659 	struct bpf_map *map;
660 	struct btf *btf;
661 	struct stat st;
662 
663 	if (!REQ_ARGS(1)) {
664 		usage();
665 		return -1;
666 	}
667 	file = GET_ARG();
668 
669 	while (argc) {
670 		if (!REQ_ARGS(2))
671 			return -1;
672 
673 		if (is_prefix(*argv, "name")) {
674 			NEXT_ARG();
675 
676 			if (obj_name[0] != '\0') {
677 				p_err("object name already specified");
678 				return -1;
679 			}
680 
681 			strncpy(obj_name, *argv, MAX_OBJ_NAME_LEN - 1);
682 			obj_name[MAX_OBJ_NAME_LEN - 1] = '\0';
683 		} else {
684 			p_err("unknown arg %s", *argv);
685 			return -1;
686 		}
687 
688 		NEXT_ARG();
689 	}
690 
691 	if (argc) {
692 		p_err("extra unknown arguments");
693 		return -1;
694 	}
695 
696 	if (stat(file, &st)) {
697 		p_err("failed to stat() %s: %s", file, strerror(errno));
698 		return -1;
699 	}
700 	file_sz = st.st_size;
701 	mmap_sz = roundup(file_sz, sysconf(_SC_PAGE_SIZE));
702 	fd = open(file, O_RDONLY);
703 	if (fd < 0) {
704 		p_err("failed to open() %s: %s", file, strerror(errno));
705 		return -1;
706 	}
707 	obj_data = mmap(NULL, mmap_sz, PROT_READ, MAP_PRIVATE, fd, 0);
708 	if (obj_data == MAP_FAILED) {
709 		obj_data = NULL;
710 		p_err("failed to mmap() %s: %s", file, strerror(errno));
711 		goto out;
712 	}
713 	if (obj_name[0] == '\0')
714 		get_obj_name(obj_name, file);
715 	opts.object_name = obj_name;
716 	if (verifier_logs)
717 		/* log_level1 + log_level2 + stats, but not stable UAPI */
718 		opts.kernel_log_level = 1 + 2 + 4;
719 	obj = bpf_object__open_mem(obj_data, file_sz, &opts);
720 	err = libbpf_get_error(obj);
721 	if (err) {
722 		char err_buf[256];
723 
724 		libbpf_strerror(err, err_buf, sizeof(err_buf));
725 		p_err("failed to open BPF object file: %s", err_buf);
726 		obj = NULL;
727 		goto out;
728 	}
729 
730 	bpf_object__for_each_map(map, obj) {
731 		if (!get_map_ident(map, ident, sizeof(ident))) {
732 			p_err("ignoring unrecognized internal map '%s'...",
733 			      bpf_map__name(map));
734 			continue;
735 		}
736 		map_cnt++;
737 	}
738 	bpf_object__for_each_program(prog, obj) {
739 		prog_cnt++;
740 	}
741 
742 	get_header_guard(header_guard, obj_name);
743 	if (use_loader) {
744 		codegen("\
745 		\n\
746 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
747 		/* THIS FILE IS AUTOGENERATED! */			    \n\
748 		#ifndef %2$s						    \n\
749 		#define %2$s						    \n\
750 									    \n\
751 		#include <stdlib.h>					    \n\
752 		#include <bpf/bpf.h>					    \n\
753 		#include <bpf/skel_internal.h>				    \n\
754 									    \n\
755 		struct %1$s {						    \n\
756 			struct bpf_loader_ctx ctx;			    \n\
757 		",
758 		obj_name, header_guard
759 		);
760 	} else {
761 		codegen("\
762 		\n\
763 		/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */   \n\
764 									    \n\
765 		/* THIS FILE IS AUTOGENERATED! */			    \n\
766 		#ifndef %2$s						    \n\
767 		#define %2$s						    \n\
768 									    \n\
769 		#include <errno.h>					    \n\
770 		#include <stdlib.h>					    \n\
771 		#include <bpf/libbpf.h>					    \n\
772 									    \n\
773 		struct %1$s {						    \n\
774 			struct bpf_object_skeleton *skeleton;		    \n\
775 			struct bpf_object *obj;				    \n\
776 		",
777 		obj_name, header_guard
778 		);
779 	}
780 
781 	if (map_cnt) {
782 		printf("\tstruct {\n");
783 		bpf_object__for_each_map(map, obj) {
784 			if (!get_map_ident(map, ident, sizeof(ident)))
785 				continue;
786 			if (use_loader)
787 				printf("\t\tstruct bpf_map_desc %s;\n", ident);
788 			else
789 				printf("\t\tstruct bpf_map *%s;\n", ident);
790 		}
791 		printf("\t} maps;\n");
792 	}
793 
794 	if (prog_cnt) {
795 		printf("\tstruct {\n");
796 		bpf_object__for_each_program(prog, obj) {
797 			if (use_loader)
798 				printf("\t\tstruct bpf_prog_desc %s;\n",
799 				       bpf_program__name(prog));
800 			else
801 				printf("\t\tstruct bpf_program *%s;\n",
802 				       bpf_program__name(prog));
803 		}
804 		printf("\t} progs;\n");
805 		printf("\tstruct {\n");
806 		bpf_object__for_each_program(prog, obj) {
807 			if (use_loader)
808 				printf("\t\tint %s_fd;\n",
809 				       bpf_program__name(prog));
810 			else
811 				printf("\t\tstruct bpf_link *%s;\n",
812 				       bpf_program__name(prog));
813 		}
814 		printf("\t} links;\n");
815 	}
816 
817 	btf = bpf_object__btf(obj);
818 	if (btf) {
819 		err = codegen_datasecs(obj, obj_name);
820 		if (err)
821 			goto out;
822 	}
823 	if (use_loader) {
824 		err = gen_trace(obj, obj_name, header_guard);
825 		goto out;
826 	}
827 
828 	codegen("\
829 		\n\
830 		};							    \n\
831 									    \n\
832 		static void						    \n\
833 		%1$s__destroy(struct %1$s *obj)				    \n\
834 		{							    \n\
835 			if (!obj)					    \n\
836 				return;					    \n\
837 			if (obj->skeleton)				    \n\
838 				bpf_object__destroy_skeleton(obj->skeleton);\n\
839 			free(obj);					    \n\
840 		}							    \n\
841 									    \n\
842 		static inline int					    \n\
843 		%1$s__create_skeleton(struct %1$s *obj);		    \n\
844 									    \n\
845 		static inline struct %1$s *				    \n\
846 		%1$s__open_opts(const struct bpf_object_open_opts *opts)    \n\
847 		{							    \n\
848 			struct %1$s *obj;				    \n\
849 			int err;					    \n\
850 									    \n\
851 			obj = (struct %1$s *)calloc(1, sizeof(*obj));	    \n\
852 			if (!obj) {					    \n\
853 				errno = ENOMEM;				    \n\
854 				return NULL;				    \n\
855 			}						    \n\
856 									    \n\
857 			err = %1$s__create_skeleton(obj);		    \n\
858 			if (err)					    \n\
859 				goto err_out;				    \n\
860 									    \n\
861 			err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
862 			if (err)					    \n\
863 				goto err_out;				    \n\
864 									    \n\
865 			return obj;					    \n\
866 		err_out:						    \n\
867 			%1$s__destroy(obj);				    \n\
868 			errno = -err;					    \n\
869 			return NULL;					    \n\
870 		}							    \n\
871 									    \n\
872 		static inline struct %1$s *				    \n\
873 		%1$s__open(void)					    \n\
874 		{							    \n\
875 			return %1$s__open_opts(NULL);			    \n\
876 		}							    \n\
877 									    \n\
878 		static inline int					    \n\
879 		%1$s__load(struct %1$s *obj)				    \n\
880 		{							    \n\
881 			return bpf_object__load_skeleton(obj->skeleton);    \n\
882 		}							    \n\
883 									    \n\
884 		static inline struct %1$s *				    \n\
885 		%1$s__open_and_load(void)				    \n\
886 		{							    \n\
887 			struct %1$s *obj;				    \n\
888 			int err;					    \n\
889 									    \n\
890 			obj = %1$s__open();				    \n\
891 			if (!obj)					    \n\
892 				return NULL;				    \n\
893 			err = %1$s__load(obj);				    \n\
894 			if (err) {					    \n\
895 				%1$s__destroy(obj);			    \n\
896 				errno = -err;				    \n\
897 				return NULL;				    \n\
898 			}						    \n\
899 			return obj;					    \n\
900 		}							    \n\
901 									    \n\
902 		static inline int					    \n\
903 		%1$s__attach(struct %1$s *obj)				    \n\
904 		{							    \n\
905 			return bpf_object__attach_skeleton(obj->skeleton);  \n\
906 		}							    \n\
907 									    \n\
908 		static inline void					    \n\
909 		%1$s__detach(struct %1$s *obj)				    \n\
910 		{							    \n\
911 			return bpf_object__detach_skeleton(obj->skeleton);  \n\
912 		}							    \n\
913 		",
914 		obj_name
915 	);
916 
917 	codegen("\
918 		\n\
919 									    \n\
920 		static inline const void *%1$s__elf_bytes(size_t *sz);	    \n\
921 									    \n\
922 		static inline int					    \n\
923 		%1$s__create_skeleton(struct %1$s *obj)			    \n\
924 		{							    \n\
925 			struct bpf_object_skeleton *s;			    \n\
926 									    \n\
927 			s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
928 			if (!s)						    \n\
929 				goto err;				    \n\
930 			obj->skeleton = s;				    \n\
931 									    \n\
932 			s->sz = sizeof(*s);				    \n\
933 			s->name = \"%1$s\";				    \n\
934 			s->obj = &obj->obj;				    \n\
935 		",
936 		obj_name
937 	);
938 	if (map_cnt) {
939 		codegen("\
940 			\n\
941 									    \n\
942 				/* maps */				    \n\
943 				s->map_cnt = %zu;			    \n\
944 				s->map_skel_sz = sizeof(*s->maps);	    \n\
945 				s->maps = (struct bpf_map_skeleton *)calloc(s->map_cnt, s->map_skel_sz);\n\
946 				if (!s->maps)				    \n\
947 					goto err;			    \n\
948 			",
949 			map_cnt
950 		);
951 		i = 0;
952 		bpf_object__for_each_map(map, obj) {
953 			if (!get_map_ident(map, ident, sizeof(ident)))
954 				continue;
955 
956 			codegen("\
957 				\n\
958 									    \n\
959 					s->maps[%zu].name = \"%s\";	    \n\
960 					s->maps[%zu].map = &obj->maps.%s;   \n\
961 				",
962 				i, bpf_map__name(map), i, ident);
963 			/* memory-mapped internal maps */
964 			if (bpf_map__is_internal(map) &&
965 			    (bpf_map__def(map)->map_flags & BPF_F_MMAPABLE)) {
966 				printf("\ts->maps[%zu].mmaped = (void **)&obj->%s;\n",
967 				       i, ident);
968 			}
969 			i++;
970 		}
971 	}
972 	if (prog_cnt) {
973 		codegen("\
974 			\n\
975 									    \n\
976 				/* programs */				    \n\
977 				s->prog_cnt = %zu;			    \n\
978 				s->prog_skel_sz = sizeof(*s->progs);	    \n\
979 				s->progs = (struct bpf_prog_skeleton *)calloc(s->prog_cnt, s->prog_skel_sz);\n\
980 				if (!s->progs)				    \n\
981 					goto err;			    \n\
982 			",
983 			prog_cnt
984 		);
985 		i = 0;
986 		bpf_object__for_each_program(prog, obj) {
987 			codegen("\
988 				\n\
989 									    \n\
990 					s->progs[%1$zu].name = \"%2$s\";    \n\
991 					s->progs[%1$zu].prog = &obj->progs.%2$s;\n\
992 					s->progs[%1$zu].link = &obj->links.%2$s;\n\
993 				",
994 				i, bpf_program__name(prog));
995 			i++;
996 		}
997 	}
998 	codegen("\
999 		\n\
1000 									    \n\
1001 			s->data = (void *)%2$s__elf_bytes(&s->data_sz);	    \n\
1002 									    \n\
1003 			return 0;					    \n\
1004 		err:							    \n\
1005 			bpf_object__destroy_skeleton(s);		    \n\
1006 			return -ENOMEM;					    \n\
1007 		}							    \n\
1008 									    \n\
1009 		static inline const void *%2$s__elf_bytes(size_t *sz)	    \n\
1010 		{							    \n\
1011 			*sz = %1$d;					    \n\
1012 			return (const void *)\"\\			    \n\
1013 		"
1014 		, file_sz, obj_name);
1015 
1016 	/* embed contents of BPF object file */
1017 	print_hex(obj_data, file_sz);
1018 
1019 	codegen("\
1020 		\n\
1021 		\";							    \n\
1022 		}							    \n\
1023 									    \n\
1024 		#endif /* %s */						    \n\
1025 		",
1026 		header_guard);
1027 	err = 0;
1028 out:
1029 	bpf_object__close(obj);
1030 	if (obj_data)
1031 		munmap(obj_data, mmap_sz);
1032 	close(fd);
1033 	return err;
1034 }
1035 
1036 static int do_object(int argc, char **argv)
1037 {
1038 	struct bpf_linker *linker;
1039 	const char *output_file, *file;
1040 	int err = 0;
1041 
1042 	if (!REQ_ARGS(2)) {
1043 		usage();
1044 		return -1;
1045 	}
1046 
1047 	output_file = GET_ARG();
1048 
1049 	linker = bpf_linker__new(output_file, NULL);
1050 	if (!linker) {
1051 		p_err("failed to create BPF linker instance");
1052 		return -1;
1053 	}
1054 
1055 	while (argc) {
1056 		file = GET_ARG();
1057 
1058 		err = bpf_linker__add_file(linker, file, NULL);
1059 		if (err) {
1060 			p_err("failed to link '%s': %s (%d)", file, strerror(err), err);
1061 			goto out;
1062 		}
1063 	}
1064 
1065 	err = bpf_linker__finalize(linker);
1066 	if (err) {
1067 		p_err("failed to finalize ELF file: %s (%d)", strerror(err), err);
1068 		goto out;
1069 	}
1070 
1071 	err = 0;
1072 out:
1073 	bpf_linker__free(linker);
1074 	return err;
1075 }
1076 
1077 static int do_help(int argc, char **argv)
1078 {
1079 	if (json_output) {
1080 		jsonw_null(json_wtr);
1081 		return 0;
1082 	}
1083 
1084 	fprintf(stderr,
1085 		"Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
1086 		"       %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
1087 		"       %1$s %2$s help\n"
1088 		"\n"
1089 		"       " HELP_SPEC_OPTIONS " |\n"
1090 		"                    {-L|--use-loader} }\n"
1091 		"",
1092 		bin_name, "gen");
1093 
1094 	return 0;
1095 }
1096 
1097 static const struct cmd cmds[] = {
1098 	{ "object",	do_object },
1099 	{ "skeleton",	do_skeleton },
1100 	{ "help",	do_help },
1101 	{ 0 }
1102 };
1103 
1104 int do_gen(int argc, char **argv)
1105 {
1106 	return cmd_select(cmds, argc, argv, do_help);
1107 }
1108