1.. SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2
3================
4bpftool-gen
5================
6-------------------------------------------------------------------------------
7tool for BPF code-generation
8-------------------------------------------------------------------------------
9
10:Manual section: 8
11
12.. include:: substitutions.rst
13
14SYNOPSIS
15========
16
17	**bpftool** [*OPTIONS*] **gen** *COMMAND*
18
19	*OPTIONS* := { |COMMON_OPTIONS| | { **-L** | **--use-loader** } }
20
21	*COMMAND* := { **object** | **skeleton** | **help** }
22
23GEN COMMANDS
24=============
25
26|	**bpftool** **gen object** *OUTPUT_FILE* *INPUT_FILE* [*INPUT_FILE*...]
27|	**bpftool** **gen skeleton** *FILE* [**name** *OBJECT_NAME*]
28|	**bpftool** **gen help**
29
30DESCRIPTION
31===========
32	**bpftool gen object** *OUTPUT_FILE* *INPUT_FILE* [*INPUT_FILE*...]
33		  Statically link (combine) together one or more *INPUT_FILE*'s
34		  into a single resulting *OUTPUT_FILE*. All the files involved
35		  are BPF ELF object files.
36
37		  The rules of BPF static linking are mostly the same as for
38		  user-space object files, but in addition to combining data
39		  and instruction sections, .BTF and .BTF.ext (if present in
40		  any of the input files) data are combined together. .BTF
41		  data is deduplicated, so all the common types across
42		  *INPUT_FILE*'s will only be represented once in the resulting
43		  BTF information.
44
45		  BPF static linking allows to partition BPF source code into
46		  individually compiled files that are then linked into
47		  a single resulting BPF object file, which can be used to
48		  generated BPF skeleton (with **gen skeleton** command) or
49		  passed directly into **libbpf** (using **bpf_object__open()**
50		  family of APIs).
51
52	**bpftool gen skeleton** *FILE*
53		  Generate BPF skeleton C header file for a given *FILE*.
54
55		  BPF skeleton is an alternative interface to existing libbpf
56		  APIs for working with BPF objects. Skeleton code is intended
57		  to significantly shorten and simplify code to load and work
58		  with BPF programs from userspace side. Generated code is
59		  tailored to specific input BPF object *FILE*, reflecting its
60		  structure by listing out available maps, program, variables,
61		  etc. Skeleton eliminates the need to lookup mentioned
62		  components by name. Instead, if skeleton instantiation
63		  succeeds, they are populated in skeleton structure as valid
64		  libbpf types (e.g., **struct bpf_map** pointer) and can be
65		  passed to existing generic libbpf APIs.
66
67		  In addition to simple and reliable access to maps and
68		  programs, skeleton provides a storage for BPF links (**struct
69		  bpf_link**) for each BPF program within BPF object. When
70		  requested, supported BPF programs will be automatically
71		  attached and resulting BPF links stored for further use by
72		  user in pre-allocated fields in skeleton struct. For BPF
73		  programs that can't be automatically attached by libbpf,
74		  user can attach them manually, but store resulting BPF link
75		  in per-program link field. All such set up links will be
76		  automatically destroyed on BPF skeleton destruction. This
77		  eliminates the need for users to manage links manually and
78		  rely on libbpf support to detach programs and free up
79		  resources.
80
81		  Another facility provided by BPF skeleton is an interface to
82		  global variables of all supported kinds: mutable, read-only,
83		  as well as extern ones. This interface allows to pre-setup
84		  initial values of variables before BPF object is loaded and
85		  verified by kernel. For non-read-only variables, the same
86		  interface can be used to fetch values of global variables on
87		  userspace side, even if they are modified by BPF code.
88
89		  During skeleton generation, contents of source BPF object
90		  *FILE* is embedded within generated code and is thus not
91		  necessary to keep around. This ensures skeleton and BPF
92		  object file are matching 1-to-1 and always stay in sync.
93		  Generated code is dual-licensed under LGPL-2.1 and
94		  BSD-2-Clause licenses.
95
96		  It is a design goal and guarantee that skeleton interfaces
97		  are interoperable with generic libbpf APIs. User should
98		  always be able to use skeleton API to create and load BPF
99		  object, and later use libbpf APIs to keep working with
100		  specific maps, programs, etc.
101
102		  As part of skeleton, few custom functions are generated.
103		  Each of them is prefixed with object name. Object name can
104		  either be derived from object file name, i.e., if BPF object
105		  file name is **example.o**, BPF object name will be
106		  **example**. Object name can be also specified explicitly
107		  through **name** *OBJECT_NAME* parameter. The following
108		  custom functions are provided (assuming **example** as
109		  the object name):
110
111		  - **example__open** and **example__open_opts**.
112		    These functions are used to instantiate skeleton. It
113		    corresponds to libbpf's **bpf_object__open**\ () API.
114		    **_opts** variants accepts extra **bpf_object_open_opts**
115		    options.
116
117		  - **example__load**.
118		    This function creates maps, loads and verifies BPF
119		    programs, initializes global data maps. It corresponds to
120		    libppf's **bpf_object__load**\ () API.
121
122		  - **example__open_and_load** combines **example__open** and
123		    **example__load** invocations in one commonly used
124		    operation.
125
126		  - **example__attach** and **example__detach**
127		    This pair of functions allow to attach and detach,
128		    correspondingly, already loaded BPF object. Only BPF
129		    programs of types supported by libbpf for auto-attachment
130		    will be auto-attached and their corresponding BPF links
131		    instantiated. For other BPF programs, user can manually
132		    create a BPF link and assign it to corresponding fields in
133		    skeleton struct. **example__detach** will detach both
134		    links created automatically, as well as those populated by
135		    user manually.
136
137		  - **example__destroy**
138		    Detach and unload BPF programs, free up all the resources
139		    used by skeleton and BPF object.
140
141		  If BPF object has global variables, corresponding structs
142		  with memory layout corresponding to global data data section
143		  layout will be created. Currently supported ones are: *.data*,
144		  *.bss*, *.rodata*, and *.kconfig* structs/data sections.
145		  These data sections/structs can be used to set up initial
146		  values of variables, if set before **example__load**.
147		  Afterwards, if target kernel supports memory-mapped BPF
148		  arrays, same structs can be used to fetch and update
149		  (non-read-only) data from userspace, with same simplicity
150		  as for BPF side.
151
152	**bpftool gen help**
153		  Print short help message.
154
155OPTIONS
156=======
157	.. include:: common_options.rst
158
159	-L, --use-loader
160		  For skeletons, generate a "light" skeleton (also known as "loader"
161		  skeleton). A light skeleton contains a loader eBPF program. It does
162		  not use the majority of the libbpf infrastructure, and does not need
163		  libelf.
164
165EXAMPLES
166========
167**$ cat example1.bpf.c**
168
169::
170
171  #include <stdbool.h>
172  #include <linux/ptrace.h>
173  #include <linux/bpf.h>
174  #include <bpf/bpf_helpers.h>
175
176  const volatile int param1 = 42;
177  bool global_flag = true;
178  struct { int x; } data = {};
179
180  SEC("raw_tp/sys_enter")
181  int handle_sys_enter(struct pt_regs *ctx)
182  {
183  	static long my_static_var;
184  	if (global_flag)
185  		my_static_var++;
186  	else
187  		data.x += param1;
188  	return 0;
189  }
190
191**$ cat example2.bpf.c**
192
193::
194
195  #include <linux/ptrace.h>
196  #include <linux/bpf.h>
197  #include <bpf/bpf_helpers.h>
198
199  struct {
200  	__uint(type, BPF_MAP_TYPE_HASH);
201  	__uint(max_entries, 128);
202  	__type(key, int);
203  	__type(value, long);
204  } my_map SEC(".maps");
205
206  SEC("raw_tp/sys_exit")
207  int handle_sys_exit(struct pt_regs *ctx)
208  {
209  	int zero = 0;
210  	bpf_map_lookup_elem(&my_map, &zero);
211  	return 0;
212  }
213
214This is example BPF application with two BPF programs and a mix of BPF maps
215and global variables. Source code is split across two source code files.
216
217**$ clang -target bpf -g example1.bpf.c -o example1.bpf.o**
218**$ clang -target bpf -g example2.bpf.c -o example2.bpf.o**
219**$ bpftool gen object example.bpf.o example1.bpf.o example2.bpf.o**
220
221This set of commands compiles *example1.bpf.c* and *example2.bpf.c*
222individually and then statically links respective object files into the final
223BPF ELF object file *example.bpf.o*.
224
225**$ bpftool gen skeleton example.bpf.o name example | tee example.skel.h**
226
227::
228
229  /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
230
231  /* THIS FILE IS AUTOGENERATED! */
232  #ifndef __EXAMPLE_SKEL_H__
233  #define __EXAMPLE_SKEL_H__
234
235  #include <stdlib.h>
236  #include <bpf/libbpf.h>
237
238  struct example {
239  	struct bpf_object_skeleton *skeleton;
240  	struct bpf_object *obj;
241  	struct {
242  		struct bpf_map *rodata;
243  		struct bpf_map *data;
244  		struct bpf_map *bss;
245  		struct bpf_map *my_map;
246  	} maps;
247  	struct {
248  		struct bpf_program *handle_sys_enter;
249  		struct bpf_program *handle_sys_exit;
250  	} progs;
251  	struct {
252  		struct bpf_link *handle_sys_enter;
253  		struct bpf_link *handle_sys_exit;
254  	} links;
255  	struct example__bss {
256  		struct {
257  			int x;
258  		} data;
259  	} *bss;
260  	struct example__data {
261  		_Bool global_flag;
262  		long int handle_sys_enter_my_static_var;
263  	} *data;
264  	struct example__rodata {
265  		int param1;
266  	} *rodata;
267  };
268
269  static void example__destroy(struct example *obj);
270  static inline struct example *example__open_opts(
271                const struct bpf_object_open_opts *opts);
272  static inline struct example *example__open();
273  static inline int example__load(struct example *obj);
274  static inline struct example *example__open_and_load();
275  static inline int example__attach(struct example *obj);
276  static inline void example__detach(struct example *obj);
277
278  #endif /* __EXAMPLE_SKEL_H__ */
279
280**$ cat example.c**
281
282::
283
284  #include "example.skel.h"
285
286  int main()
287  {
288  	struct example *skel;
289  	int err = 0;
290
291  	skel = example__open();
292  	if (!skel)
293  		goto cleanup;
294
295  	skel->rodata->param1 = 128;
296
297  	err = example__load(skel);
298  	if (err)
299  		goto cleanup;
300
301  	err = example__attach(skel);
302  	if (err)
303  		goto cleanup;
304
305  	/* all libbpf APIs are usable */
306  	printf("my_map name: %s\n", bpf_map__name(skel->maps.my_map));
307  	printf("sys_enter prog FD: %d\n",
308  	       bpf_program__fd(skel->progs.handle_sys_enter));
309
310  	/* detach and re-attach sys_exit program */
311  	bpf_link__destroy(skel->links.handle_sys_exit);
312  	skel->links.handle_sys_exit =
313  		bpf_program__attach(skel->progs.handle_sys_exit);
314
315  	printf("my_static_var: %ld\n",
316  	       skel->bss->handle_sys_enter_my_static_var);
317
318  cleanup:
319  	example__destroy(skel);
320  	return err;
321  }
322
323**# ./example**
324
325::
326
327  my_map name: my_map
328  sys_enter prog FD: 8
329  my_static_var: 7
330
331This is a stripped-out version of skeleton generated for above example code.
332