]>
git.proxmox.com Git - mirror_frr.git/blob - python/xrelfo.py
1 # SPDX-License-Identifier: GPL-2.0-or-later
2 # FRR ELF xref extractor
4 # Copyright (C) 2020 David Lamparter for NetDEF, Inc.
17 json_dump_args
["escape_forward_slashes"] = False
23 from clippy
.uidhash
import uidhash
24 from clippy
.elf
import *
25 from clippy
import frr_top_src
, CmdAttr
26 from tiabwarfo
import FieldApplicator
27 from xref2vtysh
import CommandEntry
30 with
open(os
.path
.join(frr_top_src
, "python", "xrefstructs.json"), "r") as fd
:
31 xrefstructs
= json
.load(fd
)
32 except FileNotFoundError
:
35 The "xrefstructs.json" file (created by running tiabwarfo.py with the pahole
36 tool available) could not be found. It should be included with the sources.
41 # constants, need to be kept in sync manually...
43 XREFT_THREADSCHED
= 0x100
46 XREFT_INSTALL_ELEMENT
= 0x301
50 prios
= ["0", "1", "2", "E", "W", "N", "I", "D"]
53 class XrelfoJson(object):
57 def check(self
, wopt
):
60 def to_dict(self
, refs
):
64 class Xref(ELFDissectStruct
, XrelfoJson
):
66 fieldrename
= {"type": "typ"}
69 def __init__(self
, *args
, **kwargs
):
70 super().__init
__(*args
, **kwargs
)
72 self
._container
= None
74 self
.xrefdata
.ref_from(self
, self
.typ
)
77 if self
._container
is None:
78 if self
.typ
in self
.containers
:
79 self
._container
= self
.container_of(self
.containers
[self
.typ
], "xref")
80 return self
._container
82 def check(self
, *args
, **kwargs
):
84 yield from self
._container
.check(*args
, **kwargs
)
87 class Xrefdata(ELFDissectStruct
):
90 # uid is all zeroes in the data loaded from ELF
91 fieldrename
= {"uid": "_uid"}
93 def ref_from(self
, xref
, typ
):
98 if self
.hashstr
is None:
100 return uidhash(self
.xref
.file, self
.hashstr
, self
.hashu32_0
, self
.hashu32_1
)
103 class XrefPtr(ELFDissectStruct
):
109 class XrefThreadSched(ELFDissectStruct
, XrelfoJson
):
110 struct
= "xref_threadsched"
113 Xref
.containers
[XREFT_THREADSCHED
] = XrefThreadSched
116 class XrefLogmsg(ELFDissectStruct
, XrelfoJson
):
117 struct
= "xref_logmsg"
119 def _warn_fmt(self
, text
):
120 lines
= text
.split("\n")
122 (self
.xref
.file, self
.xref
.line
),
123 "%s:%d: %s (in %s())%s\n"
129 "".join(["\n" + l
for l
in lines
[1:]]),
134 (re
.compile(r
"([\n\t]+)"), "error: log message contains tab or newline"),
135 # (re.compile(r'^(\s+)'), 'warning: log message starts with whitespace'),
137 re
.compile(r
"^((?:warn(?:ing)?|error):\s*)", re
.I
),
138 "warning: log message starts with severity",
142 # the (?<![\?:] ) avoids warning for x ? inet_ntop(...) : "(bla)"
144 re
.compile(r
"((?<![\?:] )inet_ntop\s*\(\s*(?:[AP]F_INET|2)\s*,)"),
145 "cleanup: replace inet_ntop(AF_INET, ...) with %pI4",
149 re
.compile(r
"((?<![\?:] )inet_ntop\s*\(\s*(?:[AP]F_INET6|10)\s*,)"),
150 "cleanup: replace inet_ntop(AF_INET6, ...) with %pI6",
154 # string split-up here is to not trigger "inet_ntoa forbidden"
155 re
.compile(r
"((?<![\?:] )inet_" + r
"ntoa)"),
156 "cleanup: replace inet_" + "ntoa(...) with %pI4",
160 re
.compile(r
"((?<![\?:] )ipaddr2str)"),
161 "cleanup: replace ipaddr2str(...) with %pIA",
165 re
.compile(r
"((?<![\?:] )prefix2str)"),
166 "cleanup: replace prefix2str(...) with %pFX",
170 re
.compile(r
"((?<![\?:] )prefix_mac2str)"),
171 "cleanup: replace prefix_mac2str(...) with %pEA",
175 re
.compile(r
"((?<![\?:] )sockunion2str)"),
176 "cleanup: replace sockunion2str(...) with %pSU",
179 # (re.compile(r'^(\s*__(?:func|FUNCTION|PRETTY_FUNCTION)__\s*)'), 'error: debug message starts with __func__', lambda s: (s.priority & 7 == 7) ),
182 def check(self
, wopt
):
183 def fmt_msg(rex
, itext
):
184 if sys
.stderr
.isatty():
185 items
= rex
.split(itext
)
187 for i
, text
in enumerate(items
):
189 out
.append("\033[41;37;1m%s\033[m" % repr(text
)[1:-1])
191 out
.append(repr(text
)[1:-1])
193 excerpt
= "".join(out
)
195 excerpt
= repr(itext
)[1:-1]
199 for rex
, msg
in self
.fmt_regexes
:
200 if not rex
.search(self
.fmtstring
):
203 excerpt
= fmt_msg(rex
, self
.fmtstring
)
204 yield from self
._warn
_fmt
('%s: "%s"' % (msg
, excerpt
))
207 for rex
, msg
, cond
in self
.arg_regexes
:
210 if not rex
.search(self
.args
):
213 excerpt
= fmt_msg(rex
, self
.args
)
214 yield from self
._warn
_fmt
(
215 '%s:\n\t"%s",\n\t%s' % (msg
, repr(self
.fmtstring
)[1:-1], excerpt
)
220 "%-60s %s%s %-25s [EC %d] %s"
222 "%s:%d %s()" % (self
.xref
.file, self
.xref
.line
, self
.xref
.func
),
223 prios
[self
.priority
& 7],
224 priovals
.get(self
.priority
& 0x30, " "),
225 self
.xref
.xrefdata
.uid
,
231 def to_dict(self
, xrelfo
):
232 jsobj
= dict([(i
, getattr(self
.xref
, i
)) for i
in ["file", "line", "func"]])
234 jsobj
["ec"] = self
.ec
235 jsobj
["fmtstring"] = self
.fmtstring
236 jsobj
["args"] = self
.args
237 jsobj
["priority"] = self
.priority
& 7
238 jsobj
["type"] = "logmsg"
239 jsobj
["binary"] = self
._elfsect
._elfwrap
.orig_filename
241 if self
.priority
& 0x10:
242 jsobj
.setdefault("flags", []).append("errno")
243 if self
.priority
& 0x20:
244 jsobj
.setdefault("flags", []).append("getaddrinfo")
246 xrelfo
["refs"].setdefault(self
.xref
.xrefdata
.uid
, []).append(jsobj
)
249 Xref
.containers
[XREFT_LOGMSG
] = XrefLogmsg
252 class CmdElement(ELFDissectStruct
, XrelfoJson
):
253 struct
= "cmd_element"
255 def __init__(self
, *args
, **kwargs
):
256 super().__init
__(*args
, **kwargs
)
258 def to_dict(self
, xrelfo
):
261 .setdefault(self
.name
, {})
262 .setdefault(self
._elfsect
._elfwrap
.orig_filename
, {})
267 "string": self
.string
,
272 jsobj
["attr"] = attr
= self
.attr
273 for attrname
in CmdAttr
.__members
__:
274 val
= CmdAttr
[attrname
]
276 jsobj
.setdefault("attrs", []).append(attrname
.lower())
279 jsobj
["defun"] = dict(
280 [(i
, getattr(self
.xref
, i
)) for i
in ["file", "line", "func"]]
284 Xref
.containers
[XREFT_DEFUN
] = CmdElement
287 class XrefInstallElement(ELFDissectStruct
, XrelfoJson
):
288 struct
= "xref_install_element"
290 def to_dict(self
, xrelfo
):
293 .setdefault(self
.cmd_element
.name
, {})
294 .setdefault(self
._elfsect
._elfwrap
.orig_filename
, {})
296 nodes
= jsobj
.setdefault("nodes", [])
300 "node": self
.node_type
,
302 [(i
, getattr(self
.xref
, i
)) for i
in ["file", "line", "func"]]
308 Xref
.containers
[XREFT_INSTALL_ELEMENT
] = XrefInstallElement
310 # shove in field defs
311 fieldapply
= FieldApplicator(xrefstructs
)
313 fieldapply
.add(Xrefdata
)
314 fieldapply
.add(XrefLogmsg
)
315 fieldapply
.add(XrefThreadSched
)
316 fieldapply
.add(CmdElement
)
317 fieldapply
.add(XrefInstallElement
)
331 def load_file(self
, filename
):
332 orig_filename
= filename
333 if filename
.endswith(".la") or filename
.endswith(".lo"):
334 with
open(filename
, "r") as fd
:
337 if line
.startswith("#") or line
== "" or "=" not in line
:
340 var
, val
= line
.split("=", 1)
341 if var
not in ["library_names", "pic_object"]:
343 if val
.startswith("'") or val
.startswith('"'):
346 if var
== "pic_object":
347 filename
= os
.path
.join(os
.path
.dirname(filename
), val
)
350 val
= val
.strip().split()[0]
351 filename
= os
.path
.join(os
.path
.dirname(filename
), ".libs", val
)
355 'could not process libtool file "%s"' % orig_filename
359 with
open(filename
, "rb") as fd
:
362 if hdr
== b
"\x7fELF":
363 self
.load_elf(filename
, orig_filename
)
367 path
, name
= os
.path
.split(filename
)
368 filename
= os
.path
.join(path
, ".libs", name
)
372 with
open(filename
, "r") as fd
:
376 raise ValueError("cannot determine file type for %s" % (filename
))
378 def load_elf(self
, filename
, orig_filename
):
379 edf
= ELFDissectFile(filename
)
380 edf
.orig_filename
= orig_filename
382 note
= edf
._elffile
.find_note("FRRouting", "XREF")
384 endian
= ">" if edf
._elffile
.bigendian
else "<"
385 mem
= edf
._elffile
[note
]
386 if edf
._elffile
.elfclass
== 64:
387 start
, end
= struct
.unpack(endian
+ "QQ", mem
)
389 end
+= note
.start
+ 8
391 start
, end
= struct
.unpack(endian
+ "II", mem
)
393 end
+= note
.start
+ 4
395 ptrs
= edf
.iter_data(XrefPtr
, slice(start
, end
))
398 xrefarray
= edf
.get_section("xref_array")
399 if xrefarray
is None:
400 raise ValueError("file has neither xref note nor xref_array section")
402 ptrs
= xrefarray
.iter_data(XrefPtr
)
408 self
._xrefs
.append(ptr
.xref
)
410 container
= ptr
.xref
.container()
411 if container
is None:
413 container
.to_dict(self
)
417 def load_json(self
, fd
):
419 for uid
, items
in data
["refs"].items():
420 myitems
= self
["refs"].setdefault(uid
, [])
426 for cmd
, items
in data
["cli"].items():
427 self
["cli"].setdefault(cmd
, {}).update(items
)
431 def check(self
, checks
):
432 for xref
in self
._xrefs
:
433 yield from xref
.check(checks
)
437 argp
= argparse
.ArgumentParser(description
="FRR xref ELF extractor")
438 argp
.add_argument("-o", dest
="output", type=str, help="write JSON output")
439 argp
.add_argument("--out-by-file", type=str, help="write by-file JSON output")
440 argp
.add_argument("-c", dest
="vtysh_cmds", type=str, help="write vtysh_cmd.c")
441 argp
.add_argument("-Wlog-format", action
="store_const", const
=True)
442 argp
.add_argument("-Wlog-args", action
="store_const", const
=True)
443 argp
.add_argument("-Werror", action
="store_const", const
=True)
444 argp
.add_argument("--profile", action
="store_const", const
=True)
450 help="files to read (ELF files or libtool objects)",
452 args
= argp
.parse_args()
457 cProfile
.runctx("_main(args)", globals(), {"args": args
}, sort
="cumtime")
466 for fn
in args
.binaries
:
471 sys
.stderr
.write("while processing %s:\n" % (fn
))
472 traceback
.print_exc()
474 for option
in dir(args
):
475 if option
.startswith("W") and option
!= "Werror":
476 checks
= sorted(xrelfo
.check(args
))
477 sys
.stderr
.write("".join([c
[-1] for c
in checks
]))
479 if args
.Werror
and len(checks
) > 0:
483 refs
= xrelfo
["refs"]
486 for k
, v
in refs
.items():
487 strs
= set([i
["fmtstring"] for i
in v
])
489 print("\033[31;1m%s\033[m" % k
)
494 for uid
, locs
in refs
.items():
496 filearray
= outbyfile
.setdefault(loc
["file"], [])
499 filearray
.append(loc
)
501 for k
in outbyfile
.keys():
502 outbyfile
[k
] = sorted(outbyfile
[k
], key
=lambda x
: x
["line"])
508 with
open(args
.output
+ ".tmp", "w") as fd
:
509 json
.dump(out
, fd
, indent
=2, sort_keys
=True, **json_dump_args
)
510 os
.rename(args
.output
+ ".tmp", args
.output
)
513 with
open(args
.out_by_file
+ ".tmp", "w") as fd
:
514 json
.dump(outbyfile
, fd
, indent
=2, sort_keys
=True, **json_dump_args
)
515 os
.rename(args
.out_by_file
+ ".tmp", args
.out_by_file
)
518 with
open(args
.vtysh_cmds
+ ".tmp", "w") as fd
:
519 CommandEntry
.run(out
, fd
)
520 os
.rename(args
.vtysh_cmds
+ ".tmp", args
.vtysh_cmds
)
521 if args
.Werror
and CommandEntry
.warn_counter
:
525 if __name__
== "__main__":