glibc/scripts/tst-ld-trace.py

109 lines
3.5 KiB
Python
Raw Normal View History

elf: Fix DFS sorting algorithm for LD_TRACE_LOADED_OBJECTS with missing libraries (BZ #28868) On _dl_map_object the underlying file is not opened in trace mode (in other cases where the underlying file can't be opened, _dl_map_object quits with an error). If there any missing libraries being processed, they will not be considered on final nlist size passed on _dl_sort_maps later in the function. And it is then used by _dl_sort_maps_dfs on the stack allocated working maps: 222 /* Array to hold RPO sorting results, before we copy back to maps[]. */ 223 struct link_map *rpo[nmaps]; 224 225 /* The 'head' position during each DFS iteration. Note that we start at 226 one past the last element due to first-decrement-then-store (see the 227 bottom of above dfs_traversal() routine). */ 228 struct link_map **rpo_head = &rpo[nmaps]; However while transversing the 'l_initfini' on dfs_traversal it will still consider the l_faked maps and thus update rpo more times than the allocated working 'rpo', overflowing the stack object. As suggested in bugzilla, one option would be to avoid sorting the maps for trace mode. However I think ignoring l_faked object does make sense (there is one less constraint to call the sorting function), it allows a slight less stack usage for trace, and it is slight simpler solution. The tests does trigger the stack overflow, however I tried to make it more generic to check different scenarios or missing objects. Checked on x86_64-linux-gnu. Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
2022-02-09 02:22:49 +08:00
#!/usr/bin/python3
# Dump the output of LD_TRACE_LOADED_OBJECTS in architecture neutral format.
# Copyright (C) 2022-2024 Free Software Foundation, Inc.
elf: Fix DFS sorting algorithm for LD_TRACE_LOADED_OBJECTS with missing libraries (BZ #28868) On _dl_map_object the underlying file is not opened in trace mode (in other cases where the underlying file can't be opened, _dl_map_object quits with an error). If there any missing libraries being processed, they will not be considered on final nlist size passed on _dl_sort_maps later in the function. And it is then used by _dl_sort_maps_dfs on the stack allocated working maps: 222 /* Array to hold RPO sorting results, before we copy back to maps[]. */ 223 struct link_map *rpo[nmaps]; 224 225 /* The 'head' position during each DFS iteration. Note that we start at 226 one past the last element due to first-decrement-then-store (see the 227 bottom of above dfs_traversal() routine). */ 228 struct link_map **rpo_head = &rpo[nmaps]; However while transversing the 'l_initfini' on dfs_traversal it will still consider the l_faked maps and thus update rpo more times than the allocated working 'rpo', overflowing the stack object. As suggested in bugzilla, one option would be to avoid sorting the maps for trace mode. However I think ignoring l_faked object does make sense (there is one less constraint to call the sorting function), it allows a slight less stack usage for trace, and it is slight simpler solution. The tests does trigger the stack overflow, however I tried to make it more generic to check different scenarios or missing objects. Checked on x86_64-linux-gnu. Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
2022-02-09 02:22:49 +08:00
# Copyright The GNU Toolchain Authors.
# This file is part of the GNU C Library.
#
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <https://www.gnu.org/licenses/>.
import argparse
import os
import subprocess
import sys
try:
subprocess.run
except:
class _CompletedProcess:
def __init__(self, args, returncode, stdout=None, stderr=None):
self.args = args
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
def _run(*popenargs, input=None, timeout=None, check=False, **kwargs):
assert(timeout is None)
with subprocess.Popen(*popenargs, **kwargs) as process:
try:
stdout, stderr = process.communicate(input)
except:
process.kill()
process.wait()
raise
returncode = process.poll()
if check and returncode:
raise subprocess.CalledProcessError(returncode, popenargs)
return _CompletedProcess(popenargs, returncode, stdout, stderr)
subprocess.run = _run
def is_vdso(lib):
return lib.startswith('linux-gate') or lib.startswith('linux-vdso')
def parse_trace(cmd, fref):
new_env = os.environ.copy()
new_env['LD_TRACE_LOADED_OBJECTS'] = '1'
trace_out = subprocess.run(cmd, stdout=subprocess.PIPE, check=True,
universal_newlines=True, env=new_env).stdout
trace = []
for line in trace_out.splitlines():
line = line.strip()
if is_vdso(line):
continue
fields = line.split('=>' if '=>' in line else ' ')
lib = os.path.basename(fields[0].strip())
if lib.startswith('ld'):
lib = 'ld'
elif lib.startswith('libc'):
lib = 'libc'
found = 1 if fields[1].strip() != 'not found' else 0
trace += ['{} {}'.format(lib, found)]
trace = sorted(trace)
reference = sorted(line.replace('\n','') for line in fref.readlines())
ret = 0 if trace == reference else 1
if ret != 0:
for i in reference:
if i not in trace:
print("Only in {}: {}".format(fref.name, i))
for i in trace:
if i not in reference:
print("Only in trace: {}".format(i))
sys.exit(ret)
def get_parser():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command',
help='comand to run')
parser.add_argument('reference',
help='reference file to compare')
return parser
def main(argv):
parser = get_parser()
opts = parser.parse_args(argv)
with open(opts.reference, 'r') as fref:
# Remove the initial 'env' command.
parse_trace(opts.command.split()[1:], fref)
if __name__ == '__main__':
main(sys.argv[1:])