bpf_helpers_doc.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. # Copyright (C) 2018-2019 Netronome Systems, Inc.
  5. # In case user attempts to run with Python 2.
  6. from __future__ import print_function
  7. import argparse
  8. import re
  9. import sys, os
  10. class NoHelperFound(BaseException):
  11. pass
  12. class ParsingError(BaseException):
  13. def __init__(self, line='<line not provided>', reader=None):
  14. if reader:
  15. BaseException.__init__(self,
  16. 'Error at file offset %d, parsing line: %s' %
  17. (reader.tell(), line))
  18. else:
  19. BaseException.__init__(self, 'Error parsing line: %s' % line)
  20. class Helper(object):
  21. """
  22. An object representing the description of an eBPF helper function.
  23. @proto: function prototype of the helper function
  24. @desc: textual description of the helper function
  25. @ret: description of the return value of the helper function
  26. """
  27. def __init__(self, proto='', desc='', ret=''):
  28. self.proto = proto
  29. self.desc = desc
  30. self.ret = ret
  31. def proto_break_down(self):
  32. """
  33. Break down helper function protocol into smaller chunks: return type,
  34. name, distincts arguments.
  35. """
  36. arg_re = re.compile('((\w+ )*?(\w+|...))( (\**)(\w+))?$')
  37. res = {}
  38. proto_re = re.compile('(.+) (\**)(\w+)\(((([^,]+)(, )?){1,5})\)$')
  39. capture = proto_re.match(self.proto)
  40. res['ret_type'] = capture.group(1)
  41. res['ret_star'] = capture.group(2)
  42. res['name'] = capture.group(3)
  43. res['args'] = []
  44. args = capture.group(4).split(', ')
  45. for a in args:
  46. capture = arg_re.match(a)
  47. res['args'].append({
  48. 'type' : capture.group(1),
  49. 'star' : capture.group(5),
  50. 'name' : capture.group(6)
  51. })
  52. return res
  53. class HeaderParser(object):
  54. """
  55. An object used to parse a file in order to extract the documentation of a
  56. list of eBPF helper functions. All the helpers that can be retrieved are
  57. stored as Helper object, in the self.helpers() array.
  58. @filename: name of file to parse, usually include/uapi/linux/bpf.h in the
  59. kernel tree
  60. """
  61. def __init__(self, filename):
  62. self.reader = open(filename, 'r')
  63. self.line = ''
  64. self.helpers = []
  65. def parse_helper(self):
  66. proto = self.parse_proto()
  67. desc = self.parse_desc()
  68. ret = self.parse_ret()
  69. return Helper(proto=proto, desc=desc, ret=ret)
  70. def parse_proto(self):
  71. # Argument can be of shape:
  72. # - "void"
  73. # - "type name"
  74. # - "type *name"
  75. # - Same as above, with "const" and/or "struct" in front of type
  76. # - "..." (undefined number of arguments, for bpf_trace_printk())
  77. # There is at least one term ("void"), and at most five arguments.
  78. p = re.compile(' \* ?((.+) \**\w+\((((const )?(struct )?(\w+|\.\.\.)( \**\w+)?)(, )?){1,5}\))$')
  79. capture = p.match(self.line)
  80. if not capture:
  81. raise NoHelperFound
  82. self.line = self.reader.readline()
  83. return capture.group(1)
  84. def parse_desc(self):
  85. p = re.compile(' \* ?(?:\t| {5,8})Description$')
  86. capture = p.match(self.line)
  87. if not capture:
  88. # Helper can have empty description and we might be parsing another
  89. # attribute: return but do not consume.
  90. return ''
  91. # Description can be several lines, some of them possibly empty, and it
  92. # stops when another subsection title is met.
  93. desc = ''
  94. while True:
  95. self.line = self.reader.readline()
  96. if self.line == ' *\n':
  97. desc += '\n'
  98. else:
  99. p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)')
  100. capture = p.match(self.line)
  101. if capture:
  102. desc += capture.group(1) + '\n'
  103. else:
  104. break
  105. return desc
  106. def parse_ret(self):
  107. p = re.compile(' \* ?(?:\t| {5,8})Return$')
  108. capture = p.match(self.line)
  109. if not capture:
  110. # Helper can have empty retval and we might be parsing another
  111. # attribute: return but do not consume.
  112. return ''
  113. # Return value description can be several lines, some of them possibly
  114. # empty, and it stops when another subsection title is met.
  115. ret = ''
  116. while True:
  117. self.line = self.reader.readline()
  118. if self.line == ' *\n':
  119. ret += '\n'
  120. else:
  121. p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)')
  122. capture = p.match(self.line)
  123. if capture:
  124. ret += capture.group(1) + '\n'
  125. else:
  126. break
  127. return ret
  128. def run(self):
  129. # Advance to start of helper function descriptions.
  130. offset = self.reader.read().find('* Start of BPF helper function descriptions:')
  131. if offset == -1:
  132. raise Exception('Could not find start of eBPF helper descriptions list')
  133. self.reader.seek(offset)
  134. self.reader.readline()
  135. self.reader.readline()
  136. self.line = self.reader.readline()
  137. while True:
  138. try:
  139. helper = self.parse_helper()
  140. self.helpers.append(helper)
  141. except NoHelperFound:
  142. break
  143. self.reader.close()
  144. ###############################################################################
  145. class Printer(object):
  146. """
  147. A generic class for printers. Printers should be created with an array of
  148. Helper objects, and implement a way to print them in the desired fashion.
  149. @helpers: array of Helper objects to print to standard output
  150. """
  151. def __init__(self, helpers):
  152. self.helpers = helpers
  153. def print_header(self):
  154. pass
  155. def print_footer(self):
  156. pass
  157. def print_one(self, helper):
  158. pass
  159. def print_all(self):
  160. self.print_header()
  161. for helper in self.helpers:
  162. self.print_one(helper)
  163. self.print_footer()
  164. class PrinterRST(Printer):
  165. """
  166. A printer for dumping collected information about helpers as a ReStructured
  167. Text page compatible with the rst2man program, which can be used to
  168. generate a manual page for the helpers.
  169. @helpers: array of Helper objects to print to standard output
  170. """
  171. def print_header(self):
  172. header = '''\
  173. .. Copyright (C) All BPF authors and contributors from 2014 to present.
  174. .. See git log include/uapi/linux/bpf.h in kernel tree for details.
  175. ..
  176. .. %%%LICENSE_START(VERBATIM)
  177. .. Permission is granted to make and distribute verbatim copies of this
  178. .. manual provided the copyright notice and this permission notice are
  179. .. preserved on all copies.
  180. ..
  181. .. Permission is granted to copy and distribute modified versions of this
  182. .. manual under the conditions for verbatim copying, provided that the
  183. .. entire resulting derived work is distributed under the terms of a
  184. .. permission notice identical to this one.
  185. ..
  186. .. Since the Linux kernel and libraries are constantly changing, this
  187. .. manual page may be incorrect or out-of-date. The author(s) assume no
  188. .. responsibility for errors or omissions, or for damages resulting from
  189. .. the use of the information contained herein. The author(s) may not
  190. .. have taken the same level of care in the production of this manual,
  191. .. which is licensed free of charge, as they might when working
  192. .. professionally.
  193. ..
  194. .. Formatted or processed versions of this manual, if unaccompanied by
  195. .. the source, must acknowledge the copyright and authors of this work.
  196. .. %%%LICENSE_END
  197. ..
  198. .. Please do not edit this file. It was generated from the documentation
  199. .. located in file include/uapi/linux/bpf.h of the Linux kernel sources
  200. .. (helpers description), and from scripts/bpf_helpers_doc.py in the same
  201. .. repository (header and footer).
  202. ===========
  203. BPF-HELPERS
  204. ===========
  205. -------------------------------------------------------------------------------
  206. list of eBPF helper functions
  207. -------------------------------------------------------------------------------
  208. :Manual section: 7
  209. DESCRIPTION
  210. ===========
  211. The extended Berkeley Packet Filter (eBPF) subsystem consists in programs
  212. written in a pseudo-assembly language, then attached to one of the several
  213. kernel hooks and run in reaction of specific events. This framework differs
  214. from the older, "classic" BPF (or "cBPF") in several aspects, one of them being
  215. the ability to call special functions (or "helpers") from within a program.
  216. These functions are restricted to a white-list of helpers defined in the
  217. kernel.
  218. These helpers are used by eBPF programs to interact with the system, or with
  219. the context in which they work. For instance, they can be used to print
  220. debugging messages, to get the time since the system was booted, to interact
  221. with eBPF maps, or to manipulate network packets. Since there are several eBPF
  222. program types, and that they do not run in the same context, each program type
  223. can only call a subset of those helpers.
  224. Due to eBPF conventions, a helper can not have more than five arguments.
  225. Internally, eBPF programs call directly into the compiled helper functions
  226. without requiring any foreign-function interface. As a result, calling helpers
  227. introduces no overhead, thus offering excellent performance.
  228. This document is an attempt to list and document the helpers available to eBPF
  229. developers. They are sorted by chronological order (the oldest helpers in the
  230. kernel at the top).
  231. HELPERS
  232. =======
  233. '''
  234. print(header)
  235. def print_footer(self):
  236. footer = '''
  237. EXAMPLES
  238. ========
  239. Example usage for most of the eBPF helpers listed in this manual page are
  240. available within the Linux kernel sources, at the following locations:
  241. * *samples/bpf/*
  242. * *tools/testing/selftests/bpf/*
  243. LICENSE
  244. =======
  245. eBPF programs can have an associated license, passed along with the bytecode
  246. instructions to the kernel when the programs are loaded. The format for that
  247. string is identical to the one in use for kernel modules (Dual licenses, such
  248. as "Dual BSD/GPL", may be used). Some helper functions are only accessible to
  249. programs that are compatible with the GNU Privacy License (GPL).
  250. In order to use such helpers, the eBPF program must be loaded with the correct
  251. license string passed (via **attr**) to the **bpf**\ () system call, and this
  252. generally translates into the C source code of the program containing a line
  253. similar to the following:
  254. ::
  255. char ____license[] __attribute__((section("license"), used)) = "GPL";
  256. IMPLEMENTATION
  257. ==============
  258. This manual page is an effort to document the existing eBPF helper functions.
  259. But as of this writing, the BPF sub-system is under heavy development. New eBPF
  260. program or map types are added, along with new helper functions. Some helpers
  261. are occasionally made available for additional program types. So in spite of
  262. the efforts of the community, this page might not be up-to-date. If you want to
  263. check by yourself what helper functions exist in your kernel, or what types of
  264. programs they can support, here are some files among the kernel tree that you
  265. may be interested in:
  266. * *include/uapi/linux/bpf.h* is the main BPF header. It contains the full list
  267. of all helper functions, as well as many other BPF definitions including most
  268. of the flags, structs or constants used by the helpers.
  269. * *net/core/filter.c* contains the definition of most network-related helper
  270. functions, and the list of program types from which they can be used.
  271. * *kernel/trace/bpf_trace.c* is the equivalent for most tracing program-related
  272. helpers.
  273. * *kernel/bpf/verifier.c* contains the functions used to check that valid types
  274. of eBPF maps are used with a given helper function.
  275. * *kernel/bpf/* directory contains other files in which additional helpers are
  276. defined (for cgroups, sockmaps, etc.).
  277. * The bpftool utility can be used to probe the availability of helper functions
  278. on the system (as well as supported program and map types, and a number of
  279. other parameters). To do so, run **bpftool feature probe** (see
  280. **bpftool-feature**\ (8) for details). Add the **unprivileged** keyword to
  281. list features available to unprivileged users.
  282. Compatibility between helper functions and program types can generally be found
  283. in the files where helper functions are defined. Look for the **struct
  284. bpf_func_proto** objects and for functions returning them: these functions
  285. contain a list of helpers that a given program type can call. Note that the
  286. **default:** label of the **switch ... case** used to filter helpers can call
  287. other functions, themselves allowing access to additional helpers. The
  288. requirement for GPL license is also in those **struct bpf_func_proto**.
  289. Compatibility between helper functions and map types can be found in the
  290. **check_map_func_compatibility**\ () function in file *kernel/bpf/verifier.c*.
  291. Helper functions that invalidate the checks on **data** and **data_end**
  292. pointers for network processing are listed in function
  293. **bpf_helper_changes_pkt_data**\ () in file *net/core/filter.c*.
  294. SEE ALSO
  295. ========
  296. **bpf**\ (2),
  297. **bpftool**\ (8),
  298. **cgroups**\ (7),
  299. **ip**\ (8),
  300. **perf_event_open**\ (2),
  301. **sendmsg**\ (2),
  302. **socket**\ (7),
  303. **tc-bpf**\ (8)'''
  304. print(footer)
  305. def print_proto(self, helper):
  306. """
  307. Format function protocol with bold and italics markers. This makes RST
  308. file less readable, but gives nice results in the manual page.
  309. """
  310. proto = helper.proto_break_down()
  311. print('**%s %s%s(' % (proto['ret_type'],
  312. proto['ret_star'].replace('*', '\\*'),
  313. proto['name']),
  314. end='')
  315. comma = ''
  316. for a in proto['args']:
  317. one_arg = '{}{}'.format(comma, a['type'])
  318. if a['name']:
  319. if a['star']:
  320. one_arg += ' {}**\ '.format(a['star'].replace('*', '\\*'))
  321. else:
  322. one_arg += '** '
  323. one_arg += '*{}*\\ **'.format(a['name'])
  324. comma = ', '
  325. print(one_arg, end='')
  326. print(')**')
  327. def print_one(self, helper):
  328. self.print_proto(helper)
  329. if (helper.desc):
  330. print('\tDescription')
  331. # Do not strip all newline characters: formatted code at the end of
  332. # a section must be followed by a blank line.
  333. for line in re.sub('\n$', '', helper.desc, count=1).split('\n'):
  334. print('{}{}'.format('\t\t' if line else '', line))
  335. if (helper.ret):
  336. print('\tReturn')
  337. for line in helper.ret.rstrip().split('\n'):
  338. print('{}{}'.format('\t\t' if line else '', line))
  339. print('')
  340. class PrinterHelpers(Printer):
  341. """
  342. A printer for dumping collected information about helpers as C header to
  343. be included from BPF program.
  344. @helpers: array of Helper objects to print to standard output
  345. """
  346. type_fwds = [
  347. 'struct bpf_fib_lookup',
  348. 'struct bpf_sk_lookup',
  349. 'struct bpf_perf_event_data',
  350. 'struct bpf_perf_event_value',
  351. 'struct bpf_pidns_info',
  352. 'struct bpf_redir_neigh',
  353. 'struct bpf_sock',
  354. 'struct bpf_sock_addr',
  355. 'struct bpf_sock_ops',
  356. 'struct bpf_sock_tuple',
  357. 'struct bpf_spin_lock',
  358. 'struct bpf_sysctl',
  359. 'struct bpf_tcp_sock',
  360. 'struct bpf_tunnel_key',
  361. 'struct bpf_xfrm_state',
  362. 'struct pt_regs',
  363. 'struct sk_reuseport_md',
  364. 'struct sockaddr',
  365. 'struct tcphdr',
  366. 'struct seq_file',
  367. 'struct tcp6_sock',
  368. 'struct tcp_sock',
  369. 'struct tcp_timewait_sock',
  370. 'struct tcp_request_sock',
  371. 'struct udp6_sock',
  372. 'struct task_struct',
  373. 'struct __sk_buff',
  374. 'struct sk_msg_md',
  375. 'struct xdp_md',
  376. 'struct path',
  377. 'struct btf_ptr',
  378. ]
  379. known_types = {
  380. '...',
  381. 'void',
  382. 'const void',
  383. 'char',
  384. 'const char',
  385. 'int',
  386. 'long',
  387. 'unsigned long',
  388. '__be16',
  389. '__be32',
  390. '__wsum',
  391. 'struct bpf_fib_lookup',
  392. 'struct bpf_perf_event_data',
  393. 'struct bpf_perf_event_value',
  394. 'struct bpf_pidns_info',
  395. 'struct bpf_redir_neigh',
  396. 'struct bpf_sk_lookup',
  397. 'struct bpf_sock',
  398. 'struct bpf_sock_addr',
  399. 'struct bpf_sock_ops',
  400. 'struct bpf_sock_tuple',
  401. 'struct bpf_spin_lock',
  402. 'struct bpf_sysctl',
  403. 'struct bpf_tcp_sock',
  404. 'struct bpf_tunnel_key',
  405. 'struct bpf_xfrm_state',
  406. 'struct pt_regs',
  407. 'struct sk_reuseport_md',
  408. 'struct sockaddr',
  409. 'struct tcphdr',
  410. 'struct seq_file',
  411. 'struct tcp6_sock',
  412. 'struct tcp_sock',
  413. 'struct tcp_timewait_sock',
  414. 'struct tcp_request_sock',
  415. 'struct udp6_sock',
  416. 'struct task_struct',
  417. 'struct path',
  418. 'struct btf_ptr',
  419. }
  420. mapped_types = {
  421. 'u8': '__u8',
  422. 'u16': '__u16',
  423. 'u32': '__u32',
  424. 'u64': '__u64',
  425. 's8': '__s8',
  426. 's16': '__s16',
  427. 's32': '__s32',
  428. 's64': '__s64',
  429. 'size_t': 'unsigned long',
  430. 'struct bpf_map': 'void',
  431. 'struct sk_buff': 'struct __sk_buff',
  432. 'const struct sk_buff': 'const struct __sk_buff',
  433. 'struct sk_msg_buff': 'struct sk_msg_md',
  434. 'struct xdp_buff': 'struct xdp_md',
  435. }
  436. # Helpers overloaded for different context types.
  437. overloaded_helpers = [
  438. 'bpf_get_socket_cookie',
  439. 'bpf_sk_assign',
  440. ]
  441. def print_header(self):
  442. header = '''\
  443. /* This is auto-generated file. See bpf_helpers_doc.py for details. */
  444. /* Forward declarations of BPF structs */'''
  445. print(header)
  446. for fwd in self.type_fwds:
  447. print('%s;' % fwd)
  448. print('')
  449. def print_footer(self):
  450. footer = ''
  451. print(footer)
  452. def map_type(self, t):
  453. if t in self.known_types:
  454. return t
  455. if t in self.mapped_types:
  456. return self.mapped_types[t]
  457. print("Unrecognized type '%s', please add it to known types!" % t,
  458. file=sys.stderr)
  459. sys.exit(1)
  460. seen_helpers = set()
  461. def print_one(self, helper):
  462. proto = helper.proto_break_down()
  463. if proto['name'] in self.seen_helpers:
  464. return
  465. self.seen_helpers.add(proto['name'])
  466. print('/*')
  467. print(" * %s" % proto['name'])
  468. print(" *")
  469. if (helper.desc):
  470. # Do not strip all newline characters: formatted code at the end of
  471. # a section must be followed by a blank line.
  472. for line in re.sub('\n$', '', helper.desc, count=1).split('\n'):
  473. print(' *{}{}'.format(' \t' if line else '', line))
  474. if (helper.ret):
  475. print(' *')
  476. print(' * Returns')
  477. for line in helper.ret.rstrip().split('\n'):
  478. print(' *{}{}'.format(' \t' if line else '', line))
  479. print(' */')
  480. print('static %s %s(*%s)(' % (self.map_type(proto['ret_type']),
  481. proto['ret_star'], proto['name']), end='')
  482. comma = ''
  483. for i, a in enumerate(proto['args']):
  484. t = a['type']
  485. n = a['name']
  486. if proto['name'] in self.overloaded_helpers and i == 0:
  487. t = 'void'
  488. n = 'ctx'
  489. one_arg = '{}{}'.format(comma, self.map_type(t))
  490. if n:
  491. if a['star']:
  492. one_arg += ' {}'.format(a['star'])
  493. else:
  494. one_arg += ' '
  495. one_arg += '{}'.format(n)
  496. comma = ', '
  497. print(one_arg, end='')
  498. print(') = (void *) %d;' % len(self.seen_helpers))
  499. print('')
  500. ###############################################################################
  501. # If script is launched from scripts/ from kernel tree and can access
  502. # ../include/uapi/linux/bpf.h, use it as a default name for the file to parse,
  503. # otherwise the --filename argument will be required from the command line.
  504. script = os.path.abspath(sys.argv[0])
  505. linuxRoot = os.path.dirname(os.path.dirname(script))
  506. bpfh = os.path.join(linuxRoot, 'include/uapi/linux/bpf.h')
  507. argParser = argparse.ArgumentParser(description="""
  508. Parse eBPF header file and generate documentation for eBPF helper functions.
  509. The RST-formatted output produced can be turned into a manual page with the
  510. rst2man utility.
  511. """)
  512. argParser.add_argument('--header', action='store_true',
  513. help='generate C header file')
  514. if (os.path.isfile(bpfh)):
  515. argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h',
  516. default=bpfh)
  517. else:
  518. argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h')
  519. args = argParser.parse_args()
  520. # Parse file.
  521. headerParser = HeaderParser(args.filename)
  522. headerParser.run()
  523. # Print formatted output to standard output.
  524. if args.header:
  525. printer = PrinterHelpers(headerParser.helpers)
  526. else:
  527. printer = PrinterRST(headerParser.helpers)
  528. printer.print_all()