← Documents Documentation/bpf/btf.rst GitHub 원문 ↗

Linux 6.18.37 · BPF

BPF Type Format (BTF)

BTF type/string encoding, kernel API, ELF section, split-BTF relocation, bpftool 활용과 생성·검사 방법을 설명합니다.

Source pathDocumentation/bpf/btf.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

btf.rst:1-1210

BTF는 BPF program과 map의 type·function·source line debug metadata를 compact하게 encode합니다. type id와 string table, 19개 `BTF_KIND_*`의 field 규칙을 통해 kernel과 userspace loader가 동일한 type contract를 공유합니다.

kernel API는 `BPF_BTF_LOAD`로 BTF blob을 load한 뒤 map/program 생성과 introspection에 연결합니다. ELF의 `.BTF.ext`는 function·line info와 CO-RE relocation을, `.BTF_ids`는 kernel 내부 ID list/set을, `.BTF.base`는 base BTF가 바뀌어도 split BTF를 relocate할 최소 type 설명을 담습니다.

BTF를 활용하면 bpftool이 map field를 pretty print하고 JIT dump와 verifier failure에 source line을 표시할 수 있습니다. pahole은 DWARF에서 BTF를 변환하며 LLVM BPF target은 `.BTF`와 `.BTF.ext`를 직접 생성할 수 있습니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 =====================
2 BPF Type Format (BTF)
3 =====================
4
5 1. Introduction
6 ===============
7
8 BTF (BPF Type Format) is the metadata format which encodes the debug info
9 related to BPF program/map. The name BTF was used initially to describe data
10 types. The BTF was later extended to include function info for defined
11 subroutines, and line info for source/line information.
12
13 The debug info is used for map pretty print, function signature, etc. The
14 function signature enables better bpf program/function kernel symbol. The line
15 info helps generate source annotated translated byte code, jited code and
16 verifier log.
17
18 The BTF specification contains two parts,
19 * BTF kernel API
20 * BTF ELF file format
21
22 The kernel API is the contract between user space and kernel. The kernel
23 verifies the BTF info before using it. The ELF file format is a user space
24 contract between ELF file and libbpf loader.
25
26 The type and string sections are part of the BTF kernel API, describing the
27 debug info (mostly types related) referenced by the bpf program. These two
28 sections are discussed in details in :ref:`BTF_Type_String`.
29
30 .. _BTF_Type_String:
31
32 2. BTF Type and String Encoding
33 ===============================
34
35 The file ``include/uapi/linux/btf.h`` provides high-level definition of how
36 types/strings are encoded.
37
38 The beginning of data blob must be::
39
40 struct btf_header {
41 __u16 magic;
42 __u8 version;
43 __u8 flags;
44 __u32 hdr_len;
45
46 /* All offsets are in bytes relative to the end of this header */
47 __u32 type_off; /* offset of type section */
48 __u32 type_len; /* length of type section */
49 __u32 str_off; /* offset of string section */
50 __u32 str_len; /* length of string section */
51 };
52
53 The magic is ``0xeB9F``, which has different encoding for big and little
54 endian systems, and can be used to test whether BTF is generated for big- or
55 little-endian target. The ``btf_header`` is designed to be extensible with
56 ``hdr_len`` equal to ``sizeof(struct btf_header)`` when a data blob is
57 generated.
58
59 2.1 String Encoding
60 -------------------
61
62 The first string in the string section must be a null string. The rest of
63 string table is a concatenation of other null-terminated strings.
64
65 2.2 Type Encoding
66 -----------------
67
68 The type id ``0`` is reserved for ``void`` type. The type section is parsed
69 sequentially and type id is assigned to each recognized type starting from id
70 ``1``. Currently, the following types are supported::
71
72 #define BTF_KIND_INT 1 /* Integer */
73 #define BTF_KIND_PTR 2 /* Pointer */
74 #define BTF_KIND_ARRAY 3 /* Array */
75 #define BTF_KIND_STRUCT 4 /* Struct */
76 #define BTF_KIND_UNION 5 /* Union */
77 #define BTF_KIND_ENUM 6 /* Enumeration up to 32-bit values */
78 #define BTF_KIND_FWD 7 /* Forward */
79 #define BTF_KIND_TYPEDEF 8 /* Typedef */
80 #define BTF_KIND_VOLATILE 9 /* Volatile */
81 #define BTF_KIND_CONST 10 /* Const */
82 #define BTF_KIND_RESTRICT 11 /* Restrict */
83 #define BTF_KIND_FUNC 12 /* Function */
84 #define BTF_KIND_FUNC_PROTO 13 /* Function Proto */
85 #define BTF_KIND_VAR 14 /* Variable */
86 #define BTF_KIND_DATASEC 15 /* Section */
87 #define BTF_KIND_FLOAT 16 /* Floating point */
88 #define BTF_KIND_DECL_TAG 17 /* Decl Tag */
89 #define BTF_KIND_TYPE_TAG 18 /* Type Tag */
90 #define BTF_KIND_ENUM64 19 /* Enumeration up to 64-bit values */
91
92 Note that the type section encodes debug info, not just pure types.
93 ``BTF_KIND_FUNC`` is not a type, and it represents a defined subprogram.
94
95 Each type contains the following common data::
96
97 struct btf_type {
98 __u32 name_off;
99 /* "info" bits arrangement
100 * bits 0-15: vlen (e.g. # of struct's members)
101 * bits 16-23: unused
102 * bits 24-28: kind (e.g. int, ptr, array...etc)
103 * bits 29-30: unused
104 * bit 31: kind_flag, currently used by
105 * struct, union, enum, fwd, enum64,
106 * decl_tag and type_tag
107 */
108 __u32 info;
109 /* "size" is used by INT, ENUM, STRUCT, UNION and ENUM64.
110 * "size" tells the size of the type it is describing.
111 *
112 * "type" is used by PTR, TYPEDEF, VOLATILE, CONST, RESTRICT,
113 * FUNC, FUNC_PROTO, DECL_TAG and TYPE_TAG.
114 * "type" is a type_id referring to another type.
115 */
116 union {
117 __u32 size;
118 __u32 type;
119 };
120 };
121
122 For certain kinds, the common data are followed by kind-specific data. The
123 ``name_off`` in ``struct btf_type`` specifies the offset in the string table.
124 The following sections detail encoding of each kind.
125
126 2.2.1 BTF_KIND_INT
127 ~~~~~~~~~~~~~~~~~~
128
129 ``struct btf_type`` encoding requirement:
130 * ``name_off``: any valid offset
131 * ``info.kind_flag``: 0
132 * ``info.kind``: BTF_KIND_INT
133 * ``info.vlen``: 0
134 * ``size``: the size of the int type in bytes.
135
136 ``btf_type`` is followed by a ``u32`` with the following bits arrangement::
137
138 #define BTF_INT_ENCODING(VAL) (((VAL) & 0x0f000000) >> 24)
139 #define BTF_INT_OFFSET(VAL) (((VAL) & 0x00ff0000) >> 16)
140 #define BTF_INT_BITS(VAL) ((VAL) & 0x000000ff)
141
142 The ``BTF_INT_ENCODING`` has the following attributes::
143
144 #define BTF_INT_SIGNED (1 << 0)
145 #define BTF_INT_CHAR (1 << 1)
146 #define BTF_INT_BOOL (1 << 2)
147
148 The ``BTF_INT_ENCODING()`` provides extra information: signedness, char, or
149 bool, for the int type. The char and bool encoding are mostly useful for
150 pretty print. At most one encoding can be specified for the int type.
151
152 The ``BTF_INT_BITS()`` specifies the number of actual bits held by this int
153 type. For example, a 4-bit bitfield encodes ``BTF_INT_BITS()`` equals to 4.
154 The ``btf_type.size * 8`` must be equal to or greater than ``BTF_INT_BITS()``
155 for the type. The maximum value of ``BTF_INT_BITS()`` is 128.
156
157 The ``BTF_INT_OFFSET()`` specifies the starting bit offset to calculate values
158 for this int. For example, a bitfield struct member has:
159
160 * btf member bit offset 100 from the start of the structure,
161 * btf member pointing to an int type,
162 * the int type has ``BTF_INT_OFFSET() = 2`` and ``BTF_INT_BITS() = 4``
163
164 Then in the struct memory layout, this member will occupy ``4`` bits starting
165 from bits ``100 + 2 = 102``.
166
167 Alternatively, the bitfield struct member can be the following to access the
168 same bits as the above:
169
170 * btf member bit offset 102,
171 * btf member pointing to an int type,
172 * the int type has ``BTF_INT_OFFSET() = 0`` and ``BTF_INT_BITS() = 4``
173
174 The original intention of ``BTF_INT_OFFSET()`` is to provide flexibility of
175 bitfield encoding. Currently, both llvm and pahole generate
176 ``BTF_INT_OFFSET() = 0`` for all int types.
177
178 2.2.2 BTF_KIND_PTR
179 ~~~~~~~~~~~~~~~~~~
180
181 ``struct btf_type`` encoding requirement:
182 * ``name_off``: 0
183 * ``info.kind_flag``: 0
184 * ``info.kind``: BTF_KIND_PTR
185 * ``info.vlen``: 0
186 * ``type``: the pointee type of the pointer
187
188 No additional type data follow ``btf_type``.
189
190 2.2.3 BTF_KIND_ARRAY
191 ~~~~~~~~~~~~~~~~~~~~
192
193 ``struct btf_type`` encoding requirement:
194 * ``name_off``: 0
195 * ``info.kind_flag``: 0
196 * ``info.kind``: BTF_KIND_ARRAY
197 * ``info.vlen``: 0
198 * ``size/type``: 0, not used
199
200 ``btf_type`` is followed by one ``struct btf_array``::
201
202 struct btf_array {
203 __u32 type;
204 __u32 index_type;
205 __u32 nelems;
206 };
207
208 The ``struct btf_array`` encoding:
209 * ``type``: the element type
210 * ``index_type``: the index type
211 * ``nelems``: the number of elements for this array (``0`` is also allowed).
212
213 The ``index_type`` can be any regular int type (``u8``, ``u16``, ``u32``,
214 ``u64``, ``unsigned __int128``). The original design of including
215 ``index_type`` follows DWARF, which has an ``index_type`` for its array type.
216 Currently in BTF, beyond type verification, the ``index_type`` is not used.
217
218 The ``struct btf_array`` allows chaining through element type to represent
219 multidimensional arrays. For example, for ``int a[5][6]``, the following type
220 information illustrates the chaining:
221
222 * [1]: int
223 * [2]: array, ``btf_array.type = [1]``, ``btf_array.nelems = 6``
224 * [3]: array, ``btf_array.type = [2]``, ``btf_array.nelems = 5``
225
226 Currently, both pahole and llvm collapse multidimensional array into
227 one-dimensional array, e.g., for ``a[5][6]``, the ``btf_array.nelems`` is
228 equal to ``30``. This is because the original use case is map pretty print
229 where the whole array is dumped out so one-dimensional array is enough. As
230 more BTF usage is explored, pahole and llvm can be changed to generate proper
231 chained representation for multidimensional arrays.
232
233 2.2.4 BTF_KIND_STRUCT
234 ~~~~~~~~~~~~~~~~~~~~~
235 2.2.5 BTF_KIND_UNION
236 ~~~~~~~~~~~~~~~~~~~~
237
238 ``struct btf_type`` encoding requirement:
239 * ``name_off``: 0 or offset to a valid C identifier
240 * ``info.kind_flag``: 0 or 1
241 * ``info.kind``: BTF_KIND_STRUCT or BTF_KIND_UNION
242 * ``info.vlen``: the number of struct/union members
243 * ``info.size``: the size of the struct/union in bytes
244
245 ``btf_type`` is followed by ``info.vlen`` number of ``struct btf_member``.::
246
247 struct btf_member {
248 __u32 name_off;
249 __u32 type;
250 __u32 offset;
251 };
252
253 ``struct btf_member`` encoding:
254 * ``name_off``: offset to a valid C identifier
255 * ``type``: the member type
256 * ``offset``: <see below>
257
258 If the type info ``kind_flag`` is not set, the offset contains only bit offset
259 of the member. Note that the base type of the bitfield can only be int or enum
260 type. If the bitfield size is 32, the base type can be either int or enum
261 type. If the bitfield size is not 32, the base type must be int, and int type
262 ``BTF_INT_BITS()`` encodes the bitfield size.
263
264 If the ``kind_flag`` is set, the ``btf_member.offset`` contains both member
265 bitfield size and bit offset. The bitfield size and bit offset are calculated
266 as below.::
267
268 #define BTF_MEMBER_BITFIELD_SIZE(val) ((val) >> 24)
269 #define BTF_MEMBER_BIT_OFFSET(val) ((val) & 0xffffff)
270
271 In this case, if the base type is an int type, it must be a regular int type:
272
273 * ``BTF_INT_OFFSET()`` must be 0.
274 * ``BTF_INT_BITS()`` must be equal to ``{1,2,4,8,16} * 8``.
275
276 Commit 9d5f9f701b18 introduced ``kind_flag`` and explains why both modes
277 exist.
278
279 2.2.6 BTF_KIND_ENUM
280 ~~~~~~~~~~~~~~~~~~~
281
282 ``struct btf_type`` encoding requirement:
283 * ``name_off``: 0 or offset to a valid C identifier
284 * ``info.kind_flag``: 0 for unsigned, 1 for signed
285 * ``info.kind``: BTF_KIND_ENUM
286 * ``info.vlen``: number of enum values
287 * ``size``: 1/2/4/8
288
289 ``btf_type`` is followed by ``info.vlen`` number of ``struct btf_enum``.::
290
291 struct btf_enum {
292 __u32 name_off;
293 __s32 val;
294 };
295
296 The ``btf_enum`` encoding:
297 * ``name_off``: offset to a valid C identifier
298 * ``val``: any value
299
300 If the original enum value is signed and the size is less than 4,
301 that value will be sign extended into 4 bytes. If the size is 8,
302 the value will be truncated into 4 bytes.
303
304 2.2.7 BTF_KIND_FWD
305 ~~~~~~~~~~~~~~~~~~
306
307 ``struct btf_type`` encoding requirement:
308 * ``name_off``: offset to a valid C identifier
309 * ``info.kind_flag``: 0 for struct, 1 for union
310 * ``info.kind``: BTF_KIND_FWD
311 * ``info.vlen``: 0
312 * ``type``: 0
313
314 No additional type data follow ``btf_type``.
315
316 2.2.8 BTF_KIND_TYPEDEF
317 ~~~~~~~~~~~~~~~~~~~~~~
318
319 ``struct btf_type`` encoding requirement:
320 * ``name_off``: offset to a valid C identifier
321 * ``info.kind_flag``: 0
322 * ``info.kind``: BTF_KIND_TYPEDEF
323 * ``info.vlen``: 0
324 * ``type``: the type which can be referred by name at ``name_off``
325
326 No additional type data follow ``btf_type``.
327
328 2.2.9 BTF_KIND_VOLATILE
329 ~~~~~~~~~~~~~~~~~~~~~~~
330
331 ``struct btf_type`` encoding requirement:
332 * ``name_off``: 0
333 * ``info.kind_flag``: 0
334 * ``info.kind``: BTF_KIND_VOLATILE
335 * ``info.vlen``: 0
336 * ``type``: the type with ``volatile`` qualifier
337
338 No additional type data follow ``btf_type``.
339
340 2.2.10 BTF_KIND_CONST
341 ~~~~~~~~~~~~~~~~~~~~~
342
343 ``struct btf_type`` encoding requirement:
344 * ``name_off``: 0
345 * ``info.kind_flag``: 0
346 * ``info.kind``: BTF_KIND_CONST
347 * ``info.vlen``: 0
348 * ``type``: the type with ``const`` qualifier
349
350 No additional type data follow ``btf_type``.
351
352 2.2.11 BTF_KIND_RESTRICT
353 ~~~~~~~~~~~~~~~~~~~~~~~~
354
355 ``struct btf_type`` encoding requirement:
356 * ``name_off``: 0
357 * ``info.kind_flag``: 0
358 * ``info.kind``: BTF_KIND_RESTRICT
359 * ``info.vlen``: 0
360 * ``type``: the type with ``restrict`` qualifier
361
362 No additional type data follow ``btf_type``.
363
364 2.2.12 BTF_KIND_FUNC
365 ~~~~~~~~~~~~~~~~~~~~
366
367 ``struct btf_type`` encoding requirement:
368 * ``name_off``: offset to a valid C identifier
369 * ``info.kind_flag``: 0
370 * ``info.kind``: BTF_KIND_FUNC
371 * ``info.vlen``: linkage information (BTF_FUNC_STATIC, BTF_FUNC_GLOBAL
372 or BTF_FUNC_EXTERN - see :ref:`BTF_Function_Linkage_Constants`)
373 * ``type``: a BTF_KIND_FUNC_PROTO type
374
375 No additional type data follow ``btf_type``.
376
377 A BTF_KIND_FUNC defines not a type, but a subprogram (function) whose
378 signature is defined by ``type``. The subprogram is thus an instance of that
379 type. The BTF_KIND_FUNC may in turn be referenced by a func_info in the
380 :ref:`BTF_Ext_Section` (ELF) or in the arguments to :ref:`BPF_Prog_Load`
381 (ABI).
382
383 Currently, only linkage values of BTF_FUNC_STATIC and BTF_FUNC_GLOBAL are
384 supported in the kernel.
385
386 2.2.13 BTF_KIND_FUNC_PROTO
387 ~~~~~~~~~~~~~~~~~~~~~~~~~~
388
389 ``struct btf_type`` encoding requirement:
390 * ``name_off``: 0
391 * ``info.kind_flag``: 0
392 * ``info.kind``: BTF_KIND_FUNC_PROTO
393 * ``info.vlen``: # of parameters
394 * ``type``: the return type
395
396 ``btf_type`` is followed by ``info.vlen`` number of ``struct btf_param``.::
397
398 struct btf_param {
399 __u32 name_off;
400 __u32 type;
401 };
402
403 If a BTF_KIND_FUNC_PROTO type is referred by a BTF_KIND_FUNC type, then
404 ``btf_param.name_off`` must point to a valid C identifier except for the
405 possible last argument representing the variable argument. The btf_param.type
406 refers to parameter type.
407
408 If the function has variable arguments, the last parameter is encoded with
409 ``name_off = 0`` and ``type = 0``.
410
411 2.2.14 BTF_KIND_VAR
412 ~~~~~~~~~~~~~~~~~~~
413
414 ``struct btf_type`` encoding requirement:
415 * ``name_off``: offset to a valid C identifier
416 * ``info.kind_flag``: 0
417 * ``info.kind``: BTF_KIND_VAR
418 * ``info.vlen``: 0
419 * ``type``: the type of the variable
420
421 ``btf_type`` is followed by a single ``struct btf_variable`` with the
422 following data::
423
424 struct btf_var {
425 __u32 linkage;
426 };
427
428 ``btf_var.linkage`` may take the values: BTF_VAR_STATIC, BTF_VAR_GLOBAL_ALLOCATED or BTF_VAR_GLOBAL_EXTERN -
429 see :ref:`BTF_Var_Linkage_Constants`.
430
431 Not all type of global variables are supported by LLVM at this point.
432 The following is currently available:
433
434 * static variables with or without section attributes
435 * global variables with section attributes
436
437 The latter is for future extraction of map key/value type id's from a
438 map definition.
439
440 2.2.15 BTF_KIND_DATASEC
441 ~~~~~~~~~~~~~~~~~~~~~~~
442
443 ``struct btf_type`` encoding requirement:
444 * ``name_off``: offset to a valid name associated with a variable or
445 one of .data/.bss/.rodata
446 * ``info.kind_flag``: 0
447 * ``info.kind``: BTF_KIND_DATASEC
448 * ``info.vlen``: # of variables
449 * ``size``: total section size in bytes (0 at compilation time, patched
450 to actual size by BPF loaders such as libbpf)
451
452 ``btf_type`` is followed by ``info.vlen`` number of ``struct btf_var_secinfo``.::
453
454 struct btf_var_secinfo {
455 __u32 type;
456 __u32 offset;
457 __u32 size;
458 };
459
460 ``struct btf_var_secinfo`` encoding:
461 * ``type``: the type of the BTF_KIND_VAR variable
462 * ``offset``: the in-section offset of the variable
463 * ``size``: the size of the variable in bytes
464
465 2.2.16 BTF_KIND_FLOAT
466 ~~~~~~~~~~~~~~~~~~~~~
467
468 ``struct btf_type`` encoding requirement:
469 * ``name_off``: any valid offset
470 * ``info.kind_flag``: 0
471 * ``info.kind``: BTF_KIND_FLOAT
472 * ``info.vlen``: 0
473 * ``size``: the size of the float type in bytes: 2, 4, 8, 12 or 16.
474
475 No additional type data follow ``btf_type``.
476
477 2.2.17 BTF_KIND_DECL_TAG
478 ~~~~~~~~~~~~~~~~~~~~~~~~
479
480 ``struct btf_type`` encoding requirement:
481 * ``name_off``: offset to a non-empty string
482 * ``info.kind_flag``: 0 or 1
483 * ``info.kind``: BTF_KIND_DECL_TAG
484 * ``info.vlen``: 0
485 * ``type``: ``struct``, ``union``, ``func``, ``var`` or ``typedef``
486
487 ``btf_type`` is followed by ``struct btf_decl_tag``.::
488
489 struct btf_decl_tag {
490 __u32 component_idx;
491 };
492
493 The ``type`` should be ``struct``, ``union``, ``func``, ``var`` or ``typedef``.
494 For ``var`` or ``typedef`` type, ``btf_decl_tag.component_idx`` must be ``-1``.
495 For the other three types, if the btf_decl_tag attribute is
496 applied to the ``struct``, ``union`` or ``func`` itself,
497 ``btf_decl_tag.component_idx`` must be ``-1``. Otherwise,
498 the attribute is applied to a ``struct``/``union`` member or
499 a ``func`` argument, and ``btf_decl_tag.component_idx`` should be a
500 valid index (starting from 0) pointing to a member or an argument.
501
502 If ``info.kind_flag`` is 0, then this is a normal decl tag, and the
503 ``name_off`` encodes btf_decl_tag attribute string.
504
505 If ``info.kind_flag`` is 1, then the decl tag represents an arbitrary
506 __attribute__. In this case, ``name_off`` encodes a string
507 representing the attribute-list of the attribute specifier. For
508 example, for an ``__attribute__((aligned(4)))`` the string's contents
509 is ``aligned(4)``.
510
511 2.2.18 BTF_KIND_TYPE_TAG
512 ~~~~~~~~~~~~~~~~~~~~~~~~
513
514 ``struct btf_type`` encoding requirement:
515 * ``name_off``: offset to a non-empty string
516 * ``info.kind_flag``: 0 or 1
517 * ``info.kind``: BTF_KIND_TYPE_TAG
518 * ``info.vlen``: 0
519 * ``type``: the type with ``btf_type_tag`` attribute
520
521 Currently, ``BTF_KIND_TYPE_TAG`` is only emitted for pointer types.
522 It has the following btf type chain:
523 ::
524
525 ptr -> [type_tag]*
526 -> [const | volatile | restrict | typedef]*
527 -> base_type
528
529 Basically, a pointer type points to zero or more
530 type_tag, then zero or more const/volatile/restrict/typedef
531 and finally the base type. The base type is one of
532 int, ptr, array, struct, union, enum, func_proto and float types.
533
534 Similarly to decl tags, if the ``info.kind_flag`` is 0, then this is a
535 normal type tag, and the ``name_off`` encodes btf_type_tag attribute
536 string.
537
538 If ``info.kind_flag`` is 1, then the type tag represents an arbitrary
539 __attribute__, and the ``name_off`` encodes a string representing the
540 attribute-list of the attribute specifier.
541
542 2.2.19 BTF_KIND_ENUM64
543 ~~~~~~~~~~~~~~~~~~~~~~
544
545 ``struct btf_type`` encoding requirement:
546 * ``name_off``: 0 or offset to a valid C identifier
547 * ``info.kind_flag``: 0 for unsigned, 1 for signed
548 * ``info.kind``: BTF_KIND_ENUM64
549 * ``info.vlen``: number of enum values
550 * ``size``: 1/2/4/8
551
552 ``btf_type`` is followed by ``info.vlen`` number of ``struct btf_enum64``.::
553
554 struct btf_enum64 {
555 __u32 name_off;
556 __u32 val_lo32;
557 __u32 val_hi32;
558 };
559
560 The ``btf_enum64`` encoding:
561 * ``name_off``: offset to a valid C identifier
562 * ``val_lo32``: lower 32-bit value for a 64-bit value
563 * ``val_hi32``: high 32-bit value for a 64-bit value
564
565 If the original enum value is signed and the size is less than 8,
566 that value will be sign extended into 8 bytes.
567
568 2.3 Constant Values
569 -------------------
570
571 .. _BTF_Function_Linkage_Constants:
572
573 2.3.1 Function Linkage Constant Values
574 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
575 .. table:: Function Linkage Values and Meanings
576
577 =================== ===== ===========
578 kind value description
579 =================== ===== ===========
580 ``BTF_FUNC_STATIC`` 0x0 definition of subprogram not visible outside containing compilation unit
581 ``BTF_FUNC_GLOBAL`` 0x1 definition of subprogram visible outside containing compilation unit
582 ``BTF_FUNC_EXTERN`` 0x2 declaration of a subprogram whose definition is outside the containing compilation unit
583 =================== ===== ===========
584
585
586 .. _BTF_Var_Linkage_Constants:
587
588 2.3.2 Variable Linkage Constant Values
589 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
590 .. table:: Variable Linkage Values and Meanings
591
592 ============================ ===== ===========
593 kind value description
594 ============================ ===== ===========
595 ``BTF_VAR_STATIC`` 0x0 definition of global variable not visible outside containing compilation unit
596 ``BTF_VAR_GLOBAL_ALLOCATED`` 0x1 definition of global variable visible outside containing compilation unit
597 ``BTF_VAR_GLOBAL_EXTERN`` 0x2 declaration of global variable whose definition is outside the containing compilation unit
598 ============================ ===== ===========
599
600 3. BTF Kernel API
601 =================
602
603 The following bpf syscall command involves BTF:
604 * BPF_BTF_LOAD: load a blob of BTF data into kernel
605 * BPF_MAP_CREATE: map creation with btf key and value type info.
606 * BPF_PROG_LOAD: prog load with btf function and line info.
607 * BPF_BTF_GET_FD_BY_ID: get a btf fd
608 * BPF_OBJ_GET_INFO_BY_FD: btf, func_info, line_info
609 and other btf related info are returned.
610
611 The workflow typically looks like:
612 ::
613
614 Application:
615 BPF_BTF_LOAD
616 |
617 v
618 BPF_MAP_CREATE and BPF_PROG_LOAD
619 |
620 V
621 ......
622
623 Introspection tool:
624 ......
625 BPF_{PROG,MAP}_GET_NEXT_ID (get prog/map id's)
626 |
627 V
628 BPF_{PROG,MAP}_GET_FD_BY_ID (get a prog/map fd)
629 |
630 V
631 BPF_OBJ_GET_INFO_BY_FD (get bpf_prog_info/bpf_map_info with btf_id)
632 | |
633 V |
634 BPF_BTF_GET_FD_BY_ID (get btf_fd) |
635 | |
636 V |
637 BPF_OBJ_GET_INFO_BY_FD (get btf) |
638 | |
639 V V
640 pretty print types, dump func signatures and line info, etc.
641
642
643 3.1 BPF_BTF_LOAD
644 ----------------
645
646 Load a blob of BTF data into kernel. A blob of data, described in
647 :ref:`BTF_Type_String`, can be directly loaded into the kernel. A ``btf_fd``
648 is returned to a userspace.
649
650 3.2 BPF_MAP_CREATE
651 ------------------
652
653 A map can be created with ``btf_fd`` and specified key/value type id.::
654
655 __u32 btf_fd; /* fd pointing to a BTF type data */
656 __u32 btf_key_type_id; /* BTF type_id of the key */
657 __u32 btf_value_type_id; /* BTF type_id of the value */
658
659 In libbpf, the map can be defined with extra annotation like below:
660 ::
661
662 struct {
663 __uint(type, BPF_MAP_TYPE_ARRAY);
664 __type(key, int);
665 __type(value, struct ipv_counts);
666 __uint(max_entries, 4);
667 } btf_map SEC(".maps");
668
669 During ELF parsing, libbpf is able to extract key/value type_id's and assign
670 them to BPF_MAP_CREATE attributes automatically.
671
672 .. _BPF_Prog_Load:
673
674 3.3 BPF_PROG_LOAD
675 -----------------
676
677 During prog_load, func_info and line_info can be passed to kernel with proper
678 values for the following attributes:
679 ::
680
681 __u32 insn_cnt;
682 __aligned_u64 insns;
683 ......
684 __u32 prog_btf_fd; /* fd pointing to BTF type data */
685 __u32 func_info_rec_size; /* userspace bpf_func_info size */
686 __aligned_u64 func_info; /* func info */
687 __u32 func_info_cnt; /* number of bpf_func_info records */
688 __u32 line_info_rec_size; /* userspace bpf_line_info size */
689 __aligned_u64 line_info; /* line info */
690 __u32 line_info_cnt; /* number of bpf_line_info records */
691
692 The func_info and line_info are an array of below, respectively.::
693
694 struct bpf_func_info {
695 __u32 insn_off; /* [0, insn_cnt - 1] */
696 __u32 type_id; /* pointing to a BTF_KIND_FUNC type */
697 };
698 struct bpf_line_info {
699 __u32 insn_off; /* [0, insn_cnt - 1] */
700 __u32 file_name_off; /* offset to string table for the filename */
701 __u32 line_off; /* offset to string table for the source line */
702 __u32 line_col; /* line number and column number */
703 };
704
705 func_info_rec_size is the size of each func_info record, and
706 line_info_rec_size is the size of each line_info record. Passing the record
707 size to kernel make it possible to extend the record itself in the future.
708
709 Below are requirements for func_info:
710 * func_info[0].insn_off must be 0.
711 * the func_info insn_off is in strictly increasing order and matches
712 bpf func boundaries.
713
714 Below are requirements for line_info:
715 * the first insn in each func must have a line_info record pointing to it.
716 * the line_info insn_off is in strictly increasing order.
717
718 For line_info, the line number and column number are defined as below:
719 ::
720
721 #define BPF_LINE_INFO_LINE_NUM(line_col) ((line_col) >> 10)
722 #define BPF_LINE_INFO_LINE_COL(line_col) ((line_col) & 0x3ff)
723
724 3.4 BPF_{PROG,MAP}_GET_NEXT_ID
725 ------------------------------
726
727 In kernel, every loaded program, map or btf has a unique id. The id won't
728 change during the lifetime of a program, map, or btf.
729
730 The bpf syscall command BPF_{PROG,MAP}_GET_NEXT_ID returns all id's, one for
731 each command, to user space, for bpf program or maps, respectively, so an
732 inspection tool can inspect all programs and maps.
733
734 3.5 BPF_{PROG,MAP}_GET_FD_BY_ID
735 -------------------------------
736
737 An introspection tool cannot use id to get details about program or maps.
738 A file descriptor needs to be obtained first for reference-counting purpose.
739
740 3.6 BPF_OBJ_GET_INFO_BY_FD
741 --------------------------
742
743 Once a program/map fd is acquired, an introspection tool can get the detailed
744 information from kernel about this fd, some of which are BTF-related. For
745 example, ``bpf_map_info`` returns ``btf_id`` and key/value type ids.
746 ``bpf_prog_info`` returns ``btf_id``, func_info, and line info for translated
747 bpf byte codes, and jited_line_info.
748
749 3.7 BPF_BTF_GET_FD_BY_ID
750 ------------------------
751
752 With ``btf_id`` obtained in ``bpf_map_info`` and ``bpf_prog_info``, bpf
753 syscall command BPF_BTF_GET_FD_BY_ID can retrieve a btf fd. Then, with
754 command BPF_OBJ_GET_INFO_BY_FD, the btf blob, originally loaded into the
755 kernel with BPF_BTF_LOAD, can be retrieved.
756
757 With the btf blob, ``bpf_map_info``, and ``bpf_prog_info``, an introspection
758 tool has full btf knowledge and is able to pretty print map key/values, dump
759 func signatures and line info, along with byte/jit codes.
760
761 4. ELF File Format Interface
762 ============================
763
764 4.1 .BTF section
765 ----------------
766
767 The .BTF section contains type and string data. The format of this section is
768 same as the one describe in :ref:`BTF_Type_String`.
769
770 .. _BTF_Ext_Section:
771
772 4.2 .BTF.ext section
773 --------------------
774
775 The .BTF.ext section encodes func_info, line_info and CO-RE relocations
776 which needs loader manipulation before loading into the kernel.
777
778 The specification for .BTF.ext section is defined at ``tools/lib/bpf/btf.h``
779 and ``tools/lib/bpf/btf.c``.
780
781 The current header of .BTF.ext section::
782
783 struct btf_ext_header {
784 __u16 magic;
785 __u8 version;
786 __u8 flags;
787 __u32 hdr_len;
788
789 /* All offsets are in bytes relative to the end of this header */
790 __u32 func_info_off;
791 __u32 func_info_len;
792 __u32 line_info_off;
793 __u32 line_info_len;
794
795 /* optional part of .BTF.ext header */
796 __u32 core_relo_off;
797 __u32 core_relo_len;
798 };
799
800 It is very similar to .BTF section. Instead of type/string section, it
801 contains func_info, line_info and core_relo sub-sections.
802 See :ref:`BPF_Prog_Load` for details about func_info and line_info
803 record format.
804
805 The func_info is organized as below.::
806
807 func_info_rec_size /* __u32 value */
808 btf_ext_info_sec for section #1 /* func_info for section #1 */
809 btf_ext_info_sec for section #2 /* func_info for section #2 */
810 ...
811
812 ``func_info_rec_size`` specifies the size of ``bpf_func_info`` structure when
813 .BTF.ext is generated. ``btf_ext_info_sec``, defined below, is a collection of
814 func_info for each specific ELF section.::
815
816 struct btf_ext_info_sec {
817 __u32 sec_name_off; /* offset to section name */
818 __u32 num_info;
819 /* Followed by num_info * record_size number of bytes */
820 __u8 data[0];
821 };
822
823 Here, num_info must be greater than 0.
824
825 The line_info is organized as below.::
826
827 line_info_rec_size /* __u32 value */
828 btf_ext_info_sec for section #1 /* line_info for section #1 */
829 btf_ext_info_sec for section #2 /* line_info for section #2 */
830 ...
831
832 ``line_info_rec_size`` specifies the size of ``bpf_line_info`` structure when
833 .BTF.ext is generated.
834
835 The interpretation of ``bpf_func_info->insn_off`` and
836 ``bpf_line_info->insn_off`` is different between kernel API and ELF API. For
837 kernel API, the ``insn_off`` is the instruction offset in the unit of ``struct
838 bpf_insn``. For ELF API, the ``insn_off`` is the byte offset from the
839 beginning of section (``btf_ext_info_sec->sec_name_off``).
840
841 The core_relo is organized as below.::
842
843 core_relo_rec_size /* __u32 value */
844 btf_ext_info_sec for section #1 /* core_relo for section #1 */
845 btf_ext_info_sec for section #2 /* core_relo for section #2 */
846
847 ``core_relo_rec_size`` specifies the size of ``bpf_core_relo``
848 structure when .BTF.ext is generated. All ``bpf_core_relo`` structures
849 within a single ``btf_ext_info_sec`` describe relocations applied to
850 section named by ``btf_ext_info_sec->sec_name_off``.
851
852 See :ref:`Documentation/bpf/llvm_reloc.rst <btf-co-re-relocations>`
853 for more information on CO-RE relocations.
854
855 4.3 .BTF_ids section
856 --------------------
857
858 The .BTF_ids section encodes BTF ID values that are used within the kernel.
859
860 This section is created during the kernel compilation with the help of
861 macros defined in ``include/linux/btf_ids.h`` header file. Kernel code can
862 use them to create lists and sets (sorted lists) of BTF ID values.
863
864 The ``BTF_ID_LIST`` and ``BTF_ID`` macros define unsorted list of BTF ID values,
865 with following syntax::
866
867 BTF_ID_LIST(list)
868 BTF_ID(type1, name1)
869 BTF_ID(type2, name2)
870
871 resulting in following layout in .BTF_ids section::
872
873 __BTF_ID__type1__name1__1:
874 .zero 4
875 __BTF_ID__type2__name2__2:
876 .zero 4
877
878 The ``u32 list[];`` variable is defined to access the list.
879
880 The ``BTF_ID_UNUSED`` macro defines 4 zero bytes. It's used when we
881 want to define unused entry in BTF_ID_LIST, like::
882
883 BTF_ID_LIST(bpf_skb_output_btf_ids)
884 BTF_ID(struct, sk_buff)
885 BTF_ID_UNUSED
886 BTF_ID(struct, task_struct)
887
888 The ``BTF_SET_START/END`` macros pair defines sorted list of BTF ID values
889 and their count, with following syntax::
890
891 BTF_SET_START(set)
892 BTF_ID(type1, name1)
893 BTF_ID(type2, name2)
894 BTF_SET_END(set)
895
896 resulting in following layout in .BTF_ids section::
897
898 __BTF_ID__set__set:
899 .zero 4
900 __BTF_ID__type1__name1__3:
901 .zero 4
902 __BTF_ID__type2__name2__4:
903 .zero 4
904
905 The ``struct btf_id_set set;`` variable is defined to access the list.
906
907 The ``typeX`` name can be one of following::
908
909 struct, union, typedef, func
910
911 and is used as a filter when resolving the BTF ID value.
912
913 All the BTF ID lists and sets are compiled in the .BTF_ids section and
914 resolved during the linking phase of kernel build by ``resolve_btfids`` tool.
915
916 4.4 .BTF.base section
917 ---------------------
918 Split BTF - where the .BTF section only contains types not in the associated
919 base .BTF section - is an extremely efficient way to encode type information
920 for kernel modules, since they generally consist of a few module-specific
921 types along with a large set of shared kernel types. The former are encoded
922 in split BTF, while the latter are encoded in base BTF, resulting in more
923 compact representations. A type in split BTF that refers to a type in
924 base BTF refers to it using its base BTF ID, and split BTF IDs start
925 at last_base_BTF_ID + 1.
926
927 The downside of this approach however is that this makes the split BTF
928 somewhat brittle - when the base BTF changes, base BTF ID references are
929 no longer valid and the split BTF itself becomes useless. The role of the
930 .BTF.base section is to make split BTF more resilient for cases where
931 the base BTF may change, as is the case for kernel modules not built every
932 time the kernel is for example. .BTF.base contains named base types; INTs,
933 FLOATs, STRUCTs, UNIONs, ENUM[64]s and FWDs. INTs and FLOATs are fully
934 described in .BTF.base sections, while composite types like structs
935 and unions are not fully defined - the .BTF.base type simply serves as
936 a description of the type the split BTF referred to, so structs/unions
937 have 0 members in the .BTF.base section. ENUM[64]s are similarly recorded
938 with 0 members. Any other types are added to the split BTF. This
939 distillation process then leaves us with a .BTF.base section with
940 such minimal descriptions of base types and .BTF split section which refers
941 to those base types. Later, we can relocate the split BTF using both the
942 information stored in the .BTF.base section and the new .BTF base; the type
943 information in the .BTF.base section allows us to update the split BTF
944 references to point at the corresponding new base BTF IDs.
945
946 BTF relocation happens on kernel module load when a kernel module has a
947 .BTF.base section, and libbpf also provides a btf__relocate() API to
948 accomplish this.
949
950 As an example consider the following base BTF::
951
952 [1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
953 [2] STRUCT 'foo' size=8 vlen=2
954 'f1' type_id=1 bits_offset=0
955 'f2' type_id=1 bits_offset=32
956
957 ...and associated split BTF::
958
959 [3] PTR '(anon)' type_id=2
960
961 i.e. split BTF describes a pointer to struct foo { int f1; int f2 };
962
963 .BTF.base will consist of::
964
965 [1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
966 [2] STRUCT 'foo' size=8 vlen=0
967
968 If we relocate the split BTF later using the following new base BTF::
969
970 [1] INT 'long unsigned int' size=8 bits_offset=0 nr_bits=64 encoding=(none)
971 [2] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
972 [3] STRUCT 'foo' size=8 vlen=2
973 'f1' type_id=2 bits_offset=0
974 'f2' type_id=2 bits_offset=32
975
976 ...we can use our .BTF.base description to know that the split BTF reference
977 is to struct foo, and relocation results in new split BTF::
978
979 [4] PTR '(anon)' type_id=3
980
981 Note that we had to update BTF ID and start BTF ID for the split BTF.
982
983 So we see how .BTF.base plays the role of facilitating later relocation,
984 leading to more resilient split BTF.
985
986 .BTF.base sections will be generated automatically for out-of-tree kernel module
987 builds - i.e. where KBUILD_EXTMOD is set (as it would be for "make M=path/2/mod"
988 cases). .BTF.base generation requires pahole support for the "distilled_base"
989 BTF feature; this is available in pahole v1.28 and later.
990
991 5. Using BTF
992 ============
993
994 5.1 bpftool map pretty print
995 ----------------------------
996
997 With BTF, the map key/value can be printed based on fields rather than simply
998 raw bytes. This is especially valuable for large structure or if your data
999 structure has bitfields. For example, for the following map,::
1001 enum A { A1, A2, A3, A4, A5 };
1002 typedef enum A ___A;
1003 struct tmp_t {
1004 char a1:4;
1005 int a2:4;
1006 int :4;
1007 __u32 a3:4;
1008 int b;
1009 ___A b1:4;
1010 enum A b2:4;
1011 };
1012 struct {
1013 __uint(type, BPF_MAP_TYPE_ARRAY);
1014 __type(key, int);
1015 __type(value, struct tmp_t);
1016 __uint(max_entries, 1);
1017 } tmpmap SEC(".maps");
1019 bpftool is able to pretty print like below:
1020 ::
1022 [{
1023 "key": 0,
1024 "value": {
1025 "a1": 0x2,
1026 "a2": 0x4,
1027 "a3": 0x6,
1028 "b": 7,
1029 "b1": 0x8,
1030 "b2": 0xa
1031 }
1032 }
1033 ]
1035 5.2 bpftool prog dump
1036 ---------------------
1038 The following is an example showing how func_info and line_info can help prog
1039 dump with better kernel symbol names, function prototypes and line
1040 information.::
1042 $ bpftool prog dump jited pinned /sys/fs/bpf/test_btf_haskv
1043 [...]
1044 int test_long_fname_2(struct dummy_tracepoint_args * arg):
1045 bpf_prog_44a040bf25481309_test_long_fname_2:
1046 ; static int test_long_fname_2(struct dummy_tracepoint_args *arg)
1047 0: push %rbp
1048 1: mov %rsp,%rbp
1049 4: sub $0x30,%rsp
1050 b: sub $0x28,%rbp
1051 f: mov %rbx,0x0(%rbp)
1052 13: mov %r13,0x8(%rbp)
1053 17: mov %r14,0x10(%rbp)
1054 1b: mov %r15,0x18(%rbp)
1055 1f: xor %eax,%eax
1056 21: mov %rax,0x20(%rbp)
1057 25: xor %esi,%esi
1058 ; int key = 0;
1059 27: mov %esi,-0x4(%rbp)
1060 ; if (!arg->sock)
1061 2a: mov 0x8(%rdi),%rdi
1062 ; if (!arg->sock)
1063 2e: cmp $0x0,%rdi
1064 32: je 0x0000000000000070
1065 34: mov %rbp,%rsi
1066 ; counts = bpf_map_lookup_elem(&btf_map, &key);
1067 [...]
1069 5.3 Verifier Log
1070 ----------------
1072 The following is an example of how line_info can help debugging verification
1073 failure.::
1075 /* The code at tools/testing/selftests/bpf/test_xdp_noinline.c
1076 * is modified as below.
1077 */
1078 data = (void *)(long)xdp->data;
1079 data_end = (void *)(long)xdp->data_end;
1080 /*
1081 if (data + 4 > data_end)
1082 return XDP_DROP;
1083 */
1084 *(u32 *)data = dst->dst;
1086 $ bpftool prog load ./test_xdp_noinline.o /sys/fs/bpf/test_xdp_noinline type xdp
1087 ; data = (void *)(long)xdp->data;
1088 224: (79) r2 = *(u64 *)(r10 -112)
1089 225: (61) r2 = *(u32 *)(r2 +0)
1090 ; *(u32 *)data = dst->dst;
1091 226: (63) *(u32 *)(r2 +0) = r1
1092 invalid access to packet, off=0 size=4, R2(id=0,off=0,r=0)
1093 R2 offset is outside of the packet
1095 6. BTF Generation
1096 =================
1098 You need latest pahole
1100 https://git.kernel.org/pub/scm/devel/pahole/pahole.git/
1102 or llvm (8.0 or later). The pahole acts as a dwarf2btf converter. It doesn't
1103 support .BTF.ext and btf BTF_KIND_FUNC type yet. For example,::
1105 -bash-4.4$ cat t.c
1106 struct t {
1107 int a:2;
1108 int b:3;
1109 int c:2;
1110 } g;
1111 -bash-4.4$ gcc -c -O2 -g t.c
1112 -bash-4.4$ pahole -JV t.o
1113 File t.o:
1114 [1] STRUCT t kind_flag=1 size=4 vlen=3
1115 a type_id=2 bitfield_size=2 bits_offset=0
1116 b type_id=2 bitfield_size=3 bits_offset=2
1117 c type_id=2 bitfield_size=2 bits_offset=5
1118 [2] INT int size=4 bit_offset=0 nr_bits=32 encoding=SIGNED
1120 The llvm is able to generate .BTF and .BTF.ext directly with -g for bpf target
1121 only. The assembly code (-S) is able to show the BTF encoding in assembly
1122 format.::
1124 -bash-4.4$ cat t2.c
1125 typedef int __int32;
1126 struct t2 {
1127 int a2;
1128 int (*f2)(char q1, __int32 q2, ...);
1129 int (*f3)();
1130 } g2;
1131 int main() { return 0; }
1132 int test() { return 0; }
1133 -bash-4.4$ clang -c -g -O2 --target=bpf t2.c
1134 -bash-4.4$ readelf -S t2.o
1135 ......
1136 [ 8] .BTF PROGBITS 0000000000000000 00000247
1137 000000000000016e 0000000000000000 0 0 1
1138 [ 9] .BTF.ext PROGBITS 0000000000000000 000003b5
1139 0000000000000060 0000000000000000 0 0 1
1140 [10] .rel.BTF.ext REL 0000000000000000 000007e0
1141 0000000000000040 0000000000000010 16 9 8
1142 ......
1143 -bash-4.4$ clang -S -g -O2 --target=bpf t2.c
1144 -bash-4.4$ cat t2.s
1145 ......
1146 .section .BTF,"",@progbits
1147 .short 60319 # 0xeb9f
1148 .byte 1
1149 .byte 0
1150 .long 24
1151 .long 0
1152 .long 220
1153 .long 220
1154 .long 122
1155 .long 0 # BTF_KIND_FUNC_PROTO(id = 1)
1156 .long 218103808 # 0xd000000
1157 .long 2
1158 .long 83 # BTF_KIND_INT(id = 2)
1159 .long 16777216 # 0x1000000
1160 .long 4
1161 .long 16777248 # 0x1000020
1162 ......
1163 .byte 0 # string offset=0
1164 .ascii ".text" # string offset=1
1165 .byte 0
1166 .ascii "/home/yhs/tmp-pahole/t2.c" # string offset=7
1167 .byte 0
1168 .ascii "int main() { return 0; }" # string offset=33
1169 .byte 0
1170 .ascii "int test() { return 0; }" # string offset=58
1171 .byte 0
1172 .ascii "int" # string offset=83
1173 ......
1174 .section .BTF.ext,"",@progbits
1175 .short 60319 # 0xeb9f
1176 .byte 1
1177 .byte 0
1178 .long 24
1179 .long 0
1180 .long 28
1181 .long 28
1182 .long 44
1183 .long 8 # FuncInfo
1184 .long 1 # FuncInfo section string offset=1
1185 .long 2
1186 .long .Lfunc_begin0
1187 .long 3
1188 .long .Lfunc_begin1
1189 .long 5
1190 .long 16 # LineInfo
1191 .long 1 # LineInfo section string offset=1
1192 .long 2
1193 .long .Ltmp0
1194 .long 7
1195 .long 33
1196 .long 7182 # Line 7 Col 14
1197 .long .Ltmp3
1198 .long 7
1199 .long 58
1200 .long 8206 # Line 8 Col 14
1202 7. Testing
1203 ==========
1205 The kernel BPF selftest `tools/testing/selftests/bpf/prog_tests/btf.c`_
1206 provides an extensive set of BTF-related tests.
1208 .. Links
1209 .. _tools/testing/selftests/bpf/prog_tests/btf.c:
1210 https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/prog_tests/btf.c

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

BTF 소개와 specification 범위

1-31

BTF(BPF Type Format)는 BPF program과 map 관련 debug info를 encode하는 metadata format입니다. 처음에는 data type을 설명하는 이름으로 사용됐지만, 이후 정의된 subroutine의 function info와 source·line 정보를 위한 line info까지 포함하도록 확장됐습니다.

debug info는 map pretty print와 function signature 등에 사용됩니다. function signature는 BPF program/function의 kernel symbol을 더 잘 표현하게 하고, line info는 source annotation이 붙은 translated bytecode, JIT code, verifier log를 생성하는 데 도움을 줍니다.

BTF specification은 두 부분으로 구성됩니다.

  • BTF kernel API
  • BTF ELF file format

kernel API는 userspace와 kernel 사이의 contract이며 kernel은 BTF info를 사용하기 전에 verify합니다. ELF file format은 ELF file과 libbpf loader 사이의 userspace contract입니다.

type section과 string section은 BTF kernel API의 일부로서 BPF program이 참조하는, 주로 type 관련 debug info를 설명합니다. 이 두 section은 아래 BTF Type and String Encoding에서 자세히 다룹니다.

BTF header와 string encoding

32-64

`include/uapi/linux/btf.h`는 type과 string을 encode하는 방식을 높은 수준에서 정의합니다. data blob은 다음 header로 시작해야 합니다.

struct btf_header {
    __u16   magic;
    __u8    version;
    __u8    flags;
    __u32   hdr_len;

    /* All offsets are in bytes relative to the end of this header */
    __u32   type_off;       /* offset of type section       */
    __u32   type_len;       /* length of type section       */
    __u32   str_off;        /* offset of string section     */
    __u32   str_len;        /* length of string section     */
};

magic은 `0xeB9F`입니다. big-endian과 little-endian system에서 encoding이 달라 BTF가 어느 endian target용으로 생성됐는지 검사하는 데 사용할 수 있습니다.

`btf_header`는 확장 가능하도록 설계됐으며 data blob을 생성할 때 `hdr_len`은 `sizeof(struct btf_header)`와 같습니다.

string section의 첫 string은 반드시 null string이어야 합니다. 나머지 string table은 다른 null-terminated string을 이어 붙인 형태입니다.

Type ID와 공통 btf_type encoding

65-125

type id `0`은 `void` type용으로 예약됩니다. type section을 순서대로 parse하면서 인식한 각 type에 id `1`부터 type id를 부여합니다. 현재 지원하는 kind는 다음과 같습니다.

#define BTF_KIND_INT            1       /* Integer      */
#define BTF_KIND_PTR            2       /* Pointer      */
#define BTF_KIND_ARRAY          3       /* Array        */
#define BTF_KIND_STRUCT         4       /* Struct       */
#define BTF_KIND_UNION          5       /* Union        */
#define BTF_KIND_ENUM           6       /* Enumeration up to 32-bit values */
#define BTF_KIND_FWD            7       /* Forward      */
#define BTF_KIND_TYPEDEF        8       /* Typedef      */
#define BTF_KIND_VOLATILE       9       /* Volatile     */
#define BTF_KIND_CONST          10      /* Const        */
#define BTF_KIND_RESTRICT       11      /* Restrict     */
#define BTF_KIND_FUNC           12      /* Function     */
#define BTF_KIND_FUNC_PROTO     13      /* Function Proto       */
#define BTF_KIND_VAR            14      /* Variable     */
#define BTF_KIND_DATASEC        15      /* Section      */
#define BTF_KIND_FLOAT          16      /* Floating point       */
#define BTF_KIND_DECL_TAG       17      /* Decl Tag     */
#define BTF_KIND_TYPE_TAG       18      /* Type Tag     */
#define BTF_KIND_ENUM64         19      /* Enumeration up to 64-bit values */

type section은 순수 type만이 아니라 debug info를 encode합니다. `BTF_KIND_FUNC`는 type이 아니며 정의된 subprogram을 나타냅니다.

각 type에는 다음 공통 data가 있습니다.

struct btf_type {
    __u32 name_off;
    /* "info" bits arrangement
     * bits  0-15: vlen (e.g. # of struct's members)
     * bits 16-23: unused
     * bits 24-28: kind (e.g. int, ptr, array...etc)
     * bits 29-30: unused
     * bit     31: kind_flag, currently used by
     *             struct, union, enum, fwd, enum64,
     *             decl_tag and type_tag
     */
    __u32 info;
    /* "size" is used by INT, ENUM, STRUCT, UNION and ENUM64.
     * "size" tells the size of the type it is describing.
     *
     * "type" is used by PTR, TYPEDEF, VOLATILE, CONST, RESTRICT,
     * FUNC, FUNC_PROTO, DECL_TAG and TYPE_TAG.
     * "type" is a type_id referring to another type.
     */
    union {
            __u32 size;
            __u32 type;
    };
};

특정 kind에서는 공통 data 뒤에 kind-specific data가 이어집니다. `struct btf_type`의 `name_off`는 string table offset을 지정합니다. 다음 절에서 각 kind의 encoding을 설명합니다.

BTF_KIND_INT와 bitfield

126-177

`BTF_KIND_INT`의 `struct btf_type` encoding requirement는 다음과 같습니다.

  • `name_off`: 유효한 offset
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_INT`
  • `info.vlen`: 0
  • `size`: int type의 byte 단위 size

`btf_type` 뒤에는 다음 bit arrangement를 가진 `u32`가 옵니다.

#define BTF_INT_ENCODING(VAL)   (((VAL) & 0x0f000000) >> 24)
#define BTF_INT_OFFSET(VAL)     (((VAL) & 0x00ff0000) >> 16)
#define BTF_INT_BITS(VAL)       ((VAL)  & 0x000000ff)

`BTF_INT_ENCODING`에는 다음 attribute가 있습니다.

#define BTF_INT_SIGNED  (1 << 0)
#define BTF_INT_CHAR    (1 << 1)
#define BTF_INT_BOOL    (1 << 2)

`BTF_INT_ENCODING()`은 int type의 signedness, char, bool 추가 정보를 제공합니다. char와 bool encoding은 주로 pretty print에 유용하며 int type에는 최대 하나의 encoding만 지정할 수 있습니다.

`BTF_INT_BITS()`는 이 int type이 실제로 보유한 bit 수를 지정합니다. 예를 들어 4-bit bitfield는 `BTF_INT_BITS() = 4`로 encode합니다. type의 `btf_type.size * 8`은 `BTF_INT_BITS()` 이상이어야 하며 최대값은 128입니다.

`BTF_INT_OFFSET()`은 이 int에서 value를 계산할 시작 bit offset을 지정합니다. 예를 들어 다음 bitfield struct member를 생각할 수 있습니다.

  • structure 시작에서 BTF member bit offset은 100입니다.
  • BTF member는 int type을 가리킵니다.
  • int type은 `BTF_INT_OFFSET() = 2`, `BTF_INT_BITS() = 4`입니다.

이 member는 struct memory layout에서 `100 + 2 = 102` bit부터 4 bits를 차지합니다. 같은 bit에 access하려면 다음처럼 encode할 수도 있습니다.

  • BTF member bit offset은 102입니다.
  • BTF member는 int type을 가리킵니다.
  • int type은 `BTF_INT_OFFSET() = 0`, `BTF_INT_BITS() = 4`입니다.

`BTF_INT_OFFSET()`의 원래 목적은 bitfield encoding에 flexibility를 주는 것입니다. 현재 LLVM과 pahole은 모든 int type에 `BTF_INT_OFFSET() = 0`을 생성합니다.

BTF_KIND_PTR와 BTF_KIND_ARRAY

178-232

`BTF_KIND_PTR`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_PTR`
  • `info.vlen`: 0
  • `type`: pointer가 가리키는 pointee type

`btf_type` 뒤에 추가 type data는 없습니다.

`BTF_KIND_ARRAY`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_ARRAY`
  • `info.vlen`: 0
  • `size/type`: 사용하지 않으므로 0

`btf_type` 뒤에는 `struct btf_array` 하나가 옵니다.

struct btf_array {
    __u32   type;
    __u32   index_type;
    __u32   nelems;
};

`struct btf_array`의 field는 다음과 같습니다.

  • `type`: element type
  • `index_type`: index type
  • `nelems`: array의 element 수이며 `0`도 허용

`index_type`은 `u8`, `u16`, `u32`, `u64`, `unsigned __int128` 같은 regular int type일 수 있습니다. `index_type`을 둔 초기 설계는 array type에 `index_type`이 있는 DWARF를 따랐습니다. 현재 BTF에서는 type verification 외에 `index_type`을 사용하지 않습니다.

`struct btf_array`는 element type을 따라 chain을 만들어 multidimensional array를 표현할 수 있습니다. `int a[5][6]`의 type 정보는 다음과 같습니다.

  • [1]: int
  • [2]: array, `btf_array.type = [1]`, `btf_array.nelems = 6`
  • [3]: array, `btf_array.type = [2]`, `btf_array.nelems = 5`

현재 pahole과 LLVM은 multidimensional array를 one-dimensional array로 collapse합니다. 예를 들어 `a[5][6]`의 `btf_array.nelems`는 30입니다. 초기 use case인 map pretty print에서는 array 전체를 dump하므로 one-dimensional representation이면 충분했기 때문입니다. BTF 사용이 확대되면 proper chained representation을 생성하도록 pahole과 LLVM을 바꿀 수 있습니다.

BTF_KIND_STRUCT와 BTF_KIND_UNION

233-278

struct와 union의 `struct btf_type` encoding requirement는 다음과 같습니다.

  • `name_off`: 0 또는 valid C identifier의 offset
  • `info.kind_flag`: 0 또는 1
  • `info.kind`: `BTF_KIND_STRUCT` 또는 `BTF_KIND_UNION`
  • `info.vlen`: struct/union member 수
  • `info.size`: struct/union의 byte 단위 size

`btf_type` 뒤에는 `info.vlen`개의 `struct btf_member`가 옵니다.

struct btf_member {
    __u32   name_off;
    __u32   type;
    __u32   offset;
};

`struct btf_member` encoding은 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `type`: member type
  • `offset`: 아래 규칙에 따른 값

type info의 `kind_flag`가 설정되지 않으면 offset에는 member의 bit offset만 들어갑니다. bitfield base type은 int 또는 enum만 가능합니다. bitfield size가 32이면 base type이 int 또는 enum일 수 있습니다. size가 32가 아니면 base type은 int여야 하며 int type의 `BTF_INT_BITS()`가 bitfield size를 encode합니다.

`kind_flag`가 설정되면 `btf_member.offset`에 member bitfield size와 bit offset이 모두 들어가며 다음처럼 계산합니다.

#define BTF_MEMBER_BITFIELD_SIZE(val)   ((val) >> 24)
#define BTF_MEMBER_BIT_OFFSET(val)      ((val) & 0xffffff)

이 경우 base type이 int라면 regular int type이어야 하며 다음을 만족해야 합니다.

  • `BTF_INT_OFFSET()`은 0이어야 합니다.
  • `BTF_INT_BITS()`는 `{1,2,4,8,16} * 8` 중 하나여야 합니다.

commit `9d5f9f701b18`이 `kind_flag`를 도입했으며 두 mode가 모두 존재하는 이유를 설명합니다.

BTF_KIND_ENUM과 BTF_KIND_FWD

279-316

`BTF_KIND_ENUM`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0 또는 valid C identifier의 offset
  • `info.kind_flag`: unsigned이면 0, signed이면 1
  • `info.kind`: `BTF_KIND_ENUM`
  • `info.vlen`: enum value 수
  • `size`: 1, 2, 4, 8 중 하나

`btf_type` 뒤에는 `info.vlen`개의 `struct btf_enum`이 옵니다.

struct btf_enum {
    __u32   name_off;
    __s32   val;
};

`btf_enum` encoding은 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `val`: 임의의 value

원래 enum value가 signed이고 size가 4보다 작으면 value를 4 bytes로 sign-extend합니다. size가 8이면 value를 4 bytes로 truncate합니다.

`BTF_KIND_FWD`의 encoding requirement는 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `info.kind_flag`: struct이면 0, union이면 1
  • `info.kind`: `BTF_KIND_FWD`
  • `info.vlen`: 0
  • `type`: 0

`btf_type` 뒤에 추가 type data는 없습니다.

Alias·qualifier와 BTF_KIND_FUNC

317-386

`BTF_KIND_TYPEDEF`의 encoding requirement는 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_TYPEDEF`
  • `info.vlen`: 0
  • `type`: `name_off`의 이름으로 참조할 type

`BTF_KIND_VOLATILE`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_VOLATILE`
  • `info.vlen`: 0
  • `type`: `volatile` qualifier가 붙은 type

`BTF_KIND_CONST`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_CONST`
  • `info.vlen`: 0
  • `type`: `const` qualifier가 붙은 type

`BTF_KIND_RESTRICT`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_RESTRICT`
  • `info.vlen`: 0
  • `type`: `restrict` qualifier가 붙은 type

위 네 kind 모두 `btf_type` 뒤에 추가 type data가 없습니다. `BTF_KIND_FUNC`의 encoding requirement는 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_FUNC`
  • `info.vlen`: `BTF_FUNC_STATIC`, `BTF_FUNC_GLOBAL`, `BTF_FUNC_EXTERN` 중 linkage 정보
  • `type`: `BTF_KIND_FUNC_PROTO` type

`BTF_KIND_FUNC`는 type이 아니라 `type`이 signature를 정의하는 subprogram(function)을 나타냅니다. 즉 subprogram은 해당 type의 instance입니다. `BTF_KIND_FUNC`는 `.BTF.ext`의 `func_info` 또는 `BPF_PROG_LOAD` ABI argument에서 참조될 수 있습니다.

현재 kernel은 `BTF_FUNC_STATIC`과 `BTF_FUNC_GLOBAL` linkage value만 지원합니다.

BTF_KIND_FUNC_PROTO

387-410

`BTF_KIND_FUNC_PROTO`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_FUNC_PROTO`
  • `info.vlen`: parameter 수
  • `type`: return type

`btf_type` 뒤에는 `info.vlen`개의 `struct btf_param`이 옵니다.

struct btf_param {
    __u32   name_off;
    __u32   type;
};

`BTF_KIND_FUNC_PROTO` type을 `BTF_KIND_FUNC`가 참조하면 variable argument를 나타낼 수 있는 마지막 argument를 제외하고 `btf_param.name_off`는 valid C identifier를 가리켜야 합니다. `btf_param.type`은 parameter type을 참조합니다.

function에 variable argument가 있으면 마지막 parameter를 `name_off = 0`, `type = 0`으로 encode합니다.

BTF_KIND_VAR와 BTF_KIND_DATASEC

411-464

`BTF_KIND_VAR`의 encoding requirement는 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_VAR`
  • `info.vlen`: 0
  • `type`: variable type

`btf_type` 뒤에는 다음 `struct btf_var` 하나가 옵니다.

struct btf_var {
    __u32   linkage;
};

`btf_var.linkage`는 `BTF_VAR_STATIC`, `BTF_VAR_GLOBAL_ALLOCATED`, `BTF_VAR_GLOBAL_EXTERN` 중 하나입니다.

현재 LLVM이 지원하는 global variable type은 다음과 같습니다.

  • section attribute가 있거나 없는 static variable
  • section attribute가 있는 global variable

두 번째 항목은 앞으로 map definition에서 map key/value type id를 추출하기 위한 것입니다.

`BTF_KIND_DATASEC`의 encoding requirement는 다음과 같습니다.

  • `name_off`: variable과 연결된 valid name 또는 `.data`, `.bss`, `.rodata` 중 하나의 offset
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_DATASEC`
  • `info.vlen`: variable 수
  • `size`: 전체 section의 byte 단위 size. compile 시에는 0이고 libbpf 같은 BPF loader가 실제 size로 patch합니다.

`btf_type` 뒤에는 `info.vlen`개의 `struct btf_var_secinfo`가 옵니다.

struct btf_var_secinfo {
    __u32   type;
    __u32   offset;
    __u32   size;
};

`struct btf_var_secinfo` encoding은 다음과 같습니다.

  • `type`: `BTF_KIND_VAR` variable의 type
  • `offset`: section 안에서 variable의 offset
  • `size`: variable의 byte 단위 size

BTF_KIND_FLOAT와 BTF_KIND_DECL_TAG

465-510

`BTF_KIND_FLOAT`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 유효한 offset
  • `info.kind_flag`: 0
  • `info.kind`: `BTF_KIND_FLOAT`
  • `info.vlen`: 0
  • `size`: float type의 byte 단위 size로 2, 4, 8, 12, 16 중 하나

`btf_type` 뒤에 추가 type data는 없습니다.

`BTF_KIND_DECL_TAG`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 비어 있지 않은 string의 offset
  • `info.kind_flag`: 0 또는 1
  • `info.kind`: `BTF_KIND_DECL_TAG`
  • `info.vlen`: 0
  • `type`: `struct`, `union`, `func`, `var`, `typedef` 중 하나

`btf_type` 뒤에는 다음 `struct btf_decl_tag`가 옵니다.

struct btf_decl_tag {
    __u32   component_idx;
};

`type`은 `struct`, `union`, `func`, `var`, `typedef` 중 하나여야 합니다. `var` 또는 `typedef`에서는 `btf_decl_tag.component_idx`가 `-1`이어야 합니다.

나머지 세 type에서 attribute를 `struct`, `union`, `func` 자체에 적용하면 `component_idx`는 `-1`입니다. member 또는 function argument에 적용하면 0부터 시작하는 valid member/argument index여야 합니다.

`info.kind_flag`가 0이면 normal decl tag이고 `name_off`는 `btf_decl_tag` attribute string을 encode합니다. 1이면 decl tag가 임의의 `__attribute__`를 나타내며 `name_off`는 attribute specifier의 attribute-list string을 encode합니다. 예를 들어 `__attribute__((aligned(4)))`의 string 내용은 `aligned(4)`입니다.

BTF_KIND_TYPE_TAG와 BTF_KIND_ENUM64

511-567

`BTF_KIND_TYPE_TAG`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 비어 있지 않은 string의 offset
  • `info.kind_flag`: 0 또는 1
  • `info.kind`: `BTF_KIND_TYPE_TAG`
  • `info.vlen`: 0
  • `type`: `btf_type_tag` attribute가 붙은 type

현재 `BTF_KIND_TYPE_TAG`는 pointer type에만 emit되며 다음 BTF type chain을 가집니다.

ptr -> [type_tag]*
    -> [const | volatile | restrict | typedef]*
    -> base_type

pointer type은 0개 이상의 type tag, 이어서 0개 이상의 const·volatile·restrict·typedef, 마지막으로 base type을 가리킵니다. base type은 int, ptr, array, struct, union, enum, func_proto, float 중 하나입니다.

decl tag와 마찬가지로 `info.kind_flag`가 0이면 normal type tag이고 `name_off`가 `btf_type_tag` attribute string을 encode합니다. 1이면 임의의 `__attribute__`를 나타내며 `name_off`는 attribute specifier의 attribute-list string을 encode합니다.

`BTF_KIND_ENUM64`의 encoding requirement는 다음과 같습니다.

  • `name_off`: 0 또는 valid C identifier의 offset
  • `info.kind_flag`: unsigned이면 0, signed이면 1
  • `info.kind`: `BTF_KIND_ENUM64`
  • `info.vlen`: enum value 수
  • `size`: 1, 2, 4, 8 중 하나

`btf_type` 뒤에는 `info.vlen`개의 `struct btf_enum64`가 옵니다.

struct btf_enum64 {
    __u32   name_off;
    __u32   val_lo32;
    __u32   val_hi32;
};

`btf_enum64` encoding은 다음과 같습니다.

  • `name_off`: valid C identifier의 offset
  • `val_lo32`: 64-bit value의 lower 32-bit
  • `val_hi32`: 64-bit value의 high 32-bit

원래 enum value가 signed이고 size가 8보다 작으면 value를 8 bytes로 sign-extend합니다.

Function·variable linkage constant

568-599

function linkage constant의 value와 의미는 다음과 같습니다.

kindvaluedescription
`BTF_FUNC_STATIC`0x0containing compilation unit 밖에서 보이지 않는 subprogram definition
`BTF_FUNC_GLOBAL`0x1containing compilation unit 밖에서도 보이는 subprogram definition
`BTF_FUNC_EXTERN`0x2definition이 containing compilation unit 밖에 있는 subprogram declaration

variable linkage constant의 value와 의미는 다음과 같습니다.

kindvaluedescription
`BTF_VAR_STATIC`0x0containing compilation unit 밖에서 보이지 않는 global variable definition
`BTF_VAR_GLOBAL_ALLOCATED`0x1containing compilation unit 밖에서도 보이는 global variable definition
`BTF_VAR_GLOBAL_EXTERN`0x2definition이 containing compilation unit 밖에 있는 global variable declaration

BTF kernel API workflow

600-642

BTF와 관련된 `bpf` syscall command는 다음과 같습니다.

  • `BPF_BTF_LOAD`: BTF data blob을 kernel에 load합니다.
  • `BPF_MAP_CREATE`: BTF key/value type info와 함께 map을 생성합니다.
  • `BPF_PROG_LOAD`: BTF function info와 line info를 포함해 program을 load합니다.
  • `BPF_BTF_GET_FD_BY_ID`: BTF fd를 얻습니다.
  • `BPF_OBJ_GET_INFO_BY_FD`: BTF, `func_info`, `line_info`와 그 밖의 BTF 관련 정보를 반환합니다.

일반적인 workflow는 application load 경로와 introspection 경로로 나뉩니다.

BTF load와 introspection workflow
ApplicationBPF_BTF_LOADBPF_MAP_CREATE / BPF_PROG_LOADProgram operation
Introspection toolBPF_{PROG,MAP}_GET_NEXT_IDBPF_{PROG,MAP}_GET_FD_BY_IDBPF_OBJ_GET_INFO_BY_FD: btf_idBPF_BTF_GET_FD_BY_IDBPF_OBJ_GET_INFO_BY_FD: BTF blobPretty print / signatures / line info

application은 BTF를 먼저 load한 뒤 map과 program을 만들고, introspection tool은 ID에서 fd와 BTF blob을 얻어 type·signature·line info를 해석합니다.

BPF_BTF_LOAD와 BPF_MAP_CREATE

643-673

`BPF_BTF_LOAD`는 BTF Type and String Encoding에서 설명한 BTF data blob을 kernel에 직접 load하고 userspace에 `btf_fd`를 반환합니다.

map은 `btf_fd`와 지정한 key/value type id로 생성할 수 있습니다.

__u32   btf_fd;         /* fd pointing to a BTF type data */
__u32   btf_key_type_id;        /* BTF type_id of the key */
__u32   btf_value_type_id;      /* BTF type_id of the value */

libbpf에서는 다음처럼 추가 annotation으로 map을 정의할 수 있습니다.

struct {
    __uint(type, BPF_MAP_TYPE_ARRAY);
    __type(key, int);
    __type(value, struct ipv_counts);
    __uint(max_entries, 4);
} btf_map SEC(".maps");

ELF를 parse하는 동안 libbpf는 key/value `type_id`를 추출해 `BPF_MAP_CREATE` attribute에 자동으로 할당할 수 있습니다.

BPF_PROG_LOAD의 func_info와 line_info

674-723

`prog_load` 중에는 다음 attribute에 적절한 값을 넣어 `func_info`와 `line_info`를 kernel에 전달할 수 있습니다.

__u32           insn_cnt;
__aligned_u64   insns;
......
__u32           prog_btf_fd;    /* fd pointing to BTF type data */
__u32           func_info_rec_size;     /* userspace bpf_func_info size */
__aligned_u64   func_info;      /* func info */
__u32           func_info_cnt;  /* number of bpf_func_info records */
__u32           line_info_rec_size;     /* userspace bpf_line_info size */
__aligned_u64   line_info;      /* line info */
__u32           line_info_cnt;  /* number of bpf_line_info records */

`func_info`와 `line_info`는 각각 다음 structure의 array입니다.

struct bpf_func_info {
    __u32   insn_off; /* [0, insn_cnt - 1] */
    __u32   type_id;  /* pointing to a BTF_KIND_FUNC type */
};
struct bpf_line_info {
    __u32   insn_off; /* [0, insn_cnt - 1] */
    __u32   file_name_off; /* offset to string table for the filename */
    __u32   line_off; /* offset to string table for the source line */
    __u32   line_col; /* line number and column number */
};

`func_info_rec_size`와 `line_info_rec_size`는 각 record의 size입니다. record size를 kernel에 전달하면 미래에 record 자체를 확장할 수 있습니다.

`func_info` requirement는 다음과 같습니다.

  • `func_info[0].insn_off`는 0이어야 합니다.
  • `func_info`의 `insn_off`는 strictly increasing order이며 BPF function boundary와 일치해야 합니다.

`line_info` requirement는 다음과 같습니다.

  • 각 function의 첫 instruction을 가리키는 `line_info` record가 있어야 합니다.
  • `line_info`의 `insn_off`는 strictly increasing order여야 합니다.

`line_info`의 line number와 column number는 다음처럼 정의합니다.

#define BPF_LINE_INFO_LINE_NUM(line_col)        ((line_col) >> 10)
#define BPF_LINE_INFO_LINE_COL(line_col)        ((line_col) & 0x3ff)

ID·fd 기반 introspection API

724-760

kernel에서 load된 모든 program, map, BTF는 unique id를 가집니다. 이 id는 program, map, BTF의 lifetime 동안 바뀌지 않습니다.

`BPF_{PROG,MAP}_GET_NEXT_ID` syscall command는 BPF program과 map의 모든 id를 userspace에 각각 반환하므로 inspection tool이 모든 program과 map을 조사할 수 있습니다.

introspection tool은 id만으로 program이나 map detail을 얻을 수 없습니다. reference counting을 위해 먼저 `BPF_{PROG,MAP}_GET_FD_BY_ID`로 file descriptor를 얻어야 합니다.

program/map fd를 얻으면 `BPF_OBJ_GET_INFO_BY_FD`로 해당 fd의 detail을 kernel에서 가져올 수 있으며 일부는 BTF 관련 정보입니다. `bpf_map_info`는 `btf_id`와 key/value type id를, `bpf_prog_info`는 translated BPF bytecode의 `btf_id`, `func_info`, line info와 `jited_line_info`를 반환합니다.

`bpf_map_info`와 `bpf_prog_info`에서 얻은 `btf_id`를 사용해 `BPF_BTF_GET_FD_BY_ID`로 BTF fd를 가져옵니다. 이어 `BPF_OBJ_GET_INFO_BY_FD`로 원래 `BPF_BTF_LOAD`가 kernel에 load한 BTF blob을 가져올 수 있습니다.

BTF blob, `bpf_map_info`, `bpf_prog_info`를 갖춘 introspection tool은 전체 BTF 정보를 이용해 map key/value를 pretty print하고 byte/JIT code와 함께 function signature와 line info를 dump할 수 있습니다.

.BTF와 .BTF.ext header

761-804

ELF `.BTF` section은 type data와 string data를 포함하며 format은 BTF Type and String Encoding에서 설명한 것과 같습니다.

`.BTF.ext` section은 kernel에 load하기 전에 loader가 조작해야 하는 `func_info`, `line_info`, CO-RE relocation을 encode합니다. specification은 `tools/lib/bpf/btf.h`와 `tools/lib/bpf/btf.c`에 정의돼 있습니다.

현재 `.BTF.ext` section header는 다음과 같습니다.

struct btf_ext_header {
    __u16   magic;
    __u8    version;
    __u8    flags;
    __u32   hdr_len;

    /* All offsets are in bytes relative to the end of this header */
    __u32   func_info_off;
    __u32   func_info_len;
    __u32   line_info_off;
    __u32   line_info_len;

    /* optional part of .BTF.ext header */
    __u32   core_relo_off;
    __u32   core_relo_len;
};

`.BTF` section과 매우 비슷하지만 type/string section 대신 `func_info`, `line_info`, `core_relo` sub-section을 포함합니다. `func_info`와 `line_info` record format은 `BPF_PROG_LOAD` 절을 참조하십시오.

.BTF.ext sub-section layout

805-854

`func_info`는 다음처럼 구성됩니다.

func_info_rec_size              /* __u32 value */
btf_ext_info_sec for section #1 /* func_info for section #1 */
btf_ext_info_sec for section #2 /* func_info for section #2 */
...

`func_info_rec_size`는 `.BTF.ext`를 생성할 때의 `bpf_func_info` structure size입니다. `btf_ext_info_sec`은 각 ELF section별 `func_info` collection입니다.

struct btf_ext_info_sec {
   __u32   sec_name_off; /* offset to section name */
   __u32   num_info;
   /* Followed by num_info * record_size number of bytes */
   __u8    data[0];
};

여기서 `num_info`는 0보다 커야 합니다. `line_info`는 다음처럼 구성됩니다.

line_info_rec_size              /* __u32 value */
btf_ext_info_sec for section #1 /* line_info for section #1 */
btf_ext_info_sec for section #2 /* line_info for section #2 */
...

`line_info_rec_size`는 `.BTF.ext`를 생성할 때의 `bpf_line_info` structure size입니다.

`bpf_func_info->insn_off`와 `bpf_line_info->insn_off`의 해석은 kernel API와 ELF API에서 다릅니다. kernel API에서는 `struct bpf_insn` 단위의 instruction offset이고, ELF API에서는 section 시작인 `btf_ext_info_sec->sec_name_off`부터의 byte offset입니다.

`core_relo`는 다음처럼 구성됩니다.

core_relo_rec_size              /* __u32 value */
btf_ext_info_sec for section #1 /* core_relo for section #1 */
btf_ext_info_sec for section #2 /* core_relo for section #2 */

`core_relo_rec_size`는 `.BTF.ext` 생성 시 `bpf_core_relo` structure size입니다. 하나의 `btf_ext_info_sec` 안에 있는 모든 `bpf_core_relo` structure는 `btf_ext_info_sec->sec_name_off`가 이름을 지정한 section에 적용할 relocation을 설명합니다.

CO-RE relocation에 관한 자세한 내용은 `Documentation/bpf/llvm_reloc.rst`의 `btf-co-re-relocations`를 참조하십시오.

.BTF_ids list와 set

855-915

`.BTF_ids` section은 kernel 안에서 사용하는 BTF ID value를 encode합니다. kernel compile 중 `include/linux/btf_ids.h`의 macro로 생성하며 kernel code는 이 macro로 BTF ID value의 list와 sorted list인 set을 만들 수 있습니다.

`BTF_ID_LIST`와 `BTF_ID` macro는 다음 syntax로 unsorted BTF ID list를 정의합니다.

BTF_ID_LIST(list)
BTF_ID(type1, name1)
BTF_ID(type2, name2)

그 결과 `.BTF_ids` section에는 다음 layout이 생깁니다.

__BTF_ID__type1__name1__1:
.zero 4
__BTF_ID__type2__name2__2:
.zero 4

list에 access하도록 `u32 list[];` variable이 정의됩니다.

`BTF_ID_UNUSED` macro는 zero byte 4개를 정의하며 `BTF_ID_LIST` 안의 unused entry를 만들 때 사용합니다.

BTF_ID_LIST(bpf_skb_output_btf_ids)
BTF_ID(struct, sk_buff)
BTF_ID_UNUSED
BTF_ID(struct, task_struct)

`BTF_SET_START/END` macro pair는 다음 syntax로 BTF ID value의 sorted list와 count를 정의합니다.

BTF_SET_START(set)
BTF_ID(type1, name1)
BTF_ID(type2, name2)
BTF_SET_END(set)

그 결과 `.BTF_ids` section에는 다음 layout이 생깁니다.

__BTF_ID__set__set:
.zero 4
__BTF_ID__type1__name1__3:
.zero 4
__BTF_ID__type2__name2__4:
.zero 4

list에 access하도록 `struct btf_id_set set;` variable이 정의됩니다.

`typeX` name은 다음 중 하나이며 BTF ID value를 resolve할 때 filter로 사용합니다.

struct, union, typedef, func

모든 BTF ID list와 set은 `.BTF_ids` section에 compile되며 kernel build의 linking phase에서 `resolve_btfids` tool이 resolve합니다.

Split BTF와 .BTF.base relocation

916-990

split BTF는 `.BTF` section에 연결된 base `.BTF` section에 없는 type만 담는 방식입니다. module-specific type은 적고 공유 kernel type은 많은 kernel module의 type 정보를 매우 효율적으로 encode합니다. 전자는 split BTF에, 후자는 base BTF에 encode돼 더 compact한 representation을 만듭니다.

split BTF의 type이 base BTF type을 참조할 때 base BTF ID를 사용하며 split BTF ID는 `last_base_BTF_ID + 1`부터 시작합니다.

단점은 base BTF가 바뀌면 base BTF ID reference가 더 이상 valid하지 않아 split BTF가 쓸모없어지는 brittle한 구조라는 점입니다. `.BTF.base` section은 kernel이 매번 build될 때 함께 build되지 않는 out-of-tree module처럼 base BTF가 바뀔 수 있는 경우 split BTF를 더 resilient하게 만듭니다.

`.BTF.base`에는 이름 있는 base type인 INT, FLOAT, STRUCT, UNION, ENUM/ENUM64, FWD를 담습니다. INT와 FLOAT는 완전히 설명하지만 struct·union 같은 composite type은 완전히 정의하지 않습니다. split BTF가 참조한 type을 식별하는 설명만 제공하므로 struct/union은 member 0개로 기록하며 ENUM/ENUM64도 value 0개로 기록합니다. 그 밖의 type은 split BTF에 들어갑니다.

이 distillation 결과 base type의 최소 설명을 담은 `.BTF.base`와 이를 참조하는 split `.BTF`가 남습니다. 나중에 `.BTF.base`의 정보와 새 base BTF를 함께 사용해 split BTF를 relocate할 수 있습니다. `.BTF.base` type 정보로 split BTF reference가 대응하는 새 base BTF ID를 가리키도록 update합니다.

kernel module에 `.BTF.base` section이 있으면 module load 시 BTF relocation을 수행합니다. libbpf도 같은 작업을 하는 `btf__relocate()` API를 제공합니다.

예를 들어 다음 base BTF를 생각합니다.

[1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[2] STRUCT 'foo' size=8 vlen=2
        'f1' type_id=1 bits_offset=0
        'f2' type_id=1 bits_offset=32

연결된 split BTF는 다음과 같습니다.

[3] PTR '(anon)' type_id=2

즉 split BTF는 `struct foo { int f1; int f2; }`를 가리키는 pointer를 설명합니다. `.BTF.base`는 다음과 같이 구성됩니다.

[1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[2] STRUCT 'foo' size=8 vlen=0

나중에 다음 새 base BTF로 split BTF를 relocate한다고 가정합니다.

[1] INT 'long unsigned int' size=8 bits_offset=0 nr_bits=64 encoding=(none)
[2] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[3] STRUCT 'foo' size=8 vlen=2
        'f1' type_id=2 bits_offset=0
        'f2' type_id=2 bits_offset=32

`.BTF.base` description을 사용하면 split BTF reference가 `struct foo`를 대상으로 함을 알 수 있고 relocation 결과는 다음 새 split BTF가 됩니다.

[4] PTR '(anon)' type_id=3

split BTF의 BTF ID와 시작 BTF ID를 update해야 했습니다. 이처럼 `.BTF.base`는 이후 relocation을 가능하게 해 split BTF를 더 resilient하게 만듭니다.

`.BTF.base` section은 `KBUILD_EXTMOD`가 설정되는 out-of-tree kernel module build, 예를 들어 `make M=path/2/mod`에서 자동 생성됩니다. 생성에는 pahole의 `distilled_base` BTF feature가 필요하며 pahole v1.28 이상에서 지원합니다.

bpftool map pretty print

991-1034

BTF를 사용하면 map key/value를 raw byte가 아니라 field를 기준으로 출력할 수 있습니다. 큰 structure나 bitfield가 있는 data structure에서 특히 유용합니다. 다음 map을 예로 듭니다.

enum A { A1, A2, A3, A4, A5 };
typedef enum A ___A;
struct tmp_t {
     char a1:4;
     int  a2:4;
     int  :4;
     __u32 a3:4;
     int b;
     ___A b1:4;
     enum A b2:4;
};
struct {
     __uint(type, BPF_MAP_TYPE_ARRAY);
     __type(key, int);
     __type(value, struct tmp_t);
     __uint(max_entries, 1);
} tmpmap SEC(".maps");

bpftool은 다음처럼 pretty print할 수 있습니다.

[{
      "key": 0,
      "value": {
          "a1": 0x2,
          "a2": 0x4,
          "a3": 0x6,
          "b": 7,
          "b1": 0x8,
          "b2": 0xa
      }
  }
]

bpftool prog dump

1035-1068

다음 예제는 `func_info`와 `line_info`를 이용해 더 나은 kernel symbol name, function prototype, line 정보를 포함한 program dump를 만드는 방법을 보여 줍니다.

$ bpftool prog dump jited pinned /sys/fs/bpf/test_btf_haskv
[...]
int test_long_fname_2(struct dummy_tracepoint_args * arg):
bpf_prog_44a040bf25481309_test_long_fname_2:
; static int test_long_fname_2(struct dummy_tracepoint_args *arg)
   0:   push   %rbp
   1:   mov    %rsp,%rbp
   4:   sub    $0x30,%rsp
   b:   sub    $0x28,%rbp
   f:   mov    %rbx,0x0(%rbp)
  13:   mov    %r13,0x8(%rbp)
  17:   mov    %r14,0x10(%rbp)
  1b:   mov    %r15,0x18(%rbp)
  1f:   xor    %eax,%eax
  21:   mov    %rax,0x20(%rbp)
  25:   xor    %esi,%esi
; int key = 0;
  27:   mov    %esi,-0x4(%rbp)
; if (!arg->sock)
  2a:   mov    0x8(%rdi),%rdi
; if (!arg->sock)
  2e:   cmp    $0x0,%rdi
  32:   je     0x0000000000000070
  34:   mov    %rbp,%rsi
; counts = bpf_map_lookup_elem(&btf_map, &key);
[...]

Verifier log의 source line 정보

1069-1094

다음 예제는 `line_info`가 verification failure debug에 어떻게 도움을 주는지 보여 줍니다. `tools/testing/selftests/bpf/test_xdp_noinline.c`에서 packet boundary check를 주석 처리하면 verifier log가 문제가 난 source line과 invalid packet access를 함께 표시합니다.

   /* The code at tools/testing/selftests/bpf/test_xdp_noinline.c
    * is modified as below.
    */
   data = (void *)(long)xdp->data;
   data_end = (void *)(long)xdp->data_end;
   /*
   if (data + 4 > data_end)
           return XDP_DROP;
   */
   *(u32 *)data = dst->dst;

$ bpftool prog load ./test_xdp_noinline.o /sys/fs/bpf/test_xdp_noinline type xdp
    ; data = (void *)(long)xdp->data;
    224: (79) r2 = *(u64 *)(r10 -112)
    225: (61) r2 = *(u32 *)(r2 +0)
    ; *(u32 *)data = dst->dst;
    226: (63) *(u32 *)(r2 +0) = r1
    invalid access to packet, off=0 size=4, R2(id=0,off=0,r=0)
    R2 offset is outside of the packet

pahole과 LLVM의 BTF 생성

1095-1201

BTF를 생성하려면 최신 pahole `https://git.kernel.org/pub/scm/devel/pahole/pahole.git/` 또는 LLVM 8.0 이상이 필요합니다.

pahole은 DWARF-to-BTF converter로 동작합니다. 이 문서의 설명 시점에는 `.BTF.ext`와 BTF `BTF_KIND_FUNC` type을 지원하지 않습니다. 다음은 bitfield structure를 compile하고 pahole로 BTF를 표시하는 예입니다.

-bash-4.4$ cat t.c
struct t {
  int a:2;
  int b:3;
  int c:2;
} g;
-bash-4.4$ gcc -c -O2 -g t.c
-bash-4.4$ pahole -JV t.o
File t.o:
[1] STRUCT t kind_flag=1 size=4 vlen=3
        a type_id=2 bitfield_size=2 bits_offset=0
        b type_id=2 bitfield_size=3 bits_offset=2
        c type_id=2 bitfield_size=2 bits_offset=5
[2] INT int size=4 bit_offset=0 nr_bits=32 encoding=SIGNED

LLVM은 BPF target에 `-g`를 사용할 때만 `.BTF`와 `.BTF.ext`를 직접 생성할 수 있습니다. assembly code를 생성하는 `-S`를 사용하면 BTF encoding을 assembly format으로 확인할 수 있습니다.

-bash-4.4$ cat t2.c
typedef int __int32;
struct t2 {
  int a2;
  int (*f2)(char q1, __int32 q2, ...);
  int (*f3)();
} g2;
int main() { return 0; }
int test() { return 0; }
-bash-4.4$ clang -c -g -O2 --target=bpf t2.c
-bash-4.4$ readelf -S t2.o
  ......
  [ 8] .BTF              PROGBITS         0000000000000000  00000247
       000000000000016e  0000000000000000           0     0     1
  [ 9] .BTF.ext          PROGBITS         0000000000000000  000003b5
       0000000000000060  0000000000000000           0     0     1
  [10] .rel.BTF.ext      REL              0000000000000000  000007e0
       0000000000000040  0000000000000010          16     9     8
  ......
-bash-4.4$ clang -S -g -O2 --target=bpf t2.c
-bash-4.4$ cat t2.s
  ......
        .section        .BTF,"",@progbits
        .short  60319                   # 0xeb9f
        .byte   1
        .byte   0
        .long   24
        .long   0
        .long   220
        .long   220
        .long   122
        .long   0                       # BTF_KIND_FUNC_PROTO(id = 1)
        .long   218103808               # 0xd000000
        .long   2
        .long   83                      # BTF_KIND_INT(id = 2)
        .long   16777216                # 0x1000000
        .long   4
        .long   16777248                # 0x1000020
  ......
        .byte   0                       # string offset=0
        .ascii  ".text"                 # string offset=1
        .byte   0
        .ascii  "/home/yhs/tmp-pahole/t2.c" # string offset=7
        .byte   0
        .ascii  "int main() { return 0; }" # string offset=33
        .byte   0
        .ascii  "int test() { return 0; }" # string offset=58
        .byte   0
        .ascii  "int"                   # string offset=83
  ......
        .section        .BTF.ext,"",@progbits
        .short  60319                   # 0xeb9f
        .byte   1
        .byte   0
        .long   24
        .long   0
        .long   28
        .long   28
        .long   44
        .long   8                       # FuncInfo
        .long   1                       # FuncInfo section string offset=1
        .long   2
        .long   .Lfunc_begin0
        .long   3
        .long   .Lfunc_begin1
        .long   5
        .long   16                      # LineInfo
        .long   1                       # LineInfo section string offset=1
        .long   2
        .long   .Ltmp0
        .long   7
        .long   33
        .long   7182                    # Line 7 Col 14
        .long   .Ltmp3
        .long   7
        .long   58
        .long   8206                    # Line 8 Col 14

BTF selftest

1202-1210

kernel BPF selftest `tools/testing/selftests/bpf/prog_tests/btf.c`는 광범위한 BTF 관련 test를 제공합니다.

source는 `https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/prog_tests/btf.c`에서 확인할 수 있습니다.