system_symbols.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #!/usr/bin/env python3
  2. # pylint: disable=R0902,R0912,R0914,R0915,R1702
  3. # Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>.
  4. # SPDX-License-Identifier: GPL-2.0
  5. """
  6. Parse ABI documentation and produce results from it.
  7. """
  8. import os
  9. import re
  10. import sys
  11. from concurrent import futures
  12. from datetime import datetime
  13. from random import shuffle
  14. from abi.helpers import AbiDebug
  15. class SystemSymbols:
  16. """Stores arguments for the class and initialize class vars."""
  17. def graph_add_file(self, path, link=None):
  18. """
  19. add a file path to the sysfs graph stored at self.root.
  20. """
  21. if path in self.files:
  22. return
  23. name = ""
  24. ref = self.root
  25. for edge in path.split("/"):
  26. name += edge + "/"
  27. if edge not in ref:
  28. ref[edge] = {"__name": [name.rstrip("/")]}
  29. ref = ref[edge]
  30. if link and link not in ref["__name"]:
  31. ref["__name"].append(link.rstrip("/"))
  32. self.files.add(path)
  33. def print_graph(self, root_prefix="", root=None, level=0):
  34. """Prints a reference tree graph using UTF-8 characters."""
  35. if not root:
  36. root = self.root
  37. level = 0
  38. # Prevent endless traverse
  39. if level > 5:
  40. return
  41. if level > 0:
  42. prefix = "├──"
  43. last_prefix = "└──"
  44. else:
  45. prefix = ""
  46. last_prefix = ""
  47. items = list(root.items())
  48. names = root.get("__name", [])
  49. for k, edge in items:
  50. if k == "__name":
  51. continue
  52. if not k:
  53. k = "/"
  54. if len(names) > 1:
  55. k += " links: " + ",".join(names[1:])
  56. if edge == items[-1][1]:
  57. print(root_prefix + last_prefix + k)
  58. p = root_prefix
  59. if level > 0:
  60. p += " "
  61. self.print_graph(p, edge, level + 1)
  62. else:
  63. print(root_prefix + prefix + k)
  64. p = root_prefix + "│ "
  65. self.print_graph(p, edge, level + 1)
  66. def _walk(self, root):
  67. """
  68. Walk through sysfs to get all devnodes that aren't ignored.
  69. By default, uses /sys as sysfs mounting point. If another
  70. directory is used, it replaces them to /sys at the patches.
  71. """
  72. with os.scandir(root) as obj:
  73. for entry in obj:
  74. path = os.path.join(root, entry.name)
  75. if self.sysfs:
  76. p = path.replace(self.sysfs, "/sys", count=1)
  77. else:
  78. p = path
  79. if self.re_ignore.search(p):
  80. return
  81. # Handle link first to avoid directory recursion
  82. if entry.is_symlink():
  83. real = os.path.realpath(path)
  84. if not self.sysfs:
  85. self.aliases[path] = real
  86. else:
  87. real = real.replace(self.sysfs, "/sys", count=1)
  88. # Add absfile location to graph if it doesn't exist
  89. if not self.re_ignore.search(real):
  90. # Add link to the graph
  91. self.graph_add_file(real, p)
  92. elif entry.is_file():
  93. self.graph_add_file(p)
  94. elif entry.is_dir():
  95. self._walk(path)
  96. def __init__(self, abi, sysfs="/sys", hints=False):
  97. """
  98. Initialize internal variables and get a list of all files inside
  99. sysfs that can currently be parsed.
  100. Please notice that there are several entries on sysfs that aren't
  101. documented as ABI. Ignore those.
  102. The real paths will be stored under self.files. Aliases will be
  103. stored in separate, as self.aliases.
  104. """
  105. self.abi = abi
  106. self.log = abi.log
  107. if sysfs != "/sys":
  108. self.sysfs = sysfs.rstrip("/")
  109. else:
  110. self.sysfs = None
  111. self.hints = hints
  112. self.root = {}
  113. self.aliases = {}
  114. self.files = set()
  115. dont_walk = [
  116. # Those require root access and aren't documented at ABI
  117. f"^{sysfs}/kernel/debug",
  118. f"^{sysfs}/kernel/tracing",
  119. f"^{sysfs}/fs/pstore",
  120. f"^{sysfs}/fs/bpf",
  121. f"^{sysfs}/fs/fuse",
  122. # This is not documented at ABI
  123. f"^{sysfs}/module",
  124. f"^{sysfs}/fs/cgroup", # this is big and has zero docs under ABI
  125. f"^{sysfs}/firmware", # documented elsewhere: ACPI, DT bindings
  126. "sections|notes", # aren't actually part of ABI
  127. # kernel-parameters.txt - not easy to parse
  128. "parameters",
  129. ]
  130. self.re_ignore = re.compile("|".join(dont_walk))
  131. print(f"Reading {sysfs} directory contents...", file=sys.stderr)
  132. self._walk(sysfs)
  133. def check_file(self, refs, found):
  134. """Check missing ABI symbols for a given sysfs file."""
  135. res_list = []
  136. try:
  137. for names in refs:
  138. fname = names[0]
  139. res = {
  140. "found": False,
  141. "fname": fname,
  142. "msg": "",
  143. }
  144. res_list.append(res)
  145. re_what = self.abi.get_regexes(fname)
  146. if not re_what:
  147. self.abi.log.warning(f"missing rules for {fname}")
  148. continue
  149. for name in names:
  150. for r in re_what:
  151. if self.abi.debug & AbiDebug.UNDEFINED:
  152. self.log.debug("check if %s matches '%s'", name, r.pattern)
  153. if r.match(name):
  154. res["found"] = True
  155. if found:
  156. res["msg"] += f" {fname}: regex:\n\t"
  157. continue
  158. if self.hints and not res["found"]:
  159. res["msg"] += f" {fname} not found. Tested regexes:\n"
  160. for r in re_what:
  161. res["msg"] += " " + r.pattern + "\n"
  162. except KeyboardInterrupt:
  163. pass
  164. return res_list
  165. def _ref_interactor(self, root):
  166. """Recursive function to interact over the sysfs tree."""
  167. for k, v in root.items():
  168. if isinstance(v, dict):
  169. yield from self._ref_interactor(v)
  170. if root == self.root or k == "__name":
  171. continue
  172. if self.abi.re_string:
  173. fname = v["__name"][0]
  174. if self.abi.re_string.search(fname):
  175. yield v
  176. else:
  177. yield v
  178. def get_fileref(self, all_refs, chunk_size):
  179. """Interactor to group refs into chunks."""
  180. n = 0
  181. refs = []
  182. for ref in all_refs:
  183. refs.append(ref)
  184. n += 1
  185. if n >= chunk_size:
  186. yield refs
  187. n = 0
  188. refs = []
  189. yield refs
  190. def check_undefined_symbols(self, max_workers=None, chunk_size=50,
  191. found=None, dry_run=None):
  192. """Seach ABI for sysfs symbols missing documentation."""
  193. self.abi.parse_abi()
  194. if self.abi.debug & AbiDebug.GRAPH:
  195. self.print_graph()
  196. all_refs = []
  197. for ref in self._ref_interactor(self.root):
  198. all_refs.append(ref["__name"])
  199. if dry_run:
  200. print("Would check", file=sys.stderr)
  201. for ref in all_refs:
  202. print(", ".join(ref))
  203. return
  204. print("Starting to search symbols (it may take several minutes):",
  205. file=sys.stderr)
  206. start = datetime.now()
  207. old_elapsed = None
  208. # Python doesn't support multithreading due to limitations on its
  209. # global lock (GIL). While Python 3.13 finally made GIL optional,
  210. # there are still issues related to it. Also, we want to have
  211. # backward compatibility with older versions of Python.
  212. #
  213. # So, use instead multiprocess. However, Python is very slow passing
  214. # data from/to multiple processes. Also, it may consume lots of memory
  215. # if the data to be shared is not small. So, we need to group workload
  216. # in chunks that are big enough to generate performance gains while
  217. # not being so big that would cause out-of-memory.
  218. num_refs = len(all_refs)
  219. print(f"Number of references to parse: {num_refs}", file=sys.stderr)
  220. if not max_workers:
  221. max_workers = os.cpu_count()
  222. elif max_workers > os.cpu_count():
  223. max_workers = os.cpu_count()
  224. max_workers = max(max_workers, 1)
  225. max_chunk_size = int((num_refs + max_workers - 1) / max_workers)
  226. chunk_size = min(chunk_size, max_chunk_size)
  227. chunk_size = max(1, chunk_size)
  228. if max_workers > 1:
  229. executor = futures.ProcessPoolExecutor
  230. # Place references in a random order. This may help improving
  231. # performance, by mixing complex/simple expressions when creating
  232. # chunks
  233. shuffle(all_refs)
  234. else:
  235. # Python has a high overhead with processes. When there's just
  236. # one worker, it is faster to not create a new process.
  237. # Yet, User still deserves to have a progress print. So, use
  238. # python's "thread", which is actually a single process, using
  239. # an internal schedule to switch between tasks. No performance
  240. # gains for non-IO tasks, but still it can be quickly interrupted
  241. # from time to time to display progress.
  242. executor = futures.ThreadPoolExecutor
  243. not_found = []
  244. f_list = []
  245. with executor(max_workers=max_workers) as exe:
  246. for refs in self.get_fileref(all_refs, chunk_size):
  247. if refs:
  248. try:
  249. f_list.append(exe.submit(self.check_file, refs, found))
  250. except KeyboardInterrupt:
  251. return
  252. total = len(f_list)
  253. if not total:
  254. if self.abi.re_string:
  255. print(f"No ABI symbol matches {self.abi.search_string}")
  256. else:
  257. self.abi.log.warning("No ABI symbols found")
  258. return
  259. print(f"{len(f_list):6d} jobs queued on {max_workers} workers",
  260. file=sys.stderr)
  261. while f_list:
  262. try:
  263. t = futures.wait(f_list, timeout=1,
  264. return_when=futures.FIRST_COMPLETED)
  265. done = t[0]
  266. for fut in done:
  267. res_list = fut.result()
  268. for res in res_list:
  269. if not res["found"]:
  270. not_found.append(res["fname"])
  271. if res["msg"]:
  272. print(res["msg"])
  273. f_list.remove(fut)
  274. except KeyboardInterrupt:
  275. return
  276. except RuntimeError as e:
  277. self.abi.log.warning(f"Future: {e}")
  278. break
  279. if sys.stderr.isatty():
  280. elapsed = str(datetime.now() - start).split(".", maxsplit=1)[0]
  281. if len(f_list) < total:
  282. elapsed += f" ({total - len(f_list)}/{total} jobs completed). "
  283. if elapsed != old_elapsed:
  284. print(elapsed + "\r", end="", flush=True,
  285. file=sys.stderr)
  286. old_elapsed = elapsed
  287. elapsed = str(datetime.now() - start).split(".", maxsplit=1)[0]
  288. print(elapsed, file=sys.stderr)
  289. for f in sorted(not_found):
  290. print(f"{f} not found.")