]>
git.proxmox.com Git - mirror_frr.git/blob - python/xrelfo.py
1 # FRR ELF xref extractor
3 # Copyright (C) 2020 David Lamparter for NetDEF, Inc.
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; either version 2 of the License, or (at your option)
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 # You should have received a copy of the GNU General Public License along
16 # with this program; see the file COPYING; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
30 json_dump_args
["escape_forward_slashes"] = False
36 from clippy
.uidhash
import uidhash
37 from clippy
.elf
import *
38 from clippy
import frr_top_src
, CmdAttr
39 from tiabwarfo
import FieldApplicator
40 from xref2vtysh
import CommandEntry
43 with
open(os
.path
.join(frr_top_src
, "python", "xrefstructs.json"), "r") as fd
:
44 xrefstructs
= json
.load(fd
)
45 except FileNotFoundError
:
48 The "xrefstructs.json" file (created by running tiabwarfo.py with the pahole
49 tool available) could not be found. It should be included with the sources.
54 # constants, need to be kept in sync manually...
56 XREFT_THREADSCHED
= 0x100
59 XREFT_INSTALL_ELEMENT
= 0x301
63 prios
= ["0", "1", "2", "E", "W", "N", "I", "D"]
66 class XrelfoJson(object):
70 def check(self
, wopt
):
73 def to_dict(self
, refs
):
77 class Xref(ELFDissectStruct
, XrelfoJson
):
79 fieldrename
= {"type": "typ"}
82 def __init__(self
, *args
, **kwargs
):
83 super().__init
__(*args
, **kwargs
)
85 self
._container
= None
87 self
.xrefdata
.ref_from(self
, self
.typ
)
90 if self
._container
is None:
91 if self
.typ
in self
.containers
:
92 self
._container
= self
.container_of(self
.containers
[self
.typ
], "xref")
93 return self
._container
95 def check(self
, *args
, **kwargs
):
97 yield from self
._container
.check(*args
, **kwargs
)
100 class Xrefdata(ELFDissectStruct
):
103 # uid is all zeroes in the data loaded from ELF
104 fieldrename
= {"uid": "_uid"}
106 def ref_from(self
, xref
, typ
):
111 if self
.hashstr
is None:
113 return uidhash(self
.xref
.file, self
.hashstr
, self
.hashu32_0
, self
.hashu32_1
)
116 class XrefPtr(ELFDissectStruct
):
122 class XrefThreadSched(ELFDissectStruct
, XrelfoJson
):
123 struct
= "xref_threadsched"
126 Xref
.containers
[XREFT_THREADSCHED
] = XrefThreadSched
129 class XrefLogmsg(ELFDissectStruct
, XrelfoJson
):
130 struct
= "xref_logmsg"
132 def _warn_fmt(self
, text
):
133 lines
= text
.split("\n")
135 (self
.xref
.file, self
.xref
.line
),
136 "%s:%d: %s (in %s())%s\n"
142 "".join(["\n" + l
for l
in lines
[1:]]),
147 (re
.compile(r
"([\n\t]+)"), "error: log message contains tab or newline"),
148 # (re.compile(r'^(\s+)'), 'warning: log message starts with whitespace'),
150 re
.compile(r
"^((?:warn(?:ing)?|error):\s*)", re
.I
),
151 "warning: log message starts with severity",
155 # the (?<![\?:] ) avoids warning for x ? inet_ntop(...) : "(bla)"
157 re
.compile(r
"((?<![\?:] )inet_ntop\s*\(\s*(?:[AP]F_INET|2)\s*,)"),
158 "cleanup: replace inet_ntop(AF_INET, ...) with %pI4",
162 re
.compile(r
"((?<![\?:] )inet_ntop\s*\(\s*(?:[AP]F_INET6|10)\s*,)"),
163 "cleanup: replace inet_ntop(AF_INET6, ...) with %pI6",
167 re
.compile(r
"((?<![\?:] )inet_ntoa)"),
168 "cleanup: replace inet_ntoa(...) with %pI4",
172 re
.compile(r
"((?<![\?:] )ipaddr2str)"),
173 "cleanup: replace ipaddr2str(...) with %pIA",
177 re
.compile(r
"((?<![\?:] )prefix2str)"),
178 "cleanup: replace prefix2str(...) with %pFX",
182 re
.compile(r
"((?<![\?:] )prefix_mac2str)"),
183 "cleanup: replace prefix_mac2str(...) with %pEA",
187 re
.compile(r
"((?<![\?:] )sockunion2str)"),
188 "cleanup: replace sockunion2str(...) with %pSU",
191 # (re.compile(r'^(\s*__(?:func|FUNCTION|PRETTY_FUNCTION)__\s*)'), 'error: debug message starts with __func__', lambda s: (s.priority & 7 == 7) ),
194 def check(self
, wopt
):
195 def fmt_msg(rex
, itext
):
196 if sys
.stderr
.isatty():
197 items
= rex
.split(itext
)
199 for i
, text
in enumerate(items
):
201 out
.append("\033[41;37;1m%s\033[m" % repr(text
)[1:-1])
203 out
.append(repr(text
)[1:-1])
205 excerpt
= "".join(out
)
207 excerpt
= repr(itext
)[1:-1]
211 for rex
, msg
in self
.fmt_regexes
:
212 if not rex
.search(self
.fmtstring
):
215 excerpt
= fmt_msg(rex
, self
.fmtstring
)
216 yield from self
._warn
_fmt
('%s: "%s"' % (msg
, excerpt
))
219 for rex
, msg
, cond
in self
.arg_regexes
:
222 if not rex
.search(self
.args
):
225 excerpt
= fmt_msg(rex
, self
.args
)
226 yield from self
._warn
_fmt
(
227 '%s:\n\t"%s",\n\t%s' % (msg
, repr(self
.fmtstring
)[1:-1], excerpt
)
232 "%-60s %s%s %-25s [EC %d] %s"
234 "%s:%d %s()" % (self
.xref
.file, self
.xref
.line
, self
.xref
.func
),
235 prios
[self
.priority
& 7],
236 priovals
.get(self
.priority
& 0x30, " "),
237 self
.xref
.xrefdata
.uid
,
243 def to_dict(self
, xrelfo
):
244 jsobj
= dict([(i
, getattr(self
.xref
, i
)) for i
in ["file", "line", "func"]])
246 jsobj
["ec"] = self
.ec
247 jsobj
["fmtstring"] = self
.fmtstring
248 jsobj
["args"] = self
.args
249 jsobj
["priority"] = self
.priority
& 7
250 jsobj
["type"] = "logmsg"
251 jsobj
["binary"] = self
._elfsect
._elfwrap
.orig_filename
253 if self
.priority
& 0x10:
254 jsobj
.setdefault("flags", []).append("errno")
255 if self
.priority
& 0x20:
256 jsobj
.setdefault("flags", []).append("getaddrinfo")
258 xrelfo
["refs"].setdefault(self
.xref
.xrefdata
.uid
, []).append(jsobj
)
261 Xref
.containers
[XREFT_LOGMSG
] = XrefLogmsg
264 class CmdElement(ELFDissectStruct
, XrelfoJson
):
265 struct
= "cmd_element"
267 def __init__(self
, *args
, **kwargs
):
268 super().__init
__(*args
, **kwargs
)
270 def to_dict(self
, xrelfo
):
273 .setdefault(self
.name
, {})
274 .setdefault(self
._elfsect
._elfwrap
.orig_filename
, {})
279 "string": self
.string
,
284 jsobj
["attr"] = attr
= self
.attr
285 for attrname
in CmdAttr
.__members
__:
286 val
= CmdAttr
[attrname
]
288 jsobj
.setdefault("attrs", []).append(attrname
.lower())
291 jsobj
["defun"] = dict(
292 [(i
, getattr(self
.xref
, i
)) for i
in ["file", "line", "func"]]
296 Xref
.containers
[XREFT_DEFUN
] = CmdElement
299 class XrefInstallElement(ELFDissectStruct
, XrelfoJson
):
300 struct
= "xref_install_element"
302 def to_dict(self
, xrelfo
):
305 .setdefault(self
.cmd_element
.name
, {})
306 .setdefault(self
._elfsect
._elfwrap
.orig_filename
, {})
308 nodes
= jsobj
.setdefault("nodes", [])
312 "node": self
.node_type
,
314 [(i
, getattr(self
.xref
, i
)) for i
in ["file", "line", "func"]]
320 Xref
.containers
[XREFT_INSTALL_ELEMENT
] = XrefInstallElement
322 # shove in field defs
323 fieldapply
= FieldApplicator(xrefstructs
)
325 fieldapply
.add(Xrefdata
)
326 fieldapply
.add(XrefLogmsg
)
327 fieldapply
.add(XrefThreadSched
)
328 fieldapply
.add(CmdElement
)
329 fieldapply
.add(XrefInstallElement
)
343 def load_file(self
, filename
):
344 orig_filename
= filename
345 if filename
.endswith(".la") or filename
.endswith(".lo"):
346 with
open(filename
, "r") as fd
:
349 if line
.startswith("#") or line
== "" or "=" not in line
:
352 var
, val
= line
.split("=", 1)
353 if var
not in ["library_names", "pic_object"]:
355 if val
.startswith("'") or val
.startswith('"'):
358 if var
== "pic_object":
359 filename
= os
.path
.join(os
.path
.dirname(filename
), val
)
362 val
= val
.strip().split()[0]
363 filename
= os
.path
.join(os
.path
.dirname(filename
), ".libs", val
)
367 'could not process libtool file "%s"' % orig_filename
371 with
open(filename
, "rb") as fd
:
374 if hdr
== b
"\x7fELF":
375 self
.load_elf(filename
, orig_filename
)
379 path
, name
= os
.path
.split(filename
)
380 filename
= os
.path
.join(path
, ".libs", name
)
384 with
open(filename
, "r") as fd
:
388 raise ValueError("cannot determine file type for %s" % (filename
))
390 def load_elf(self
, filename
, orig_filename
):
391 edf
= ELFDissectFile(filename
)
392 edf
.orig_filename
= orig_filename
394 note
= edf
._elffile
.find_note("FRRouting", "XREF")
396 endian
= ">" if edf
._elffile
.bigendian
else "<"
397 mem
= edf
._elffile
[note
]
398 if edf
._elffile
.elfclass
== 64:
399 start
, end
= struct
.unpack(endian
+ "QQ", mem
)
401 end
+= note
.start
+ 8
403 start
, end
= struct
.unpack(endian
+ "II", mem
)
405 end
+= note
.start
+ 4
407 ptrs
= edf
.iter_data(XrefPtr
, slice(start
, end
))
410 xrefarray
= edf
.get_section("xref_array")
411 if xrefarray
is None:
412 raise ValueError("file has neither xref note nor xref_array section")
414 ptrs
= xrefarray
.iter_data(XrefPtr
)
420 self
._xrefs
.append(ptr
.xref
)
422 container
= ptr
.xref
.container()
423 if container
is None:
425 container
.to_dict(self
)
429 def load_json(self
, fd
):
431 for uid
, items
in data
["refs"].items():
432 myitems
= self
["refs"].setdefault(uid
, [])
438 for cmd
, items
in data
["cli"].items():
439 self
["cli"].setdefault(cmd
, {}).update(items
)
443 def check(self
, checks
):
444 for xref
in self
._xrefs
:
445 yield from xref
.check(checks
)
449 argp
= argparse
.ArgumentParser(description
="FRR xref ELF extractor")
450 argp
.add_argument("-o", dest
="output", type=str, help="write JSON output")
451 argp
.add_argument("--out-by-file", type=str, help="write by-file JSON output")
452 argp
.add_argument("-c", dest
="vtysh_cmds", type=str, help="write vtysh_cmd.c")
453 argp
.add_argument("-Wlog-format", action
="store_const", const
=True)
454 argp
.add_argument("-Wlog-args", action
="store_const", const
=True)
455 argp
.add_argument("-Werror", action
="store_const", const
=True)
456 argp
.add_argument("--profile", action
="store_const", const
=True)
462 help="files to read (ELF files or libtool objects)",
464 args
= argp
.parse_args()
469 cProfile
.runctx("_main(args)", globals(), {"args": args
}, sort
="cumtime")
478 for fn
in args
.binaries
:
483 sys
.stderr
.write("while processing %s:\n" % (fn
))
484 traceback
.print_exc()
486 for option
in dir(args
):
487 if option
.startswith("W") and option
!= "Werror":
488 checks
= sorted(xrelfo
.check(args
))
489 sys
.stderr
.write("".join([c
[-1] for c
in checks
]))
491 if args
.Werror
and len(checks
) > 0:
495 refs
= xrelfo
["refs"]
498 for k
, v
in refs
.items():
499 strs
= set([i
["fmtstring"] for i
in v
])
501 print("\033[31;1m%s\033[m" % k
)
506 for uid
, locs
in refs
.items():
508 filearray
= outbyfile
.setdefault(loc
["file"], [])
511 filearray
.append(loc
)
513 for k
in outbyfile
.keys():
514 outbyfile
[k
] = sorted(outbyfile
[k
], key
=lambda x
: x
["line"])
520 with
open(args
.output
+ ".tmp", "w") as fd
:
521 json
.dump(out
, fd
, indent
=2, sort_keys
=True, **json_dump_args
)
522 os
.rename(args
.output
+ ".tmp", args
.output
)
525 with
open(args
.out_by_file
+ ".tmp", "w") as fd
:
526 json
.dump(outbyfile
, fd
, indent
=2, sort_keys
=True, **json_dump_args
)
527 os
.rename(args
.out_by_file
+ ".tmp", args
.out_by_file
)
530 with
open(args
.vtysh_cmds
+ ".tmp", "w") as fd
:
531 CommandEntry
.run(out
, fd
)
532 os
.rename(args
.vtysh_cmds
+ ".tmp", args
.vtysh_cmds
)
533 if args
.Werror
and CommandEntry
.warn_counter
:
537 if __name__
== "__main__":