1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0-only 3# 4# Copyright (C) 2018-2019 Netronome Systems, Inc. 5# Copyright (C) 2021 Isovalent, Inc. 6 7# In case user attempts to run with Python 2. 8from __future__ import print_function 9 10import argparse 11import re 12import sys, os 13 14class NoHelperFound(BaseException): 15 pass 16 17class NoSyscallCommandFound(BaseException): 18 pass 19 20class ParsingError(BaseException): 21 def __init__(self, line='<line not provided>', reader=None): 22 if reader: 23 BaseException.__init__(self, 24 'Error at file offset %d, parsing line: %s' % 25 (reader.tell(), line)) 26 else: 27 BaseException.__init__(self, 'Error parsing line: %s' % line) 28 29 30class APIElement(object): 31 """ 32 An object representing the description of an aspect of the eBPF API. 33 @proto: prototype of the API symbol 34 @desc: textual description of the symbol 35 @ret: (optional) description of any associated return value 36 """ 37 def __init__(self, proto='', desc='', ret=''): 38 self.proto = proto 39 self.desc = desc 40 self.ret = ret 41 42 43class Helper(APIElement): 44 """ 45 An object representing the description of an eBPF helper function. 46 @proto: function prototype of the helper function 47 @desc: textual description of the helper function 48 @ret: description of the return value of the helper function 49 """ 50 def proto_break_down(self): 51 """ 52 Break down helper function protocol into smaller chunks: return type, 53 name, distincts arguments. 54 """ 55 arg_re = re.compile('((\w+ )*?(\w+|...))( (\**)(\w+))?$') 56 res = {} 57 proto_re = re.compile('(.+) (\**)(\w+)\(((([^,]+)(, )?){1,5})\)$') 58 59 capture = proto_re.match(self.proto) 60 res['ret_type'] = capture.group(1) 61 res['ret_star'] = capture.group(2) 62 res['name'] = capture.group(3) 63 res['args'] = [] 64 65 args = capture.group(4).split(', ') 66 for a in args: 67 capture = arg_re.match(a) 68 res['args'].append({ 69 'type' : capture.group(1), 70 'star' : capture.group(5), 71 'name' : capture.group(6) 72 }) 73 74 return res 75 76 77class HeaderParser(object): 78 """ 79 An object used to parse a file in order to extract the documentation of a 80 list of eBPF helper functions. All the helpers that can be retrieved are 81 stored as Helper object, in the self.helpers() array. 82 @filename: name of file to parse, usually include/uapi/linux/bpf.h in the 83 kernel tree 84 """ 85 def __init__(self, filename): 86 self.reader = open(filename, 'r') 87 self.line = '' 88 self.helpers = [] 89 self.commands = [] 90 self.desc_unique_helpers = set() 91 self.define_unique_helpers = [] 92 self.desc_syscalls = [] 93 self.enum_syscalls = [] 94 95 def parse_element(self): 96 proto = self.parse_symbol() 97 desc = self.parse_desc(proto) 98 ret = self.parse_ret(proto) 99 return APIElement(proto=proto, desc=desc, ret=ret) 100 101 def parse_helper(self): 102 proto = self.parse_proto() 103 desc = self.parse_desc(proto) 104 ret = self.parse_ret(proto) 105 return Helper(proto=proto, desc=desc, ret=ret) 106 107 def parse_symbol(self): 108 p = re.compile(' \* ?(BPF\w+)$') 109 capture = p.match(self.line) 110 if not capture: 111 raise NoSyscallCommandFound 112 end_re = re.compile(' \* ?NOTES$') 113 end = end_re.match(self.line) 114 if end: 115 raise NoSyscallCommandFound 116 self.line = self.reader.readline() 117 return capture.group(1) 118 119 def parse_proto(self): 120 # Argument can be of shape: 121 # - "void" 122 # - "type name" 123 # - "type *name" 124 # - Same as above, with "const" and/or "struct" in front of type 125 # - "..." (undefined number of arguments, for bpf_trace_printk()) 126 # There is at least one term ("void"), and at most five arguments. 127 p = re.compile(' \* ?((.+) \**\w+\((((const )?(struct )?(\w+|\.\.\.)( \**\w+)?)(, )?){1,5}\))$') 128 capture = p.match(self.line) 129 if not capture: 130 raise NoHelperFound 131 self.line = self.reader.readline() 132 return capture.group(1) 133 134 def parse_desc(self, proto): 135 p = re.compile(' \* ?(?:\t| {5,8})Description$') 136 capture = p.match(self.line) 137 if not capture: 138 raise Exception("No description section found for " + proto) 139 # Description can be several lines, some of them possibly empty, and it 140 # stops when another subsection title is met. 141 desc = '' 142 desc_present = False 143 while True: 144 self.line = self.reader.readline() 145 if self.line == ' *\n': 146 desc += '\n' 147 else: 148 p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)') 149 capture = p.match(self.line) 150 if capture: 151 desc_present = True 152 desc += capture.group(1) + '\n' 153 else: 154 break 155 156 if not desc_present: 157 raise Exception("No description found for " + proto) 158 return desc 159 160 def parse_ret(self, proto): 161 p = re.compile(' \* ?(?:\t| {5,8})Return$') 162 capture = p.match(self.line) 163 if not capture: 164 raise Exception("No return section found for " + proto) 165 # Return value description can be several lines, some of them possibly 166 # empty, and it stops when another subsection title is met. 167 ret = '' 168 ret_present = False 169 while True: 170 self.line = self.reader.readline() 171 if self.line == ' *\n': 172 ret += '\n' 173 else: 174 p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)') 175 capture = p.match(self.line) 176 if capture: 177 ret_present = True 178 ret += capture.group(1) + '\n' 179 else: 180 break 181 182 if not ret_present: 183 raise Exception("No return found for " + proto) 184 return ret 185 186 def seek_to(self, target, help_message, discard_lines = 1): 187 self.reader.seek(0) 188 offset = self.reader.read().find(target) 189 if offset == -1: 190 raise Exception(help_message) 191 self.reader.seek(offset) 192 self.reader.readline() 193 for _ in range(discard_lines): 194 self.reader.readline() 195 self.line = self.reader.readline() 196 197 def parse_desc_syscall(self): 198 self.seek_to('* DOC: eBPF Syscall Commands', 199 'Could not find start of eBPF syscall descriptions list') 200 while True: 201 try: 202 command = self.parse_element() 203 self.commands.append(command) 204 self.desc_syscalls.append(command.proto) 205 206 except NoSyscallCommandFound: 207 break 208 209 def parse_enum_syscall(self): 210 self.seek_to('enum bpf_cmd {', 211 'Could not find start of bpf_cmd enum', 0) 212 # Searches for either one or more BPF\w+ enums 213 bpf_p = re.compile('\s*(BPF\w+)+') 214 # Searches for an enum entry assigned to another entry, 215 # for e.g. BPF_PROG_RUN = BPF_PROG_TEST_RUN, which is 216 # not documented hence should be skipped in check to 217 # determine if the right number of syscalls are documented 218 assign_p = re.compile('\s*(BPF\w+)\s*=\s*(BPF\w+)') 219 bpf_cmd_str = '' 220 while True: 221 capture = assign_p.match(self.line) 222 if capture: 223 # Skip line if an enum entry is assigned to another entry 224 self.line = self.reader.readline() 225 continue 226 capture = bpf_p.match(self.line) 227 if capture: 228 bpf_cmd_str += self.line 229 else: 230 break 231 self.line = self.reader.readline() 232 # Find the number of occurences of BPF\w+ 233 self.enum_syscalls = re.findall('(BPF\w+)+', bpf_cmd_str) 234 235 def parse_desc_helpers(self): 236 self.seek_to('* Start of BPF helper function descriptions:', 237 'Could not find start of eBPF helper descriptions list') 238 while True: 239 try: 240 helper = self.parse_helper() 241 self.helpers.append(helper) 242 proto = helper.proto_break_down() 243 self.desc_unique_helpers.add(proto['name']) 244 except NoHelperFound: 245 break 246 247 def parse_define_helpers(self): 248 # Parse the number of FN(...) in #define __BPF_FUNC_MAPPER to compare 249 # later with the number of unique function names present in description. 250 # Note: seek_to(..) discards the first line below the target search text, 251 # resulting in FN(unspec) being skipped and not added to self.define_unique_helpers. 252 self.seek_to('#define __BPF_FUNC_MAPPER(FN)', 253 'Could not find start of eBPF helper definition list') 254 # Searches for either one or more FN(\w+) defines or a backslash for newline 255 p = re.compile('\s*(FN\(\w+\))+|\\\\') 256 fn_defines_str = '' 257 while True: 258 capture = p.match(self.line) 259 if capture: 260 fn_defines_str += self.line 261 else: 262 break 263 self.line = self.reader.readline() 264 # Find the number of occurences of FN(\w+) 265 self.define_unique_helpers = re.findall('FN\(\w+\)', fn_defines_str) 266 267 def run(self): 268 self.parse_desc_syscall() 269 self.parse_enum_syscall() 270 self.parse_desc_helpers() 271 self.parse_define_helpers() 272 self.reader.close() 273 274############################################################################### 275 276class Printer(object): 277 """ 278 A generic class for printers. Printers should be created with an array of 279 Helper objects, and implement a way to print them in the desired fashion. 280 @parser: A HeaderParser with objects to print to standard output 281 """ 282 def __init__(self, parser): 283 self.parser = parser 284 self.elements = [] 285 286 def print_header(self): 287 pass 288 289 def print_footer(self): 290 pass 291 292 def print_one(self, helper): 293 pass 294 295 def print_all(self): 296 self.print_header() 297 for elem in self.elements: 298 self.print_one(elem) 299 self.print_footer() 300 301 def elem_number_check(self, desc_unique_elem, define_unique_elem, type, instance): 302 """ 303 Checks the number of helpers/syscalls documented within the header file 304 description with those defined as part of enum/macro and raise an 305 Exception if they don't match. 306 """ 307 nr_desc_unique_elem = len(desc_unique_elem) 308 nr_define_unique_elem = len(define_unique_elem) 309 if nr_desc_unique_elem != nr_define_unique_elem: 310 exception_msg = ''' 311The number of unique %s in description (%d) doesn\'t match the number of unique %s defined in %s (%d) 312''' % (type, nr_desc_unique_elem, type, instance, nr_define_unique_elem) 313 if nr_desc_unique_elem < nr_define_unique_elem: 314 # Function description is parsed until no helper is found (which can be due to 315 # misformatting). Hence, only print the first missing/misformatted helper/enum. 316 exception_msg += ''' 317The description for %s is not present or formatted correctly. 318''' % (define_unique_elem[nr_desc_unique_elem]) 319 raise Exception(exception_msg) 320 321class PrinterRST(Printer): 322 """ 323 A generic class for printers that print ReStructured Text. Printers should 324 be created with a HeaderParser object, and implement a way to print API 325 elements in the desired fashion. 326 @parser: A HeaderParser with objects to print to standard output 327 """ 328 def __init__(self, parser): 329 self.parser = parser 330 331 def print_license(self): 332 license = '''\ 333.. Copyright (C) All BPF authors and contributors from 2014 to present. 334.. See git log include/uapi/linux/bpf.h in kernel tree for details. 335.. 336.. %%%LICENSE_START(VERBATIM) 337.. Permission is granted to make and distribute verbatim copies of this 338.. manual provided the copyright notice and this permission notice are 339.. preserved on all copies. 340.. 341.. Permission is granted to copy and distribute modified versions of this 342.. manual under the conditions for verbatim copying, provided that the 343.. entire resulting derived work is distributed under the terms of a 344.. permission notice identical to this one. 345.. 346.. Since the Linux kernel and libraries are constantly changing, this 347.. manual page may be incorrect or out-of-date. The author(s) assume no 348.. responsibility for errors or omissions, or for damages resulting from 349.. the use of the information contained herein. The author(s) may not 350.. have taken the same level of care in the production of this manual, 351.. which is licensed free of charge, as they might when working 352.. professionally. 353.. 354.. Formatted or processed versions of this manual, if unaccompanied by 355.. the source, must acknowledge the copyright and authors of this work. 356.. %%%LICENSE_END 357.. 358.. Please do not edit this file. It was generated from the documentation 359.. located in file include/uapi/linux/bpf.h of the Linux kernel sources 360.. (helpers description), and from scripts/bpf_doc.py in the same 361.. repository (header and footer). 362''' 363 print(license) 364 365 def print_elem(self, elem): 366 if (elem.desc): 367 print('\tDescription') 368 # Do not strip all newline characters: formatted code at the end of 369 # a section must be followed by a blank line. 370 for line in re.sub('\n$', '', elem.desc, count=1).split('\n'): 371 print('{}{}'.format('\t\t' if line else '', line)) 372 373 if (elem.ret): 374 print('\tReturn') 375 for line in elem.ret.rstrip().split('\n'): 376 print('{}{}'.format('\t\t' if line else '', line)) 377 378 print('') 379 380class PrinterHelpersRST(PrinterRST): 381 """ 382 A printer for dumping collected information about helpers as a ReStructured 383 Text page compatible with the rst2man program, which can be used to 384 generate a manual page for the helpers. 385 @parser: A HeaderParser with Helper objects to print to standard output 386 """ 387 def __init__(self, parser): 388 self.elements = parser.helpers 389 self.elem_number_check(parser.desc_unique_helpers, parser.define_unique_helpers, 'helper', '__BPF_FUNC_MAPPER') 390 391 def print_header(self): 392 header = '''\ 393=========== 394BPF-HELPERS 395=========== 396------------------------------------------------------------------------------- 397list of eBPF helper functions 398------------------------------------------------------------------------------- 399 400:Manual section: 7 401 402DESCRIPTION 403=========== 404 405The extended Berkeley Packet Filter (eBPF) subsystem consists in programs 406written in a pseudo-assembly language, then attached to one of the several 407kernel hooks and run in reaction of specific events. This framework differs 408from the older, "classic" BPF (or "cBPF") in several aspects, one of them being 409the ability to call special functions (or "helpers") from within a program. 410These functions are restricted to a white-list of helpers defined in the 411kernel. 412 413These helpers are used by eBPF programs to interact with the system, or with 414the context in which they work. For instance, they can be used to print 415debugging messages, to get the time since the system was booted, to interact 416with eBPF maps, or to manipulate network packets. Since there are several eBPF 417program types, and that they do not run in the same context, each program type 418can only call a subset of those helpers. 419 420Due to eBPF conventions, a helper can not have more than five arguments. 421 422Internally, eBPF programs call directly into the compiled helper functions 423without requiring any foreign-function interface. As a result, calling helpers 424introduces no overhead, thus offering excellent performance. 425 426This document is an attempt to list and document the helpers available to eBPF 427developers. They are sorted by chronological order (the oldest helpers in the 428kernel at the top). 429 430HELPERS 431======= 432''' 433 PrinterRST.print_license(self) 434 print(header) 435 436 def print_footer(self): 437 footer = ''' 438EXAMPLES 439======== 440 441Example usage for most of the eBPF helpers listed in this manual page are 442available within the Linux kernel sources, at the following locations: 443 444* *samples/bpf/* 445* *tools/testing/selftests/bpf/* 446 447LICENSE 448======= 449 450eBPF programs can have an associated license, passed along with the bytecode 451instructions to the kernel when the programs are loaded. The format for that 452string is identical to the one in use for kernel modules (Dual licenses, such 453as "Dual BSD/GPL", may be used). Some helper functions are only accessible to 454programs that are compatible with the GNU Privacy License (GPL). 455 456In order to use such helpers, the eBPF program must be loaded with the correct 457license string passed (via **attr**) to the **bpf**\ () system call, and this 458generally translates into the C source code of the program containing a line 459similar to the following: 460 461:: 462 463 char ____license[] __attribute__((section("license"), used)) = "GPL"; 464 465IMPLEMENTATION 466============== 467 468This manual page is an effort to document the existing eBPF helper functions. 469But as of this writing, the BPF sub-system is under heavy development. New eBPF 470program or map types are added, along with new helper functions. Some helpers 471are occasionally made available for additional program types. So in spite of 472the efforts of the community, this page might not be up-to-date. If you want to 473check by yourself what helper functions exist in your kernel, or what types of 474programs they can support, here are some files among the kernel tree that you 475may be interested in: 476 477* *include/uapi/linux/bpf.h* is the main BPF header. It contains the full list 478 of all helper functions, as well as many other BPF definitions including most 479 of the flags, structs or constants used by the helpers. 480* *net/core/filter.c* contains the definition of most network-related helper 481 functions, and the list of program types from which they can be used. 482* *kernel/trace/bpf_trace.c* is the equivalent for most tracing program-related 483 helpers. 484* *kernel/bpf/verifier.c* contains the functions used to check that valid types 485 of eBPF maps are used with a given helper function. 486* *kernel/bpf/* directory contains other files in which additional helpers are 487 defined (for cgroups, sockmaps, etc.). 488* The bpftool utility can be used to probe the availability of helper functions 489 on the system (as well as supported program and map types, and a number of 490 other parameters). To do so, run **bpftool feature probe** (see 491 **bpftool-feature**\ (8) for details). Add the **unprivileged** keyword to 492 list features available to unprivileged users. 493 494Compatibility between helper functions and program types can generally be found 495in the files where helper functions are defined. Look for the **struct 496bpf_func_proto** objects and for functions returning them: these functions 497contain a list of helpers that a given program type can call. Note that the 498**default:** label of the **switch ... case** used to filter helpers can call 499other functions, themselves allowing access to additional helpers. The 500requirement for GPL license is also in those **struct bpf_func_proto**. 501 502Compatibility between helper functions and map types can be found in the 503**check_map_func_compatibility**\ () function in file *kernel/bpf/verifier.c*. 504 505Helper functions that invalidate the checks on **data** and **data_end** 506pointers for network processing are listed in function 507**bpf_helper_changes_pkt_data**\ () in file *net/core/filter.c*. 508 509SEE ALSO 510======== 511 512**bpf**\ (2), 513**bpftool**\ (8), 514**cgroups**\ (7), 515**ip**\ (8), 516**perf_event_open**\ (2), 517**sendmsg**\ (2), 518**socket**\ (7), 519**tc-bpf**\ (8)''' 520 print(footer) 521 522 def print_proto(self, helper): 523 """ 524 Format function protocol with bold and italics markers. This makes RST 525 file less readable, but gives nice results in the manual page. 526 """ 527 proto = helper.proto_break_down() 528 529 print('**%s %s%s(' % (proto['ret_type'], 530 proto['ret_star'].replace('*', '\\*'), 531 proto['name']), 532 end='') 533 534 comma = '' 535 for a in proto['args']: 536 one_arg = '{}{}'.format(comma, a['type']) 537 if a['name']: 538 if a['star']: 539 one_arg += ' {}**\ '.format(a['star'].replace('*', '\\*')) 540 else: 541 one_arg += '** ' 542 one_arg += '*{}*\\ **'.format(a['name']) 543 comma = ', ' 544 print(one_arg, end='') 545 546 print(')**') 547 548 def print_one(self, helper): 549 self.print_proto(helper) 550 self.print_elem(helper) 551 552 553class PrinterSyscallRST(PrinterRST): 554 """ 555 A printer for dumping collected information about the syscall API as a 556 ReStructured Text page compatible with the rst2man program, which can be 557 used to generate a manual page for the syscall. 558 @parser: A HeaderParser with APIElement objects to print to standard 559 output 560 """ 561 def __init__(self, parser): 562 self.elements = parser.commands 563 self.elem_number_check(parser.desc_syscalls, parser.enum_syscalls, 'syscall', 'bpf_cmd') 564 565 def print_header(self): 566 header = '''\ 567=== 568bpf 569=== 570------------------------------------------------------------------------------- 571Perform a command on an extended BPF object 572------------------------------------------------------------------------------- 573 574:Manual section: 2 575 576COMMANDS 577======== 578''' 579 PrinterRST.print_license(self) 580 print(header) 581 582 def print_one(self, command): 583 print('**%s**' % (command.proto)) 584 self.print_elem(command) 585 586 587class PrinterHelpers(Printer): 588 """ 589 A printer for dumping collected information about helpers as C header to 590 be included from BPF program. 591 @parser: A HeaderParser with Helper objects to print to standard output 592 """ 593 def __init__(self, parser): 594 self.elements = parser.helpers 595 self.elem_number_check(parser.desc_unique_helpers, parser.define_unique_helpers, 'helper', '__BPF_FUNC_MAPPER') 596 597 type_fwds = [ 598 'struct bpf_fib_lookup', 599 'struct bpf_sk_lookup', 600 'struct bpf_perf_event_data', 601 'struct bpf_perf_event_value', 602 'struct bpf_pidns_info', 603 'struct bpf_redir_neigh', 604 'struct bpf_sock', 605 'struct bpf_sock_addr', 606 'struct bpf_sock_ops', 607 'struct bpf_sock_tuple', 608 'struct bpf_spin_lock', 609 'struct bpf_sysctl', 610 'struct bpf_tcp_sock', 611 'struct bpf_tunnel_key', 612 'struct bpf_xfrm_state', 613 'struct linux_binprm', 614 'struct pt_regs', 615 'struct sk_reuseport_md', 616 'struct sockaddr', 617 'struct tcphdr', 618 'struct seq_file', 619 'struct tcp6_sock', 620 'struct tcp_sock', 621 'struct tcp_timewait_sock', 622 'struct tcp_request_sock', 623 'struct udp6_sock', 624 'struct unix_sock', 625 'struct task_struct', 626 627 'struct __sk_buff', 628 'struct sk_msg_md', 629 'struct xdp_md', 630 'struct path', 631 'struct btf_ptr', 632 'struct inode', 633 'struct socket', 634 'struct file', 635 'struct bpf_timer', 636 'struct mptcp_sock', 637 'struct bpf_dynptr', 638 ] 639 known_types = { 640 '...', 641 'void', 642 'const void', 643 'char', 644 'const char', 645 'int', 646 'long', 647 'unsigned long', 648 649 '__be16', 650 '__be32', 651 '__wsum', 652 653 'struct bpf_fib_lookup', 654 'struct bpf_perf_event_data', 655 'struct bpf_perf_event_value', 656 'struct bpf_pidns_info', 657 'struct bpf_redir_neigh', 658 'struct bpf_sk_lookup', 659 'struct bpf_sock', 660 'struct bpf_sock_addr', 661 'struct bpf_sock_ops', 662 'struct bpf_sock_tuple', 663 'struct bpf_spin_lock', 664 'struct bpf_sysctl', 665 'struct bpf_tcp_sock', 666 'struct bpf_tunnel_key', 667 'struct bpf_xfrm_state', 668 'struct linux_binprm', 669 'struct pt_regs', 670 'struct sk_reuseport_md', 671 'struct sockaddr', 672 'struct tcphdr', 673 'struct seq_file', 674 'struct tcp6_sock', 675 'struct tcp_sock', 676 'struct tcp_timewait_sock', 677 'struct tcp_request_sock', 678 'struct udp6_sock', 679 'struct unix_sock', 680 'struct task_struct', 681 'struct path', 682 'struct btf_ptr', 683 'struct inode', 684 'struct socket', 685 'struct file', 686 'struct bpf_timer', 687 'struct mptcp_sock', 688 'struct bpf_dynptr', 689 } 690 mapped_types = { 691 'u8': '__u8', 692 'u16': '__u16', 693 'u32': '__u32', 694 'u64': '__u64', 695 's8': '__s8', 696 's16': '__s16', 697 's32': '__s32', 698 's64': '__s64', 699 'size_t': 'unsigned long', 700 'struct bpf_map': 'void', 701 'struct sk_buff': 'struct __sk_buff', 702 'const struct sk_buff': 'const struct __sk_buff', 703 'struct sk_msg_buff': 'struct sk_msg_md', 704 'struct xdp_buff': 'struct xdp_md', 705 } 706 # Helpers overloaded for different context types. 707 overloaded_helpers = [ 708 'bpf_get_socket_cookie', 709 'bpf_sk_assign', 710 ] 711 712 def print_header(self): 713 header = '''\ 714/* This is auto-generated file. See bpf_doc.py for details. */ 715 716/* Forward declarations of BPF structs */''' 717 718 print(header) 719 for fwd in self.type_fwds: 720 print('%s;' % fwd) 721 print('') 722 723 def print_footer(self): 724 footer = '' 725 print(footer) 726 727 def map_type(self, t): 728 if t in self.known_types: 729 return t 730 if t in self.mapped_types: 731 return self.mapped_types[t] 732 print("Unrecognized type '%s', please add it to known types!" % t, 733 file=sys.stderr) 734 sys.exit(1) 735 736 seen_helpers = set() 737 738 def print_one(self, helper): 739 proto = helper.proto_break_down() 740 741 if proto['name'] in self.seen_helpers: 742 return 743 self.seen_helpers.add(proto['name']) 744 745 print('/*') 746 print(" * %s" % proto['name']) 747 print(" *") 748 if (helper.desc): 749 # Do not strip all newline characters: formatted code at the end of 750 # a section must be followed by a blank line. 751 for line in re.sub('\n$', '', helper.desc, count=1).split('\n'): 752 print(' *{}{}'.format(' \t' if line else '', line)) 753 754 if (helper.ret): 755 print(' *') 756 print(' * Returns') 757 for line in helper.ret.rstrip().split('\n'): 758 print(' *{}{}'.format(' \t' if line else '', line)) 759 760 print(' */') 761 print('static %s %s(*%s)(' % (self.map_type(proto['ret_type']), 762 proto['ret_star'], proto['name']), end='') 763 comma = '' 764 for i, a in enumerate(proto['args']): 765 t = a['type'] 766 n = a['name'] 767 if proto['name'] in self.overloaded_helpers and i == 0: 768 t = 'void' 769 n = 'ctx' 770 one_arg = '{}{}'.format(comma, self.map_type(t)) 771 if n: 772 if a['star']: 773 one_arg += ' {}'.format(a['star']) 774 else: 775 one_arg += ' ' 776 one_arg += '{}'.format(n) 777 comma = ', ' 778 print(one_arg, end='') 779 780 print(') = (void *) %d;' % len(self.seen_helpers)) 781 print('') 782 783############################################################################### 784 785# If script is launched from scripts/ from kernel tree and can access 786# ../include/uapi/linux/bpf.h, use it as a default name for the file to parse, 787# otherwise the --filename argument will be required from the command line. 788script = os.path.abspath(sys.argv[0]) 789linuxRoot = os.path.dirname(os.path.dirname(script)) 790bpfh = os.path.join(linuxRoot, 'include/uapi/linux/bpf.h') 791 792printers = { 793 'helpers': PrinterHelpersRST, 794 'syscall': PrinterSyscallRST, 795} 796 797argParser = argparse.ArgumentParser(description=""" 798Parse eBPF header file and generate documentation for the eBPF API. 799The RST-formatted output produced can be turned into a manual page with the 800rst2man utility. 801""") 802argParser.add_argument('--header', action='store_true', 803 help='generate C header file') 804if (os.path.isfile(bpfh)): 805 argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h', 806 default=bpfh) 807else: 808 argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h') 809argParser.add_argument('target', nargs='?', default='helpers', 810 choices=printers.keys(), help='eBPF API target') 811args = argParser.parse_args() 812 813# Parse file. 814headerParser = HeaderParser(args.filename) 815headerParser.run() 816 817# Print formatted output to standard output. 818if args.header: 819 if args.target != 'helpers': 820 raise NotImplementedError('Only helpers header generation is supported') 821 printer = PrinterHelpers(headerParser) 822else: 823 printer = printers[args.target](headerParser) 824printer.print_all() 825