xref: /linux/scripts/lib/abi/abi_parser.py (revision 98a4324a8b7bbe433483c90524026be0ccc9ffa8)
1#!/usr/bin/env python3
2# pylint: disable=R0902,R0903,R0911,R0912,R0913,R0914,R0915,R0917,C0302
3# Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>.
4# SPDX-License-Identifier: GPL-2.0
5
6"""
7Parse ABI documentation and produce results from it.
8"""
9
10from argparse import Namespace
11import logging
12import os
13import re
14
15from pprint import pformat
16from random import randrange, seed
17
18# Import Python modules
19
20from helpers import AbiDebug, ABI_DIR
21
22
23class AbiParser:
24    """Main class to parse ABI files"""
25
26    TAGS = r"(what|where|date|kernelversion|contact|description|users)"
27    XREF = r"(?:^|\s|\()(\/(?:sys|config|proc|dev|kvd)\/[^,.:;\)\s]+)(?:[,.:;\)\s]|\Z)"
28
29    def __init__(self, directory, logger=None,
30                 enable_lineno=False, show_warnings=True, debug=0):
31        """Stores arguments for the class and initialize class vars"""
32
33        self.directory = directory
34        self.enable_lineno = enable_lineno
35        self.show_warnings = show_warnings
36        self.debug = debug
37
38        if not logger:
39            self.log = logging.getLogger("get_abi")
40        else:
41            self.log = logger
42
43        self.data = {}
44        self.what_symbols = {}
45        self.file_refs = {}
46        self.what_refs = {}
47
48        # Ignore files that contain such suffixes
49        self.ignore_suffixes = (".rej", ".org", ".orig", ".bak", "~")
50
51        # Regular expressions used on parser
52        self.re_abi_dir = re.compile(r"(.*)" + ABI_DIR)
53        self.re_tag = re.compile(r"(\S+)(:\s*)(.*)", re.I)
54        self.re_valid = re.compile(self.TAGS)
55        self.re_start_spc = re.compile(r"(\s*)(\S.*)")
56        self.re_whitespace = re.compile(r"^\s+")
57
58        # Regular used on print
59        self.re_what = re.compile(r"(\/?(?:[\w\-]+\/?){1,2})")
60        self.re_escape = re.compile(r"([\.\x01-\x08\x0e-\x1f\x21-\x2f\x3a-\x40\x7b-\xff])")
61        self.re_unprintable = re.compile(r"([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xff]+)")
62        self.re_title_mark = re.compile(r"\n[\-\*\=\^\~]+\n")
63        self.re_doc = re.compile(r"Documentation/(?!devicetree)(\S+)\.rst")
64        self.re_abi = re.compile(r"(Documentation/ABI/)([\w\/\-]+)")
65        self.re_xref_node = re.compile(self.XREF)
66
67    def warn(self, fdata, msg, extra=None):
68        """Displays a parse error if warning is enabled"""
69
70        if not self.show_warnings:
71            return
72
73        msg = f"{fdata.fname}:{fdata.ln}: {msg}"
74        if extra:
75            msg += "\n\t\t" + extra
76
77        self.log.warning(msg)
78
79    def add_symbol(self, what, fname, ln=None, xref=None):
80        """Create a reference table describing where each 'what' is located"""
81
82        if what not in self.what_symbols:
83            self.what_symbols[what] = {"file": {}}
84
85        if fname not in self.what_symbols[what]["file"]:
86            self.what_symbols[what]["file"][fname] = []
87
88        if ln and ln not in self.what_symbols[what]["file"][fname]:
89            self.what_symbols[what]["file"][fname].append(ln)
90
91        if xref:
92            self.what_symbols[what]["xref"] = xref
93
94    def _parse_line(self, fdata, line):
95        """Parse a single line of an ABI file"""
96
97        new_what = False
98        new_tag = False
99        content = None
100
101        match = self.re_tag.match(line)
102        if match:
103            new = match.group(1).lower()
104            sep = match.group(2)
105            content = match.group(3)
106
107            match = self.re_valid.search(new)
108            if match:
109                new_tag = match.group(1)
110            else:
111                if fdata.tag == "description":
112                    # New "tag" is actually part of description.
113                    # Don't consider it a tag
114                    new_tag = False
115                elif fdata.tag != "":
116                    self.warn(fdata, f"tag '{fdata.tag}' is invalid", line)
117
118        if new_tag:
119            # "where" is Invalid, but was a common mistake. Warn if found
120            if new_tag == "where":
121                self.warn(fdata, "tag 'Where' is invalid. Should be 'What:' instead")
122                new_tag = "what"
123
124            if new_tag == "what":
125                fdata.space = None
126
127                if content not in self.what_symbols:
128                    self.add_symbol(what=content, fname=fdata.fname, ln=fdata.ln)
129
130                if fdata.tag == "what":
131                    fdata.what.append(content.strip("\n"))
132                else:
133                    if fdata.key:
134                        if "description" not in self.data.get(fdata.key, {}):
135                            self.warn(fdata, f"{fdata.key} doesn't have a description")
136
137                        for w in fdata.what:
138                            self.add_symbol(what=w, fname=fdata.fname,
139                                            ln=fdata.what_ln, xref=fdata.key)
140
141                    fdata.label = content
142                    new_what = True
143
144                    key = "abi_" + content.lower()
145                    fdata.key = self.re_unprintable.sub("_", key).strip("_")
146
147                    # Avoid duplicated keys but using a defined seed, to make
148                    # the namespace identical if there aren't changes at the
149                    # ABI symbols
150                    seed(42)
151
152                    while fdata.key in self.data:
153                        char = randrange(0, 51) + ord("A")
154                        if char > ord("Z"):
155                            char += ord("a") - ord("Z") - 1
156
157                        fdata.key += chr(char)
158
159                    if fdata.key and fdata.key not in self.data:
160                        self.data[fdata.key] = {
161                            "what": [content],
162                            "file": [fdata.file_ref],
163                            "path": fdata.ftype,
164                            "line_no": fdata.ln,
165                        }
166
167                    fdata.what = self.data[fdata.key]["what"]
168
169                self.what_refs[content] = fdata.key
170                fdata.tag = new_tag
171                fdata.what_ln = fdata.ln
172
173                if fdata.nametag["what"]:
174                    t = (content, fdata.key)
175                    if t not in fdata.nametag["symbols"]:
176                        fdata.nametag["symbols"].append(t)
177
178                return
179
180            if fdata.tag and new_tag:
181                fdata.tag = new_tag
182
183                if new_what:
184                    fdata.label = ""
185
186                    if "description" in self.data[fdata.key]:
187                        self.data[fdata.key]["description"] += "\n\n"
188
189                    if fdata.file_ref not in self.data[fdata.key]["file"]:
190                        self.data[fdata.key]["file"].append(fdata.file_ref)
191
192                    if self.debug == AbiDebug.WHAT_PARSING:
193                        self.log.debug("what: %s", fdata.what)
194
195                if not fdata.what:
196                    self.warn(fdata, "'What:' should come first:", line)
197                    return
198
199                if new_tag == "description":
200                    fdata.space = None
201
202                    if content:
203                        sep = sep.replace(":", " ")
204
205                        c = " " * len(new_tag) + sep + content
206                        c = c.expandtabs()
207
208                        match = self.re_start_spc.match(c)
209                        if match:
210                            # Preserve initial spaces for the first line
211                            fdata.space = match.group(1)
212                            content = match.group(2) + "\n"
213
214                self.data[fdata.key][fdata.tag] = content
215
216            return
217
218        # Store any contents before tags at the database
219        if not fdata.tag and "what" in fdata.nametag:
220            fdata.nametag["description"] += line
221            return
222
223        if fdata.tag == "description":
224            content = line.expandtabs()
225
226            if self.re_whitespace.sub("", content) == "":
227                self.data[fdata.key][fdata.tag] += "\n"
228                return
229
230            if fdata.space is None:
231                match = self.re_start_spc.match(content)
232                if match:
233                    # Preserve initial spaces for the first line
234                    fdata.space = match.group(1)
235
236                    content = match.group(2) + "\n"
237            else:
238                if content.startswith(fdata.space):
239                    content = content[len(fdata.space):]
240
241                else:
242                    fdata.space = ""
243
244            if fdata.tag == "what":
245                w = content.strip("\n")
246                if w:
247                    self.data[fdata.key][fdata.tag].append(w)
248            else:
249                self.data[fdata.key][fdata.tag] += content
250            return
251
252        content = line.strip()
253        if fdata.tag:
254            if fdata.tag == "what":
255                w = content.strip("\n")
256                if w:
257                    self.data[fdata.key][fdata.tag].append(w)
258            else:
259                self.data[fdata.key][fdata.tag] += "\n" + content.rstrip("\n")
260            return
261
262        # Everything else is error
263        if content:
264            self.warn(fdata, "Unexpected content", line)
265
266    def parse_readme(self, nametag, fname):
267        """Parse ABI README file"""
268
269        with open(fname, "r", encoding="utf8", errors="backslashreplace") as fp:
270            nametag["description"] = "```\n"
271            for line in fp:
272                nametag["description"] += "  " + line
273
274            nametag["description"] += "```\n"
275
276    def parse_file(self, fname, path, basename):
277        """Parse a single file"""
278
279        ref = f"abi_file_{path}_{basename}"
280        ref = self.re_unprintable.sub("_", ref).strip("_")
281
282        # Store per-file state into a namespace variable. This will be used
283        # by the per-line parser state machine and by the warning function.
284        fdata = Namespace
285
286        fdata.fname = fname
287        fdata.name = basename
288
289        pos = fname.find(ABI_DIR)
290        if pos > 0:
291            f = fname[pos:]
292        else:
293            f = fname
294
295        fdata.file_ref = (f, ref)
296        self.file_refs[f] = ref
297
298        fdata.ln = 0
299        fdata.what_ln = 0
300        fdata.tag = ""
301        fdata.label = ""
302        fdata.what = []
303        fdata.key = None
304        fdata.xrefs = None
305        fdata.space = None
306        fdata.ftype = path.split("/")[0]
307
308        fdata.nametag = {}
309        fdata.nametag["what"] = [f"File {path}/{basename}"]
310        fdata.nametag["type"] = "File"
311        fdata.nametag["path"] = fdata.ftype
312        fdata.nametag["file"] = [fdata.file_ref]
313        fdata.nametag["line_no"] = 1
314        fdata.nametag["description"] = ""
315        fdata.nametag["symbols"] = []
316
317        self.data[ref] = fdata.nametag
318
319        if self.debug & AbiDebug.WHAT_OPEN:
320            self.log.debug("Opening file %s", fname)
321
322        if basename == "README":
323            self.parse_readme(fdata.nametag, fname)
324            return
325
326        with open(fname, "r", encoding="utf8", errors="backslashreplace") as fp:
327            for line in fp:
328                fdata.ln += 1
329
330                self._parse_line(fdata, line)
331
332            if "description" in fdata.nametag:
333                fdata.nametag["description"] = fdata.nametag["description"].lstrip("\n")
334
335            if fdata.key:
336                if "description" not in self.data.get(fdata.key, {}):
337                    self.warn(fdata, f"{fdata.key} doesn't have a description")
338
339                for w in fdata.what:
340                    self.add_symbol(what=w, fname=fname, xref=fdata.key)
341
342    def _parse_abi(self, root=None):
343        """Internal function to parse documentation ABI recursively"""
344
345        if not root:
346            root = self.directory
347
348        with os.scandir(root) as obj:
349            for entry in obj:
350                name = os.path.join(root, entry.name)
351
352                if entry.is_dir():
353                    self._parse_abi(name)
354                    continue
355
356                if not entry.is_file():
357                    continue
358
359                basename = os.path.basename(name)
360
361                if basename.startswith("."):
362                    continue
363
364                if basename.endswith(self.ignore_suffixes):
365                    continue
366
367                path = self.re_abi_dir.sub("", os.path.dirname(name))
368
369                self.parse_file(name, path, basename)
370
371    def parse_abi(self, root=None):
372        """Parse documentation ABI"""
373
374        self._parse_abi(root)
375
376        if self.debug & AbiDebug.DUMP_ABI_STRUCTS:
377            self.log.debug(pformat(self.data))
378
379    def desc_txt(self, desc):
380        """Print description as found inside ABI files"""
381
382        desc = desc.strip(" \t\n")
383
384        return desc + "\n\n"
385
386    def desc_rst(self, desc):
387        """Enrich ReST output by creating cross-references"""
388
389        # Remove title markups from the description
390        # Having titles inside ABI files will only work if extra
391        # care would be taken in order to strictly follow the same
392        # level order for each markup.
393        desc = self.re_title_mark.sub("\n\n", "\n" + desc)
394        desc = desc.rstrip(" \t\n").lstrip("\n")
395
396        # Python's regex performance for non-compiled expressions is a lot
397        # than Perl, as Perl automatically caches them at their
398        # first usage. Here, we'll need to do the same, as otherwise the
399        # performance penalty is be high
400
401        new_desc = ""
402        for d in desc.split("\n"):
403            if d == "":
404                new_desc += "\n"
405                continue
406
407            # Use cross-references for doc files where needed
408            d = self.re_doc.sub(r":doc:`/\1`", d)
409
410            # Use cross-references for ABI generated docs where needed
411            matches = self.re_abi.findall(d)
412            for m in matches:
413                abi = m[0] + m[1]
414
415                xref = self.file_refs.get(abi)
416                if not xref:
417                    # This may happen if ABI is on a separate directory,
418                    # like parsing ABI testing and symbol is at stable.
419                    # The proper solution is to move this part of the code
420                    # for it to be inside sphinx/kernel_abi.py
421                    self.log.info("Didn't find ABI reference for '%s'", abi)
422                else:
423                    new = self.re_escape.sub(r"\\\1", m[1])
424                    d = re.sub(fr"\b{abi}\b", f":ref:`{new} <{xref}>`", d)
425
426            # Seek for cross reference symbols like /sys/...
427            # Need to be careful to avoid doing it on a code block
428            if d[0] not in [" ", "\t"]:
429                matches = self.re_xref_node.findall(d)
430                for m in matches:
431                    # Finding ABI here is more complex due to wildcards
432                    xref = self.what_refs.get(m)
433                    if xref:
434                        new = self.re_escape.sub(r"\\\1", m)
435                        d = re.sub(fr"\b{m}\b", f":ref:`{new} <{xref}>`", d)
436
437            new_desc += d + "\n"
438
439        return new_desc + "\n\n"
440
441    def doc(self, output_in_txt=False, show_symbols=True, show_file=True,
442            filter_path=None):
443        """Print ABI at stdout"""
444
445        part = None
446        for key, v in sorted(self.data.items(),
447                             key=lambda x: (x[1].get("type", ""),
448                                            x[1].get("what"))):
449
450            wtype = v.get("type", "Symbol")
451            file_ref = v.get("file")
452            names = v.get("what", [""])
453
454            if wtype == "File":
455                if not show_file:
456                    continue
457            else:
458                if not show_symbols:
459                    continue
460
461            if filter_path:
462                if filter_path == "README":
463                    if not names[0].endswith("README"):
464                        continue
465                else:
466                    if v.get("path") != filter_path:
467                        continue
468
469            msg = ""
470
471            if wtype != "File":
472                cur_part = names[0]
473                if cur_part.find("/") >= 0:
474                    match = self.re_what.match(cur_part)
475                    if match:
476                        symbol = match.group(1).rstrip("/")
477                        cur_part = "Symbols under " + symbol
478
479                if cur_part and cur_part != part:
480                    part = cur_part
481                    msg += f"{part}\n{"-" * len(part)}\n\n"
482
483                msg += f".. _{key}:\n\n"
484
485                max_len = 0
486                for i in range(0, len(names)):           # pylint: disable=C0200
487                    names[i] = "**" + self.re_escape.sub(r"\\\1", names[i]) + "**"
488
489                    max_len = max(max_len, len(names[i]))
490
491                msg += "+-" + "-" * max_len + "-+\n"
492                for name in names:
493                    msg += f"| {name}" + " " * (max_len - len(name)) + " |\n"
494                    msg += "+-" + "-" * max_len + "-+\n"
495                msg += "\n"
496
497            for ref in file_ref:
498                if wtype == "File":
499                    msg += f".. _{ref[1]}:\n\n"
500                else:
501                    base = os.path.basename(ref[0])
502                    msg += f"Defined on file :ref:`{base} <{ref[1]}>`\n\n"
503
504            if wtype == "File":
505                msg += f"{names[0]}\n{"-" * len(names[0])}\n\n"
506
507            desc = v.get("description")
508            if not desc and wtype != "File":
509                msg += f"DESCRIPTION MISSING for {names[0]}\n\n"
510
511            if desc:
512                if output_in_txt:
513                    msg += self.desc_txt(desc)
514                else:
515                    msg += self.desc_rst(desc)
516
517            symbols = v.get("symbols")
518            if symbols:
519                msg += "Has the following ABI:\n\n"
520
521                for w, label in symbols:
522                    # Escape special chars from content
523                    content = self.re_escape.sub(r"\\\1", w)
524
525                    msg += f"- :ref:`{content} <{label}>`\n\n"
526
527            users = v.get("users")
528            if users and users.strip(" \t\n"):
529                msg += f"Users:\n\t{users.strip("\n").replace('\n', '\n\t')}\n\n"
530
531            ln = v.get("line_no", 1)
532
533            yield (msg, file_ref[0][0], ln)
534
535    def check_issues(self):
536        """Warn about duplicated ABI entries"""
537
538        for what, v in self.what_symbols.items():
539            files = v.get("file")
540            if not files:
541                # Should never happen if the parser works properly
542                self.log.warning("%s doesn't have a file associated", what)
543                continue
544
545            if len(files) == 1:
546                continue
547
548            f = []
549            for fname, lines in sorted(files.items()):
550                if not lines:
551                    f.append(f"{fname}")
552                elif len(lines) == 1:
553                    f.append(f"{fname}:{lines[0]}")
554                else:
555                    f.append(f"{fname} lines {", ".join(str(x) for x in lines)}")
556
557            self.log.warning("%s is defined %d times: %s", what, len(f), "; ".join(f))
558
559    def search_symbols(self, expr):
560        """ Searches for ABI symbols """
561
562        regex = re.compile(expr, re.I)
563
564        found_keys = 0
565        for t in sorted(self.data.items(), key=lambda x: [0]):
566            v = t[1]
567
568            wtype = v.get("type", "")
569            if wtype == "File":
570                continue
571
572            for what in v.get("what", [""]):
573                if regex.search(what):
574                    found_keys += 1
575
576                    kernelversion = v.get("kernelversion", "").strip(" \t\n")
577                    date = v.get("date", "").strip(" \t\n")
578                    contact = v.get("contact", "").strip(" \t\n")
579                    users = v.get("users", "").strip(" \t\n")
580                    desc = v.get("description", "").strip(" \t\n")
581
582                    files = []
583                    for f in v.get("file", ()):
584                        files.append(f[0])
585
586                    what = str(found_keys) + ". " + what
587                    title_tag = "-" * len(what)
588
589                    print(f"\n{what}\n{title_tag}\n")
590
591                    if kernelversion:
592                        print(f"Kernel version:\t\t{kernelversion}")
593
594                    if date:
595                        print(f"Date:\t\t\t{date}")
596
597                    if contact:
598                        print(f"Contact:\t\t{contact}")
599
600                    if users:
601                        print(f"Users:\t\t\t{users}")
602
603                    print(f"Defined on file{'s'[:len(files) ^ 1]}:\t{", ".join(files)}")
604
605                    if desc:
606                        print(f"\n{desc.strip("\n")}\n")
607
608        if not found_keys:
609            print(f"Regular expression /{expr}/ not found.")
610