bpf_doc.py 36 KB

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