bpf_doc.py 32 KB

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