diff options
Diffstat (limited to 'gdb')
118 files changed, 6470 insertions, 1221 deletions
diff --git a/gdb/Makefile.in b/gdb/Makefile.in index 9275f8d..9f21695 100644 --- a/gdb/Makefile.in +++ b/gdb/Makefile.in @@ -479,6 +479,7 @@ SELFTESTS_SRCS = \ unittests/ptid-selftests.c \ unittests/main-thread-selftests.c \ unittests/mkdir-recursive-selftests.c \ + unittests/remote-arg-selftests.c \ unittests/rsp-low-selftests.c \ unittests/scoped_fd-selftests.c \ unittests/scoped_ignore_signal-selftests.c \ @@ -769,6 +770,7 @@ ALL_64_TARGET_OBS = \ mips-sde-tdep.o \ mips-tdep.o \ mips64-obsd-tdep.o \ + riscv-canonicalize-syscall-gen.o \ riscv-fbsd-tdep.o \ riscv-linux-tdep.o \ riscv-none-tdep.o \ @@ -896,6 +898,7 @@ ALL_TARGET_OBS = \ sparc-ravenscar-thread.o \ sparc-sol2-tdep.o \ sparc-tdep.o \ + svr4-tls-tdep.o \ symfile-mem.o \ tic6x-linux-tdep.o \ tic6x-tdep.o \ @@ -1520,6 +1523,7 @@ HFILES_NO_SRCDIR = \ stabsread.h \ stack.h \ stap-probe.h \ + svr4-tls-tdep.h \ symfile.h \ symtab.h \ target.h \ @@ -1883,6 +1887,7 @@ ALLDEPFILES = \ sparc64-obsd-tdep.c \ sparc64-sol2-tdep.c \ sparc64-tdep.c \ + svr4-tls-tdep.c \ tilegx-linux-nat.c \ tilegx-linux-tdep.c \ tilegx-tdep.c \ @@ -40,6 +40,14 @@ namespace into which the library was loaded, if more than one namespace is active. +* New built-in convenience variables $_active_linker_namespaces and + $_current_linker_namespace. These show the number of active linkage + namespaces, and the namespace to which the current location belongs to. + In systems that don't support linkage namespaces, these always return 1 + and [[0]] respectively. + + * Add record full support for rv64gc architectures + * New commands maintenance check psymtabs @@ -54,6 +62,11 @@ show riscv numeric-register-names (e.g 'x1') or their abi names (e.g. 'ra'). Defaults to 'off', matching the old behaviour (abi names). +info linker-namespaces +info linker-namespaces [[N]] + Print information about the given linker namespace (identified as N), + or about all the namespaces if no argument is given. + * Changed commands info sharedlibrary @@ -61,6 +74,26 @@ info sharedlibrary command are now for the full memory range allocated to the shared library. +* GDB-internal Thread Local Storage (TLS) support + + ** Linux targets for the x86_64, aarch64, ppc64, s390x, and riscv + architectures now have GDB-internal support for TLS address + lookup in addition to that traditionally provided by the + libthread_db library. This internal support works for programs + linked against either the GLIBC or MUSL C libraries. For + programs linked against MUSL, this new internal support provides + new debug functionality, allowing access to TLS variables, due to + the fact that MUSL does not implement the libthread_db library. + Internal TLS support is also useful in cross-debugging + situations, debugging statically linked binaries, and debugging + programs linked against GLIBC 2.33 and earlier, but which are not + linked against libpthread. + + ** The command 'maint set force-internal-tls-address-lookup on' may + be used to force the internal TLS lookup mechanisms to be used. + Otherwise, TLS lookup via libthread_db will still be preferred, + when available. + * Python API ** New class gdb.Color for dealing with colors. diff --git a/gdb/aarch64-linux-tdep.c b/gdb/aarch64-linux-tdep.c index 9cee355..b6cdcf0 100644 --- a/gdb/aarch64-linux-tdep.c +++ b/gdb/aarch64-linux-tdep.c @@ -24,6 +24,7 @@ #include "gdbarch.h" #include "glibc-tdep.h" #include "linux-tdep.h" +#include "svr4-tls-tdep.h" #include "aarch64-tdep.h" #include "aarch64-linux-tdep.h" #include "osabi.h" @@ -35,6 +36,7 @@ #include "target/target.h" #include "expop.h" #include "auxv.h" +#include "inferior.h" #include "regcache.h" #include "regset.h" @@ -2701,6 +2703,57 @@ aarch64_use_target_description_from_corefile_notes (gdbarch *gdbarch, return true; } +/* Fetch and return the TLS DTV (dynamic thread vector) address for PTID. + Throw a suitable TLS error if something goes wrong. */ + +static CORE_ADDR +aarch64_linux_get_tls_dtv_addr (struct gdbarch *gdbarch, ptid_t ptid, + svr4_tls_libc libc) +{ + /* On aarch64, the thread pointer is found in the TPIDR register. + Note that this is the first register in the TLS feature - see + features/aarch64-tls.c - and it will always be present. */ + regcache *regcache + = get_thread_arch_regcache (current_inferior (), ptid, gdbarch); + aarch64_gdbarch_tdep *tdep = gdbarch_tdep<aarch64_gdbarch_tdep> (gdbarch); + target_fetch_registers (regcache, tdep->tls_regnum_base); + ULONGEST thr_ptr; + if (regcache->cooked_read (tdep->tls_regnum_base, &thr_ptr) != REG_VALID) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch thread pointer")); + + CORE_ADDR dtv_ptr_addr; + switch (libc) + { + case svr4_tls_libc_musl: + /* MUSL: The DTV pointer is found at the very end of the pthread + struct which is located *before* the thread pointer. I.e. + the thread pointer will be just beyond the end of the struct, + so the address of the DTV pointer is found one pointer-size + before the thread pointer. */ + dtv_ptr_addr = thr_ptr - (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + break; + case svr4_tls_libc_glibc: + /* GLIBC: The thread pointer (tpidr) points at the TCB (thread control + block). On aarch64, this struct (tcbhead_t) is defined to + contain two pointers. The first is a pointer to the DTV and + the second is a pointer to private data. So the DTV pointer + address is the same as the thread pointer. */ + dtv_ptr_addr = thr_ptr; + break; + default: + throw_error (TLS_GENERIC_ERROR, _("Unknown aarch64 C library")); + break; + } + gdb::byte_vector buf (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + if (target_read_memory (dtv_ptr_addr, buf.data (), buf.size ()) != 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch DTV address")); + + const struct builtin_type *builtin = builtin_type (gdbarch); + CORE_ADDR dtv_addr = gdbarch_pointer_to_address + (gdbarch, builtin->builtin_data_ptr, buf.data ()); + return dtv_addr; +} + static void aarch64_linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) { @@ -2722,6 +2775,9 @@ aarch64_linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) /* Enable TLS support. */ set_gdbarch_fetch_tls_load_module_address (gdbarch, svr4_fetch_objfile_link_map); + set_gdbarch_get_thread_local_address (gdbarch, + svr4_tls_get_thread_local_address); + svr4_tls_register_tls_methods (info, gdbarch, aarch64_linux_get_tls_dtv_addr); /* Shared library handling. */ set_gdbarch_skip_trampoline_code (gdbarch, find_solib_trampoline_target); diff --git a/gdb/ada-varobj.c b/gdb/ada-varobj.c index 140fc71..c87e7be 100644 --- a/gdb/ada-varobj.c +++ b/gdb/ada-varobj.c @@ -379,16 +379,14 @@ ada_varobj_get_number_of_children (struct value *parent_value, whose index is CHILD_INDEX: - If CHILD_NAME is not NULL, then a copy of the child's name - is saved in *CHILD_NAME. This copy must be deallocated - with xfree after use. + is saved in *CHILD_NAME. - If CHILD_VALUE is not NULL, then save the child's value in *CHILD_VALUE. Same thing for the child's type with CHILD_TYPE if not NULL. - If CHILD_PATH_EXPR is not NULL, then compute the child's - path expression. The resulting string must be deallocated - after use with xfree. + path expression. Computing the child's path expression requires the PARENT_PATH_EXPR to be non-NULL. Otherwise, PARENT_PATH_EXPR may be null if @@ -805,9 +803,7 @@ ada_varobj_get_type_of_child (struct value *parent_value, } /* Return a string that contains the image of the given VALUE, using - the print options OPTS as the options for formatting the result. - - The resulting string must be deallocated after use with xfree. */ + the print options OPTS as the options for formatting the result. */ static std::string ada_varobj_get_value_image (struct value *value, @@ -825,9 +821,7 @@ ada_varobj_get_value_image (struct value *value, in the array inside square brackets, but there are situations where it's useful to add more info. - OPTS are the print options used when formatting the result. - - The result should be deallocated after use using xfree. */ + OPTS are the print options used when formatting the result. */ static std::string ada_varobj_get_value_of_array_variable (struct value *value, diff --git a/gdb/amd64-linux-tdep.c b/gdb/amd64-linux-tdep.c index 494e744..e5a2ab9 100644 --- a/gdb/amd64-linux-tdep.c +++ b/gdb/amd64-linux-tdep.c @@ -33,7 +33,9 @@ #include "amd64-linux-tdep.h" #include "i386-linux-tdep.h" #include "linux-tdep.h" +#include "svr4-tls-tdep.h" #include "gdbsupport/x86-xstate.h" +#include "inferior.h" #include "amd64-tdep.h" #include "solib-svr4.h" @@ -1832,6 +1834,39 @@ amd64_linux_remove_non_address_bits_watchpoint (gdbarch *gdbarch, return (addr & amd64_linux_lam_untag_mask ()); } +/* Fetch and return the TLS DTV (dynamic thread vector) address for PTID. + Throw a suitable TLS error if something goes wrong. */ + +static CORE_ADDR +amd64_linux_get_tls_dtv_addr (struct gdbarch *gdbarch, ptid_t ptid, + enum svr4_tls_libc libc) +{ + /* On x86-64, the thread pointer is found in the fsbase register. */ + regcache *regcache + = get_thread_arch_regcache (current_inferior (), ptid, gdbarch); + target_fetch_registers (regcache, AMD64_FSBASE_REGNUM); + ULONGEST fsbase; + if (regcache->cooked_read (AMD64_FSBASE_REGNUM, &fsbase) != REG_VALID) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch thread pointer")); + + /* The thread pointer (fsbase) points at the TCB (thread control + block). The first two members of this struct are both pointers, + where the first will be a pointer to the TCB (i.e. it points at + itself) and the second will be a pointer to the DTV (dynamic + thread vector). There are many other fields too, but the one + we care about here is the DTV pointer. Compute the address + of the DTV pointer, fetch it, and convert it to an address. */ + CORE_ADDR dtv_ptr_addr = fsbase + gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT; + gdb::byte_vector buf (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + if (target_read_memory (dtv_ptr_addr, buf.data (), buf.size ()) != 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch DTV address")); + + const struct builtin_type *builtin = builtin_type (gdbarch); + CORE_ADDR dtv_addr = gdbarch_pointer_to_address + (gdbarch, builtin->builtin_data_ptr, buf.data ()); + return dtv_addr; +} + static void amd64_linux_init_abi_common(struct gdbarch_info info, struct gdbarch *gdbarch, int num_disp_step_buffers) @@ -1862,6 +1897,9 @@ amd64_linux_init_abi_common(struct gdbarch_info info, struct gdbarch *gdbarch, /* Enable TLS support. */ set_gdbarch_fetch_tls_load_module_address (gdbarch, svr4_fetch_objfile_link_map); + set_gdbarch_get_thread_local_address (gdbarch, + svr4_tls_get_thread_local_address); + svr4_tls_register_tls_methods (info, gdbarch, amd64_linux_get_tls_dtv_addr); /* GNU/Linux uses SVR4-style shared libraries. */ set_gdbarch_skip_trampoline_code (gdbarch, find_solib_trampoline_target); diff --git a/gdb/cli/cli-cmds.c b/gdb/cli/cli-cmds.c index 7e13ef8..9a5021f 100644 --- a/gdb/cli/cli-cmds.c +++ b/gdb/cli/cli-cmds.c @@ -833,7 +833,7 @@ echo_command (const char *text, int from_tty) gdb_printf ("%c", c); } - gdb_stdout->reset_style (); + gdb_stdout->emit_style_escape (ui_file_style ()); /* Force this output to appear now. */ gdb_flush (gdb_stdout); diff --git a/gdb/configure b/gdb/configure index e8a649f..c029c30 100755 --- a/gdb/configure +++ b/gdb/configure @@ -28991,7 +28991,7 @@ else fi -if test "${enable_gdb_compile}" == yes; then +if test "${enable_gdb_compile}" = yes; then $as_echo "#define HAVE_COMPILE 1" >>confdefs.h diff --git a/gdb/configure.ac b/gdb/configure.ac index e0cc3c8..7ba799b 100644 --- a/gdb/configure.ac +++ b/gdb/configure.ac @@ -1231,7 +1231,7 @@ AC_ARG_ENABLE([gdb-compile], [GDB_CHECK_YES_NO_VAL([$enableval], [--enable-gdb-compile])], [enable_gdb_compile=yes]) -if test "${enable_gdb_compile}" == yes; then +if test "${enable_gdb_compile}" = yes; then AC_DEFINE(HAVE_COMPILE, 1, [Define if compiling support to gdb compile.]) CONFIG_OBS="$CONFIG_OBS \$(SUBDIR_GCC_COMPILE_OBS)" else diff --git a/gdb/configure.tgt b/gdb/configure.tgt index 18a15c0..72cdcee 100644 --- a/gdb/configure.tgt +++ b/gdb/configure.tgt @@ -150,7 +150,7 @@ aarch64*-*-linux*) arch/aarch64-scalable-linux.o \ arch/arm.o arch/arm-linux.o arch/arm-get-next-pcs.o \ arm-tdep.o arm-linux-tdep.o \ - glibc-tdep.o linux-tdep.o solib-svr4.o \ + glibc-tdep.o linux-tdep.o solib-svr4.o svr4-tls-tdep.o \ symfile-mem.o linux-record.o" ;; @@ -503,7 +503,7 @@ powerpc-*-aix* | rs6000-*-* | powerpc64-*-aix*) powerpc*-*-linux*) # Target: PowerPC running Linux gdb_target_obs="rs6000-tdep.o ppc-linux-tdep.o ppc-sysv-tdep.o \ - ppc64-tdep.o solib-svr4.o \ + ppc64-tdep.o solib-svr4.o svr4-tls-tdep.o \ glibc-tdep.o symfile-mem.o linux-tdep.o \ ravenscar-thread.o ppc-ravenscar-thread.o \ linux-record.o \ @@ -524,7 +524,8 @@ powerpc*-*-*) s390*-*-linux*) # Target: S390 running Linux gdb_target_obs="s390-linux-tdep.o s390-tdep.o solib-svr4.o \ - linux-tdep.o linux-record.o symfile-mem.o" + linux-tdep.o linux-record.o symfile-mem.o \ + svr4-tls-tdep.o" ;; riscv*-*-freebsd*) @@ -534,8 +535,9 @@ riscv*-*-freebsd*) riscv*-*-linux*) # Target: Linux/RISC-V - gdb_target_obs="riscv-linux-tdep.o glibc-tdep.o \ - linux-tdep.o solib-svr4.o symfile-mem.o linux-record.o" + gdb_target_obs="riscv-linux-tdep.o riscv-canonicalize-syscall-gen.o \ + glibc-tdep.o linux-tdep.o solib-svr4.o symfile-mem.o \ + linux-record.o svr4-tls-tdep.o" ;; riscv*-*-*) @@ -705,7 +707,7 @@ x86_64-*-elf*) x86_64-*-linux*) # Target: GNU/Linux x86-64 gdb_target_obs="amd64-linux-tdep.o ${i386_tobjs} \ - i386-linux-tdep.o glibc-tdep.o \ + i386-linux-tdep.o glibc-tdep.o svr4-tls-tdep.o \ solib-svr4.o symfile-mem.o linux-tdep.o linux-record.o \ arch/i386-linux-tdesc.o arch/amd64-linux-tdesc.o \ arch/x86-linux-tdesc-features.o" diff --git a/gdb/contrib/cc-with-tweaks.sh b/gdb/contrib/cc-with-tweaks.sh index de56018..930ba5c 100755 --- a/gdb/contrib/cc-with-tweaks.sh +++ b/gdb/contrib/cc-with-tweaks.sh @@ -42,6 +42,7 @@ # -Z invoke objcopy --compress-debug-sections # -z compress using dwz # -m compress using dwz -m +# -5 compress using dwz -m -5 # -i make an index (.gdb_index) # -c make an index (currently .gdb_index) in a cache dir # -n make a dwarf5 index (.debug_names) @@ -88,6 +89,7 @@ want_index=false index_options="" want_index_cache=false want_dwz=false +dwz_5flag= want_multi=false want_dwp=false want_objcopy_compress=false @@ -101,6 +103,7 @@ while [ $# -gt 0 ]; do -n) want_index=true; index_options=-dwarf-5;; -c) want_index_cache=true ;; -m) want_multi=true ;; + -5) want_multi=true; dwz_5flag=-5 ;; -p) want_dwp=true ;; -l) want_gnu_debuglink=true ;; *) break ;; @@ -269,7 +272,7 @@ elif [ "$want_multi" = true ]; then rm -f "$dwz_file" cp "$output_file" "${output_file}.alt" - $DWZ -m "$dwz_file" "$output_file" "${output_file}.alt" > /dev/null + $DWZ $dwz_5flag -m "$dwz_file" "$output_file" "${output_file}.alt" > /dev/null rm -f "${output_file}.alt" # Validate dwz's work by checking if the expected output file exists. diff --git a/gdb/copyright.py b/gdb/copyright.py index 5ec9944..bd854dc 100755 --- a/gdb/copyright.py +++ b/gdb/copyright.py @@ -30,13 +30,16 @@ # # This removes the bulk of the changes which are most likely to be correct. +# pyright: strict + import argparse import locale import os import os.path +import pathlib import subprocess import sys -from typing import List, Optional +from typing import Iterable def get_update_list(): @@ -66,24 +69,20 @@ def get_update_list(): .split("\0") ) - def include_file(filename): - (dirname, basename) = os.path.split(filename) - dirbasename = os.path.basename(dirname) - return not ( - basename in EXCLUDE_ALL_LIST - or dirbasename in EXCLUDE_ALL_LIST - or dirname in EXCLUDE_LIST - or dirname in NOT_FSF_LIST - or dirname in BY_HAND - or filename in EXCLUDE_LIST - or filename in NOT_FSF_LIST - or filename in BY_HAND - ) + full_exclude_list = EXCLUDE_LIST + BY_HAND + + def include_file(filename: str): + path = pathlib.Path(filename) + for pattern in full_exclude_list: + if path.full_match(pattern): + return False + + return True return filter(include_file, result) -def update_files(update_list): +def update_files(update_list: Iterable[str]): """Update the copyright header of the files in the given list. We use gnulib's update-copyright script for that. @@ -128,7 +127,7 @@ def update_files(update_list): print("*** " + line) -def may_have_copyright_notice(filename): +def may_have_copyright_notice(filename: str): """Check that the given file does not seem to have a copyright notice. The filename is relative to the root directory. @@ -166,7 +165,7 @@ def get_parser() -> argparse.ArgumentParser: return parser -def main(argv: List[str]) -> Optional[int]: +def main(argv: list[str]) -> int | None: """The main subprogram.""" parser = get_parser() _ = parser.parse_args(argv) @@ -210,8 +209,14 @@ def main(argv: List[str]) -> Optional[int]: # generated, non-FSF, or otherwise special (e.g. license text, # or test cases which must be sensitive to line numbering). # -# Filenames are relative to the root directory. +# Entries are treated as glob patterns. EXCLUDE_LIST = ( + "**/aclocal.m4", + "**/configure", + "**/COPYING.LIB", + "**/COPYING", + "**/fdl.texi", + "**/gpl.texi", "gdb/copying.c", "gdb/nat/glibc_thread_db.h", "gdb/CONTRIBUTE", @@ -219,45 +224,11 @@ EXCLUDE_LIST = ( "gdbsupport/unordered_dense.h", "gnulib/doc/gendocs_template", "gnulib/doc/gendocs_template_min", - "gnulib/import", + "gnulib/import/**", "gnulib/config.in", "gnulib/Makefile.in", -) - -# Files which should not be modified, either because they are -# generated, non-FSF, or otherwise special (e.g. license text, -# or test cases which must be sensitive to line numbering). -# -# Matches any file or directory name anywhere. Use with caution. -# This is mostly for files that can be found in multiple directories. -# Eg: We want all files named COPYING to be left untouched. - -EXCLUDE_ALL_LIST = ( - "COPYING", - "COPYING.LIB", - "configure", - "fdl.texi", - "gpl.texi", - "aclocal.m4", -) - -# The list of files to update by hand. -BY_HAND = ( - # Nothing at the moment :-). -) - -# Files containing multiple copyright headers. This script is only -# fixing the first one it finds, so we need to finish the update -# by hand. -MULTIPLE_COPYRIGHT_HEADERS = ( - "gdb/doc/gdb.texinfo", - "gdb/doc/refcard.tex", - "gdb/syscalls/update-netbsd.sh", -) - -# The list of file which have a copyright, but not held by the FSF. -# Filenames are relative to the root directory. -NOT_FSF_LIST = ( + "sim/Makefile.in", + # The files below have a copyright, but not held by the FSF. "gdb/exc_request.defs", "gdb/gdbtk", "gdb/testsuite/gdb.gdbtk/", @@ -294,9 +265,27 @@ NOT_FSF_LIST = ( "sim/mips/sim-main.c", "sim/moxie/moxie-gdb.dts", # Not a single file in sim/ppc/ appears to be copyright FSF :-(. - "sim/ppc", + "sim/ppc/**", "sim/testsuite/mips/mips32-dsp2.s", ) +# The list of files to update by hand. +# +# Entries are treated as glob patterns. +BY_HAND: tuple[str, ...] = ( + # Nothing at the moment :-). +) + +# Files containing multiple copyright headers. This script is only +# fixing the first one it finds, so we need to finish the update +# by hand. +# +# Entries are treated as glob patterns. +MULTIPLE_COPYRIGHT_HEADERS = ( + "gdb/doc/gdb.texinfo", + "gdb/doc/refcard.tex", + "gdb/syscalls/update-netbsd.sh", +) + if __name__ == "__main__": sys.exit(main(sys.argv[1:])) diff --git a/gdb/disasm-selftests.c b/gdb/disasm-selftests.c index ffd25bd..3ccc174 100644 --- a/gdb/disasm-selftests.c +++ b/gdb/disasm-selftests.c @@ -21,6 +21,7 @@ #include "gdbsupport/selftest.h" #include "selftest-arch.h" #include "gdbarch.h" +#include "disasm-selftests.h" namespace selftests { @@ -329,6 +330,92 @@ memory_error_test (struct gdbarch *gdbarch) SELF_CHECK (saw_memory_error); } +/* Disassemble INSN (a GDBARCH insn), and return the result. */ + +static std::string +disassemble_one_insn_to_string (struct gdbarch *gdbarch, + gdb::array_view<const gdb_byte> insn) +{ + string_file buffer; + + class gdb_disassembler_test : public gdb_disassembler + { + public: + + explicit gdb_disassembler_test (struct gdbarch *gdbarch, + gdb::array_view<const gdb_byte> insn, + string_file &buffer) + : gdb_disassembler (gdbarch, + &buffer, + gdb_disassembler_test::read_memory), + m_insn (insn) + { + } + + int + print_insn (CORE_ADDR memaddr) + { + try + { + return gdb_disassembler::print_insn (memaddr); + } + catch (const gdb_exception_error &) + { + return -1; + } + } + + private: + gdb::array_view<const gdb_byte> m_insn; + + static int read_memory (bfd_vma memaddr, gdb_byte *myaddr, + unsigned int len, + struct disassemble_info *info) noexcept + { + gdb_disassembler_test *self + = static_cast<gdb_disassembler_test *>(info->application_data); + + if (len > self->m_insn.size ()) + return -1; + + for (size_t i = 0; i < len; i++) + myaddr[i] = self->m_insn[i]; + + return 0; + } + }; + + gdb_disassembler_test di (gdbarch, insn, buffer); + if (di.print_insn (0) != insn.size ()) + return ""; + + return buffer.string (); +} + +/* See disasm-selftests.h. */ + +void +disassemble_insn (gdbarch *gdbarch, gdb::byte_vector &insn, + const std::string &expected) +{ + std::string buffer + = disassemble_one_insn_to_string (gdbarch, insn); + + bool check_ok = buffer == expected; + + if (run_verbose () || !check_ok) + { + for (gdb_byte b : insn) + debug_printf ("0x%02x ", b); + debug_printf ("-> %s\n", buffer.c_str ()); + } + + if (!check_ok) + debug_printf ("expected: %s\n", expected.c_str ()); + + SELF_CHECK (check_ok); +} + } /* namespace selftests */ void _initialize_disasm_selftests (); diff --git a/gdb/disasm-selftests.h b/gdb/disasm-selftests.h new file mode 100644 index 0000000..29acf87 --- /dev/null +++ b/gdb/disasm-selftests.h @@ -0,0 +1,32 @@ +/* Copyright (C) 2025 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#ifndef GDB_DISASM_SELFTESTS_H +#define GDB_DISASM_SELFTESTS_H + +namespace selftests +{ + +/* Check that disassembly of INSN (a GDBARCH insn) matches EXPECTED. */ + +void +disassemble_insn (gdbarch *gdbarch, gdb::byte_vector &insn, + const std::string &expected); + +} + +#endif /* GDB_DISASM_SELFTESTS_H */ diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo index b251c8e..362e6e7 100644 --- a/gdb/doc/gdb.texinfo +++ b/gdb/doc/gdb.texinfo @@ -4090,6 +4090,56 @@ When @samp{on} @value{GDBN} will print additional messages when threads are created and deleted. @end table +@cindex thread local storage +@cindex @acronym{TLS} +For some debugging targets, @value{GDBN} has support for accessing +variables that reside in Thread Local Storage (@acronym{TLS}). +@acronym{TLS} variables are similar to global variables, except that +each thread has its own copy of the variable. While often used in +multi-threaded programs, @acronym{TLS} variables can also be used in +programs without threads. The C library variable @var{errno} is, +perhaps, the most prominent example of a @acronym{TLS} variable that +is frequently used in non-threaded programs. For targets where +@value{GDBN} does not have good @acronym{TLS} support, printing or +changing the value of @var{errno} might not be directly possible. + +@sc{gnu}/Linux and FreeBSD targets have support for accessing +@acronym{TLS} variables. On @sc{gnu}/Linux, the helper library, +@code{libthread_db}, is used to help resolve the addresses of +@acronym{TLS} variables. Some FreeBSD and some @sc{gnu}/Linux targets +also have @value{GDBN}-internal @acronym{TLS} resolution code. +@sc{gnu}/Linux targets will attempt to use the @acronym{TLS} address +lookup functionality provided by @code{libthread_db}, but will fall +back to using its internal @acronym{TLS} support when +@code{libthread_db} is not available. This can happen in +cross-debugging scenarios or when debugging programs that are linked +in such a way that @code{libthread_db} support is unavailable -- this +includes statically linked programs, linking against @acronym{GLIBC} +versions earlier than 2.34, but not with @code{libpthread}, and use of +other (non-@acronym{GLIBC}) C libraries. + +@table @code +@kindex maint set force-internal-tls-address-lookup +@kindex maint show force-internal-tls-address-lookup +@cindex internal @acronym{TLS} address lookup +@item maint set force-internal-tls-address-lookup +@itemx maint show force-internal-tls-address-lookup +Turns on or off forced use of @value{GDBN}-internal @acronym{TLS} +address lookup code. Use @code{on} to enable and @code{off} to +disable. The default for this setting is @code{off}. + +When disabled, @value{GDBN} will attempt to use a helper +@code{libthread_db} library if possible, but will fall back to use of +its own internal @acronym{TLS} address lookup mechanisms if necessary. + +When enabled, @value{GDBN} will only use @value{GDBN}'s internal +@acronym{TLS} address lookup mechanisms, if they exist. + +This command is only available for @sc{gnu}/Linux targets. Its +primary use is for testing -- certain tests in the @value{GDBN} test +suite use this command to force use of internal TLS address lookup. +@end table + @node Forks @section Debugging Forks @@ -7807,9 +7857,9 @@ previous instruction; otherwise, it will work in record mode, if the platform supports reverse execution, or stop if not. Currently, process record and replay is supported on ARM, Aarch64, -LoongArch, Moxie, PowerPC, PowerPC64, S/390, and x86 (i386/amd64) running -GNU/Linux. Process record and replay can be used both when native -debugging, and when remote debugging via @code{gdbserver}. +LoongArch, Moxie, PowerPC, PowerPC64, S/390, RISC-V and x86 (i386/amd64) +running GNU/Linux. Process record and replay can be used both when +native debugging, and when remote debugging via @code{gdbserver}. When recording an inferior, @value{GDBN} may print auxiliary information during stepping commands and commands displaying the execution history. @@ -13046,6 +13096,18 @@ variable which may be @samp{truecolor} or @samp{24bit}. Other color spaces are determined by the "Co" termcap which in turn depends on the @env{TERM} environment variable. +@vindex $_active_linker_namespaces@r{, convenience variable} +@item $_active_linker_namespaces +Number of active linkage namespaces in the inferior. In systems with no +support for linkage namespaces, this variable will always be set to @samp{1}. + +@vindex $_current_linker_namespace@r{, convenience variable} +@item $_current_linker_namespace +The namespace which contains the current location in the inferior. This +returns GDB's internal identifier for namespaces, which is @samp{[[@var{n}]]} +where @var{n} is a zero-based namespace number. In systems with no support +for linkage namespaces, this variable will always be set to @samp{[[0]]}. + @end table @node Convenience Funs @@ -22212,6 +22274,22 @@ less useful than setting a catchpoint, because it does not allow for conditions or commands as a catchpoint does. @table @code +@kindex info linker-namespaces +@item info linker-namespaces +@item info linker-namespaces @code{[[@var{n}]]} + +With no argument, print the number of linker namespaces which are +currently active --- that is, namespaces that have libraries loaded +into them. Then, it prints the number of libraries loaded into each +namespace, and all the libraries loaded into them, in the same way +as @code{info sharedlibrary}. + +If an argument @code{[[@var{n}]]} is provided, only prints the +library count and the libraried for the provided namespace @var{n}. +The surrounding square brackets are optional. +@end table + +@table @code @item set stop-on-solib-events @kindex set stop-on-solib-events This command controls whether @value{GDBN} should give you control diff --git a/gdb/doc/python.texi b/gdb/doc/python.texi index 50342bb..afbd62f 100644 --- a/gdb/doc/python.texi +++ b/gdb/doc/python.texi @@ -257,7 +257,7 @@ Python code must not override these, or even change the options using signals, @value{GDBN} will most likely stop working correctly. Note that it is unfortunately common for GUI toolkits to install a @code{SIGCHLD} handler. When creating a new Python thread, you can -use @code{gdb.block_signals} or @code{gdb.Thread} to handle this +use @code{gdb.blocked_signals} or @code{gdb.Thread} to handle this correctly; see @ref{Threading in GDB}. @item @@ -654,22 +654,22 @@ threads, you must be careful to only call @value{GDBN}-specific functions in the @value{GDBN} thread. @value{GDBN} provides some functions to help with this. -@defun gdb.block_signals () +@defun gdb.blocked_signals () As mentioned earlier (@pxref{Basic Python}), certain signals must be -delivered to the @value{GDBN} main thread. The @code{block_signals} +delivered to the @value{GDBN} main thread. The @code{blocked_signals} function returns a context manager that will block these signals on entry. This can be used when starting a new thread to ensure that the signals are blocked there, like: @smallexample -with gdb.block_signals(): +with gdb.blocked_signals(): start_new_thread() @end smallexample @end defun @deftp {class} gdb.Thread This is a subclass of Python's @code{threading.Thread} class. It -overrides the @code{start} method to call @code{block_signals}, making +overrides the @code{start} method to call @code{blocked_signals}, making this an easy-to-use drop-in replacement for creating threads that will work well in @value{GDBN}. @end deftp @@ -4554,8 +4554,8 @@ registered. The help text for the new command is taken from the Python documentation string for the command's class, if there is one. If no -documentation string is provided, the default value ``This command is -not documented.'' is used. +documentation string is provided, the default value @samp{This command +is not documented.} is used. @end defun @cindex don't repeat Python command @@ -7049,13 +7049,13 @@ writable. @cindex colors in python @tindex gdb.Color -You can assign instance of @code{Color} to the @code{value} of +You can assign instance of @code{gdb.Color} to the @code{value} of a @code{Parameter} instance created with @code{PARAM_COLOR}. -@code{Color} may refer to an index from color palette or contain components -of a color from some colorspace. +@code{gdb.Color} may refer to an index from a color palette or contain +components of a color from some color space. -@defun Color.__init__ (@r{[}@var{value} @r{[}, @var{color-space}@r{]}@r{]}) +@defun Color.__init__ (@r{[}value @r{[}, color_space@r{]}@r{]}) @var{value} is @code{None} (meaning the terminal's default color), an integer index of a color in palette, tuple with color components @@ -7065,8 +7065,9 @@ or one of the following color names: @samp{green}, @samp{yellow}, @samp{blue}, @samp{magenta}, @samp{cyan}, or @samp{white}. -@var{color-space} should be one of the @samp{COLORSPACE_} constants. This -argument tells @value{GDBN} which color space @var{value} belongs. +@var{color_space} should be one of the @samp{COLORSPACE_} constants +listed below. This argument tells @value{GDBN} which color space +@var{value} belongs. @end defun @defvar Color.is_none @@ -7094,7 +7095,7 @@ This attribute exist if @code{is_direct} is @code{True}. Its value is tuple with integer components of a color. @end defvar -@defun Color.escape_sequence (@var{self}, @var{is_foreground}) +@defun Color.escape_sequence (is_foreground) Returns string to change terminal's color to this. If @var{is_foreground} is @code{True}, then the returned sequence will change @@ -7136,6 +7137,8 @@ Direct 24-bit RGB colors. @end table +It is not possible to sub-class the @code{Color} class. + @node Architectures In Python @subsubsection Python representation of architectures @cindex Python architectures diff --git a/gdb/dwarf2/attribute.c b/gdb/dwarf2/attribute.c index 1278f97..8ff0353 100644 --- a/gdb/dwarf2/attribute.c +++ b/gdb/dwarf2/attribute.c @@ -73,7 +73,8 @@ attribute::form_is_string () const || form == DW_FORM_strx3 || form == DW_FORM_strx4 || form == DW_FORM_GNU_str_index - || form == DW_FORM_GNU_strp_alt); + || form == DW_FORM_GNU_strp_alt + || form == DW_FORM_strp_sup); } /* See attribute.h. */ @@ -185,11 +186,43 @@ attribute::unsigned_constant () const /* See attribute.h. */ +std::optional<LONGEST> +attribute::signed_constant () const +{ + if (form_is_strictly_signed ()) + return u.snd; + + switch (form) + { + case DW_FORM_data8: + case DW_FORM_udata: + /* Not sure if DW_FORM_udata should be handled or not. Anyway + for DW_FORM_data8, there's no need to sign-extend. */ + return u.snd; + + case DW_FORM_data1: + return sign_extend (u.unsnd, 8); + case DW_FORM_data2: + return sign_extend (u.unsnd, 16); + case DW_FORM_data4: + return sign_extend (u.unsnd, 32); + } + + /* For DW_FORM_data16 see attribute::form_is_constant. */ + complaint (_("Attribute value is not a constant (%s)"), + dwarf_form_name (form)); + return {}; +} + +/* See attribute.h. */ + bool attribute::form_is_unsigned () const { return (form == DW_FORM_ref_addr || form == DW_FORM_GNU_ref_alt + || form == DW_FORM_ref_sup4 + || form == DW_FORM_ref_sup8 || form == DW_FORM_data2 || form == DW_FORM_data4 || form == DW_FORM_data8 @@ -293,5 +326,8 @@ attribute::as_boolean () const return true; else if (form == DW_FORM_flag) return u.unsnd != 0; - return constant_value (0) != 0; + /* Using signed_constant here will work even for the weird case + where a negative value is provided. Probably doesn't matter but + also seems harmless. */ + return signed_constant ().value_or (0) != 0; } diff --git a/gdb/dwarf2/attribute.h b/gdb/dwarf2/attribute.h index 70edff3..31ff018 100644 --- a/gdb/dwarf2/attribute.h +++ b/gdb/dwarf2/attribute.h @@ -114,6 +114,15 @@ struct attribute returned. */ std::optional<ULONGEST> unsigned_constant () const; + /* Return a signed constant value. This only handles constant forms + (i.e., form_is_constant -- and not the extended list of + "unsigned" forms) and assumes a signed value is desired. This + function will sign-extend DW_FORM_data* values. + + If non-constant form is used, then complaint is issued and an + empty value is returned. */ + std::optional<LONGEST> signed_constant () const; + /* Return non-zero if ATTR's value falls in the 'constant' class, or zero otherwise. When this function returns true, you can apply the constant_value method to it. @@ -144,7 +153,9 @@ struct attribute || form == DW_FORM_ref4 || form == DW_FORM_ref8 || form == DW_FORM_ref_udata - || form == DW_FORM_GNU_ref_alt); + || form == DW_FORM_GNU_ref_alt + || form == DW_FORM_ref_sup4 + || form == DW_FORM_ref_sup8); } /* Check if the attribute's form is a DW_FORM_block* @@ -164,10 +175,29 @@ struct attribute false. */ bool form_is_strictly_signed () const; + /* Check if the attribute's form is an unsigned constant form. This + only returns true for forms that are strictly unsigned -- that + is, for a context-dependent form like DW_FORM_data1, this returns + false. */ + bool form_is_strictly_unsigned () const + { + return form == DW_FORM_udata; + } + /* Check if the attribute's form is a form that requires "reprocessing". */ bool form_requires_reprocessing () const; + /* Check if attribute's form refers to the separate "dwz" file. + This is only useful for references to the .debug_info section, + not to the supplementary .debug_str section. */ + bool form_is_alt () const + { + return (form == DW_FORM_GNU_ref_alt + || form == DW_FORM_ref_sup4 + || form == DW_FORM_ref_sup8); + } + /* Return DIE offset of this attribute. Return 0 with complaint if the attribute is not of the required kind. */ diff --git a/gdb/dwarf2/comp-unit-head.c b/gdb/dwarf2/comp-unit-head.c index 8ec8897..a35d664 100644 --- a/gdb/dwarf2/comp-unit-head.c +++ b/gdb/dwarf2/comp-unit-head.c @@ -26,7 +26,6 @@ #include "dwarf2/comp-unit-head.h" #include "dwarf2/leb.h" -#include "dwarf2/read.h" #include "dwarf2/section.h" #include "dwarf2/stringify.h" #include "dwarf2/error.h" @@ -149,15 +148,13 @@ read_comp_unit_head (struct comp_unit_head *cu_header, Perform various error checking on the header. */ static void -error_check_comp_unit_head (dwarf2_per_objfile *per_objfile, - struct comp_unit_head *header, - struct dwarf2_section_info *section, - struct dwarf2_section_info *abbrev_section) +error_check_comp_unit_head (comp_unit_head *header, + dwarf2_section_info *section, + dwarf2_section_info *abbrev_section) { const char *filename = section->get_file_name (); - if (to_underlying (header->abbrev_sect_off) - >= abbrev_section->get_size (per_objfile->objfile)) + if (to_underlying (header->abbrev_sect_off) >= abbrev_section->size) error (_(DWARF_ERROR_PREFIX "bad offset (%s) in compilation unit header " "(offset %s + 6) [in module %s]"), @@ -179,12 +176,10 @@ error_check_comp_unit_head (dwarf2_per_objfile *per_objfile, /* See comp-unit-head.h. */ const gdb_byte * -read_and_check_comp_unit_head (dwarf2_per_objfile *per_objfile, - struct comp_unit_head *header, - struct dwarf2_section_info *section, - struct dwarf2_section_info *abbrev_section, - const gdb_byte *info_ptr, - rcuh_kind section_kind) +read_and_check_comp_unit_head (comp_unit_head *header, + dwarf2_section_info *section, + dwarf2_section_info *abbrev_section, + const gdb_byte *info_ptr, rcuh_kind section_kind) { const gdb_byte *beg_of_comp_unit = info_ptr; @@ -194,7 +189,7 @@ read_and_check_comp_unit_head (dwarf2_per_objfile *per_objfile, header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit); - error_check_comp_unit_head (per_objfile, header, section, abbrev_section); + error_check_comp_unit_head (header, section, abbrev_section); return info_ptr; } diff --git a/gdb/dwarf2/comp-unit-head.h b/gdb/dwarf2/comp-unit-head.h index 5134893..ea09153 100644 --- a/gdb/dwarf2/comp-unit-head.h +++ b/gdb/dwarf2/comp-unit-head.h @@ -129,11 +129,8 @@ extern const gdb_byte *read_comp_unit_head The contents of the header are stored in HEADER. The result is a pointer to the start of the first DIE. */ extern const gdb_byte *read_and_check_comp_unit_head - (dwarf2_per_objfile *per_objfile, - struct comp_unit_head *header, - struct dwarf2_section_info *section, - struct dwarf2_section_info *abbrev_section, - const gdb_byte *info_ptr, + (comp_unit_head *header, dwarf2_section_info *section, + dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr, rcuh_kind section_kind); #endif /* GDB_DWARF2_COMP_UNIT_HEAD_H */ diff --git a/gdb/dwarf2/cooked-indexer.c b/gdb/dwarf2/cooked-indexer.c index 1f3a235..b8b66cf 100644 --- a/gdb/dwarf2/cooked-indexer.c +++ b/gdb/dwarf2/cooked-indexer.c @@ -222,7 +222,7 @@ cooked_indexer::scan_attributes (dwarf2_per_cu *scanning_per_cu, case DW_AT_abstract_origin: case DW_AT_extension: origin_offset = attr.get_ref_die_offset (); - origin_is_dwz = attr.form == DW_FORM_GNU_ref_alt; + origin_is_dwz = attr.form_is_alt (); break; case DW_AT_external: @@ -423,7 +423,7 @@ cooked_indexer::index_imported_unit (cutu_reader *reader, if (attr.name == DW_AT_import) { sect_off = attr.get_ref_die_offset (); - is_dwz = (attr.form == DW_FORM_GNU_ref_alt + is_dwz = (attr.form_is_alt () || reader->cu ()->per_cu->is_dwz); } } diff --git a/gdb/dwarf2/die.c b/gdb/dwarf2/die.c index 8c3d2ca..7ed18bf 100644 --- a/gdb/dwarf2/die.c +++ b/gdb/dwarf2/die.c @@ -90,6 +90,8 @@ dump_die_shallow (struct ui_file *f, int indent, struct die_info *die) gdb_puts (hex_string (die->attrs[i].as_unsigned ()), f); break; case DW_FORM_GNU_ref_alt: + case DW_FORM_ref_sup4: + case DW_FORM_ref_sup8: gdb_printf (f, "alt ref address: "); gdb_puts (hex_string (die->attrs[i].as_unsigned ()), f); break; @@ -123,6 +125,7 @@ dump_die_shallow (struct ui_file *f, int indent, struct die_info *die) case DW_FORM_strx: case DW_FORM_GNU_str_index: case DW_FORM_GNU_strp_alt: + case DW_FORM_strp_sup: gdb_printf (f, "string: \"%s\" (%s canonicalized)", die->attrs[i].as_string () ? die->attrs[i].as_string () : "", diff --git a/gdb/dwarf2/dwz.c b/gdb/dwarf2/dwz.c index e5e18a1..583103b 100644 --- a/gdb/dwarf2/dwz.c +++ b/gdb/dwarf2/dwz.c @@ -21,6 +21,7 @@ #include "build-id.h" #include "debuginfod-support.h" +#include "dwarf2/leb.h" #include "dwarf2/read.h" #include "dwarf2/sect-names.h" #include "filenames.h" @@ -34,15 +35,17 @@ const char * dwz_file::read_string (struct objfile *objfile, LONGEST str_offset) { - str.read (objfile); + /* This must be true because the sections are read in when the + dwz_file is created. */ + gdb_assert (str.readin); if (str.buffer == NULL) - error (_("DW_FORM_GNU_strp_alt used without .debug_str " + error (_("supplementary DWARF file missing .debug_str " "section [in module %s]"), this->filename ()); if (str_offset >= str.size) - error (_("DW_FORM_GNU_strp_alt pointing outside of " - ".debug_str section [in module %s]"), + error (_("invalid string reference to supplementary DWARF file " + "[in module %s]"), this->filename ()); gdb_assert (HOST_CHAR_BIT == 8); if (str.buffer[str_offset] == '\0') @@ -85,6 +88,139 @@ locate_dwz_sections (struct objfile *objfile, bfd *abfd, asection *sectp, } } +/* Helper that throws an exception when reading the .debug_sup + section. */ + +static void +debug_sup_failure (const char *text, bfd *abfd) +{ + error (_("%s [in modules %s]"), text, bfd_get_filename (abfd)); +} + +/* Look for the .debug_sup section and read it. If the section does + not exist, this returns false. If the section does exist but fails + to parse for some reason, an exception is thrown. Otherwise, if + everything goes well, this returns true and fills in the out + parameters. */ + +static bool +get_debug_sup_info (bfd *abfd, + std::string *filename, + size_t *buildid_len, + gdb::unique_xmalloc_ptr<bfd_byte> *buildid) +{ + asection *sect = bfd_get_section_by_name (abfd, ".debug_sup"); + if (sect == nullptr) + return false; + + bfd_byte *contents; + if (!bfd_malloc_and_get_section (abfd, sect, &contents)) + debug_sup_failure (_("could not read .debug_sup section"), abfd); + + gdb::unique_xmalloc_ptr<bfd_byte> content_holder (contents); + bfd_size_type size = bfd_section_size (sect); + + /* Version of this section. */ + if (size < 4) + debug_sup_failure (_(".debug_sup section too short"), abfd); + unsigned int version = read_2_bytes (abfd, contents); + contents += 2; + size -= 2; + if (version != 5) + debug_sup_failure (_(".debug_sup has wrong version number"), abfd); + + /* Skip the is_supplementary value. We already ensured there were + enough bytes, above. */ + ++contents; + --size; + + /* The spec says that in the supplementary file, this must be \0, + but it doesn't seem very important. */ + const char *fname = (const char *) contents; + size_t len = strlen (fname) + 1; + if (filename != nullptr) + *filename = fname; + contents += len; + size -= len; + + if (size == 0) + debug_sup_failure (_(".debug_sup section missing ID"), abfd); + + unsigned int bytes_read; + *buildid_len = read_unsigned_leb128 (abfd, contents, &bytes_read); + contents += bytes_read; + size -= bytes_read; + + if (size < *buildid_len) + debug_sup_failure (_("extra data after .debug_sup section ID"), abfd); + + if (*buildid_len != 0) + buildid->reset ((bfd_byte *) xmemdup (contents, *buildid_len, + *buildid_len)); + + return true; +} + +/* Validate that ABFD matches the given BUILDID. If DWARF5 is true, + then this is done by examining the .debug_sup data. */ + +static bool +verify_id (bfd *abfd, size_t len, const bfd_byte *buildid, bool dwarf5) +{ + if (!bfd_check_format (abfd, bfd_object)) + return false; + + if (dwarf5) + { + size_t new_len; + gdb::unique_xmalloc_ptr<bfd_byte> new_id; + + if (!get_debug_sup_info (abfd, nullptr, &new_len, &new_id)) + return false; + return (len == new_len + && memcmp (buildid, new_id.get (), len) == 0); + } + else + return build_id_verify (abfd, len, buildid); +} + +/* Find either the .debug_sup or .gnu_debugaltlink section and return + its contents. Returns true on success and sets out parameters, or + false if nothing is found. */ + +static bool +read_alt_info (bfd *abfd, std::string *filename, + size_t *buildid_len, + gdb::unique_xmalloc_ptr<bfd_byte> *buildid, + bool *dwarf5) +{ + if (get_debug_sup_info (abfd, filename, buildid_len, buildid)) + { + *dwarf5 = true; + return true; + } + + bfd_size_type buildid_len_arg; + bfd_set_error (bfd_error_no_error); + bfd_byte *buildid_out; + gdb::unique_xmalloc_ptr<char> new_filename + (bfd_get_alt_debug_link_info (abfd, &buildid_len_arg, + &buildid_out)); + if (new_filename == nullptr) + { + if (bfd_get_error () == bfd_error_no_error) + return false; + error (_("could not read '.gnu_debugaltlink' section: %s"), + bfd_errmsg (bfd_get_error ())); + } + *filename = new_filename.get (); + + *buildid_len = buildid_len_arg; + buildid->reset (buildid_out); + *dwarf5 = false; + return true; +} + /* Attempt to find a .dwz file (whose full path is represented by FILENAME) in all of the specified debug file directories provided. @@ -93,7 +229,7 @@ locate_dwz_sections (struct objfile *objfile, bfd *abfd, asection *sectp, static gdb_bfd_ref_ptr dwz_search_other_debugdirs (std::string &filename, bfd_byte *buildid, - size_t buildid_len) + size_t buildid_len, bool dwarf5) { /* Let's assume that the path represented by FILENAME has the "/.dwz/" subpath in it. This is what (most) GNU/Linux @@ -161,7 +297,7 @@ dwz_search_other_debugdirs (std::string &filename, bfd_byte *buildid, if (dwz_bfd == nullptr) continue; - if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid)) + if (!verify_id (dwz_bfd.get (), buildid_len, buildid, dwarf5)) { dwz_bfd.reset (nullptr); continue; @@ -177,11 +313,8 @@ dwz_search_other_debugdirs (std::string &filename, bfd_byte *buildid, /* See dwz.h. */ void -dwarf2_read_dwz_file (dwarf2_per_objfile *per_objfile) +dwz_file::read_dwz_file (dwarf2_per_objfile *per_objfile) { - bfd_size_type buildid_len_arg; - size_t buildid_len; - bfd_byte *buildid; dwarf2_per_bfd *per_bfd = per_objfile->per_bfd; /* This may query the user via the debuginfod support, so it may @@ -193,24 +326,17 @@ dwarf2_read_dwz_file (dwarf2_per_objfile *per_objfile) /* Set this early, so that on error it remains NULL. */ per_bfd->dwz_file.emplace (nullptr); - bfd_set_error (bfd_error_no_error); - gdb::unique_xmalloc_ptr<char> data - (bfd_get_alt_debug_link_info (per_bfd->obfd, - &buildid_len_arg, &buildid)); - if (data == NULL) + size_t buildid_len; + gdb::unique_xmalloc_ptr<bfd_byte> buildid; + std::string filename; + bool dwarf5; + if (!read_alt_info (per_bfd->obfd, &filename, &buildid_len, &buildid, + &dwarf5)) { - if (bfd_get_error () == bfd_error_no_error) - return; - error (_("could not read '.gnu_debugaltlink' section: %s"), - bfd_errmsg (bfd_get_error ())); + /* Nothing found, nothing to do. */ + return; } - gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid); - - buildid_len = (size_t) buildid_len_arg; - - std::string filename = data.get (); - if (!IS_ABSOLUTE_PATH (filename.c_str ())) { gdb::unique_xmalloc_ptr<char> abs = gdb_realpath (per_bfd->filename ()); @@ -223,25 +349,26 @@ dwarf2_read_dwz_file (dwarf2_per_objfile *per_objfile) gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename.c_str (), gnutarget)); if (dwz_bfd != NULL) { - if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid)) + if (!verify_id (dwz_bfd.get (), buildid_len, buildid.get (), dwarf5)) dwz_bfd.reset (nullptr); } if (dwz_bfd == NULL) - dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid); + dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid.get ()); if (dwz_bfd == nullptr) { /* If the user has provided us with different debug file directories, we can try them in order. */ - dwz_bfd = dwz_search_other_debugdirs (filename, buildid, buildid_len); + dwz_bfd = dwz_search_other_debugdirs (filename, buildid.get (), + buildid_len, dwarf5); } if (dwz_bfd == nullptr) { gdb::unique_xmalloc_ptr<char> alt_filename; scoped_fd fd - = debuginfod_debuginfo_query (buildid, buildid_len, + = debuginfod_debuginfo_query (buildid.get (), buildid_len, per_bfd->filename (), &alt_filename); if (fd.get () >= 0) @@ -252,16 +379,18 @@ dwarf2_read_dwz_file (dwarf2_per_objfile *per_objfile) if (dwz_bfd == nullptr) warning (_("File \"%s\" from debuginfod cannot be opened as bfd"), alt_filename.get ()); - else if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid)) + else if (!verify_id (dwz_bfd.get (), buildid_len, buildid.get (), + dwarf5)) dwz_bfd.reset (nullptr); } } if (dwz_bfd == NULL) - error (_("could not find '.gnu_debugaltlink' file for %s"), + error (_("could not find supplementary DWARF file (%s) for %s"), + filename.c_str (), per_bfd->filename ()); - auto result = std::make_unique<dwz_file> (std::move (dwz_bfd)); + dwz_file_up result (new dwz_file (std::move (dwz_bfd))); for (asection *sec : gdb_bfd_sections (result->dwz_bfd)) locate_dwz_sections (per_objfile->objfile, result->dwz_bfd.get (), diff --git a/gdb/dwarf2/dwz.h b/gdb/dwarf2/dwz.h index 9f69123..372f7e6 100644 --- a/gdb/dwarf2/dwz.h +++ b/gdb/dwarf2/dwz.h @@ -31,10 +31,12 @@ struct dwarf2_per_objfile; struct dwz_file { - dwz_file (gdb_bfd_ref_ptr &&bfd) - : dwz_bfd (std::move (bfd)) - { - } + /* Open the separate '.dwz' debug file, if needed. This will set + the appropriate field in the per-BFD structure. If the DWZ file + exists, the relevant sections are read in as well. Throws an + exception if the .gnu_debugaltlink or .debug_sup section exists + but is invalid or if the file cannot be found. */ + static void read_dwz_file (dwarf2_per_objfile *per_objfile); const char *filename () const { @@ -64,16 +66,15 @@ struct dwz_file return a pointer to the string. */ const char *read_string (struct objfile *objfile, LONGEST str_offset); -}; -using dwz_file_up = std::unique_ptr<dwz_file>; +private: -/* Open the separate '.dwz' debug file, if needed. This just sets the - appropriate field in the per-BFD structure. If the DWZ file - exists, the relevant sections are read in as well. Throws an error - if the .gnu_debugaltlink section exists but the file cannot be - found. */ + explicit dwz_file (gdb_bfd_ref_ptr &&bfd) + : dwz_bfd (std::move (bfd)) + { + } +}; -extern void dwarf2_read_dwz_file (dwarf2_per_objfile *per_objfile); +using dwz_file_up = std::unique_ptr<dwz_file>; #endif /* GDB_DWARF2_DWZ_H */ diff --git a/gdb/dwarf2/macro.c b/gdb/dwarf2/macro.c index 9b8f093..1dc3a9e 100644 --- a/gdb/dwarf2/macro.c +++ b/gdb/dwarf2/macro.c @@ -259,6 +259,7 @@ skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end, case DW_FORM_sec_offset: case DW_FORM_strp: case DW_FORM_GNU_strp_alt: + case DW_FORM_strp_sup: bytes += offset_size; break; diff --git a/gdb/dwarf2/read.c b/gdb/dwarf2/read.c index 794c397..2523ca8 100644 --- a/gdb/dwarf2/read.c +++ b/gdb/dwarf2/read.c @@ -622,15 +622,21 @@ struct variant_field /* A variant can contain other variant parts. */ std::vector<variant_part_builder> variant_parts; - /* If we see a DW_TAG_variant, then this will be set if this is the - default branch. */ - bool default_branch = false; /* If we see a DW_AT_discr_value, then this will be the discriminant - value. */ - ULONGEST discriminant_value = 0; + value. Just the attribute is stored here, because we have to + defer deciding whether the value is signed or unsigned until the + end. */ + const attribute *discriminant_attr = nullptr; /* If we see a DW_AT_discr_list, then this is a pointer to the list data. */ struct dwarf_block *discr_list_data = nullptr; + + /* If both DW_AT_discr_value and DW_AT_discr_list are absent, then + this is the default branch. */ + bool is_default () const + { + return discriminant_attr == nullptr && discr_list_data == nullptr; + } }; /* This represents a DW_TAG_variant_part. */ @@ -1039,14 +1045,7 @@ static struct dwo_unit *lookup_dwo_unit_in_dwp (dwarf2_per_bfd *per_bfd, struct dwp_file *dwp_file, const char *comp_dir, ULONGEST signature, int is_debug_types); -static struct dwp_file *get_dwp_file (dwarf2_per_objfile *per_objfile); - -static struct dwo_unit *lookup_dwo_comp_unit - (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir, - ULONGEST signature); - -static struct dwo_unit *lookup_dwo_type_unit - (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir); +static void open_and_init_dwp_file (dwarf2_per_objfile *per_objfile); static void queue_and_load_all_dwo_tus (dwarf2_cu *cu); @@ -1289,7 +1288,16 @@ dwarf2_has_info (struct objfile *objfile, BFD, to avoid races. */ try { - dwarf2_read_dwz_file (per_objfile); + dwz_file::read_dwz_file (per_objfile); + } + catch (const gdb_exception_error &err) + { + warning (_("%s"), err.what ()); + } + + try + { + open_and_init_dwp_file (per_objfile); } catch (const gdb_exception_error &err) { @@ -1632,7 +1640,7 @@ dw2_do_instantiate_symtab (dwarf2_per_cu *per_cu, && per_objfile->per_bfd->index_table != NULL && !per_objfile->per_bfd->index_table->version_check () /* DWP files aren't supported yet. */ - && get_dwp_file (per_objfile) == NULL) + && per_objfile->per_bfd->dwp_file == nullptr) queue_and_load_all_dwo_tus (cu); } @@ -2387,12 +2395,12 @@ read_abbrev_offset (dwarf2_per_objfile *per_objfile, and fill them into DWO_FILE's type unit hash table. It will process only type units, therefore DW_UT_type. */ -static void -create_dwo_debug_type_hash_table (dwarf2_per_objfile *per_objfile, - dwo_file *dwo_file, dwarf2_section_info *section, - rcuh_kind section_kind) +void +cutu_reader::create_dwo_debug_type_hash_table (dwarf2_per_bfd *per_bfd, + dwo_file *dwo_file, + dwarf2_section_info *section, + rcuh_kind section_kind) { - struct objfile *objfile = per_objfile->objfile; struct dwarf2_section_info *abbrev_section; bfd *abfd; const gdb_byte *info_ptr, *end_ptr; @@ -2403,7 +2411,6 @@ create_dwo_debug_type_hash_table (dwarf2_per_objfile *per_objfile, section->get_name (), abbrev_section->get_file_name ()); - section->read (objfile); info_ptr = section->buffer; if (info_ptr == NULL) @@ -2432,8 +2439,8 @@ create_dwo_debug_type_hash_table (dwarf2_per_objfile *per_objfile, /* We need to read the type's signature in order to build the hash table, but we don't need anything else just yet. */ - ptr = read_and_check_comp_unit_head (per_objfile, &header, section, - abbrev_section, ptr, section_kind); + ptr = read_and_check_comp_unit_head (&header, section, abbrev_section, + ptr, section_kind); length = header.get_length_with_initial (); @@ -2447,8 +2454,7 @@ create_dwo_debug_type_hash_table (dwarf2_per_objfile *per_objfile, continue; } - dwo_unit *dwo_tu - = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, dwo_unit); + dwo_unit *dwo_tu = OBSTACK_ZALLOC (&per_bfd->obstack, dwo_unit); dwo_tu->dwo_file = dwo_file; dwo_tu->signature = header.signature; dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu; @@ -2478,14 +2484,14 @@ create_dwo_debug_type_hash_table (dwarf2_per_objfile *per_objfile, Note: This function processes DWO files only, not DWP files. */ -static void -create_dwo_debug_types_hash_table - (dwarf2_per_objfile *per_objfile, dwo_file *dwo_file, +void +cutu_reader::create_dwo_debug_types_hash_table + (dwarf2_per_bfd *per_bfd, dwo_file *dwo_file, gdb::array_view<dwarf2_section_info> type_sections) { for (dwarf2_section_info §ion : type_sections) - create_dwo_debug_type_hash_table (per_objfile, dwo_file, §ion, - rcuh_kind::TYPE); + create_dwo_debug_type_hash_table (per_bfd, dwo_file, §ion, + rcuh_kind::TYPE); } /* Add an entry for signature SIG to per_bfd->signatured_types. */ @@ -2610,7 +2616,7 @@ lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig) { dwarf2_per_objfile *per_objfile = cu->per_objfile; dwarf2_per_bfd *per_bfd = per_objfile->per_bfd; - struct dwp_file *dwp_file = get_dwp_file (per_objfile); + dwp_file *dwp_file = per_objfile->per_bfd->dwp_file.get (); gdb_assert (cu->dwo_unit); gdb_assert (dwp_file != NULL); @@ -2652,7 +2658,7 @@ lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig) { /* We're in a DWO/DWP file, and we're using .gdb_index. These cases require special processing. */ - if (get_dwp_file (per_objfile) == NULL) + if (per_objfile->per_bfd->dwp_file == nullptr) return lookup_dwo_signatured_type (cu, sig); else return lookup_dwp_signatured_type (cu, sig); @@ -2712,9 +2718,8 @@ cutu_reader::read_cutu_die_from_dwo (dwarf2_cu *cu, dwo_unit *dwo_unit, die_info *stub_comp_unit_die, const char *stub_comp_dir) { - dwarf2_per_objfile *per_objfile = cu->per_objfile; dwarf2_per_cu *per_cu = cu->per_cu; - struct objfile *objfile = per_objfile->objfile; + struct objfile *objfile = cu->per_objfile->objfile; bfd *abfd; struct dwarf2_section_info *dwo_abbrev_section; @@ -2790,9 +2795,10 @@ cutu_reader::read_cutu_die_from_dwo (dwarf2_cu *cu, dwo_unit *dwo_unit, { signatured_type *sig_type = (struct signatured_type *) per_cu; - m_info_ptr = read_and_check_comp_unit_head (per_objfile, &cu->header, - section, dwo_abbrev_section, + m_info_ptr = read_and_check_comp_unit_head (&cu->header, section, + dwo_abbrev_section, m_info_ptr, rcuh_kind::TYPE); + /* This is not an assert because it can be caused by bad debug info. */ if (sig_type->signature != cu->header.signature) { @@ -2818,7 +2824,7 @@ cutu_reader::read_cutu_die_from_dwo (dwarf2_cu *cu, dwo_unit *dwo_unit, else { m_info_ptr - = read_and_check_comp_unit_head (per_objfile, &cu->header, section, + = read_and_check_comp_unit_head (&cu->header, section, dwo_abbrev_section, m_info_ptr, rcuh_kind::COMPILE); gdb_assert (dwo_unit->sect_off == cu->header.sect_off); @@ -2873,8 +2879,9 @@ lookup_dwo_id (struct dwarf2_cu *cu, struct die_info* comp_unit_die) Returns nullptr if the specified DWO unit cannot be found. */ -static struct dwo_unit * -lookup_dwo_unit (dwarf2_cu *cu, die_info *comp_unit_die, const char *dwo_name) +dwo_unit * +cutu_reader::lookup_dwo_unit (dwarf2_cu *cu, die_info *comp_unit_die, + const char *dwo_name) { #if CXX_STD_THREAD /* We need a lock here to handle the DWO hash table. */ @@ -3047,7 +3054,7 @@ cutu_reader::cutu_reader (dwarf2_per_cu &this_cu, if (this_cu.is_debug_types) { m_info_ptr - = read_and_check_comp_unit_head (&per_objfile, &cu->header, section, + = read_and_check_comp_unit_head (&cu->header, section, abbrev_section, m_info_ptr, rcuh_kind::TYPE); @@ -3070,7 +3077,7 @@ cutu_reader::cutu_reader (dwarf2_per_cu &this_cu, else { m_info_ptr - = read_and_check_comp_unit_head (&per_objfile, &cu->header, section, + = read_and_check_comp_unit_head (&cu->header, section, abbrev_section, m_info_ptr, rcuh_kind::COMPILE); @@ -3204,12 +3211,11 @@ cutu_reader::cutu_reader (dwarf2_per_cu &this_cu, m_info_ptr = section->buffer + to_underlying (this_cu.sect_off); const gdb_byte *begin_info_ptr = m_info_ptr; - m_info_ptr - = read_and_check_comp_unit_head (&per_objfile, &m_new_cu->header, section, - abbrev_section, m_info_ptr, - (this_cu.is_debug_types - ? rcuh_kind::TYPE - : rcuh_kind::COMPILE)); + m_info_ptr = read_and_check_comp_unit_head (&m_new_cu->header, section, + abbrev_section, m_info_ptr, + (this_cu.is_debug_types + ? rcuh_kind::TYPE + : rcuh_kind::COMPILE)); m_new_cu->str_offsets_base = parent_cu.str_offsets_base; m_new_cu->addr_base = parent_cu.addr_base; @@ -3510,7 +3516,7 @@ process_skeletonless_type_units (dwarf2_per_objfile *per_objfile, cooked_index_worker_result *storage) { /* Skeletonless TUs in DWP files without .gdb_index is not supported yet. */ - if (get_dwp_file (per_objfile) == nullptr) + if (per_objfile->per_bfd->dwp_file == nullptr) for (const dwo_file_up &file : per_objfile->per_bfd->dwo_files) for (dwo_unit *unit : file->tus) process_skeletonless_type_unit (unit, per_objfile, storage); @@ -3692,6 +3698,7 @@ read_comp_units_from_section (dwarf2_per_objfile *per_objfile, { const gdb_byte *info_ptr; struct objfile *objfile = per_objfile->objfile; + dwarf2_per_bfd *per_bfd = per_objfile->per_bfd; dwarf_read_debug_printf ("Reading %s for %s", section->get_name (), @@ -3708,20 +3715,19 @@ read_comp_units_from_section (dwarf2_per_objfile *per_objfile, sect_offset sect_off = (sect_offset) (info_ptr - section->buffer); comp_unit_head cu_header; - read_and_check_comp_unit_head (per_objfile, &cu_header, section, - abbrev_section, info_ptr, - section_kind); + read_and_check_comp_unit_head (&cu_header, section, abbrev_section, + info_ptr, section_kind); unsigned int length = cu_header.get_length_with_initial (); /* Save the compilation unit for later lookup. */ if (cu_header.unit_type != DW_UT_type) - this_cu - = per_objfile->per_bfd->allocate_per_cu (section, sect_off, length, is_dwz); + this_cu = per_bfd->allocate_per_cu (section, sect_off, length, is_dwz); else { - auto sig_type = per_objfile->per_bfd->allocate_signatured_type - (section, sect_off, length, is_dwz, cu_header.signature); + auto sig_type + = per_bfd->allocate_signatured_type (section, sect_off, length, + is_dwz, cu_header.signature); signatured_type *sig_ptr = sig_type.get (); sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu; this_cu.reset (sig_type.release ()); @@ -3737,7 +3743,7 @@ read_comp_units_from_section (dwarf2_per_objfile *per_objfile, } info_ptr = info_ptr + this_cu->length (); - per_objfile->per_bfd->all_units.push_back (std::move (this_cu)); + per_bfd->all_units.push_back (std::move (this_cu)); } } @@ -3896,11 +3902,13 @@ cutu_reader::skip_one_attribute (dwarf_form form, const gdb_byte *info_ptr) case DW_FORM_data4: case DW_FORM_ref4: case DW_FORM_strx4: + case DW_FORM_ref_sup4: return info_ptr + 4; case DW_FORM_data8: case DW_FORM_ref8: case DW_FORM_ref_sig8: + case DW_FORM_ref_sup8: return info_ptr + 8; case DW_FORM_data16: @@ -3913,6 +3921,7 @@ cutu_reader::skip_one_attribute (dwarf_form form, const gdb_byte *info_ptr) case DW_FORM_sec_offset: case DW_FORM_strp: case DW_FORM_GNU_strp_alt: + case DW_FORM_strp_sup: return info_ptr + m_cu->header.offset_size; case DW_FORM_exprloc: @@ -5023,7 +5032,7 @@ process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu) if (attr != NULL) { sect_offset sect_off = attr->get_ref_die_offset (); - bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz); + bool is_dwz = attr->form_is_alt () || cu->per_cu->is_dwz; dwarf2_per_objfile *per_objfile = cu->per_objfile; dwarf2_per_cu *per_cu = dwarf2_find_containing_comp_unit (sect_off, is_dwz, @@ -6307,16 +6316,14 @@ lookup_dwo_file (dwarf2_per_bfd *per_bfd, const char *dwo_name, /* Create the dwo_units for the CUs in a DWO_FILE. Note: This function processes DWO files only, not DWP files. */ -static void -create_dwo_cus_hash_table (dwarf2_cu *cu, dwo_file &dwo_file) +void +cutu_reader::create_dwo_cus_hash_table (dwarf2_cu *cu, dwo_file &dwo_file) { dwarf2_per_objfile *per_objfile = cu->per_objfile; - struct objfile *objfile = per_objfile->objfile; dwarf2_per_bfd *per_bfd = per_objfile->per_bfd; const gdb_byte *info_ptr, *end_ptr; auto §ion = dwo_file.sections.info; - section.read (objfile); info_ptr = section.buffer; if (info_ptr == NULL) @@ -6536,27 +6543,18 @@ create_dwo_cus_hash_table (dwarf2_cu *cu, dwo_file &dwo_file) Note: This function processes DWP files only, not DWO files. */ static struct dwp_hash_table * -create_dwp_hash_table (dwarf2_per_objfile *per_objfile, - struct dwp_file *dwp_file, int is_debug_types) +create_dwp_hash_table (dwarf2_per_bfd *per_bfd, struct dwp_file *dwp_file, + dwarf2_section_info &index) { - struct objfile *objfile = per_objfile->objfile; bfd *dbfd = dwp_file->dbfd.get (); - const gdb_byte *index_ptr, *index_end; - struct dwarf2_section_info *index; uint32_t version, nr_columns, nr_units, nr_slots; struct dwp_hash_table *htab; - if (is_debug_types) - index = &dwp_file->sections.tu_index; - else - index = &dwp_file->sections.cu_index; - - if (index->empty ()) + if (index.empty ()) return NULL; - index->read (objfile); - index_ptr = index->buffer; - index_end = index_ptr + index->size; + const gdb_byte *index_ptr = index.buffer; + const gdb_byte *index_end = index_ptr + index.size; /* For Version 5, the version is really 2 bytes of data & 2 bytes of padding. For now it's safe to just read 4 bytes (particularly as it's difficult to @@ -6587,7 +6585,7 @@ create_dwp_hash_table (dwarf2_per_objfile *per_objfile, pulongest (nr_slots), dwp_file->name); } - htab = OBSTACK_ZALLOC (&per_objfile->per_bfd->obstack, struct dwp_hash_table); + htab = OBSTACK_ZALLOC (&per_bfd->obstack, struct dwp_hash_table); htab->version = version; htab->nr_columns = nr_columns; htab->nr_units = nr_units; @@ -7526,9 +7524,9 @@ try_open_dwop_file (dwarf2_per_bfd *per_bfd, const char *file_name, int is_dwp, Upon success, the canonicalized path of the file is stored in the bfd, same as symfile_bfd_open. */ -static gdb_bfd_ref_ptr -open_dwo_file (dwarf2_per_bfd *per_bfd, const char *file_name, - const char *comp_dir) +gdb_bfd_ref_ptr +cutu_reader::open_dwo_file (dwarf2_per_bfd *per_bfd, const char *file_name, + const char *comp_dir) { if (IS_ABSOLUTE_PATH (file_name)) return try_open_dwop_file (per_bfd, file_name, @@ -7563,9 +7561,9 @@ open_dwo_file (dwarf2_per_bfd *per_bfd, const char *file_name, /* This function is mapped across the sections and remembers the offset and size of each of the DWO debugging sections we are interested in. */ -static void -dwarf2_locate_dwo_sections (struct objfile *objfile, bfd *abfd, - asection *sectp, dwo_sections *dwo_sections) +void +cutu_reader::locate_dwo_sections (struct objfile *objfile, bfd *abfd, + asection *sectp, dwo_sections *dwo_sections) { const struct dwop_section_names *names = &dwop_section_names; @@ -7612,11 +7610,12 @@ dwarf2_locate_dwo_sections (struct objfile *objfile, bfd *abfd, by PER_CU. This is for the non-DWP case. The result is NULL if DWO_NAME can't be found. */ -static dwo_file_up -open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name, - const char *comp_dir) +dwo_file_up +cutu_reader::open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir) { dwarf2_per_objfile *per_objfile = cu->per_objfile; + dwarf2_per_bfd *per_bfd = per_objfile->per_bfd; gdb_bfd_ref_ptr dbfd = open_dwo_file (per_objfile->per_bfd, dwo_name, comp_dir); @@ -7633,16 +7632,16 @@ open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name, dwo_file->dbfd = std::move (dbfd); for (asection *sec : gdb_bfd_sections (dwo_file->dbfd)) - dwarf2_locate_dwo_sections (per_objfile->objfile, dwo_file->dbfd.get (), - sec, &dwo_file->sections); + this->locate_dwo_sections (per_objfile->objfile, dwo_file->dbfd.get (), sec, + &dwo_file->sections); create_dwo_cus_hash_table (cu, *dwo_file); if (cu->header.version < 5) - create_dwo_debug_types_hash_table (per_objfile, dwo_file.get (), + create_dwo_debug_types_hash_table (per_bfd, dwo_file.get (), dwo_file->sections.types); else - create_dwo_debug_type_hash_table (per_objfile, dwo_file.get (), + create_dwo_debug_type_hash_table (per_bfd, dwo_file.get (), &dwo_file->sections.info, rcuh_kind::COMPILE); @@ -7810,10 +7809,9 @@ open_dwp_file (dwarf2_per_bfd *per_bfd, const char *file_name) } /* Initialize the use of the DWP file for the current objfile. - By convention the name of the DWP file is ${objfile}.dwp. - The result is NULL if it can't be found. */ + By convention the name of the DWP file is ${objfile}.dwp. */ -static dwp_file_up +static void open_and_init_dwp_file (dwarf2_per_objfile *per_objfile) { struct objfile *objfile = per_objfile->objfile; @@ -7851,7 +7849,7 @@ open_and_init_dwp_file (dwarf2_per_objfile *per_objfile) { dwarf_read_debug_printf ("DWP file not found: %s", dwp_name.c_str ()); - return dwp_file_up (); + return; } const char *name = bfd_get_filename (dbfd.get ()); @@ -7865,9 +7863,10 @@ open_and_init_dwp_file (dwarf2_per_objfile *per_objfile) dwarf2_locate_common_dwp_sections (objfile, dwp_file->dbfd.get (), sec, dwp_file.get ()); - dwp_file->cus = create_dwp_hash_table (per_objfile, dwp_file.get (), 0); - - dwp_file->tus = create_dwp_hash_table (per_objfile, dwp_file.get (), 1); + dwp_file->cus = create_dwp_hash_table (per_bfd, dwp_file.get (), + dwp_file->sections.cu_index); + dwp_file->tus = create_dwp_hash_table (per_bfd, dwp_file.get (), + dwp_file->sections.tu_index); /* The DWP file version is stored in the hash table. Oh well. */ if (dwp_file->cus && dwp_file->tus @@ -7907,20 +7906,8 @@ open_and_init_dwp_file (dwarf2_per_objfile *per_objfile) bfd_cache_close (dwp_file->dbfd.get ()); - return dwp_file; -} - -/* Wrapper around open_and_init_dwp_file, only open it once. */ - -static struct dwp_file * -get_dwp_file (dwarf2_per_objfile *per_objfile) -{ - if (!per_objfile->per_bfd->dwp_checked) - { - per_objfile->per_bfd->dwp_file = open_and_init_dwp_file (per_objfile); - per_objfile->per_bfd->dwp_checked = 1; - } - return per_objfile->per_bfd->dwp_file.get (); + /* Everything worked, install this dwp_file in the per_bfd. */ + per_objfile->per_bfd->dwp_file = std::move (dwp_file); } /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit. @@ -7939,22 +7926,23 @@ get_dwp_file (dwarf2_per_objfile *per_objfile) The result is a pointer to the dwo_unit object or NULL if we didn't find it (dwo_id mismatch or couldn't find the DWO/DWP file). */ -static struct dwo_unit * -lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir, - ULONGEST signature, int is_debug_types) +dwo_unit * +cutu_reader::lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir, ULONGEST signature, + int is_debug_types) { dwarf2_per_objfile *per_objfile = cu->per_objfile; dwarf2_per_bfd *per_bfd = per_objfile->per_bfd; struct objfile *objfile = per_objfile->objfile; const char *kind = is_debug_types ? "TU" : "CU"; - struct dwp_file *dwp_file; /* First see if there's a DWP file. If we have a DWP file but didn't find the DWO inside it, don't look for the original DWO file. It makes gdb behave differently depending on whether one is debugging in the build tree. */ - dwp_file = get_dwp_file (per_objfile); + dwp_file *dwp_file = per_objfile->per_bfd->dwp_file.get (); + if (dwp_file != NULL) { const struct dwp_hash_table *dwp_htab = @@ -8055,9 +8043,9 @@ lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir, /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU. See lookup_dwo_cutu_unit for details. */ -static struct dwo_unit * -lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir, - ULONGEST signature) +dwo_unit * +cutu_reader::lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir, ULONGEST signature) { gdb_assert (!cu->per_cu->is_debug_types); @@ -8067,8 +8055,9 @@ lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir, /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU. See lookup_dwo_cutu_unit for details. */ -static struct dwo_unit * -lookup_dwo_type_unit (dwarf2_cu *cu, const char *dwo_name, const char *comp_dir) +dwo_unit * +cutu_reader::lookup_dwo_type_unit (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir) { gdb_assert (cu->per_cu->is_debug_types); @@ -8111,7 +8100,7 @@ queue_and_load_all_dwo_tus (dwarf2_cu *cu) gdb_assert (cu != nullptr); gdb_assert (!cu->per_cu->is_debug_types); - gdb_assert (get_dwp_file (cu->per_objfile) == nullptr); + gdb_assert (cu->per_objfile->per_bfd->dwp_file == nullptr); dwo_unit = cu->dwo_unit; gdb_assert (dwo_unit != NULL); @@ -9940,7 +9929,7 @@ handle_member_location (struct die_info *die, struct dwarf2_cu *cu, so if we see it, we can assume that a constant form is really a constant and not a section offset. */ if (attr->form_is_constant ()) - *offset = attr->constant_value (0); + *offset = attr->unsigned_constant ().value_or (0); else if (attr->form_is_section_offset ()) dwarf2_complex_location_expr_complaint (); else if (attr->form_is_block () @@ -9958,7 +9947,7 @@ handle_member_location (struct die_info *die, struct dwarf2_cu *cu, attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu); if (attr != nullptr) { - *offset = attr->constant_value (0); + *offset = attr->unsigned_constant ().value_or (0); return 1; } } @@ -9980,7 +9969,7 @@ handle_member_location (struct die_info *die, struct dwarf2_cu *cu, { if (attr->form_is_constant ()) { - LONGEST offset = attr->constant_value (0); + LONGEST offset = attr->unsigned_constant ().value_or (0); /* Work around this GCC 11 bug, where it would erroneously use -1 data member locations, instead of 0: @@ -10029,7 +10018,7 @@ handle_member_location (struct die_info *die, struct dwarf2_cu *cu, { attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu); if (attr != nullptr) - field->set_loc_bitpos (attr->constant_value (0)); + field->set_loc_bitpos (attr->unsigned_constant ().value_or (0)); } } @@ -10098,7 +10087,7 @@ dwarf2_add_field (struct field_info *fip, struct die_info *die, /* Get bit size of field (zero if none). */ attr = dwarf2_attr (die, DW_AT_bit_size, cu); if (attr != nullptr) - fp->set_bitsize (attr->constant_value (0)); + fp->set_bitsize (attr->unsigned_constant ().value_or (0)); else fp->set_bitsize (0); @@ -10107,6 +10096,7 @@ dwarf2_add_field (struct field_info *fip, struct die_info *die, attr = dwarf2_attr (die, DW_AT_bit_offset, cu); if (attr != nullptr && attr->form_is_constant ()) { + ULONGEST bit_offset = attr->unsigned_constant ().value_or (0); if (gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG) { /* For big endian bits, the DW_AT_bit_offset gives the @@ -10114,7 +10104,7 @@ dwarf2_add_field (struct field_info *fip, struct die_info *die, anonymous object to the MSB of the field. We don't have to do anything special since we don't need to know the size of the anonymous object. */ - fp->set_loc_bitpos (fp->loc_bitpos () + attr->constant_value (0)); + fp->set_loc_bitpos (fp->loc_bitpos () + bit_offset); } else { @@ -10125,7 +10115,6 @@ dwarf2_add_field (struct field_info *fip, struct die_info *die, the field itself. The result is the bit offset of the LSB of the field. */ int anonymous_size; - int bit_offset = attr->constant_value (0); attr = dwarf2_attr (die, DW_AT_byte_size, cu); if (attr != nullptr && attr->form_is_constant ()) @@ -10133,7 +10122,7 @@ dwarf2_add_field (struct field_info *fip, struct die_info *die, /* The size of the anonymous object containing the bit field is explicit, so use the indicated size (in bytes). */ - anonymous_size = attr->constant_value (0); + anonymous_size = attr->unsigned_constant ().value_or (0); } else { @@ -10286,13 +10275,19 @@ convert_variant_range (struct obstack *obstack, const variant_field &variant, { std::vector<discriminant_range> ranges; - if (variant.default_branch) + if (variant.is_default ()) return {}; if (variant.discr_list_data == nullptr) { - discriminant_range r - = {variant.discriminant_value, variant.discriminant_value}; + ULONGEST value; + + if (is_unsigned) + value = variant.discriminant_attr->unsigned_constant ().value_or (0); + else + value = variant.discriminant_attr->signed_constant ().value_or (0); + + discriminant_range r = { value, value }; ranges.push_back (r); } else @@ -11106,7 +11101,7 @@ read_structure_type (struct die_info *die, struct dwarf2_cu *cu) if (attr != nullptr) { if (attr->form_is_constant ()) - type->set_length (attr->constant_value (0)); + type->set_length (attr->unsigned_constant ().value_or (0)); else { struct dynamic_prop prop; @@ -11251,12 +11246,14 @@ handle_variant (struct die_info *die, struct type *type, { discr = dwarf2_attr (die, DW_AT_discr_list, cu); if (discr == nullptr || discr->as_block ()->size == 0) - variant.default_branch = true; + { + /* Nothing to do here -- default branch. */ + } else variant.discr_list_data = discr->as_block (); } else - variant.discriminant_value = discr->constant_value (0); + variant.discriminant_attr = discr; for (die_info *variant_child : die->children ()) handle_struct_member_die (variant_child, type, fi, template_args, cu); @@ -11582,25 +11579,30 @@ die_byte_order (die_info *die, dwarf2_cu *cu, enum bfd_endian *byte_order) /* Assuming DIE is an enumeration type, and TYPE is its associated type, update TYPE using some information only available in DIE's - children. In particular, the fields are computed. */ + children. In particular, the fields are computed. If IS_UNSIGNED + is set, the enumeration type's sign is already known (a true value + means unsigned), and so examining the constants to determine the + sign isn't needed; when this is unset, the enumerator constants are + read as signed values. */ static void update_enumeration_type_from_children (struct die_info *die, struct type *type, - struct dwarf2_cu *cu) + struct dwarf2_cu *cu, + std::optional<bool> is_unsigned) { - int unsigned_enum = 1; - int flag_enum = 1; + /* This is used to check whether the enum is signed or unsigned; for + simplicity, it is always correct regardless of whether + IS_UNSIGNED is set. */ + bool unsigned_enum = is_unsigned.value_or (true); + bool flag_enum = true; - auto_obstack obstack; std::vector<struct field> fields; for (die_info *child_die : die->children ()) { struct attribute *attr; LONGEST value; - const gdb_byte *bytes; - struct dwarf2_locexpr_baton *baton; const char *name; if (child_die->tag != DW_TAG_enumerator) @@ -11614,19 +11616,26 @@ update_enumeration_type_from_children (struct die_info *die, if (name == NULL) name = "<anonymous enumerator>"; - dwarf2_const_value_attr (attr, type, name, &obstack, cu, - &value, &bytes, &baton); - if (value < 0) - { - unsigned_enum = 0; - flag_enum = 0; - } + /* Can't check UNSIGNED_ENUM here because that is + optimistic. */ + if (is_unsigned.has_value () && *is_unsigned) + value = attr->unsigned_constant ().value_or (0); else { - if (count_one_bits_ll (value) >= 2) - flag_enum = 0; + /* Read as signed, either because we don't know the sign or + because we know it is definitely signed. */ + value = attr->signed_constant ().value_or (0); + + if (value < 0) + { + unsigned_enum = false; + flag_enum = false; + } } + if (flag_enum && count_one_bits_ll (value) >= 2) + flag_enum = false; + struct field &field = fields.emplace_back (); field.set_name (dwarf2_physname (name, child_die, cu)); field.set_loc_enumval (value); @@ -11635,13 +11644,10 @@ update_enumeration_type_from_children (struct die_info *die, if (!fields.empty ()) type->copy_fields (fields); else - flag_enum = 0; - - if (unsigned_enum) - type->set_is_unsigned (true); + flag_enum = false; - if (flag_enum) - type->set_is_flag_enum (true); + type->set_is_unsigned (unsigned_enum); + type->set_is_flag_enum (flag_enum); } /* Given a DW_AT_enumeration_type die, set its type. We do not @@ -11685,7 +11691,7 @@ read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu) attr = dwarf2_attr (die, DW_AT_byte_size, cu); if (attr != nullptr) - type->set_length (attr->constant_value (0)); + type->set_length (attr->unsigned_constant ().value_or (0)); else type->set_length (0); @@ -11699,6 +11705,11 @@ read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu) if (die_is_declaration (die, cu)) type->set_is_stub (true); + /* If the underlying type is known, and is unsigned, then we'll + assume the enumerator constants are unsigned. Otherwise we have + to assume they are signed. */ + std::optional<bool> is_unsigned; + /* If this type has an underlying type that is not a stub, then we may use its attributes. We always use the "unsigned" attribute in this situation, because ordinarily we guess whether the type @@ -11711,7 +11722,8 @@ read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu) struct type *underlying_type = type->target_type (); underlying_type = check_typedef (underlying_type); - type->set_is_unsigned (underlying_type->is_unsigned ()); + is_unsigned = underlying_type->is_unsigned (); + type->set_is_unsigned (*is_unsigned); if (type->length () == 0) type->set_length (underlying_type->length ()); @@ -11731,7 +11743,7 @@ read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu) Note that, as usual, this must come after set_die_type to avoid infinite recursion when trying to compute the names of the enumerators. */ - update_enumeration_type_from_children (die, type, cu); + update_enumeration_type_from_children (die, type, cu, is_unsigned); return type; } @@ -12081,7 +12093,7 @@ read_array_type (struct die_info *die, struct dwarf2_cu *cu) attr = dwarf2_attr (die, DW_AT_bit_stride, cu); if (attr != NULL) - bit_stride = attr->constant_value (0); + bit_stride = attr->unsigned_constant ().value_or (0); /* Irix 6.2 native cc creates array types without children for arrays with unspecified length. */ @@ -12305,7 +12317,7 @@ mark_common_block_symbol_computed (struct symbol *sym, if (member_loc->form_is_constant ()) { - offset = member_loc->constant_value (0); + offset = member_loc->unsigned_constant ().value_or (0); baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size; } else @@ -12620,7 +12632,8 @@ read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu) attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu); if (attr_byte_size) - byte_size = attr_byte_size->constant_value (cu_header->addr_size); + byte_size = (attr_byte_size->unsigned_constant () + .value_or (cu_header->addr_size)); else byte_size = cu_header->addr_size; @@ -12732,7 +12745,8 @@ read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu, type = lookup_reference_type (target_type, refcode); attr = dwarf2_attr (die, DW_AT_byte_size, cu); if (attr != nullptr) - type->set_length (attr->constant_value (cu_header->addr_size)); + type->set_length (attr->unsigned_constant () + .value_or (cu_header->addr_size)); else type->set_length (cu_header->addr_size); @@ -12896,9 +12910,7 @@ read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu) len = dwarf2_attr (die, DW_AT_byte_size, cu); if (len != nullptr && len->form_is_constant ()) { - /* Pass 0 as the default as we know this attribute is constant - and the default value will not be returned. */ - LONGEST sz = len->constant_value (0); + LONGEST sz = len->unsigned_constant ().value_or (0); prop_type = objfile_int_type (objfile, sz, true); } else @@ -12917,15 +12929,14 @@ read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu) else if (attr != nullptr) { /* This DW_AT_string_length just contains the length with no - indirection. There's no need to create a dynamic property in this - case. Pass 0 for the default value as we know it will not be - returned in this case. */ - length = attr->constant_value (0); + indirection. There's no need to create a dynamic property in + this case. */ + length = attr->unsigned_constant ().value_or (0); } else if ((attr = dwarf2_attr (die, DW_AT_byte_size, cu)) != nullptr) { /* We don't currently support non-constant byte sizes for strings. */ - length = attr->constant_value (1); + length = attr->unsigned_constant ().value_or (1); } else { @@ -13234,10 +13245,10 @@ get_mpz (struct dwarf2_cu *cu, gdb_mpz *value, struct attribute *attr) ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE, true); } - else if (attr->form_is_unsigned ()) + else if (attr->form_is_strictly_unsigned ()) *value = gdb_mpz (attr->as_unsigned ()); else - *value = gdb_mpz (attr->constant_value (1)); + *value = gdb_mpz (attr->signed_constant ().value_or (1)); } /* Assuming DIE is a rational DW_TAG_constant, read the DIE's @@ -13416,14 +13427,14 @@ finish_fixed_point_type (struct type *type, const char *suffix, } else if (attr->name == DW_AT_binary_scale) { - LONGEST scale_exp = attr->constant_value (0); + LONGEST scale_exp = attr->signed_constant ().value_or (0); gdb_mpz &num_or_denom = scale_exp > 0 ? scale_num : scale_denom; num_or_denom <<= std::abs (scale_exp); } else if (attr->name == DW_AT_decimal_scale) { - LONGEST scale_exp = attr->constant_value (0); + LONGEST scale_exp = attr->signed_constant ().value_or (0); gdb_mpz &num_or_denom = scale_exp > 0 ? scale_num : scale_denom; num_or_denom = gdb_mpz::pow (10, std::abs (scale_exp)); @@ -13635,7 +13646,7 @@ read_base_type (struct die_info *die, struct dwarf2_cu *cu) } attr = dwarf2_attr (die, DW_AT_byte_size, cu); if (attr != nullptr) - bits = attr->constant_value (0) * TARGET_CHAR_BIT; + bits = attr->unsigned_constant ().value_or (0) * TARGET_CHAR_BIT; name = dwarf2_full_name (nullptr, die, cu); if (!name) complaint (_("DW_AT_name missing from DW_TAG_base_type")); @@ -13786,22 +13797,28 @@ read_base_type (struct die_info *die, struct dwarf2_cu *cu) attr = dwarf2_attr (die, DW_AT_bit_size, cu); if (attr != nullptr && attr->form_is_constant ()) { - unsigned real_bit_size = attr->constant_value (0); + unsigned real_bit_size = attr->unsigned_constant ().value_or (0); if (real_bit_size >= 0 && real_bit_size <= 8 * type->length ()) { attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu); /* Only use the attributes if they make sense together. */ - if (attr == nullptr - || (attr->form_is_constant () - && attr->constant_value (0) >= 0 - && (attr->constant_value (0) + real_bit_size - <= 8 * type->length ()))) + std::optional<ULONGEST> bit_offset; + if (attr == nullptr) + bit_offset = 0; + else if (attr->form_is_constant ()) + { + bit_offset = attr->unsigned_constant (); + if (bit_offset.has_value () + && *bit_offset + real_bit_size > 8 * type->length ()) + bit_offset.reset (); + } + if (bit_offset.has_value ()) { TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_size = real_bit_size; if (attr != nullptr) TYPE_MAIN_TYPE (type)->type_specific.int_stuff.bit_offset - = attr->constant_value (0); + = *bit_offset; } } } @@ -14114,8 +14131,13 @@ read_subrange_type (struct die_info *die, struct dwarf2_cu *cu) LONGEST bias = 0; struct attribute *bias_attr = dwarf2_attr (die, DW_AT_GNU_bias, cu); - if (bias_attr != nullptr && bias_attr->form_is_constant ()) - bias = bias_attr->constant_value (0); + if (bias_attr != nullptr) + { + if (base_type->is_unsigned ()) + bias = (LONGEST) bias_attr->unsigned_constant ().value_or (0); + else + bias = bias_attr->signed_constant ().value_or (0); + } /* Normally, the DWARF producers are expected to use a signed constant form (Eg. DW_FORM_sdata) to express negative bounds. @@ -14202,7 +14224,7 @@ read_subrange_type (struct die_info *die, struct dwarf2_cu *cu) attr = dwarf2_attr (die, DW_AT_byte_size, cu); if (attr != nullptr) - range_type->set_length (attr->constant_value (0)); + range_type->set_length (attr->unsigned_constant ().value_or (0)); maybe_set_alignment (cu, die, range_type); @@ -14934,10 +14956,12 @@ cutu_reader::read_attribute_value (attribute *attr, unsigned form, info_ptr += 2; break; case DW_FORM_data4: + case DW_FORM_ref_sup4: attr->set_unsigned (read_4_bytes (m_abfd, info_ptr)); info_ptr += 4; break; case DW_FORM_data8: + case DW_FORM_ref_sup8: attr->set_unsigned (read_8_bytes (m_abfd, info_ptr)); info_ptr += 8; break; @@ -14989,6 +15013,7 @@ cutu_reader::read_attribute_value (attribute *attr, unsigned form, } [[fallthrough]]; case DW_FORM_GNU_strp_alt: + case DW_FORM_strp_sup: { dwz_file *dwz = per_objfile->per_bfd->get_dwz_file (true); LONGEST str_offset @@ -17186,13 +17211,10 @@ new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu, list was that this is unspecified. We choose to always zero-extend because that is the interpretation long in use by GCC. */ -static gdb_byte * -dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack, - struct dwarf2_cu *cu, LONGEST *value, int bits) +static void +dwarf2_const_value_data (const struct attribute *attr, LONGEST *value, + int bits) { - struct objfile *objfile = cu->per_objfile->objfile; - enum bfd_endian byte_order = bfd_big_endian (objfile->obfd.get ()) ? - BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE; LONGEST l = attr->constant_value (0); if (bits < sizeof (*value) * 8) @@ -17200,16 +17222,8 @@ dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack, l &= ((LONGEST) 1 << bits) - 1; *value = l; } - else if (bits == sizeof (*value) * 8) - *value = l; else - { - gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8); - store_unsigned_integer (bytes, bits / 8, byte_order, l); - return bytes; - } - - return NULL; + *value = l; } /* Read a constant value from an attribute. Either set *VALUE, or if @@ -17271,6 +17285,7 @@ dwarf2_const_value_attr (const struct attribute *attr, struct type *type, case DW_FORM_strx: case DW_FORM_GNU_str_index: case DW_FORM_GNU_strp_alt: + case DW_FORM_strp_sup: /* The string is already allocated on the objfile obstack, point directly to it. */ *bytes = (const gdb_byte *) attr->as_string (); @@ -17294,16 +17309,16 @@ dwarf2_const_value_attr (const struct attribute *attr, struct type *type, converted to host endianness, so we just need to sign- or zero-extend it as appropriate. */ case DW_FORM_data1: - *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8); + dwarf2_const_value_data (attr, value, 8); break; case DW_FORM_data2: - *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16); + dwarf2_const_value_data (attr, value, 16); break; case DW_FORM_data4: - *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32); + dwarf2_const_value_data (attr, value, 32); break; case DW_FORM_data8: - *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64); + dwarf2_const_value_data (attr, value, 64); break; case DW_FORM_sdata: @@ -17477,7 +17492,7 @@ lookup_die_type (struct die_info *die, const struct attribute *attr, /* First see if we have it cached. */ - if (attr->form == DW_FORM_GNU_ref_alt) + if (attr->form_is_alt ()) { sect_offset sect_off = attr->get_ref_die_offset (); dwarf2_per_cu *per_cu @@ -18261,15 +18276,14 @@ follow_die_ref (struct die_info *src_die, const struct attribute *attr, struct dwarf2_cu *cu = *ref_cu; struct die_info *die; - if (attr->form != DW_FORM_GNU_ref_alt && src_die->sect_off == sect_off) + if (!attr->form_is_alt () && src_die->sect_off == sect_off) { /* Self-reference, we're done. */ return src_die; } die = follow_die_offset (sect_off, - (attr->form == DW_FORM_GNU_ref_alt - || cu->per_cu->is_dwz), + attr->form_is_alt () || cu->per_cu->is_dwz, ref_cu); if (!die) error (_(DWARF_ERROR_PREFIX @@ -18480,6 +18494,7 @@ dwarf2_fetch_constant_bytes (sect_offset sect_off, case DW_FORM_strx: case DW_FORM_GNU_str_index: case DW_FORM_GNU_strp_alt: + case DW_FORM_strp_sup: /* The string is already allocated on the objfile obstack, point directly to it. */ { @@ -18508,31 +18523,23 @@ dwarf2_fetch_constant_bytes (sect_offset sect_off, zero-extend it as appropriate. */ case DW_FORM_data1: type = die_type (die, cu); - result = dwarf2_const_value_data (attr, obstack, cu, &value, 8); - if (result == NULL) - result = write_constant_as_bytes (obstack, byte_order, - type, value, len); + dwarf2_const_value_data (attr, &value, 8); + result = write_constant_as_bytes (obstack, byte_order, type, value, len); break; case DW_FORM_data2: type = die_type (die, cu); - result = dwarf2_const_value_data (attr, obstack, cu, &value, 16); - if (result == NULL) - result = write_constant_as_bytes (obstack, byte_order, - type, value, len); + dwarf2_const_value_data (attr, &value, 16); + result = write_constant_as_bytes (obstack, byte_order, type, value, len); break; case DW_FORM_data4: type = die_type (die, cu); - result = dwarf2_const_value_data (attr, obstack, cu, &value, 32); - if (result == NULL) - result = write_constant_as_bytes (obstack, byte_order, - type, value, len); + dwarf2_const_value_data (attr, &value, 32); + result = write_constant_as_bytes (obstack, byte_order, type, value, len); break; case DW_FORM_data8: type = die_type (die, cu); - result = dwarf2_const_value_data (attr, obstack, cu, &value, 64); - if (result == NULL) - result = write_constant_as_bytes (obstack, byte_order, - type, value, len); + dwarf2_const_value_data (attr, &value, 64); + result = write_constant_as_bytes (obstack, byte_order, type, value, len); break; case DW_FORM_sdata: @@ -19189,7 +19196,7 @@ dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym, /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside the section. If so, fall through to the complaint in the other branch. */ - && attr->as_unsigned () < section->get_size (objfile)) + && attr->as_unsigned () < section->size) { struct dwarf2_loclist_baton *baton; diff --git a/gdb/dwarf2/read.h b/gdb/dwarf2/read.h index 3177b19..f3e043c 100644 --- a/gdb/dwarf2/read.h +++ b/gdb/dwarf2/read.h @@ -533,9 +533,9 @@ struct dwarf2_per_bfd } /* Return the separate '.dwz' debug file. If there is no - .gnu_debugaltlink section in the file, then the result depends on - REQUIRE: if REQUIRE is true, error out; if REQUIRE is false, - return nullptr. */ + .gnu_debugaltlink or .debug_sup section in the file, then the + result depends on REQUIRE: if REQUIRE is true, error out; if + REQUIRE is false, return nullptr. */ struct dwz_file *get_dwz_file (bool require = false) { gdb_assert (!require || this->dwz_file.has_value ()); @@ -546,7 +546,7 @@ struct dwarf2_per_bfd { result = this->dwz_file->get (); if (require && result == nullptr) - error (_("could not read '.gnu_debugaltlink' section")); + error (_("could not find supplementary DWARF file")); } return result; @@ -634,9 +634,6 @@ public: /* Set of dwo_file objects. */ dwo_file_up_set dwo_files; - /* True if we've checked for whether there is a DWP file. */ - bool dwp_checked = false; - /* The DWP file if there is one, or NULL. */ dwp_file_up dwp_file; @@ -1028,6 +1025,39 @@ private: const char *read_dwo_str_index (ULONGEST str_index); + gdb_bfd_ref_ptr open_dwo_file (dwarf2_per_bfd *per_bfd, const char *file_name, + const char *comp_dir); + + dwo_file_up open_and_init_dwo_file (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir); + + void locate_dwo_sections (struct objfile *objfile, bfd *abfd, asection *sectp, + struct dwo_sections *dwo_sections); + + void create_dwo_cus_hash_table (dwarf2_cu *cu, dwo_file &dwo_file); + + void create_dwo_debug_types_hash_table + (dwarf2_per_bfd *per_bfd, dwo_file *dwo_file, + gdb::array_view<dwarf2_section_info> type_sections); + + void create_dwo_debug_type_hash_table (dwarf2_per_bfd *per_bfd, + dwo_file *dwo_file, + dwarf2_section_info *section, + rcuh_kind section_kind); + + dwo_unit *lookup_dwo_cutu (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir, ULONGEST signature, + int is_debug_types); + + dwo_unit *lookup_dwo_comp_unit (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir, ULONGEST signature); + + dwo_unit *lookup_dwo_type_unit (dwarf2_cu *cu, const char *dwo_name, + const char *comp_dir); + + dwo_unit *lookup_dwo_unit (dwarf2_cu *cu, die_info *comp_unit_die, + const char *dwo_name); + /* The bfd of die_section. */ bfd *m_abfd; diff --git a/gdb/dwarf2/section.h b/gdb/dwarf2/section.h index 85da485..b9d3c31 100644 --- a/gdb/dwarf2/section.h +++ b/gdb/dwarf2/section.h @@ -81,19 +81,6 @@ struct dwarf2_section_info If the section is compressed, uncompress it before returning. */ void read (struct objfile *objfile); - /* A helper function that returns the size of a section in a safe way. - If you are positive that the section has been read before using the - size, then it is safe to refer to the dwarf2_section_info object's - "size" field directly. In other cases, you must call this - function, because for compressed sections the size field is not set - correctly until the section has been read. */ - bfd_size_type get_size (struct objfile *objfile) - { - if (!readin) - read (objfile); - return size; - } - /* Issue a complaint that something was outside the bounds of this buffer. */ void overflow_complaint () const; @@ -994,9 +994,10 @@ add_struct_fields (struct type *type, completion_list &output, output.emplace_back (concat (prefix, type->field (i).name (), nullptr)); } - else if (type->field (i).type ()->code () == TYPE_CODE_UNION) + else if (type->field (i).type ()->code () == TYPE_CODE_UNION + || type->field (i).type ()->code () == TYPE_CODE_STRUCT) { - /* Recurse into anonymous unions. */ + /* Recurse into anonymous unions and structures. */ add_struct_fields (type->field (i).type (), output, fieldname, namelen, prefix); } diff --git a/gdb/findvar.c b/gdb/findvar.c index 2938931..9da5c48 100644 --- a/gdb/findvar.c +++ b/gdb/findvar.c @@ -485,7 +485,8 @@ language_defn::read_var_value (struct symbol *var, /* Determine address of TLS variable. */ if (obj_section && (obj_section->the_bfd_section->flags & SEC_THREAD_LOCAL) != 0) - addr = target_translate_tls_address (obj_section->objfile, addr); + addr = target_translate_tls_address (obj_section->objfile, addr, + var->print_name ()); } break; diff --git a/gdb/infrun.c b/gdb/infrun.c index 3d5ede8..0b87287 100644 --- a/gdb/infrun.c +++ b/gdb/infrun.c @@ -3972,7 +3972,8 @@ delete_just_stopped_threads_single_step_breakpoints (void) void print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid, - const struct target_waitstatus &ws) + const struct target_waitstatus &ws, + process_stratum_target *proc_target) { infrun_debug_printf ("target_wait (%s [%s], status) =", waiton_ptid.to_string ().c_str (), @@ -3981,6 +3982,20 @@ print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid, result_ptid.to_string ().c_str (), target_pid_to_str (result_ptid).c_str ()); infrun_debug_printf (" %s", ws.to_string ().c_str ()); + + if (proc_target != nullptr) + infrun_debug_printf (" from target %d (%s)", + proc_target->connection_number, + proc_target->shortname ()); +} + +/* Wrapper for print_target_wait_results above for convenience. */ + +static void +print_target_wait_results (ptid_t waiton_ptid, + const execution_control_state &ecs) +{ + print_target_wait_results (waiton_ptid, ecs.ptid, ecs.ws, ecs.target); } /* Select a thread at random, out of those which are resumed and have @@ -4332,7 +4347,8 @@ prepare_for_detach (void) event.ptid = do_target_wait_1 (inf, pid_ptid, &event.ws, 0); if (debug_infrun) - print_target_wait_results (pid_ptid, event.ptid, event.ws); + print_target_wait_results (pid_ptid, event.ptid, event.ws, + event.target); handle_one (event); } @@ -4388,7 +4404,7 @@ wait_for_inferior (inferior *inf) ecs.target = inf->process_target (); if (debug_infrun) - print_target_wait_results (minus_one_ptid, ecs.ptid, ecs.ws); + print_target_wait_results (minus_one_ptid, ecs); /* Now figure out what to do with the result of the result. */ handle_inferior_event (&ecs); @@ -4669,7 +4685,7 @@ fetch_inferior_event () switch_to_target_no_thread (ecs.target); if (debug_infrun) - print_target_wait_results (minus_one_ptid, ecs.ptid, ecs.ws); + print_target_wait_results (minus_one_ptid, ecs); /* If an error happens while handling the event, propagate GDB's knowledge of the executing state to the frontend/user running @@ -5232,7 +5248,8 @@ poll_one_curr_target (struct target_waitstatus *ws) event_ptid = target_wait (minus_one_ptid, ws, TARGET_WNOHANG); if (debug_infrun) - print_target_wait_results (minus_one_ptid, event_ptid, *ws); + print_target_wait_results (minus_one_ptid, event_ptid, *ws, + current_inferior ()->process_target ()); return event_ptid; } diff --git a/gdb/infrun.h b/gdb/infrun.h index 2067fd5..b9b64ac 100644 --- a/gdb/infrun.h +++ b/gdb/infrun.h @@ -256,7 +256,8 @@ extern void print_stop_event (struct ui_out *uiout, bool displays = true); /* Pretty print the results of target_wait, for debugging purposes. */ extern void print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid, - const struct target_waitstatus &ws); + const struct target_waitstatus &ws, + process_stratum_target *proc_target); extern int signal_stop_state (int); diff --git a/gdb/linux-tdep.c b/gdb/linux-tdep.c index 141c119..bbffb3d 100644 --- a/gdb/linux-tdep.c +++ b/gdb/linux-tdep.c @@ -3137,6 +3137,7 @@ VM_DONTDUMP flag (\"dd\" in /proc/PID/smaps) when generating the corefile. For\ more information about this file, refer to the manpage of proc(5) and core(5)."), NULL, show_dump_excluded_mappings, &setlist, &showlist); + } /* Fetch (and possibly build) an appropriate `link_map_offsets' for diff --git a/gdb/microblaze-linux-tdep.c b/gdb/microblaze-linux-tdep.c index 0f2f272..8dcbeaa 100644 --- a/gdb/microblaze-linux-tdep.c +++ b/gdb/microblaze-linux-tdep.c @@ -49,6 +49,9 @@ microblaze_linux_memory_remove_breakpoint (struct gdbarch *gdbarch, /* Determine appropriate breakpoint contents and size for this address. */ bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &bplen); + /* Make sure we see the memory breakpoints. */ + scoped_restore restore_memory + = make_scoped_restore_show_memory_breakpoints (1); val = target_read_memory (addr, old_contents, bplen); /* If our breakpoint is no longer at the address, this means that the diff --git a/gdb/minsyms.c b/gdb/minsyms.c index 649a9f1..9ac3145 100644 --- a/gdb/minsyms.c +++ b/gdb/minsyms.c @@ -1688,7 +1688,8 @@ find_minsym_type_and_address (minimal_symbol *msymbol, { /* Skip translation if caller does not need the address. */ if (address_p != NULL) - *address_p = target_translate_tls_address (objfile, addr); + *address_p = target_translate_tls_address + (objfile, addr, bound_msym.minsym->print_name ()); return builtin_type (objfile)->nodebug_tls_symbol; } diff --git a/gdb/pager.h b/gdb/pager.h index 3c4fcdf..052337d 100644 --- a/gdb/pager.h +++ b/gdb/pager.h @@ -50,7 +50,6 @@ public: } void emit_style_escape (const ui_file_style &style) override; - void reset_style () override; void flush () override; diff --git a/gdb/ppc-linux-tdep.c b/gdb/ppc-linux-tdep.c index 3050a9e..441f317 100644 --- a/gdb/ppc-linux-tdep.c +++ b/gdb/ppc-linux-tdep.c @@ -49,6 +49,7 @@ #include "arch-utils.h" #include "xml-syscall.h" #include "linux-tdep.h" +#include "svr4-tls-tdep.h" #include "linux-record.h" #include "record-full.h" #include "infrun.h" @@ -2071,6 +2072,63 @@ ppc64_linux_gcc_target_options (struct gdbarch *gdbarch) return ""; } +/* Fetch and return the TLS DTV (dynamic thread vector) address for PTID. + Throw a suitable TLS error if something goes wrong. */ + +static CORE_ADDR +ppc64_linux_get_tls_dtv_addr (struct gdbarch *gdbarch, ptid_t ptid, + enum svr4_tls_libc libc) +{ + /* On ppc64, the thread pointer is found in r13. Fetch this + register. */ + regcache *regcache + = get_thread_arch_regcache (current_inferior (), ptid, gdbarch); + int thread_pointer_regnum = PPC_R0_REGNUM + 13; + target_fetch_registers (regcache, thread_pointer_regnum); + ULONGEST thr_ptr; + if (regcache->cooked_read (thread_pointer_regnum, &thr_ptr) != REG_VALID) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch thread pointer")); + + /* The thread pointer (r13) is an address that is 0x7000 ahead of + the *end* of the TCB (thread control block). The field + holding the DTV address is at the very end of the TCB. + Therefore, the DTV pointer address can be found by + subtracting (0x7000+8) from the thread pointer. Compute the + address of the DTV pointer, fetch it, and convert it to an + address. */ + CORE_ADDR dtv_ptr_addr = thr_ptr - 0x7000 - 8; + gdb::byte_vector buf (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + if (target_read_memory (dtv_ptr_addr, buf.data (), buf.size ()) != 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch DTV address")); + + const struct builtin_type *builtin = builtin_type (gdbarch); + CORE_ADDR dtv_addr = gdbarch_pointer_to_address + (gdbarch, builtin->builtin_data_ptr, buf.data ()); + return dtv_addr; +} + +/* For internal TLS lookup, return the DTP offset, which is the offset + to subtract from a DTV entry, in order to obtain the address of the + TLS block. */ + +static ULONGEST +ppc_linux_get_tls_dtp_offset (struct gdbarch *gdbarch, ptid_t ptid, + svr4_tls_libc libc) +{ + if (libc == svr4_tls_libc_musl) + { + /* This value is DTP_OFFSET, which represents the value to + subtract from the DTV entry. For PPC, it can be found in + MUSL's arch/powerpc64/pthread_arch.h and + arch/powerpc32/pthread_arch.h. (Both values are the same.) + It represents the value to subtract from the DTV entry, once + it has been fetched from the DTV array. */ + return 0x8000; + } + else + return 0; +} + static displaced_step_prepare_status ppc_linux_displaced_step_prepare (gdbarch *arch, thread_info *thread, CORE_ADDR &displaced_pc) @@ -2284,6 +2342,11 @@ ppc_linux_init_abi (struct gdbarch_info info, set_gdbarch_gnu_triplet_regexp (gdbarch, ppc64_gnu_triplet_regexp); /* Set GCC target options. */ set_gdbarch_gcc_target_options (gdbarch, ppc64_linux_gcc_target_options); + /* Internal thread local address support. */ + set_gdbarch_get_thread_local_address (gdbarch, + svr4_tls_get_thread_local_address); + svr4_tls_register_tls_methods (info, gdbarch, ppc64_linux_get_tls_dtv_addr, + ppc_linux_get_tls_dtp_offset); } set_gdbarch_core_read_description (gdbarch, ppc_linux_core_read_description); diff --git a/gdb/printcmd.c b/gdb/printcmd.c index e8be470..2be5eaa 100644 --- a/gdb/printcmd.c +++ b/gdb/printcmd.c @@ -2883,7 +2883,7 @@ static void printf_command (const char *arg, int from_tty) { ui_printf (arg, gdb_stdout); - gdb_stdout->reset_style (); + gdb_stdout->emit_style_escape (ui_file_style ()); gdb_stdout->wrap_here (0); gdb_stdout->flush (); } diff --git a/gdb/python/py-breakpoint.c b/gdb/python/py-breakpoint.c index 861e9a3..58998f5 100644 --- a/gdb/python/py-breakpoint.c +++ b/gdb/python/py-breakpoint.c @@ -948,7 +948,7 @@ bppy_init (PyObject *self, PyObject *args, PyObject *kwargs) else { PyErr_SetString (PyExc_RuntimeError, - _("Line keyword should be an integer or a string. ")); + _("Line keyword should be an integer or a string.")); return -1; } } diff --git a/gdb/python/py-color.c b/gdb/python/py-color.c index 91ad7ae..e208506 100644 --- a/gdb/python/py-color.c +++ b/gdb/python/py-color.c @@ -64,7 +64,8 @@ create_color_object (const ui_file_style::color &color) bool gdbpy_is_color (PyObject *obj) { - return PyObject_IsInstance (obj, (PyObject *) &colorpy_object_type); + gdb_assert (obj != nullptr); + return PyObject_TypeCheck (obj, &colorpy_object_type) != 0; } /* See py-color.h. */ @@ -80,33 +81,33 @@ gdbpy_get_color (PyObject *obj) static PyObject * get_attr (PyObject *obj, PyObject *attr_name) { - if (! PyUnicode_Check (attr_name)) + if (!PyUnicode_Check (attr_name)) return PyObject_GenericGetAttr (obj, attr_name); colorpy_object *self = (colorpy_object *) obj; const ui_file_style::color &color = self->color; - if (! PyUnicode_CompareWithASCIIString (attr_name, "colorspace")) + if (!PyUnicode_CompareWithASCIIString (attr_name, "colorspace")) { int value = static_cast<int> (color.colorspace ()); return gdb_py_object_from_longest (value).release (); } - if (! PyUnicode_CompareWithASCIIString (attr_name, "is_none")) + if (!PyUnicode_CompareWithASCIIString (attr_name, "is_none")) return PyBool_FromLong (color.is_none ()); - if (! PyUnicode_CompareWithASCIIString (attr_name, "is_indexed")) + if (!PyUnicode_CompareWithASCIIString (attr_name, "is_indexed")) return PyBool_FromLong (color.is_indexed ()); - if (! PyUnicode_CompareWithASCIIString (attr_name, "is_direct")) + if (!PyUnicode_CompareWithASCIIString (attr_name, "is_direct")) return PyBool_FromLong (color.is_direct ()); if (color.is_indexed () - && ! PyUnicode_CompareWithASCIIString (attr_name, "index")) + && !PyUnicode_CompareWithASCIIString (attr_name, "index")) return gdb_py_object_from_longest (color.get_value ()).release (); if (color.is_direct () - && ! PyUnicode_CompareWithASCIIString (attr_name, "components")) + && !PyUnicode_CompareWithASCIIString (attr_name, "components")) { uint8_t rgb[3]; color.get_rgb (rgb); @@ -135,21 +136,21 @@ get_attr (PyObject *obj, PyObject *attr_name) /* Implementation of Color.escape_sequence (self, is_fg) -> str. */ static PyObject * -colorpy_escape_sequence (PyObject *self, PyObject *is_fg_obj) +colorpy_escape_sequence (PyObject *self, PyObject *args, PyObject *kwargs) { - if (!gdbpy_is_color (self)) - { - PyErr_SetString (PyExc_RuntimeError, - _("Object is not gdb.Color.")); - return nullptr; - } + static const char *keywords[] = { "is_foreground", nullptr }; + PyObject *is_fg_obj; - if (! PyBool_Check (is_fg_obj)) - { - PyErr_SetString (PyExc_RuntimeError, - _("A boolean argument is required.")); - return nullptr; - } + /* Parse method arguments. */ + if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "O!", keywords, + &PyBool_Type, &is_fg_obj)) + return nullptr; + + /* Python ensures the type of SELF. */ + gdb_assert (gdbpy_is_color (self)); + + /* The argument parsing ensures we have a bool. */ + gdb_assert (PyBool_Check (is_fg_obj)); bool is_fg = is_fg_obj == Py_True; std::string s = gdbpy_get_color (self).to_ansi (is_fg); @@ -175,17 +176,20 @@ colorpy_init (PyObject *self, PyObject *args, PyObject *kwds) PyObject *colorspace_obj = nullptr; color_space colorspace = color_space::MONOCHROME; - if (! PyArg_ParseTuple (args, "|OO", &value_obj, &colorspace_obj)) + static const char *keywords[] = { "value", "color_space", nullptr }; + + if (!gdb_PyArg_ParseTupleAndKeywords (args, kwds, "|OO", keywords, + &value_obj, &colorspace_obj)) return -1; try { - if (colorspace_obj) + if (colorspace_obj != nullptr) { if (PyLong_Check (colorspace_obj)) { long colorspace_id = -1; - if (! gdb_py_int_as_long (colorspace_obj, &colorspace_id)) + if (!gdb_py_int_as_long (colorspace_obj, &colorspace_id)) return -1; if (!color_space_safe_cast (&colorspace, colorspace_id)) error (_("colorspace %ld is out of range."), colorspace_id); @@ -201,11 +205,11 @@ colorpy_init (PyObject *self, PyObject *args, PyObject *kwds) else if (PyLong_Check (value_obj)) { long value = -1; - if (! gdb_py_int_as_long (value_obj, &value)) + if (!gdb_py_int_as_long (value_obj, &value)) return -1; if (value < 0 || value > INT_MAX) error (_("value %ld is out of range."), value); - if (colorspace_obj) + if (colorspace_obj != nullptr) obj->color = ui_file_style::color (colorspace, value); else obj->color = ui_file_style::color (value); @@ -256,7 +260,6 @@ colorpy_init (PyObject *self, PyObject *args, PyObject *kwds) return gdbpy_handle_gdb_exception (-1, except); } - Py_INCREF (self); return 0; } @@ -272,10 +275,10 @@ colorpy_str (PyObject *self) static int gdbpy_initialize_color (void) { - for (auto & pair : colorspace_constants) - if (PyModule_AddIntConstant (gdb_module, pair.name, - static_cast<long> (pair.value)) < 0) - return -1; + for (auto &pair : colorspace_constants) + if (PyModule_AddIntConstant (gdb_module, pair.name, + static_cast<long> (pair.value)) < 0) + return -1; colorpy_object_type.tp_new = PyType_GenericNew; return gdbpy_type_ready (&colorpy_object_type, gdb_module); @@ -285,7 +288,8 @@ gdbpy_initialize_color (void) static PyMethodDef color_methods[] = { - { "escape_sequence", colorpy_escape_sequence, METH_O, + { "escape_sequence", (PyCFunction) colorpy_escape_sequence, + METH_VARARGS | METH_KEYWORDS, "escape_sequence (is_foreground) -> str.\n\ Return the ANSI escape sequence for this color.\n\ IS_FOREGROUND indicates whether this is a foreground or background color."}, @@ -313,7 +317,7 @@ PyTypeObject colorpy_object_type = get_attr, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ "GDB color object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ diff --git a/gdb/python/py-disasm.c b/gdb/python/py-disasm.c index 9ca8d22..17064dc 100644 --- a/gdb/python/py-disasm.c +++ b/gdb/python/py-disasm.c @@ -1311,12 +1311,13 @@ gdbpy_print_insn (struct gdbarch *gdbarch, CORE_ADDR memaddr, return {}; } - /* Check the result is a DisassemblerResult (or a sub-class). */ - if (!PyObject_IsInstance (result.get (), - (PyObject *) &disasm_result_object_type)) + /* Check the result is a DisassemblerResult. */ + if (!PyObject_TypeCheck (result.get (), &disasm_result_object_type)) { - PyErr_SetString (PyExc_TypeError, - _("Result is not a DisassemblerResult.")); + PyErr_Format + (PyExc_TypeError, + _("Result from Disassembler must be gdb.DisassemblerResult, not %s."), + Py_TYPE (result.get ())->tp_name); gdbpy_print_stack (); return std::optional<int> (-1); } diff --git a/gdb/python/py-registers.c b/gdb/python/py-registers.c index 78a806c..9be2e3c 100644 --- a/gdb/python/py-registers.c +++ b/gdb/python/py-registers.c @@ -403,8 +403,7 @@ gdbpy_parse_register_id (struct gdbarch *gdbarch, PyObject *pyo_reg_id, PyErr_SetString (PyExc_ValueError, "Bad register"); } /* The register could be a gdb.RegisterDescriptor object. */ - else if (PyObject_IsInstance (pyo_reg_id, - (PyObject *) ®ister_descriptor_object_type)) + else if (PyObject_TypeCheck (pyo_reg_id, ®ister_descriptor_object_type)) { register_descriptor_object *reg = (register_descriptor_object *) pyo_reg_id; diff --git a/gdb/python/py-unwind.c b/gdb/python/py-unwind.c index ab34971..d43d7e9 100644 --- a/gdb/python/py-unwind.c +++ b/gdb/python/py-unwind.c @@ -929,9 +929,9 @@ frame_unwind_python::sniff (const frame_info_ptr &this_frame, /* Received UnwindInfo, cache data. */ PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0); - if (PyObject_IsInstance (pyo_unwind_info, - (PyObject *) &unwind_info_object_type) <= 0) - error (_("A Unwinder should return gdb.UnwindInfo instance.")); + if (!PyObject_TypeCheck (pyo_unwind_info, &unwind_info_object_type)) + error (_("an Unwinder should return gdb.UnwindInfo, not %s."), + Py_TYPE (pyo_unwind_info)->tp_name); { unwind_info_object *unwind_info = diff --git a/gdb/python/py-value.c b/gdb/python/py-value.c index 3855bde..8a2e263 100644 --- a/gdb/python/py-value.c +++ b/gdb/python/py-value.c @@ -1096,8 +1096,7 @@ valpy_getitem (PyObject *self, PyObject *key) res_val = value_struct_elt (&tmp, {}, field.get (), NULL, "struct/class/union"); else if (bitpos >= 0) - res_val = value_struct_elt_bitpos (&tmp, bitpos, field_type, - "struct/class/union"); + res_val = value_struct_elt_bitpos (tmp, bitpos, field_type); else if (base_class_type != NULL) { struct type *val_type; diff --git a/gdb/remote.c b/gdb/remote.c index 7dc057c..73dc426 100644 --- a/gdb/remote.c +++ b/gdb/remote.c @@ -80,6 +80,7 @@ #include "async-event.h" #include "gdbsupport/selftest.h" #include "cli/cli-style.h" +#include "gdbsupport/remote-args.h" /* The remote target. */ @@ -4943,7 +4944,7 @@ remote_target::process_initial_stop_replies (int from_tty) event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG); if (remote_debug) - print_target_wait_results (waiton_ptid, event_ptid, ws); + print_target_wait_results (waiton_ptid, event_ptid, ws, this); switch (ws.kind ()) { @@ -10835,16 +10836,15 @@ remote_target::extended_remote_run (const std::string &args) if (!args.empty ()) { - int i; + std::vector<std::string> split_args = gdb::remote_args::split (args); - gdb_argv argv (args.c_str ()); - for (i = 0; argv[i] != NULL; i++) + for (const auto &a : split_args) { - if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ()) + if (a.size () * 2 + 1 + len >= get_remote_packet_size ()) error (_("Argument list too long for run packet")); rs->buf[len++] = ';'; - len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len, - strlen (argv[i])); + len += 2 * bin2hex ((gdb_byte *) a.c_str (), rs->buf.data () + len, + a.size ()); } } diff --git a/gdb/riscv-canonicalize-syscall-gen.c b/gdb/riscv-canonicalize-syscall-gen.c new file mode 100644 index 0000000..67e5410 --- /dev/null +++ b/gdb/riscv-canonicalize-syscall-gen.c @@ -0,0 +1,358 @@ +/* DO NOT EDIT: Autogenerated by riscv-canonicalize-syscall-gen.py + + Copyright (C) 2024-2025 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#include "defs.h" +#include "riscv-linux-tdep.h" + +/* riscv64_canonicalize_syscall maps from the native riscv 64 Linux set + of syscall ids into a canonical set of syscall ids used by + process record. */ + +enum gdb_syscall +riscv64_canonicalize_syscall (int syscall) +{ + switch (syscall) + { + case 0: return gdb_sys_io_setup; + case 1: return gdb_sys_io_destroy; + case 2: return gdb_sys_io_submit; + case 3: return gdb_sys_io_cancel; + case 4: return gdb_sys_io_getevents; + case 5: return gdb_sys_setxattr; + case 6: return gdb_sys_lsetxattr; + case 7: return gdb_sys_fsetxattr; + case 8: return gdb_sys_getxattr; + case 9: return gdb_sys_lgetxattr; + case 10: return gdb_sys_fgetxattr; + case 11: return gdb_sys_listxattr; + case 12: return gdb_sys_llistxattr; + case 13: return gdb_sys_flistxattr; + case 14: return gdb_sys_removexattr; + case 15: return gdb_sys_lremovexattr; + case 16: return gdb_sys_fremovexattr; + case 17: return gdb_sys_getcwd; + case 18: return gdb_sys_lookup_dcookie; + case 19: return gdb_sys_eventfd2; + case 20: return gdb_sys_epoll_create1; + case 21: return gdb_sys_epoll_ctl; + case 22: return gdb_sys_epoll_pwait; + case 23: return gdb_sys_dup; + case 24: return gdb_sys_dup3; + case 25: return gdb_sys_fcntl; + case 26: return gdb_sys_inotify_init1; + case 27: return gdb_sys_inotify_add_watch; + case 28: return gdb_sys_inotify_rm_watch; + case 29: return gdb_sys_ioctl; + case 30: return gdb_sys_ioprio_set; + case 31: return gdb_sys_ioprio_get; + case 32: return gdb_sys_flock; + case 33: return gdb_sys_mknodat; + case 34: return gdb_sys_mkdirat; + case 35: return gdb_sys_unlinkat; + case 36: return gdb_sys_symlinkat; + case 37: return gdb_sys_linkat; + /* case 39: return gdb_sys_umount2; */ + case 40: return gdb_sys_mount; + case 41: return gdb_sys_pivot_root; + case 42: return gdb_sys_nfsservctl; + case 43: return gdb_sys_statfs; + case 44: return gdb_sys_fstatfs; + case 45: return gdb_sys_truncate; + case 46: return gdb_sys_ftruncate; + case 47: return gdb_sys_fallocate; + case 48: return gdb_sys_faccessat; + case 49: return gdb_sys_chdir; + case 50: return gdb_sys_fchdir; + case 51: return gdb_sys_chroot; + case 52: return gdb_sys_fchmod; + case 53: return gdb_sys_fchmodat; + case 54: return gdb_sys_fchownat; + case 55: return gdb_sys_fchown; + case 56: return gdb_sys_openat; + case 57: return gdb_sys_close; + case 58: return gdb_sys_vhangup; + case 59: return gdb_sys_pipe2; + case 60: return gdb_sys_quotactl; + case 61: return gdb_sys_getdents64; + case 62: return gdb_sys_lseek; + case 63: return gdb_sys_read; + case 64: return gdb_sys_write; + case 65: return gdb_sys_readv; + case 66: return gdb_sys_writev; + case 67: return gdb_sys_pread64; + case 68: return gdb_sys_pwrite64; + /* case 69: return gdb_sys_preadv; */ + /* case 70: return gdb_sys_pwritev; */ + case 71: return gdb_sys_sendfile; + case 72: return gdb_sys_pselect6; + case 73: return gdb_sys_ppoll; + /* case 74: return gdb_sys_signalfd4; */ + case 75: return gdb_sys_vmsplice; + case 76: return gdb_sys_splice; + case 77: return gdb_sys_tee; + case 78: return gdb_sys_readlinkat; + case 79: return gdb_sys_newfstatat; + case 80: return gdb_sys_fstat; + case 81: return gdb_sys_sync; + case 82: return gdb_sys_fsync; + case 83: return gdb_sys_fdatasync; + case 84: return gdb_sys_sync_file_range; + /* case 85: return gdb_sys_timerfd_create; */ + /* case 86: return gdb_sys_timerfd_settime; */ + /* case 87: return gdb_sys_timerfd_gettime; */ + /* case 88: return gdb_sys_utimensat; */ + case 89: return gdb_sys_acct; + case 90: return gdb_sys_capget; + case 91: return gdb_sys_capset; + case 92: return gdb_sys_personality; + case 93: return gdb_sys_exit; + case 94: return gdb_sys_exit_group; + case 95: return gdb_sys_waitid; + case 96: return gdb_sys_set_tid_address; + case 97: return gdb_sys_unshare; + case 98: return gdb_sys_futex; + case 99: return gdb_sys_set_robust_list; + case 100: return gdb_sys_get_robust_list; + case 101: return gdb_sys_nanosleep; + case 102: return gdb_sys_getitimer; + case 103: return gdb_sys_setitimer; + case 104: return gdb_sys_kexec_load; + case 105: return gdb_sys_init_module; + case 106: return gdb_sys_delete_module; + case 107: return gdb_sys_timer_create; + case 108: return gdb_sys_timer_gettime; + case 109: return gdb_sys_timer_getoverrun; + case 110: return gdb_sys_timer_settime; + case 111: return gdb_sys_timer_delete; + case 112: return gdb_sys_clock_settime; + case 113: return gdb_sys_clock_gettime; + case 114: return gdb_sys_clock_getres; + case 115: return gdb_sys_clock_nanosleep; + case 116: return gdb_sys_syslog; + case 117: return gdb_sys_ptrace; + case 118: return gdb_sys_sched_setparam; + case 119: return gdb_sys_sched_setscheduler; + case 120: return gdb_sys_sched_getscheduler; + case 121: return gdb_sys_sched_getparam; + case 122: return gdb_sys_sched_setaffinity; + case 123: return gdb_sys_sched_getaffinity; + case 124: return gdb_sys_sched_yield; + case 125: return gdb_sys_sched_get_priority_max; + case 126: return gdb_sys_sched_get_priority_min; + case 127: return gdb_sys_sched_rr_get_interval; + case 128: return gdb_sys_restart_syscall; + case 129: return gdb_sys_kill; + case 130: return gdb_sys_tkill; + case 131: return gdb_sys_tgkill; + case 132: return gdb_sys_sigaltstack; + case 133: return gdb_sys_rt_sigsuspend; + case 134: return gdb_sys_rt_sigaction; + case 135: return gdb_sys_rt_sigprocmask; + case 136: return gdb_sys_rt_sigpending; + case 137: return gdb_sys_rt_sigtimedwait; + case 138: return gdb_sys_rt_sigqueueinfo; + case 139: return gdb_sys_rt_sigreturn; + case 140: return gdb_sys_setpriority; + case 141: return gdb_sys_getpriority; + case 142: return gdb_sys_reboot; + case 143: return gdb_sys_setregid; + case 144: return gdb_sys_setgid; + case 145: return gdb_sys_setreuid; + case 146: return gdb_sys_setuid; + case 147: return gdb_sys_setresuid; + case 148: return gdb_sys_getresuid; + case 149: return gdb_sys_setresgid; + case 150: return gdb_sys_getresgid; + case 151: return gdb_sys_setfsuid; + case 152: return gdb_sys_setfsgid; + case 153: return gdb_sys_times; + case 154: return gdb_sys_setpgid; + case 155: return gdb_sys_getpgid; + case 156: return gdb_sys_getsid; + case 157: return gdb_sys_setsid; + case 158: return gdb_sys_getgroups; + case 159: return gdb_sys_setgroups; + case 160: return gdb_sys_uname; + case 161: return gdb_sys_sethostname; + case 162: return gdb_sys_setdomainname; + case 163: return gdb_sys_getrlimit; + case 164: return gdb_sys_setrlimit; + case 165: return gdb_sys_getrusage; + case 166: return gdb_sys_umask; + case 167: return gdb_sys_prctl; + case 168: return gdb_sys_getcpu; + case 169: return gdb_sys_gettimeofday; + case 170: return gdb_sys_settimeofday; + case 171: return gdb_sys_adjtimex; + case 172: return gdb_sys_getpid; + case 173: return gdb_sys_getppid; + case 174: return gdb_sys_getuid; + case 175: return gdb_sys_geteuid; + case 176: return gdb_sys_getgid; + case 177: return gdb_sys_getegid; + case 178: return gdb_sys_gettid; + case 179: return gdb_sys_sysinfo; + case 180: return gdb_sys_mq_open; + case 181: return gdb_sys_mq_unlink; + case 182: return gdb_sys_mq_timedsend; + case 183: return gdb_sys_mq_timedreceive; + case 184: return gdb_sys_mq_notify; + case 185: return gdb_sys_mq_getsetattr; + case 186: return gdb_sys_msgget; + case 187: return gdb_sys_msgctl; + case 188: return gdb_sys_msgrcv; + case 189: return gdb_sys_msgsnd; + case 190: return gdb_sys_semget; + case 191: return gdb_sys_semctl; + case 192: return gdb_sys_semtimedop; + case 193: return gdb_sys_semop; + case 194: return gdb_sys_shmget; + case 195: return gdb_sys_shmctl; + case 196: return gdb_sys_shmat; + case 197: return gdb_sys_shmdt; + case 198: return gdb_sys_socket; + case 199: return gdb_sys_socketpair; + case 200: return gdb_sys_bind; + case 201: return gdb_sys_listen; + case 202: return gdb_sys_accept; + case 203: return gdb_sys_connect; + case 204: return gdb_sys_getsockname; + case 205: return gdb_sys_getpeername; + case 206: return gdb_sys_sendto; + case 207: return gdb_sys_recvfrom; + case 208: return gdb_sys_setsockopt; + case 209: return gdb_sys_getsockopt; + case 210: return gdb_sys_shutdown; + case 211: return gdb_sys_sendmsg; + case 212: return gdb_sys_recvmsg; + case 213: return gdb_sys_readahead; + case 214: return gdb_sys_brk; + case 215: return gdb_sys_munmap; + case 216: return gdb_sys_mremap; + case 217: return gdb_sys_add_key; + case 218: return gdb_sys_request_key; + case 219: return gdb_sys_keyctl; + case 220: return gdb_sys_clone; + case 221: return gdb_sys_execve; + case 222: return gdb_sys_old_mmap; + case 223: return gdb_sys_fadvise64; + case 224: return gdb_sys_swapon; + case 225: return gdb_sys_swapoff; + case 226: return gdb_sys_mprotect; + case 227: return gdb_sys_msync; + case 228: return gdb_sys_mlock; + case 229: return gdb_sys_munlock; + case 230: return gdb_sys_mlockall; + case 231: return gdb_sys_munlockall; + case 232: return gdb_sys_mincore; + case 233: return gdb_sys_madvise; + case 234: return gdb_sys_remap_file_pages; + case 235: return gdb_sys_mbind; + case 236: return gdb_sys_get_mempolicy; + case 237: return gdb_sys_set_mempolicy; + case 238: return gdb_sys_migrate_pages; + case 239: return gdb_sys_move_pages; + /* case 240: return gdb_sys_rt_tgsigqueueinfo; */ + /* case 241: return gdb_sys_perf_event_open; */ + case 242: return gdb_sys_accept4; + /* case 243: return gdb_sys_recvmmsg; */ + /* case 258: return gdb_sys_riscv_hwprobe; */ + /* case 259: return gdb_sys_riscv_flush_icache; */ + case 260: return gdb_sys_wait4; + /* case 261: return gdb_sys_prlimit64; */ + /* case 262: return gdb_sys_fanotify_init; */ + /* case 263: return gdb_sys_fanotify_mark; */ + /* case 264: return gdb_sys_name_to_handle_at; */ + /* case 265: return gdb_sys_open_by_handle_at; */ + /* case 266: return gdb_sys_clock_adjtime; */ + /* case 267: return gdb_sys_syncfs; */ + /* case 268: return gdb_sys_setns; */ + /* case 269: return gdb_sys_sendmmsg; */ + /* case 270: return gdb_sys_process_vm_readv; */ + /* case 271: return gdb_sys_process_vm_writev; */ + /* case 272: return gdb_sys_kcmp; */ + /* case 273: return gdb_sys_finit_module; */ + /* case 274: return gdb_sys_sched_setattr; */ + /* case 275: return gdb_sys_sched_getattr; */ + /* case 276: return gdb_sys_renameat2; */ + /* case 277: return gdb_sys_seccomp; */ + case 278: return gdb_sys_getrandom; + /* case 279: return gdb_sys_memfd_create; */ + /* case 280: return gdb_sys_bpf; */ + /* case 281: return gdb_sys_execveat; */ + /* case 282: return gdb_sys_userfaultfd; */ + /* case 283: return gdb_sys_membarrier; */ + /* case 284: return gdb_sys_mlock2; */ + /* case 285: return gdb_sys_copy_file_range; */ + /* case 286: return gdb_sys_preadv2; */ + /* case 287: return gdb_sys_pwritev2; */ + /* case 288: return gdb_sys_pkey_mprotect; */ + /* case 289: return gdb_sys_pkey_alloc; */ + /* case 290: return gdb_sys_pkey_free; */ + case 291: return gdb_sys_statx; + /* case 292: return gdb_sys_io_pgetevents; */ + /* case 293: return gdb_sys_rseq; */ + /* case 294: return gdb_sys_kexec_file_load; */ + /* case 424: return gdb_sys_pidfd_send_signal; */ + /* case 425: return gdb_sys_io_uring_setup; */ + /* case 426: return gdb_sys_io_uring_enter; */ + /* case 427: return gdb_sys_io_uring_register; */ + /* case 428: return gdb_sys_open_tree; */ + /* case 429: return gdb_sys_move_mount; */ + /* case 430: return gdb_sys_fsopen; */ + /* case 431: return gdb_sys_fsconfig; */ + /* case 432: return gdb_sys_fsmount; */ + /* case 433: return gdb_sys_fspick; */ + /* case 434: return gdb_sys_pidfd_open; */ + /* case 435: return gdb_sys_clone3; */ + /* case 436: return gdb_sys_close_range; */ + /* case 437: return gdb_sys_openat2; */ + /* case 438: return gdb_sys_pidfd_getfd; */ + /* case 439: return gdb_sys_faccessat2; */ + /* case 440: return gdb_sys_process_madvise; */ + /* case 441: return gdb_sys_epoll_pwait2; */ + /* case 442: return gdb_sys_mount_setattr; */ + /* case 443: return gdb_sys_quotactl_fd; */ + /* case 444: return gdb_sys_landlock_create_ruleset; */ + /* case 445: return gdb_sys_landlock_add_rule; */ + /* case 446: return gdb_sys_landlock_restrict_self; */ + /* case 447: return gdb_sys_memfd_secret; */ + /* case 448: return gdb_sys_process_mrelease; */ + /* case 449: return gdb_sys_futex_waitv; */ + /* case 450: return gdb_sys_set_mempolicy_home_node; */ + /* case 451: return gdb_sys_cachestat; */ + /* case 452: return gdb_sys_fchmodat2; */ + /* case 453: return gdb_sys_map_shadow_stack; */ + /* case 454: return gdb_sys_futex_wake; */ + /* case 455: return gdb_sys_futex_wait; */ + /* case 456: return gdb_sys_futex_requeue; */ + /* case 457: return gdb_sys_statmount; */ + /* case 458: return gdb_sys_listmount; */ + /* case 459: return gdb_sys_lsm_get_self_attr; */ + /* case 460: return gdb_sys_lsm_set_self_attr; */ + /* case 461: return gdb_sys_lsm_list_modules; */ + /* case 462: return gdb_sys_mseal; */ + /* case 463: return gdb_sys_setxattrat; */ + /* case 464: return gdb_sys_getxattrat; */ + /* case 465: return gdb_sys_listxattrat; */ + /* case 466: return gdb_sys_removexattrat; */ + default: + return gdb_sys_no_syscall; + } +} diff --git a/gdb/riscv-linux-tdep.c b/gdb/riscv-linux-tdep.c index 4c0c65c..e1ea615 100644 --- a/gdb/riscv-linux-tdep.c +++ b/gdb/riscv-linux-tdep.c @@ -20,11 +20,18 @@ #include "osabi.h" #include "glibc-tdep.h" #include "linux-tdep.h" +#include "svr4-tls-tdep.h" #include "solib-svr4.h" #include "regset.h" #include "tramp-frame.h" #include "trad-frame.h" #include "gdbarch.h" +#include "record-full.h" +#include "linux-record.h" +#include "riscv-linux-tdep.h" +#include "inferior.h" + +extern unsigned int record_debug; /* The following value is derived from __NR_rt_sigreturn in <include/uapi/asm-generic/unistd.h> from the Linux source tree. */ @@ -173,6 +180,327 @@ riscv_linux_syscall_next_pc (const frame_info_ptr &frame) return pc + 4 /* Length of the ECALL insn. */; } +/* RISC-V process record-replay constructs: syscall, signal etc. */ + +static linux_record_tdep riscv_linux_record_tdep; + +using regnum_type = int; + +/* Record registers from first to last for process-record. */ + +static bool +save_registers (struct regcache *regcache, regnum_type first, regnum_type last) +{ + gdb_assert (regcache != nullptr); + + for (regnum_type i = first; i != last; ++i) + if (record_full_arch_list_add_reg (regcache, i)) + return false; + return true; +}; + +/* Record all registers but PC register for process-record. */ + +static bool +riscv_all_but_pc_registers_record (struct regcache *regcache) +{ + gdb_assert (regcache != nullptr); + + struct gdbarch *gdbarch = regcache->arch (); + riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch); + const struct riscv_gdbarch_features &features = tdep->isa_features; + + if (!save_registers (regcache, RISCV_ZERO_REGNUM + 1, RISCV_PC_REGNUM)) + return false; + + if (features.flen + && !save_registers (regcache, RISCV_FIRST_FP_REGNUM, + RISCV_LAST_FP_REGNUM + 1)) + return false; + + return true; +} + +/* Handler for riscv system call instruction recording. */ + +static int +riscv_linux_syscall_record (struct regcache *regcache, + unsigned long svc_number) +{ + gdb_assert (regcache != nullptr); + + enum gdb_syscall syscall_gdb = riscv64_canonicalize_syscall (svc_number); + + if (record_debug > 1) + gdb_printf (gdb_stdlog, "Made syscall %s.\n", plongest (svc_number)); + + if (syscall_gdb == gdb_sys_no_syscall) + { + warning (_("Process record and replay target doesn't " + "support syscall number %s\n"), plongest (svc_number)); + return -1; + } + + if (syscall_gdb == gdb_sys_sigreturn || syscall_gdb == gdb_sys_rt_sigreturn) + { + if (!riscv_all_but_pc_registers_record (regcache)) + return -1; + return 0; + } + + int ret = record_linux_system_call (syscall_gdb, regcache, + &riscv_linux_record_tdep); + if (ret != 0) + return ret; + + /* Record the return value of the system call. */ + if (record_full_arch_list_add_reg (regcache, RISCV_A0_REGNUM)) + return -1; + + return 0; +} + +/* Initialize the riscv64_linux_record_tdep. */ + +static void +riscv64_linux_record_tdep_init (struct gdbarch *gdbarch, + struct linux_record_tdep & + riscv_linux_record_tdep) +{ + gdb_assert (gdbarch != nullptr); + + /* These values are the size of the type that + will be used in a system call. */ + riscv_linux_record_tdep.size_pointer + = gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT; + riscv_linux_record_tdep.size__old_kernel_stat = 48; + riscv_linux_record_tdep.size_tms = 32; + riscv_linux_record_tdep.size_loff_t = 8; + riscv_linux_record_tdep.size_flock = 32; + riscv_linux_record_tdep.size_oldold_utsname = 45; + riscv_linux_record_tdep.size_ustat = 32; + riscv_linux_record_tdep.size_old_sigaction = 32; + riscv_linux_record_tdep.size_old_sigset_t = 8; + riscv_linux_record_tdep.size_rlimit = 16; + riscv_linux_record_tdep.size_rusage = 144; + riscv_linux_record_tdep.size_timeval = 8; + riscv_linux_record_tdep.size_timezone = 8; + riscv_linux_record_tdep.size_old_gid_t = 2; + riscv_linux_record_tdep.size_old_uid_t = 2; + riscv_linux_record_tdep.size_fd_set = 128; + riscv_linux_record_tdep.size_old_dirent = 268; + riscv_linux_record_tdep.size_statfs = 120; + riscv_linux_record_tdep.size_statfs64 = 120; + riscv_linux_record_tdep.size_sockaddr = 16; + riscv_linux_record_tdep.size_int + = gdbarch_int_bit (gdbarch) / TARGET_CHAR_BIT; + riscv_linux_record_tdep.size_long + = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT; + riscv_linux_record_tdep.size_ulong + = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT; + riscv_linux_record_tdep.size_msghdr = 104; + riscv_linux_record_tdep.size_itimerval = 16; + riscv_linux_record_tdep.size_stat = 128; + riscv_linux_record_tdep.size_old_utsname = 325; + riscv_linux_record_tdep.size_sysinfo = 112; + riscv_linux_record_tdep.size_msqid_ds = 104; + riscv_linux_record_tdep.size_shmid_ds = 88; + riscv_linux_record_tdep.size_new_utsname = 390; + riscv_linux_record_tdep.size_timex = 188; + riscv_linux_record_tdep.size_mem_dqinfo = 72; + riscv_linux_record_tdep.size_if_dqblk = 68; + riscv_linux_record_tdep.size_fs_quota_stat = 64; + riscv_linux_record_tdep.size_timespec = 16; + riscv_linux_record_tdep.size_pollfd = 8; + riscv_linux_record_tdep.size_NFS_FHSIZE = 32; + riscv_linux_record_tdep.size_knfsd_fh = 36; + riscv_linux_record_tdep.size_TASK_COMM_LEN = 4; + riscv_linux_record_tdep.size_sigaction = 24; + riscv_linux_record_tdep.size_sigset_t = 8; + riscv_linux_record_tdep.size_siginfo_t = 128; + riscv_linux_record_tdep.size_cap_user_data_t = 8; + riscv_linux_record_tdep.size_stack_t = 24; + riscv_linux_record_tdep.size_off_t = riscv_linux_record_tdep.size_long; + riscv_linux_record_tdep.size_stat64 = 136; + riscv_linux_record_tdep.size_gid_t = 4; + riscv_linux_record_tdep.size_uid_t = 4; + riscv_linux_record_tdep.size_PAGE_SIZE = 4096; + riscv_linux_record_tdep.size_flock64 = 32; + riscv_linux_record_tdep.size_user_desc = 37; + riscv_linux_record_tdep.size_io_event = 32; + riscv_linux_record_tdep.size_iocb = 64; + riscv_linux_record_tdep.size_epoll_event = 16; + riscv_linux_record_tdep.size_itimerspec + = riscv_linux_record_tdep.size_timespec * 2; + riscv_linux_record_tdep.size_mq_attr = 64; + riscv_linux_record_tdep.size_termios = 36; + riscv_linux_record_tdep.size_termios2 = 44; + riscv_linux_record_tdep.size_pid_t = 4; + riscv_linux_record_tdep.size_winsize = 8; + riscv_linux_record_tdep.size_serial_struct = 72; + riscv_linux_record_tdep.size_serial_icounter_struct = 80; + riscv_linux_record_tdep.size_hayes_esp_config = 12; + riscv_linux_record_tdep.size_size_t = 8; + riscv_linux_record_tdep.size_iovec = 16; + riscv_linux_record_tdep.size_time_t = 8; + + /* These values are the second argument of system call "sys_ioctl". + They are obtained from Linux Kernel source. */ + riscv_linux_record_tdep.ioctl_TCGETS = 0x5401; + riscv_linux_record_tdep.ioctl_TCSETS = 0x5402; + riscv_linux_record_tdep.ioctl_TCSETSW = 0x5403; + riscv_linux_record_tdep.ioctl_TCSETSF = 0x5404; + riscv_linux_record_tdep.ioctl_TCGETA = 0x5405; + riscv_linux_record_tdep.ioctl_TCSETA = 0x5406; + riscv_linux_record_tdep.ioctl_TCSETAW = 0x5407; + riscv_linux_record_tdep.ioctl_TCSETAF = 0x5408; + riscv_linux_record_tdep.ioctl_TCSBRK = 0x5409; + riscv_linux_record_tdep.ioctl_TCXONC = 0x540a; + riscv_linux_record_tdep.ioctl_TCFLSH = 0x540b; + riscv_linux_record_tdep.ioctl_TIOCEXCL = 0x540c; + riscv_linux_record_tdep.ioctl_TIOCNXCL = 0x540d; + riscv_linux_record_tdep.ioctl_TIOCSCTTY = 0x540e; + riscv_linux_record_tdep.ioctl_TIOCGPGRP = 0x540f; + riscv_linux_record_tdep.ioctl_TIOCSPGRP = 0x5410; + riscv_linux_record_tdep.ioctl_TIOCOUTQ = 0x5411; + riscv_linux_record_tdep.ioctl_TIOCSTI = 0x5412; + riscv_linux_record_tdep.ioctl_TIOCGWINSZ = 0x5413; + riscv_linux_record_tdep.ioctl_TIOCSWINSZ = 0x5414; + riscv_linux_record_tdep.ioctl_TIOCMGET = 0x5415; + riscv_linux_record_tdep.ioctl_TIOCMBIS = 0x5416; + riscv_linux_record_tdep.ioctl_TIOCMBIC = 0x5417; + riscv_linux_record_tdep.ioctl_TIOCMSET = 0x5418; + riscv_linux_record_tdep.ioctl_TIOCGSOFTCAR = 0x5419; + riscv_linux_record_tdep.ioctl_TIOCSSOFTCAR = 0x541a; + riscv_linux_record_tdep.ioctl_FIONREAD = 0x541b; + riscv_linux_record_tdep.ioctl_TIOCINQ + = riscv_linux_record_tdep.ioctl_FIONREAD; + riscv_linux_record_tdep.ioctl_TIOCLINUX = 0x541c; + riscv_linux_record_tdep.ioctl_TIOCCONS = 0x541d; + riscv_linux_record_tdep.ioctl_TIOCGSERIAL = 0x541e; + riscv_linux_record_tdep.ioctl_TIOCSSERIAL = 0x541f; + riscv_linux_record_tdep.ioctl_TIOCPKT = 0x5420; + riscv_linux_record_tdep.ioctl_FIONBIO = 0x5421; + riscv_linux_record_tdep.ioctl_TIOCNOTTY = 0x5422; + riscv_linux_record_tdep.ioctl_TIOCSETD = 0x5423; + riscv_linux_record_tdep.ioctl_TIOCGETD = 0x5424; + riscv_linux_record_tdep.ioctl_TCSBRKP = 0x5425; + riscv_linux_record_tdep.ioctl_TIOCTTYGSTRUCT = 0x5426; + riscv_linux_record_tdep.ioctl_TIOCSBRK = 0x5427; + riscv_linux_record_tdep.ioctl_TIOCCBRK = 0x5428; + riscv_linux_record_tdep.ioctl_TIOCGSID = 0x5429; + riscv_linux_record_tdep.ioctl_TCGETS2 = 0x802c542a; + riscv_linux_record_tdep.ioctl_TCSETS2 = 0x402c542b; + riscv_linux_record_tdep.ioctl_TCSETSW2 = 0x402c542c; + riscv_linux_record_tdep.ioctl_TCSETSF2 = 0x402c542d; + riscv_linux_record_tdep.ioctl_TIOCGPTN = 0x80045430; + riscv_linux_record_tdep.ioctl_TIOCSPTLCK = 0x40045431; + riscv_linux_record_tdep.ioctl_FIONCLEX = 0x5450; + riscv_linux_record_tdep.ioctl_FIOCLEX = 0x5451; + riscv_linux_record_tdep.ioctl_FIOASYNC = 0x5452; + riscv_linux_record_tdep.ioctl_TIOCSERCONFIG = 0x5453; + riscv_linux_record_tdep.ioctl_TIOCSERGWILD = 0x5454; + riscv_linux_record_tdep.ioctl_TIOCSERSWILD = 0x5455; + riscv_linux_record_tdep.ioctl_TIOCGLCKTRMIOS = 0x5456; + riscv_linux_record_tdep.ioctl_TIOCSLCKTRMIOS = 0x5457; + riscv_linux_record_tdep.ioctl_TIOCSERGSTRUCT = 0x5458; + riscv_linux_record_tdep.ioctl_TIOCSERGETLSR = 0x5459; + riscv_linux_record_tdep.ioctl_TIOCSERGETMULTI = 0x545a; + riscv_linux_record_tdep.ioctl_TIOCSERSETMULTI = 0x545b; + riscv_linux_record_tdep.ioctl_TIOCMIWAIT = 0x545c; + riscv_linux_record_tdep.ioctl_TIOCGICOUNT = 0x545d; + riscv_linux_record_tdep.ioctl_TIOCGHAYESESP = 0x545e; + riscv_linux_record_tdep.ioctl_TIOCSHAYESESP = 0x545f; + riscv_linux_record_tdep.ioctl_FIOQSIZE = 0x5460; + + /* These values are the second argument of system call "sys_fcntl" + and "sys_fcntl64". They are obtained from Linux Kernel source. */ + riscv_linux_record_tdep.fcntl_F_GETLK = 5; + riscv_linux_record_tdep.fcntl_F_GETLK64 = 12; + riscv_linux_record_tdep.fcntl_F_SETLK64 = 13; + riscv_linux_record_tdep.fcntl_F_SETLKW64 = 14; + + riscv_linux_record_tdep.arg1 = RISCV_A0_REGNUM; + riscv_linux_record_tdep.arg2 = RISCV_A1_REGNUM; + riscv_linux_record_tdep.arg3 = RISCV_A2_REGNUM; + riscv_linux_record_tdep.arg4 = RISCV_A3_REGNUM; + riscv_linux_record_tdep.arg5 = RISCV_A4_REGNUM; + riscv_linux_record_tdep.arg6 = RISCV_A5_REGNUM; +} + +/* Fetch and return the TLS DTV (dynamic thread vector) address for PTID. + Throw a suitable TLS error if something goes wrong. */ + +static CORE_ADDR +riscv_linux_get_tls_dtv_addr (struct gdbarch *gdbarch, ptid_t ptid, + svr4_tls_libc libc) +{ + /* On RISC-V, the thread pointer is found in TP. */ + regcache *regcache + = get_thread_arch_regcache (current_inferior (), ptid, gdbarch); + int thread_pointer_regnum = RISCV_TP_REGNUM; + target_fetch_registers (regcache, thread_pointer_regnum); + ULONGEST thr_ptr; + if (regcache->cooked_read (thread_pointer_regnum, &thr_ptr) != REG_VALID) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch thread pointer")); + + CORE_ADDR dtv_ptr_addr; + switch (libc) + { + case svr4_tls_libc_musl: + /* MUSL: The DTV pointer is found at the very end of the pthread + struct which is located *before* the thread pointer. I.e. + the thread pointer will be just beyond the end of the struct, + so the address of the DTV pointer is found one pointer-size + before the thread pointer. */ + dtv_ptr_addr + = thr_ptr - (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + break; + case svr4_tls_libc_glibc: + /* GLIBC: The thread pointer (TP) points just beyond the end of + the TCB (thread control block). On RISC-V, this struct + (tcbhead_t) is defined to contain two pointers. The first is + a pointer to the DTV and the second is a pointer to private + data. So the DTV pointer address is 16 bytes (i.e. the size of + two pointers) before thread pointer. */ + + dtv_ptr_addr + = thr_ptr - 2 * (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + break; + default: + throw_error (TLS_GENERIC_ERROR, _("Unknown RISC-V C library")); + break; + } + + gdb::byte_vector buf (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + if (target_read_memory (dtv_ptr_addr, buf.data (), buf.size ()) != 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch DTV address")); + + const struct builtin_type *builtin = builtin_type (gdbarch); + CORE_ADDR dtv_addr = gdbarch_pointer_to_address + (gdbarch, builtin->builtin_data_ptr, buf.data ()); + return dtv_addr; +} + +/* For internal TLS lookup, return the DTP offset, which is the offset + to subtract from a DTV entry, in order to obtain the address of the + TLS block. */ + +static ULONGEST +riscv_linux_get_tls_dtp_offset (struct gdbarch *gdbarch, ptid_t ptid, + svr4_tls_libc libc) +{ + if (libc == svr4_tls_libc_musl) + { + /* This value is DTP_OFFSET in MUSL's arch/riscv64/pthread_arch.h. + It represents the value to subtract from the DTV entry, once + it has been loaded. */ + return 0x800; + } + else + return 0; +} + /* Initialize RISC-V Linux ABI info. */ static void @@ -198,6 +526,10 @@ riscv_linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) /* Enable TLS support. */ set_gdbarch_fetch_tls_load_module_address (gdbarch, svr4_fetch_objfile_link_map); + set_gdbarch_get_thread_local_address (gdbarch, + svr4_tls_get_thread_local_address); + svr4_tls_register_tls_methods (info, gdbarch, riscv_linux_get_tls_dtv_addr, + riscv_linux_get_tls_dtp_offset); set_gdbarch_iterate_over_regset_sections (gdbarch, riscv_linux_iterate_over_regset_sections); @@ -205,6 +537,9 @@ riscv_linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) tramp_frame_prepend_unwinder (gdbarch, &riscv_linux_sigframe); tdep->syscall_next_pc = riscv_linux_syscall_next_pc; + tdep->riscv_syscall_record = riscv_linux_syscall_record; + + riscv64_linux_record_tdep_init (gdbarch, riscv_linux_record_tdep); } /* Initialize RISC-V Linux target support. */ diff --git a/gdb/riscv-linux-tdep.h b/gdb/riscv-linux-tdep.h new file mode 100644 index 0000000..9dd9e37 --- /dev/null +++ b/gdb/riscv-linux-tdep.h @@ -0,0 +1,29 @@ +/* Copyright (C) 2024-2025 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#ifndef GDB_RISCV_LINUX_TDEP_H +#define GDB_RISCV_LINUX_TDEP_H + +#include "linux-record.h" + +/* riscv64_canonicalize_syscall maps from the native riscv Linux set + of syscall ids into a canonical set of syscall ids used by + process record. */ + +extern enum gdb_syscall riscv64_canonicalize_syscall (int syscall); + +#endif /* GDB_RISCV_LINUX_TDEP_H */ diff --git a/gdb/riscv-tdep.c b/gdb/riscv-tdep.c index 91f6dff..a735c09 100644 --- a/gdb/riscv-tdep.c +++ b/gdb/riscv-tdep.c @@ -54,9 +54,12 @@ #include "observable.h" #include "prologue-value.h" #include "arch/riscv.h" +#include "record-full.h" #include "riscv-ravenscar-thread.h" #include "gdbsupport/gdb-safe-ctype.h" +#include <vector> + /* The stack must be 16-byte aligned. */ #define SP_ALIGNMENT 16 @@ -1669,6 +1672,11 @@ public: int imm_signed () const { return m_imm.s; } + /* Fetch instruction from target memory at ADDR, return the content of + the instruction, and update LEN with the instruction length. */ + static ULONGEST fetch_instruction (struct gdbarch *gdbarch, + CORE_ADDR addr, int *len); + private: /* Extract 5 bit register field at OFFSET from instruction OPCODE. */ @@ -1814,11 +1822,6 @@ private: m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S); } - /* Fetch instruction from target memory at ADDR, return the content of - the instruction, and update LEN with the instruction length. */ - static ULONGEST fetch_instruction (struct gdbarch *gdbarch, - CORE_ADDR addr, int *len); - /* The length of the instruction in bytes. Should be 2 or 4. */ int m_length; @@ -4433,6 +4436,9 @@ riscv_gdbarch_init (struct gdbarch_info info, set_gdbarch_stap_register_indirection_suffixes (gdbarch, stap_register_indirection_suffixes); + /* Process record-replay */ + set_gdbarch_process_record (gdbarch, riscv_process_record); + /* Hook in OS ABI-specific overrides, if they have been registered. */ gdbarch_init_osabi (info, gdbarch); @@ -4866,3 +4872,673 @@ equivalent change in the disassembler output."), &setriscvcmdlist, &showriscvcmdlist); } + +/* A wrapper to read register under number regnum to address addr. + Returns false if error happened and makes warning. */ + +static bool +try_read (struct regcache *regcache, int regnum, ULONGEST &addr) +{ + gdb_assert (regcache != nullptr); + + if (regcache->raw_read (regnum, &addr) + != register_status::REG_VALID) + { + warning (_("Can not read at address %lx"), addr); + return false; + } + return true; +} + +/* Helper class to record instruction. */ + +class riscv_recorded_insn final +{ +public: + /* Type for saved register. */ + using regnum_type = int; + /* Type for saved memory. First is address, second is length. */ + using memory_type = std::pair<CORE_ADDR, int>; + + /* Enum class that represents which type does recording belong to. */ + enum class record_type + { + UNKNOWN, + ORDINARY, + + /* Corner cases. */ + ECALL, + EBREAK, + }; + +private: + /* Type for set of registers that need to be saved. */ + using recorded_regs = std::vector<regnum_type>; + /* Type for set of memory records that need to be saved. */ + using recorded_mems = std::vector<memory_type>; + + /* Type for memory address, extracted from memory_type. */ + using mem_addr = decltype (std::declval<memory_type> ().first); + /* Type for memory length, extracted from memory_type. */ + using mem_len = decltype (std::declval<memory_type> ().second); + + /* Record type of current instruction. */ + record_type m_record_type = record_type::UNKNOWN; + + /* Flag that represents was there an error in current recording. */ + bool m_error_occured = false; + + /* Set of registers that need to be recorded. */ + recorded_regs m_regs; + /* Set of memory chunks that need to be recorded. */ + recorded_mems m_mems; + + /* Width in bytes of the general purpose registers for GDBARCH, + where recording is happening. */ + int m_xlen = 0; + + /* Helper for decode 16-bit instruction RS1. */ + static regnum_type + decode_crs1_short (ULONGEST opcode) noexcept + { + return ((opcode >> OP_SH_CRS1S) & OP_MASK_CRS1S) + 8; + } + + /* Helper for decode 16-bit instruction RS2. */ + static regnum_type + decode_crs2_short (ULONGEST opcode) noexcept + { + return ((opcode >> OP_SH_CRS2S) & OP_MASK_CRS2S) + 8; + } + + /* Helper for decode 16-bit instruction CRS1. */ + static regnum_type + decode_crs1 (ULONGEST opcode) noexcept + { + return ((opcode >> OP_SH_RD) & OP_MASK_RD); + } + + /* Helper for decode 16-bit instruction CRS2. */ + static regnum_type + decode_crs2 (ULONGEST opcode) noexcept + { + return ((opcode >> OP_SH_CRS2) & OP_MASK_CRS2); + } + + /* Helper for decode 32-bit instruction RD. */ + static regnum_type + decode_rd (ULONGEST ival) noexcept + { + return (ival >> OP_SH_RD) & OP_MASK_RD; + } + + /* Helper for decode 32-bit instruction RS1. */ + static regnum_type + decode_rs1 (ULONGEST ival) noexcept + { + return (ival >> OP_SH_RS1) & OP_MASK_RS1; + } + + /* Helper for decode 32-bit instruction RS2. */ + static regnum_type + decode_rs2 (ULONGEST ival) noexcept + { + return (ival >> OP_SH_RS2) & OP_MASK_RS2; + } + + /* Helper for decode 32-bit instruction CSR. */ + static regnum_type + decode_csr (ULONGEST ival) noexcept + { + return (ival >> OP_SH_CSR) & OP_MASK_CSR; + } + + /* Set ordinary record type. Always returns true. */ + bool + set_ordinary_record_type () noexcept + { + m_record_type = record_type::ORDINARY; + return true; + } + + /* Set error happened. Always returns false. */ + bool + set_error () noexcept + { + m_error_occured = true; + return false; + } + + /* Check if current recording has an error. */ + bool + has_error () const noexcept + { + return m_error_occured; + } + + /* Reads register. Sets error and returns false if error happened. */ + bool + read_reg (struct regcache *regcache, regnum_type reg, + ULONGEST &addr) noexcept + { + gdb_assert (regcache != nullptr); + + if (!try_read (regcache, reg, addr)) + return set_error (); + return true; + } + + /* Save register. Returns true or aborts if exception happened. */ + bool + save_reg (regnum_type regnum) noexcept + { + m_regs.emplace_back (regnum); + return true; + } + + /* Save memory chunk. Returns true or aborts if exception happened. */ + bool + save_mem (mem_addr addr, mem_len len) noexcept + { + m_mems.emplace_back (addr, len); + return true; + } + + /* Returns true if instruction needs only saving pc. */ + static bool + need_save_pc (ULONGEST ival) noexcept + { + return (is_beq_insn (ival) || is_bne_insn (ival) || is_blt_insn (ival) + || is_bge_insn (ival) || is_bltu_insn (ival) || is_bgeu_insn (ival) + || is_fence_insn (ival) || is_pause_insn (ival) + || is_fence_i_insn (ival)); + } + + /* Returns true if instruction is classified. */ + bool + try_save_pc (ULONGEST ival) noexcept + { + if (!need_save_pc (ival)) + return false; + + return set_ordinary_record_type (); + } + + /* Returns true if instruction needs only saving pc and rd. */ + static bool + need_save_pc_rd (ULONGEST ival) noexcept + { + return (is_lui_insn (ival) || is_auipc_insn (ival) || is_jal_insn (ival) + || is_jalr_insn (ival) || is_lb_insn (ival) || is_lh_insn (ival) + || is_lw_insn (ival) || is_lbu_insn (ival) || is_lhu_insn (ival) + || is_addi_insn (ival) || is_slti_insn (ival) + || is_sltiu_insn (ival) || is_xori_insn (ival) || is_ori_insn (ival) + || is_andi_insn (ival) || is_slli_rv32_insn (ival) + || is_srli_rv32_insn (ival) || is_srai_rv32_insn (ival) + || is_add_insn (ival) || is_sub_insn (ival) || is_sll_insn (ival) + || is_slt_insn (ival) || is_sltu_insn (ival) || is_xor_insn (ival) + || is_srl_insn (ival) || is_sra_insn (ival) || is_or_insn (ival) + || is_and_insn (ival) || is_lwu_insn (ival) || is_ld_insn (ival) + || is_slli_insn (ival) || is_srli_insn (ival) || is_srai_insn (ival) + || is_addiw_insn (ival) || is_slliw_insn (ival) + || is_srliw_insn (ival) || is_sraiw_insn (ival) + || is_addw_insn (ival) || is_subw_insn (ival) || is_sllw_insn (ival) + || is_srlw_insn (ival) || is_sraw_insn (ival) || is_mul_insn (ival) + || is_mulh_insn (ival) || is_mulhsu_insn (ival) + || is_mulhu_insn (ival) || is_div_insn (ival) || is_divu_insn (ival) + || is_rem_insn (ival) || is_remu_insn (ival) || is_mulw_insn (ival) + || is_divw_insn (ival) || is_divuw_insn (ival) + || is_remw_insn (ival) || is_remuw_insn (ival) + || is_lr_w_insn (ival) || is_lr_d_insn (ival) + || is_fcvt_w_s_insn (ival) || is_fcvt_wu_s_insn (ival) + || is_fmv_x_s_insn (ival) || is_feq_s_insn (ival) + || is_flt_s_insn (ival) || is_fle_s_insn (ival) + || is_fclass_s_insn (ival) || is_fcvt_l_s_insn (ival) + || is_fcvt_lu_s_insn (ival) || is_feq_d_insn (ival) + || is_flt_d_insn (ival) || is_fle_d_insn (ival) + || is_fclass_d_insn (ival) || is_fcvt_w_d_insn (ival) + || is_fcvt_wu_d_insn (ival) || is_fcvt_l_d_insn (ival) + || is_fcvt_lu_d_insn (ival) || is_fmv_x_d_insn (ival)); + } + + /* Returns true if instruction is classified. This function can set + m_error_occured. */ + bool + try_save_pc_rd (ULONGEST ival) noexcept + { + if (!need_save_pc_rd (ival)) + return false; + + return (!save_reg (decode_rd (ival)) || set_ordinary_record_type ()); + } + + /* Returns true if instruction needs only saving pc and + floating point rd. */ + static bool + need_save_pc_fprd (ULONGEST ival) noexcept + { + return (is_flw_insn (ival) || is_fmadd_s_insn (ival) + || is_fmsub_s_insn (ival) || is_fnmsub_s_insn (ival) + || is_fnmadd_s_insn (ival) || is_fadd_s_insn (ival) + || is_fsub_s_insn (ival) || is_fmul_s_insn (ival) + || is_fdiv_s_insn (ival) || is_fsqrt_s_insn (ival) + || is_fsgnj_s_insn (ival) || is_fsgnjn_s_insn (ival) + || is_fsgnjx_s_insn (ival) || is_fmin_s_insn (ival) + || is_fmax_s_insn (ival) || is_fcvt_s_w_insn (ival) + || is_fcvt_s_wu_insn (ival) || is_fmv_s_x_insn (ival) + || is_fcvt_s_l_insn (ival) || is_fcvt_s_lu_insn (ival) + || is_fld_insn (ival) || is_fmadd_d_insn (ival) + || is_fmsub_d_insn (ival) || is_fnmsub_d_insn (ival) + || is_fnmadd_d_insn (ival) || is_fadd_d_insn (ival) + || is_fsub_d_insn (ival) || is_fmul_d_insn (ival) + || is_fdiv_d_insn (ival) || is_fsqrt_d_insn (ival) + || is_fsgnj_d_insn (ival) || is_fsgnjn_d_insn (ival) + || is_fsgnjx_d_insn (ival) || is_fmin_d_insn (ival) + || is_fmax_d_insn (ival) || is_fcvt_s_d_insn (ival) + || is_fcvt_d_s_insn (ival) || is_fcvt_d_w_insn (ival) + || is_fcvt_d_wu_insn (ival) || is_fcvt_d_l_insn (ival) + || is_fcvt_d_lu_insn (ival) || is_fmv_d_x_insn (ival)); + } + + /* Returns true if instruction is classified. This function can set + m_error_occured. */ + bool + try_save_pc_fprd (ULONGEST ival) noexcept + { + if (!need_save_pc_fprd (ival)) + return false; + + return (!save_reg (RISCV_FIRST_FP_REGNUM + decode_rd (ival)) + || set_ordinary_record_type ()); + } + + /* Returns true if instruction needs only saving pc, rd and csr. */ + static bool + need_save_pc_rd_csr (ULONGEST ival) noexcept + { + return (is_csrrw_insn (ival) || is_csrrs_insn (ival) || is_csrrc_insn (ival) + || is_csrrwi_insn (ival) || is_csrrsi_insn (ival) + || is_csrrc_insn (ival)); + } + + /* Returns true if instruction is classified. This function can set + m_error_occured. */ + bool + try_save_pc_rd_csr (ULONGEST ival) noexcept + { + if (!need_save_pc_rd_csr (ival)) + return false; + + return (!save_reg (decode_rd (ival)) + || !save_reg (RISCV_FIRST_CSR_REGNUM + decode_csr (ival)) + || set_ordinary_record_type ()); + } + + /* Returns the size of the memory chunk that needs to be saved if the + instruction belongs to the group that needs only saving pc and memory. + Otherwise returns 0. */ + static mem_len + need_save_pc_mem (ULONGEST ival) noexcept + { + if (is_sb_insn (ival)) + return 1; + if (is_sh_insn (ival)) + return 2; + if (is_sw_insn (ival) || is_fsw_insn (ival)) + return 4; + if (is_sd_insn (ival) || is_fsd_insn (ival)) + return 8; + return 0; + } + + /* Returns true if instruction is classified. This function can set + m_error_occured. */ + bool + try_save_pc_mem (ULONGEST ival, struct regcache *regcache) noexcept + { + gdb_assert (regcache != nullptr); + + mem_addr addr = mem_addr{}; + mem_len len = need_save_pc_mem (ival); + if (len <= 0) + return false; + + mem_len offset = EXTRACT_STYPE_IMM (ival); + return (!read_reg (regcache, decode_rs1 (ival), addr) + || !save_mem (addr + offset, len) || set_ordinary_record_type ()); + } + + /* Returns the size of the memory chunk that needs to be saved if the + instruction belongs to the group that needs only saving pc, rd and memory. + Otherwise returns 0. */ + static mem_len + need_save_pc_rd_mem (ULONGEST ival) noexcept + { + if (is_sc_w_insn (ival) || is_amoswap_w_insn (ival) + || is_amoadd_w_insn (ival) || is_amoxor_w_insn (ival) + || is_amoand_w_insn (ival) || is_amoor_w_insn (ival) + || is_amomin_w_insn (ival) || is_amomax_w_insn (ival) + || is_amominu_w_insn (ival) || is_amomaxu_w_insn (ival)) + return 4; + if (is_sc_d_insn (ival) || is_amoswap_d_insn (ival) + || is_amoadd_d_insn (ival) || is_amoxor_d_insn (ival) + || is_amoand_d_insn (ival) || is_amoor_d_insn (ival) + || is_amomin_d_insn (ival) || is_amomax_d_insn (ival) + || is_amominu_d_insn (ival) || is_amomaxu_d_insn (ival)) + return 8; + return 0; + } + + /* Returns true if instruction is classified. This function can set + m_error_occured. */ + bool + try_save_pc_rd_mem (ULONGEST ival, struct regcache *regcache) noexcept + { + gdb_assert (regcache != nullptr); + + mem_len len = need_save_pc_rd_mem (ival); + mem_addr addr = 0; + if (len <= 0) + return false; + + return (!read_reg (regcache, decode_rs1 (ival), addr) + || !save_mem (addr, len) || !save_reg (decode_rd (ival)) + || set_ordinary_record_type ()); + } + + /* Returns true if instruction is successfully recordered. The length of + the instruction must be equal 4 bytes. */ + bool + record_insn_len4 (ULONGEST ival, struct regcache *regcache) noexcept + { + gdb_assert (regcache != nullptr); + + if (is_ecall_insn (ival)) + { + m_record_type = record_type::ECALL; + return true; + } + + if (is_ebreak_insn (ival)) + { + m_record_type = record_type::EBREAK; + return true; + } + + if (try_save_pc (ival) || try_save_pc_rd (ival) || try_save_pc_fprd (ival) + || try_save_pc_rd_csr (ival) || try_save_pc_mem (ival, regcache) + || try_save_pc_rd_mem (ival, regcache)) + return !has_error (); + + warning (_("Currently this instruction with len 4(%lx) is unsupported"), + ival); + return false; + } + + /* Returns true if instruction is successfully recordered. The length of + the instruction must be equal 2 bytes. */ + bool + record_insn_len2 (ULONGEST ival, struct regcache *regcache) noexcept + { + gdb_assert (regcache != nullptr); + + mem_addr addr = mem_addr{}; + + /* The order here is very important, because + opcodes of some instructions may be the same. */ + + if (is_c_addi4spn_insn (ival) || is_c_lw_insn (ival) + || (m_xlen == 8 && is_c_ld_insn (ival))) + return (!save_reg (decode_crs2_short (ival)) + || set_ordinary_record_type ()); + + if (is_c_fld_insn (ival) || (m_xlen == 4 && is_c_flw_insn (ival))) + return (!save_reg (RISCV_FIRST_FP_REGNUM + decode_crs2_short (ival)) + || set_ordinary_record_type ()); + + if (is_c_fsd_insn (ival) || (m_xlen == 8 && is_c_sd_insn (ival))) + { + ULONGEST offset = ULONGEST{EXTRACT_CLTYPE_LD_IMM (ival)}; + return (!read_reg (regcache, decode_crs1_short (ival), addr) + || !save_mem (addr + offset, 8) || set_ordinary_record_type ()); + } + + if ((m_xlen == 4 && is_c_fsw_insn (ival)) || is_c_sw_insn (ival)) + { + ULONGEST offset = ULONGEST{EXTRACT_CLTYPE_LW_IMM (ival)}; + return (!read_reg (regcache, decode_crs1_short (ival), addr) + || !save_mem (addr + offset, 4) || set_ordinary_record_type ()); + } + + if (is_c_nop_insn (ival)) + return set_ordinary_record_type (); + + if (is_c_addi_insn (ival)) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (m_xlen == 4 && is_c_jal_insn (ival)) + return (!save_reg (RISCV_RA_REGNUM) || set_ordinary_record_type ()); + + if ((m_xlen == 8 && is_c_addiw_insn (ival)) || is_c_li_insn (ival)) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (is_c_addi16sp_insn (ival)) + return (!save_reg (RISCV_SP_REGNUM) || set_ordinary_record_type ()); + + if (is_c_lui_insn (ival)) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (is_c_srli_insn (ival) || is_c_srai_insn (ival) || is_c_andi_insn (ival) + || is_c_sub_insn (ival) || is_c_xor_insn (ival) || is_c_or_insn (ival) + || is_c_and_insn (ival) || (m_xlen == 8 && is_c_subw_insn (ival)) + || (m_xlen == 8 && is_c_addw_insn (ival))) + return (!save_reg (decode_crs1_short (ival)) + || set_ordinary_record_type ()); + + if (is_c_j_insn (ival) || is_c_beqz_insn (ival) || is_c_bnez_insn (ival)) + return set_ordinary_record_type (); + + if (is_c_slli_insn (ival)) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (is_c_fldsp_insn (ival) || (m_xlen == 4 && is_c_flwsp_insn (ival))) + return (!save_reg (RISCV_FIRST_FP_REGNUM + decode_crs1 (ival)) + || set_ordinary_record_type ()); + + if (is_c_lwsp_insn (ival) || (m_xlen == 8 && is_c_ldsp_insn (ival))) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (is_c_jr_insn (ival)) + return set_ordinary_record_type (); + + if (is_c_mv_insn (ival)) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (is_c_ebreak_insn (ival)) + { + m_record_type = record_type::EBREAK; + return true; + } + + if (is_c_jalr_insn (ival)) + return (!save_reg (RISCV_RA_REGNUM) || set_ordinary_record_type ()); + + if (is_c_add_insn (ival)) + return (!save_reg (decode_crs1 (ival)) || set_ordinary_record_type ()); + + if (is_c_fsdsp_insn (ival) || (m_xlen == 8 && is_c_sdsp_insn (ival))) + { + ULONGEST offset = ULONGEST{EXTRACT_CSSTYPE_SDSP_IMM (ival)}; + return (!read_reg (regcache, RISCV_SP_REGNUM, addr) + || !save_mem (addr + offset, 8) || set_ordinary_record_type ()); + } + + if (is_c_swsp_insn (ival) || (m_xlen == 4 && is_c_fswsp_insn (ival))) + { + ULONGEST offset = ULONGEST{EXTRACT_CSSTYPE_SWSP_IMM (ival)}; + return (!read_reg (regcache, RISCV_SP_REGNUM, addr) + || !save_mem (addr + offset, 4) || set_ordinary_record_type ()); + } + + warning (_("Currently this instruction with len 2(%lx) is unsupported"), + ival); + return false; + } + +public: + /* Iterator for registers that need to be recorded. */ + using regs_iter = recorded_regs::const_iterator; + /* Iterator for memory chunks that need to be recorded. */ + using mems_iter = recorded_mems::const_iterator; + + /* Record instruction at address addr. Returns false if error happened. */ + bool + record (gdbarch *gdbarch, struct regcache *regcache, CORE_ADDR addr) noexcept + { + gdb_assert (gdbarch != nullptr); + gdb_assert (regcache != nullptr); + + int m_length = 0; + m_xlen = riscv_isa_xlen (gdbarch); + ULONGEST ival = riscv_insn::fetch_instruction (gdbarch, addr, &m_length); + if (!save_reg (RISCV_PC_REGNUM)) + return false; + + if (m_length == 4) + return record_insn_len4 (ival, regcache); + + if (m_length == 2) + return record_insn_len2 (ival, regcache); + + /* 6 bytes or more. If the instruction is longer than 8 bytes, we don't + have full instruction bits in ival. At least, such long instructions + are not defined yet, so just ignore it. */ + gdb_assert (m_length > 0 && m_length % 2 == 0); + + warning (_("Can not record unknown instruction (opcode = %lx)"), ival); + return false; + } + + /* Get record type of instruction. */ + record_type + get_record_type () const noexcept + { + return m_record_type; + } + + /* Returns an iterator to the beginning of the registers that need + to be saved. */ + regs_iter + regs_begin () const noexcept + { + return m_regs.begin (); + } + + /* Returns an iterator to the end of the registers that need + to be saved. */ + regs_iter + regs_end () const noexcept + { + return m_regs.end (); + } + + /* Returns an iterator to the beginning of the memory chunks that need + to be saved. */ + mems_iter + mems_begin () const noexcept + { + return m_mems.begin (); + } + + /* Returns an iterator to the end of the memory chunks that need + to be saved. */ + mems_iter + mems_end () const noexcept + { + return m_mems.end (); + } +}; + +/* A helper function to record instruction using record API. */ + +static int +riscv_record_insn_details (struct gdbarch *gdbarch, struct regcache *regcache, + const riscv_recorded_insn &insn) +{ + gdb_assert (gdbarch != nullptr); + gdb_assert (regcache != nullptr); + + riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch); + auto regs_begin = insn.regs_begin (); + auto regs_end = insn.regs_end (); + if (std::any_of (regs_begin, + regs_end, + [®cache] (auto &®_it) + { + return record_full_arch_list_add_reg (regcache, reg_it); + })) + return -1; + + auto mems_begin = insn.mems_begin (); + auto mems_end = insn.mems_end (); + if (std::any_of (mems_begin, + mems_end, + [] (auto &&mem_it) + { + return record_full_arch_list_add_mem (mem_it.first, + mem_it.second); + })) + return -1; + + switch (insn.get_record_type ()) + { + case riscv_recorded_insn::record_type::ORDINARY: + break; + + case riscv_recorded_insn::record_type::ECALL: + { + if (!tdep->riscv_syscall_record) + { + warning (_("Syscall record is not supported")); + return -1; + } + ULONGEST reg_val = ULONGEST{}; + if (!try_read (regcache, RISCV_A7_REGNUM, reg_val)) + return -1; + return tdep->riscv_syscall_record (regcache, reg_val); + } + + case riscv_recorded_insn::record_type::EBREAK: + break; + + default: + return -1; + } + return 0; +} + +/* Parse the current instruction and record the values of the registers and + memory that will be changed in current instruction to record_arch_list. + Return -1 if something is wrong. */ + +int +riscv_process_record (struct gdbarch *gdbarch, struct regcache *regcache, + CORE_ADDR addr) +{ + gdb_assert (gdbarch != nullptr); + gdb_assert (regcache != nullptr); + + riscv_recorded_insn insn; + if (!insn.record (gdbarch, regcache, addr)) + { + record_full_arch_list_add_end (); + return -1; + } + + int ret_val = riscv_record_insn_details (gdbarch, regcache, insn); + + if (record_full_arch_list_add_end ()) + return -1; + + return ret_val; +} diff --git a/gdb/riscv-tdep.h b/gdb/riscv-tdep.h index ad1e959..2903aef 100644 --- a/gdb/riscv-tdep.h +++ b/gdb/riscv-tdep.h @@ -35,7 +35,11 @@ enum RISCV_FP_REGNUM = 8, /* Frame Pointer. */ RISCV_A0_REGNUM = 10, /* First argument. */ RISCV_A1_REGNUM = 11, /* Second argument. */ - RISCV_A7_REGNUM = 17, /* Seventh argument. */ + RISCV_A2_REGNUM = 12, /* Third argument. */ + RISCV_A3_REGNUM = 13, /* Forth argument. */ + RISCV_A4_REGNUM = 14, /* Fifth argument. */ + RISCV_A5_REGNUM = 15, /* Sixth argument. */ + RISCV_A7_REGNUM = 17, /* Register to pass syscall number. */ RISCV_PC_REGNUM = 32, /* Program Counter. */ RISCV_NUM_INTEGER_REGS = 32, @@ -113,6 +117,10 @@ struct riscv_gdbarch_tdep : gdbarch_tdep_base /* Return the expected next PC assuming FRAME is stopped at a syscall instruction. */ CORE_ADDR (*syscall_next_pc) (const frame_info_ptr &frame) = nullptr; + + /* Syscall record. */ + int (*riscv_syscall_record) (struct regcache *regcache, + unsigned long svc_number) = nullptr; }; @@ -177,6 +185,12 @@ extern void riscv_supply_regset (const struct regset *regset, struct regcache *regcache, int regnum, const void *regs, size_t len); +/* Parse the current instruction, and record the values of the + registers and memory that will be changed by the current + instruction. Returns -1 if something goes wrong, 0 otherwise. */ +extern int riscv_process_record (struct gdbarch *gdbarch, + struct regcache *regcache, CORE_ADDR addr); + /* The names of the RISC-V target description features. */ extern const char *riscv_feature_name_csr; diff --git a/gdb/s390-linux-tdep.c b/gdb/s390-linux-tdep.c index 04c523b..bd1f42c 100644 --- a/gdb/s390-linux-tdep.c +++ b/gdb/s390-linux-tdep.c @@ -29,6 +29,7 @@ #include "gdbcore.h" #include "linux-record.h" #include "linux-tdep.h" +#include "svr4-tls-tdep.h" #include "objfiles.h" #include "osabi.h" #include "regcache.h" @@ -40,6 +41,7 @@ #include "target.h" #include "trad-frame.h" #include "xml-syscall.h" +#include "inferior.h" #include "features/s390-linux32v1.c" #include "features/s390-linux32v2.c" @@ -1124,6 +1126,45 @@ s390_init_linux_record_tdep (struct linux_record_tdep *record_tdep, record_tdep->ioctl_FIOQSIZE = 0x545e; } +/* Fetch and return the TLS DTV (dynamic thread vector) address for PTID. + Throw a suitable TLS error if something goes wrong. */ + +static CORE_ADDR +s390_linux_get_tls_dtv_addr (struct gdbarch *gdbarch, ptid_t ptid, + enum svr4_tls_libc libc) +{ + /* On S390, the thread pointer is found in two registers A0 and A1 + (or, using gdb naming, acr0 and acr1) A0 contains the top 32 + bits of the address and A1 contains the bottom 32 bits. */ + regcache *regcache + = get_thread_arch_regcache (current_inferior (), ptid, gdbarch); + target_fetch_registers (regcache, S390_A0_REGNUM); + target_fetch_registers (regcache, S390_A1_REGNUM); + ULONGEST thr_ptr_lo, thr_ptr_hi, thr_ptr; + if (regcache->cooked_read (S390_A0_REGNUM, &thr_ptr_hi) != REG_VALID + || regcache->cooked_read (S390_A1_REGNUM, &thr_ptr_lo) != REG_VALID) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch thread pointer")); + thr_ptr = (thr_ptr_hi << 32) + thr_ptr_lo; + + /* The thread pointer points at the TCB (thread control block). The + first two members of this struct are both pointers, where the + first will be a pointer to the TCB (i.e. it points at itself) + and the second will be a pointer to the DTV (dynamic thread + vector). There are many other fields too, but the one we care + about here is the DTV pointer. Compute the address of the DTV + pointer, fetch it, and convert it to an address. */ + CORE_ADDR dtv_ptr_addr + = thr_ptr + gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT; + gdb::byte_vector buf (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + if (target_read_memory (dtv_ptr_addr, buf.data (), buf.size ()) != 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch DTV address")); + + const struct builtin_type *builtin = builtin_type (gdbarch); + CORE_ADDR dtv_addr = gdbarch_pointer_to_address + (gdbarch, builtin->builtin_data_ptr, buf.data ()); + return dtv_addr; +} + /* Initialize OSABI common for GNU/Linux on 31- and 64-bit systems. */ static void @@ -1152,6 +1193,9 @@ s390_linux_init_abi_any (struct gdbarch_info info, struct gdbarch *gdbarch) /* Enable TLS support. */ set_gdbarch_fetch_tls_load_module_address (gdbarch, svr4_fetch_objfile_link_map); + set_gdbarch_get_thread_local_address (gdbarch, + svr4_tls_get_thread_local_address); + svr4_tls_register_tls_methods (info, gdbarch, s390_linux_get_tls_dtv_addr); /* Support reverse debugging. */ set_gdbarch_process_record_signal (gdbarch, s390_linux_record_signal); diff --git a/gdb/s390-tdep.c b/gdb/s390-tdep.c index d030a4d..a3b7658 100644 --- a/gdb/s390-tdep.c +++ b/gdb/s390-tdep.c @@ -41,6 +41,8 @@ #include "value.h" #include "inferior.h" #include "dwarf2/loc.h" +#include "gdbsupport/selftest.h" +#include "gdb/disasm-selftests.h" #include "features/s390-linux32.c" #include "features/s390x-linux64.c" @@ -7468,6 +7470,51 @@ s390_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches) return gdbarch; } +#if GDB_SELF_TEST +namespace selftests { + +/* Return bfd_arch_info representing s390x. */ + +static const bfd_arch_info * +bfd_arch_info_s390x () +{ + return bfd_lookup_arch (bfd_arch_s390, bfd_mach_s390_64); +} + +/* Return gdbarch representing s390x. */ + +static gdbarch * +gdbarch_s390x () +{ + struct gdbarch_info info; + info.bfd_arch_info = bfd_arch_info_s390x (); + if (info.bfd_arch_info == nullptr) + return nullptr; + + info.osabi = GDB_OSABI_NONE; + return gdbarch_find_by_info (info); +} + +/* Check disassembly of s390x instructions. */ + +static void +disassemble_s390x () +{ + gdbarch *gdbarch = gdbarch_s390x (); + if (gdbarch == nullptr) + return; + + scoped_restore disassembler_options_restore + = make_scoped_restore (&s390_disassembler_options, "zarch"); + + gdb::byte_vector insn = { 0xb9, 0x68, 0x00, 0x03 }; + disassemble_insn (gdbarch, insn, "clzg\t%r0,%r3"); +} + +} /* namespace selftests */ + +#endif /* GDB_SELF_TEST */ + void _initialize_s390_tdep (); void _initialize_s390_tdep () @@ -7477,4 +7524,9 @@ _initialize_s390_tdep () initialize_tdesc_s390_linux32 (); initialize_tdesc_s390x_linux64 (); + +#if GDB_SELF_TEST + selftests::register_test ("disassemble-s390x", + selftests::disassemble_s390x); +#endif /* GDB_SELF_TEST */ } diff --git a/gdb/solib-svr4.c b/gdb/solib-svr4.c index 83cb389..458c4ba 100644 --- a/gdb/solib-svr4.c +++ b/gdb/solib-svr4.c @@ -431,6 +431,14 @@ struct svr4_info /* This identifies which namespaces are active. A namespace is considered active when there is at least one shared object loaded into it. */ std::set<size_t> active_namespaces; + + /* This flag indicates whether initializations related to the + GLIBC TLS module id tracking code have been performed. */ + bool glibc_tls_slots_inited = false; + + /* A vector of link map addresses for GLIBC TLS slots. See comment + for tls_maybe_fill_slot for more information. */ + std::vector<CORE_ADDR> glibc_tls_slots; }; /* Per-program-space data key. */ @@ -451,6 +459,12 @@ svr4_maybe_add_namespace (svr4_info *info, CORE_ADDR lmid) info->namespace_id.push_back (lmid); info->active_namespaces.insert (i); + + /* Create or update the convenience variable "active_namespaces". + It only needs to be updated here, as this only changes when a + dlmopen or dlclose call happens. */ + set_internalvar_integer (lookup_internalvar ("_active_linker_namespaces"), + info->active_namespaces.size ()); } /* Return whether DEBUG_BASE is the default namespace of INFO. */ @@ -629,10 +643,10 @@ read_program_header (int type, int *p_arch_size, CORE_ADDR *base_addr) return buf; } +/* See solib-svr4.h. */ -/* Return program interpreter string. */ -static std::optional<gdb::byte_vector> -find_program_interpreter (void) +std::optional<gdb::byte_vector> +svr4_find_program_interpreter () { /* If we have a current exec_bfd, use its section table. */ if (current_program_space->exec_bfd () @@ -1574,6 +1588,198 @@ svr4_fetch_objfile_link_map (struct objfile *objfile) return 0; } +/* Return true if bfd section BFD_SECT is a thread local section + (i.e. either named ".tdata" or ".tbss"), and false otherwise. */ + +static bool +is_thread_local_section (struct bfd_section *bfd_sect) +{ + return ((strcmp (bfd_sect->name, ".tdata") == 0 + || strcmp (bfd_sect->name, ".tbss") == 0) + && bfd_sect->size != 0); +} + +/* Return true if objfile OBJF contains a thread local section, and + false otherwise. */ + +static bool +has_thread_local_section (const objfile *objf) +{ + for (obj_section *objsec : objf->sections ()) + if (is_thread_local_section (objsec->the_bfd_section)) + return true; + return false; +} + +/* Return true if solib SO contains a thread local section, and false + otherwise. */ + +static bool +has_thread_local_section (const solib &so) +{ + for (const target_section &p : so.sections) + if (is_thread_local_section (p.the_bfd_section)) + return true; + return false; +} + +/* For the MUSL C library, given link map address LM_ADDR, return the + corresponding TLS module id, or 0 if not found. + + Background: Unlike the mechanism used by glibc (see below), the + scheme used by the MUSL C library is pretty simple. If the + executable contains TLS variables it gets module id 1. Otherwise, + the first shared object loaded which contains TLS variables is + assigned to module id 1. TLS-containing shared objects are then + assigned consecutive module ids, based on the order that they are + loaded. When unloaded via dlclose, module ids are reassigned as if + that module had never been loaded. */ + +int +musl_link_map_to_tls_module_id (CORE_ADDR lm_addr) +{ + /* When lm_addr is zero, the program is statically linked. Any TLS + variables will be in module id 1. */ + if (lm_addr == 0) + return 1; + + int mod_id = 0; + if (has_thread_local_section (current_program_space->symfile_object_file)) + mod_id++; + + struct svr4_info *info = get_svr4_info (current_program_space); + + /* Cause svr4_current_sos() to be run if it hasn't been already. */ + if (info->main_lm_addr == 0) + solib_add (NULL, 0, auto_solib_add); + + /* Handle case where lm_addr corresponds to the main program. + Return value is either 0, when there are no TLS variables, or 1, + when there are. */ + if (lm_addr == info->main_lm_addr) + return mod_id; + + /* Iterate through the shared objects, possibly incrementing the + module id, and returning mod_id should a match be found. */ + for (const solib &so : current_program_space->solibs ()) + { + if (has_thread_local_section (so)) + mod_id++; + + auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ()); + if (li->lm_addr == lm_addr) + return mod_id; + } + return 0; +} + +/* For GLIBC, given link map address LM_ADDR, return the corresponding TLS + module id, or 0 if not found. */ + +int +glibc_link_map_to_tls_module_id (CORE_ADDR lm_addr) +{ + /* When lm_addr is zero, the program is statically linked. Any TLS + variables will be in module id 1. */ + if (lm_addr == 0) + return 1; + + /* Look up lm_addr in the TLS slot data structure. */ + struct svr4_info *info = get_svr4_info (current_program_space); + auto it = std::find (info->glibc_tls_slots.begin (), + info->glibc_tls_slots.end (), + lm_addr); + if (it == info->glibc_tls_slots.end ()) + return 0; + else + return 1 + it - info->glibc_tls_slots.begin (); +} + +/* Conditionally, based on whether the shared object, SO, contains TLS + variables, assign a link map address to a TLS module id slot. This + code is GLIBC-specific and may only work for specific GLIBC + versions. That said, it is known to work for (at least) GLIBC + versions 2.27 thru 2.40. + + Background: In order to implement internal TLS address lookup + code, it is necessary to find the module id that has been + associated with a specific link map address. In GLIBC, the TLS + module id is stored in struct link_map, in the member + 'l_tls_modid'. While the first several members of struct link_map + are part of the SVR4 ABI, the offset to l_tls_modid definitely is + not. Therefore, since we don't know the offset to l_tls_modid, we + cannot simply look it up - which is a shame, because things would + be so much more easy and obviously accurate, if we could access + l_tls_modid. + + GLIBC has a concept of TLS module id slots. These slots are + allocated consecutively as shared objects containing TLS variables + are loaded. When unloaded (e.g. via dlclose()), the corresponding + slot is marked as unused, but may be used again when later loading + a shared object. + + The functions tls_maybe_fill_slot and tls_maybe_erase_slot are + associated with the observers 'solib_loaded' and 'solib_unloaded'. + They (attempt to) track use of TLS module id slots in the same way + that GLIBC does, which will hopefully provide an accurate module id + when asked to provide it via glibc_link_map_to_tls_module_id(), + above. */ + +static void +tls_maybe_fill_slot (solib &so) +{ + struct svr4_info *info = get_svr4_info (current_program_space); + if (!info->glibc_tls_slots_inited) + { + /* Cause svr4_current_sos() to be run if it hasn't been already. */ + if (info->main_lm_addr == 0) + svr4_current_sos_direct (info); + + /* Quit early when main_lm_addr is still 0. */ + if (info->main_lm_addr == 0) + return; + + /* Also quit early when symfile_object_file is not yet known. */ + if (current_program_space->symfile_object_file == nullptr) + return; + + if (has_thread_local_section (current_program_space->symfile_object_file)) + info->glibc_tls_slots.push_back (info->main_lm_addr); + info->glibc_tls_slots_inited = true; + } + + if (has_thread_local_section (so)) + { + auto it = std::find (info->glibc_tls_slots.begin (), + info->glibc_tls_slots.end (), + 0); + auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ()); + if (it == info->glibc_tls_slots.end ()) + info->glibc_tls_slots.push_back (li->lm_addr); + else + *it = li->lm_addr; + } +} + +/* Remove a link map address from the TLS module slot data structure. + As noted above, this code is GLIBC-specific. */ + +static void +tls_maybe_erase_slot (program_space *pspace, const solib &so, + bool still_in_use, bool silent) +{ + if (still_in_use) + return; + + struct svr4_info *info = get_svr4_info (pspace); + auto *li = gdb::checked_static_cast<lm_info_svr4 *> (so.lm_info.get ()); + auto it = std::find (info->glibc_tls_slots.begin (), + info->glibc_tls_slots.end (), + li->lm_addr); + if (it != info->glibc_tls_slots.end ()) + *it = 0; +} + /* On some systems, the only way to recognize the link map entry for the main executable file is by looking at its name. Return non-zero iff SONAME matches one of the known main executable names. */ @@ -2371,7 +2577,7 @@ enable_break (struct svr4_info *info, int from_tty) /* Find the program interpreter; if not found, warn the user and drop into the old breakpoint at symbol code. */ std::optional<gdb::byte_vector> interp_name_holder - = find_program_interpreter (); + = svr4_find_program_interpreter (); if (interp_name_holder) { const char *interp_name = (const char *) interp_name_holder->data (); @@ -3552,6 +3758,54 @@ svr4_num_active_namespaces () return info->active_namespaces.size (); } +/* See solib_ops::get_solibs_in_ns in solist.h. */ +static std::vector<const solib *> +svr4_get_solibs_in_ns (int nsid) +{ + std::vector<const solib*> ns_solibs; + svr4_info *info = get_svr4_info (current_program_space); + + /* If the namespace ID is inactive, there will be no active + libraries, so we can have an early exit, as a treat. */ + if (info->active_namespaces.count (nsid) != 1) + return ns_solibs; + + /* Since we only have the names of solibs in a given namespace, + we'll need to walk through the solib list of the inferior and + find which solib objects correspond to which svr4_so. We create + an unordered map with the names and lm_info to check things + faster, and to be able to remove SOs from the map, to avoid + returning the dynamic linker multiple times. */ + CORE_ADDR debug_base = info->namespace_id[nsid]; + std::unordered_map<std::string, const lm_info_svr4 *> namespace_solibs; + for (svr4_so &so : info->solib_lists[debug_base]) + { + namespace_solibs[so.name] + = gdb::checked_static_cast<const lm_info_svr4 *> + (so.lm_info.get ()); + } + for (const solib &so: current_program_space->solibs ()) + { + auto *lm_inferior + = gdb::checked_static_cast<const lm_info_svr4 *> (so.lm_info.get ()); + + /* This is inspired by the svr4_same, by finding the svr4_so object + in the map, and then double checking if the lm_info is considered + the same. */ + if (namespace_solibs.count (so.so_original_name) > 0 + && namespace_solibs[so.so_original_name]->l_addr_inferior + == lm_inferior->l_addr_inferior) + { + ns_solibs.push_back (&so); + /* Remove the SO from the map, so that we don't end up + printing the dynamic linker multiple times. */ + namespace_solibs.erase (so.so_original_name); + } + } + + return ns_solibs; +} + const struct solib_ops svr4_so_ops = { svr4_relocate_section_addresses, @@ -3569,6 +3823,7 @@ const struct solib_ops svr4_so_ops = svr4_find_solib_addr, svr4_find_solib_ns, svr4_num_active_namespaces, + svr4_get_solibs_in_ns, }; void _initialize_svr4_solib (); @@ -3577,4 +3832,8 @@ _initialize_svr4_solib () { gdb::observers::free_objfile.attach (svr4_free_objfile_observer, "solib-svr4"); + + /* Set up observers for tracking GLIBC TLS module id slots. */ + gdb::observers::solib_loaded.attach (tls_maybe_fill_slot, "solib-svr4"); + gdb::observers::solib_unloaded.attach (tls_maybe_erase_slot, "solib-svr4"); } diff --git a/gdb/solib-svr4.h b/gdb/solib-svr4.h index c08bacf..e59c8e4 100644 --- a/gdb/solib-svr4.h +++ b/gdb/solib-svr4.h @@ -112,4 +112,16 @@ extern struct link_map_offsets *svr4_lp64_fetch_link_map_offsets (void); SVR4 run time loader. */ int svr4_in_dynsym_resolve_code (CORE_ADDR pc); +/* For the MUSL C library, given link map address LM_ADDR, return the + corresponding TLS module id, or 0 if not found. */ +int musl_link_map_to_tls_module_id (CORE_ADDR lm_addr); + +/* For GLIBC, given link map address LM_ADDR, return the corresponding TLS + module id, or 0 if not found. */ +int glibc_link_map_to_tls_module_id (CORE_ADDR lm_addr); + +/* Return program interpreter string. */ + +std::optional<gdb::byte_vector> svr4_find_program_interpreter (); + #endif /* GDB_SOLIB_SVR4_H */ diff --git a/gdb/solib.c b/gdb/solib.c index 4876f1a..5c5cfbd 100644 --- a/gdb/solib.c +++ b/gdb/solib.c @@ -1010,84 +1010,61 @@ solib_add (const char *pattern, int from_tty, int readsyms) } } -/* Implement the "info sharedlibrary" command. Walk through the - shared library list and print information about each attached - library matching PATTERN. If PATTERN is elided, print them - all. */ +/* Helper function for "info sharedlibrary" and "info namespace". + This receives a list of solibs to be printed, and prints a table + with all the relevant data. If PRINT_NAMESPACE is true, figure out + the solib_ops of the current gdbarch, to calculate the namespace + that contains an solib. + Returns true if one or more solibs are missing debug information, + false otherwise. */ static void -info_sharedlibrary_command (const char *pattern, int from_tty) +print_solib_list_table (std::vector<const solib *> solib_list, + bool print_namespace) { - bool so_missing_debug_info = false; - int addr_width; - int nr_libs; gdbarch *gdbarch = current_inferior ()->arch (); - struct ui_out *uiout = current_uiout; - - if (pattern) - { - char *re_err = re_comp (pattern); - - if (re_err) - error (_ ("Invalid regexp: %s"), re_err); - } - /* "0x", a little whitespace, and two hex digits per byte of pointers. */ - addr_width = 4 + (gdbarch_ptr_bit (gdbarch) / 4); - - update_solib_list (from_tty); - - /* ui_out_emit_table table_emitter needs to know the number of rows, - so we need to make two passes over the libs. */ + int addr_width = 4 + (gdbarch_ptr_bit (gdbarch) / 4); + const solib_ops *ops = gdbarch_so_ops (gdbarch); + struct ui_out *uiout = current_uiout; + bool so_missing_debug_info = false; - nr_libs = 0; - for (const solib &so : current_program_space->solibs ()) - { - if (!so.so_name.empty ()) - { - if (pattern && !re_exec (so.so_name.c_str ())) - continue; - ++nr_libs; - } - } + /* There are 3 conditions for this command to print solib namespaces, + first PRINT_NAMESPACE has to be true, second the solib_ops has to + support multiple namespaces, and third there must be more than one + active namespace. Fold all these into the PRINT_NAMESPACE condition. */ + print_namespace = print_namespace && ops->num_active_namespaces != nullptr + && ops->num_active_namespaces () > 1; - /* How many columns the table should have. If the inferior has - more than one namespace active, we need a column to show that. */ int num_cols = 4; - const solib_ops *ops = gdbarch_so_ops (gdbarch); - if (ops->num_active_namespaces != nullptr - && ops->num_active_namespaces () > 1) + if (print_namespace) num_cols++; { - ui_out_emit_table table_emitter (uiout, num_cols, nr_libs, + ui_out_emit_table table_emitter (uiout, num_cols, solib_list.size (), "SharedLibraryTable"); /* The "- 1" is because ui_out adds one space between columns. */ uiout->table_header (addr_width - 1, ui_left, "from", "From"); uiout->table_header (addr_width - 1, ui_left, "to", "To"); - if (ops->num_active_namespaces != nullptr - && ops->num_active_namespaces () > 1) + if (print_namespace) uiout->table_header (5, ui_left, "namespace", "NS"); uiout->table_header (12 - 1, ui_left, "syms-read", "Syms Read"); uiout->table_header (0, ui_noalign, "name", "Shared Object Library"); uiout->table_body (); - for (const solib &so : current_program_space->solibs ()) + for (const solib *so : solib_list) { - if (so.so_name.empty ()) - continue; - - if (pattern && !re_exec (so.so_name.c_str ())) + if (so->so_name.empty ()) continue; ui_out_emit_tuple tuple_emitter (uiout, "lib"); - if (so.addr_high != 0) + if (so->addr_high != 0) { - uiout->field_core_addr ("from", gdbarch, so.addr_low); - uiout->field_core_addr ("to", gdbarch, so.addr_high); + uiout->field_core_addr ("from", gdbarch, so->addr_low); + uiout->field_core_addr ("to", gdbarch, so->addr_high); } else { @@ -1095,12 +1072,11 @@ info_sharedlibrary_command (const char *pattern, int from_tty) uiout->field_skip ("to"); } - if (ops->num_active_namespaces != nullptr - && ops->num_active_namespaces ()> 1) + if (print_namespace) { try { - uiout->field_fmt ("namespace", "[[%d]]", ops->find_solib_ns (so)); + uiout->field_fmt ("namespace", "[[%d]]", ops->find_solib_ns (*so)); } catch (const gdb_exception_error &er) { @@ -1109,32 +1085,157 @@ info_sharedlibrary_command (const char *pattern, int from_tty) } if (!top_level_interpreter ()->interp_ui_out ()->is_mi_like_p () - && so.symbols_loaded && !objfile_has_symbols (so.objfile)) + && so->symbols_loaded && !objfile_has_symbols (so->objfile)) { so_missing_debug_info = true; uiout->field_string ("syms-read", "Yes (*)"); } else - uiout->field_string ("syms-read", so.symbols_loaded ? "Yes" : "No"); + uiout->field_string ("syms-read", so->symbols_loaded ? "Yes" : "No"); - uiout->field_string ("name", so.so_name, file_name_style.style ()); + uiout->field_string ("name", so->so_name, file_name_style.style ()); uiout->text ("\n"); } } - if (nr_libs == 0) + if (so_missing_debug_info) + uiout->message (_ ("(*): Shared library is missing " + "debugging information.\n")); +} + +/* Implement the "info sharedlibrary" command. Walk through the + shared library list and print information about each attached + library matching PATTERN. If PATTERN is elided, print them + all. */ + +static void +info_sharedlibrary_command (const char *pattern, int from_tty) +{ + struct ui_out *uiout = current_uiout; + + if (pattern) + { + char *re_err = re_comp (pattern); + + if (re_err) + error (_ ("Invalid regexp: %s"), re_err); + } + + update_solib_list (from_tty); + + /* ui_out_emit_table table_emitter needs to know the number of rows, + so we need to make two passes over the libs. */ + + std::vector<const solib *> print_libs; + for (const solib &so : current_program_space->solibs ()) + { + if (!so.so_name.empty ()) + { + if (pattern && !re_exec (so.so_name.c_str ())) + continue; + print_libs.push_back (&so); + } + } + + print_solib_list_table (print_libs, true); + + if (print_libs.size () == 0) { if (pattern) uiout->message (_ ("No shared libraries matched.\n")); else uiout->message (_ ("No shared libraries loaded at this time.\n")); } +} + +/* Implement the "info linker-namespaces" command. If the current + gdbarch's solib_ops object does not support multiple namespaces, + this command would just look like "info sharedlibrary", so point + the user to that command instead. + If solib_ops does support multiple namespaces, this command + will group the libraries by linker namespace, or only print the + libraries in the supplied namespace. */ +static void +info_linker_namespace_command (const char *pattern, int from_tty) +{ + const solib_ops *ops = gdbarch_so_ops (current_inferior ()->arch ()); + /* This command only really makes sense for inferiors that support + linker namespaces, so we can leave early. */ + if (ops->num_active_namespaces == nullptr) + error (_("Current inferior does not support linker namespaces." \ + "Use \"info sharedlibrary\" instead")); + + struct ui_out *uiout = current_uiout; + std::vector<std::pair<int, std::vector<const solib *>>> all_solibs_to_print; + + if (pattern != nullptr) + while (*pattern == ' ') + pattern++; + + if (pattern == nullptr || pattern[0] == '\0') + { + uiout->message (_ ("There are %d linker namespaces loaded\n"), + ops->num_active_namespaces ()); + + int printed = 0; + for (int i = 0; printed < ops->num_active_namespaces (); i++) + { + std::vector<const solib *> solibs_to_print + = ops->get_solibs_in_ns (i); + if (solibs_to_print.size () > 0) + { + all_solibs_to_print.push_back (std::make_pair + (i, solibs_to_print)); + printed++; + } + } + } else { - if (so_missing_debug_info) - uiout->message (_ ("(*): Shared library is missing " - "debugging information.\n")); + int ns; + /* Check if the pattern includes the optional [[ and ]] decorators. + To match multiple occurrences, '+' needs to be escaped, and every + escape sequence must be doubled to survive the compiler pass. */ + re_comp ("^\\[\\[[0-9]\\+\\]\\]$"); + if (re_exec (pattern)) + ns = strtol (pattern+2, nullptr, 10); + else + { + char * end = nullptr; + ns = strtol (pattern, &end, 10); + if (end[0] != '\0') + error (_ ("Invalid linker namespace identifier: %s"), pattern); + } + + all_solibs_to_print.push_back + (std::make_pair (ns, ops->get_solibs_in_ns (ns))); + } + + bool ns_separator = false; + + for (auto &solibs_pair : all_solibs_to_print) + { + if (ns_separator) + uiout->message ("\n\n"); + else + ns_separator = true; + int ns = solibs_pair.first; + std::vector<const solib *> solibs_to_print = solibs_pair.second; + if (solibs_to_print.size () == 0) + { + uiout->message (_("Linker namespace [[%d]] is not active.\n"), ns); + /* If we got here, a specific namespace was requested, so there + will only be one vector. We can leave early. */ + break; + } + uiout->message + (_ ("There are %ld libraries loaded in linker namespace [[%d]]\n"), + solibs_to_print.size (), ns); + uiout->message + (_ ("Displaying libraries for linker namespace [[%d]]:\n"), ns); + + print_solib_list_table (solibs_to_print, false); } } @@ -1715,6 +1816,44 @@ default_find_solib_addr (solib &so) return {}; } +/* Implementation of the current_linker_namespace convenience variable. + This returns the GDB internal identifier of the linker namespace, + for the current frame, in the form '[[<number>]]'. If the inferior + doesn't support linker namespaces, this always returns [[0]]. */ + +static value * +current_linker_namespace_make_value (gdbarch *gdbarch, internalvar *var, + void *ignore) +{ + const solib_ops *ops = gdbarch_so_ops (gdbarch); + const language_defn *lang = language_def (get_frame_language + (get_current_frame ())); + std::string nsid = "[[0]]"; + if (ops->find_solib_ns != nullptr) + { + CORE_ADDR curr_pc = get_frame_pc (get_current_frame ()); + for (const solib &so : current_program_space->solibs ()) + if (solib_contains_address_p (so, curr_pc)) + { + nsid = string_printf ("[[%d]]", ops->find_solib_ns (so)); + break; + } + } + + + /* If the PC is not in an SO, or the solib_ops doesn't support + linker namespaces, the inferior is in the default namespace. */ + return lang->value_string (gdbarch, nsid.c_str (), nsid.length ()); +} + +/* Implementation of `$_current_linker_namespace' variable. */ + +static const struct internalvar_funcs current_linker_namespace_funcs = +{ + current_linker_namespace_make_value, + nullptr, +}; + void _initialize_solib (); void @@ -1727,6 +1866,13 @@ _initialize_solib () }, "solib"); + /* Convenience variables for debugging linker namespaces. These are + set here, even if the solib_ops doesn't support them, + for consistency. */ + create_internalvar_type_lazy ("_current_linker_namespace", + ¤t_linker_namespace_funcs, nullptr); + set_internalvar_integer (lookup_internalvar ("_active_linker_namespaces"), 1); + add_com ( "sharedlibrary", class_files, sharedlibrary_command, _ ("Load shared object library symbols for files matching REGEXP.")); @@ -1737,6 +1883,9 @@ _initialize_solib () add_com ("nosharedlibrary", class_files, no_shared_libraries_command, _ ("Unload all shared object library symbols.")); + add_info ("linker-namespaces", info_linker_namespace_command, + _ ("Get information about linker namespaces in the inferior.")); + add_setshow_boolean_cmd ("auto-solib-add", class_support, &auto_solib_add, _ ("\ Set autoloading of shared library symbols."), diff --git a/gdb/solist.h b/gdb/solist.h index 0b7bbf9..6ab5a06 100644 --- a/gdb/solist.h +++ b/gdb/solist.h @@ -194,6 +194,10 @@ struct solib_ops /* Returns the number of active namespaces in the inferior. */ int (*num_active_namespaces) (); + + /* Returns all solibs for a given namespace. If the namespace is not + active, returns an empty vector. */ + std::vector<const solib *> (*get_solibs_in_ns) (int ns); }; /* A unique pointer to a so_list. */ diff --git a/gdb/svr4-tls-tdep.c b/gdb/svr4-tls-tdep.c new file mode 100644 index 0000000..56e1470 --- /dev/null +++ b/gdb/svr4-tls-tdep.c @@ -0,0 +1,256 @@ +/* Target-dependent code for GNU/Linux, architecture independent. + + Copyright (C) 2009-2024 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#include "svr4-tls-tdep.h" +#include "solib-svr4.h" +#include "inferior.h" +#include "objfiles.h" +#include "cli/cli-cmds.h" +#include <optional> + +struct svr4_tls_gdbarch_data +{ + /* Method for looking up TLS DTV. */ + get_tls_dtv_addr_ftype *get_tls_dtv_addr = nullptr; + + /* Method for looking up the TLS DTP offset. */ + get_tls_dtp_offset_ftype *get_tls_dtp_offset = nullptr; + + /* Cached libc value for TLS lookup purposes. */ + enum svr4_tls_libc libc = svr4_tls_libc_unknown; +}; + +static const registry<gdbarch>::key<svr4_tls_gdbarch_data> + svr4_tls_gdbarch_data_handle; + +static struct svr4_tls_gdbarch_data * +get_svr4_tls_gdbarch_data (struct gdbarch *gdbarch) +{ + struct svr4_tls_gdbarch_data *result = svr4_tls_gdbarch_data_handle.get (gdbarch); + if (result == nullptr) + result = svr4_tls_gdbarch_data_handle.emplace (gdbarch); + return result; +} + +/* When true, force internal TLS address lookup instead of lookup via + the thread stratum. */ + +static bool force_internal_tls_address_lookup = false; + +/* For TLS lookup purposes, use heuristics to decide whether program + was linked against MUSL or GLIBC. */ + +static enum svr4_tls_libc +libc_tls_sniffer (struct gdbarch *gdbarch) +{ + /* Check for cached libc value. */ + svr4_tls_gdbarch_data *gdbarch_data = get_svr4_tls_gdbarch_data (gdbarch); + if (gdbarch_data->libc != svr4_tls_libc_unknown) + return gdbarch_data->libc; + + svr4_tls_libc libc = svr4_tls_libc_unknown; + + /* Fetch the program interpreter. */ + std::optional<gdb::byte_vector> interp_name_holder + = svr4_find_program_interpreter (); + if (interp_name_holder) + { + /* A dynamically linked program linked against MUSL will have a + "ld-musl-" in its interpreter name. (Two examples of MUSL + interpreter names are "/lib/ld-musl-x86_64.so.1" and + "lib/ld-musl-aarch64.so.1".) If it's not found, assume GLIBC. */ + const char *interp_name = (const char *) interp_name_holder->data (); + if (strstr (interp_name, "/ld-musl-") != nullptr) + libc = svr4_tls_libc_musl; + else + libc = svr4_tls_libc_glibc; + gdbarch_data->libc = libc; + return libc; + } + + /* If there is no interpreter name, it's statically linked. For + programs with TLS data, a program statically linked against MUSL + will have the symbols 'main_tls' and 'builtin_tls'. If both of + these are present, assume that it was statically linked against + MUSL, otherwise assume GLIBC. */ + if (lookup_minimal_symbol (current_program_space, "main_tls").minsym + != nullptr + && lookup_minimal_symbol (current_program_space, "builtin_tls").minsym + != nullptr) + libc = svr4_tls_libc_musl; + else + libc = svr4_tls_libc_glibc; + gdbarch_data->libc = libc; + return libc; +} + +/* Implement gdbarch method, get_thread_local_address, for architectures + which provide a method for determining the DTV and possibly the DTP + offset. */ + +CORE_ADDR +svr4_tls_get_thread_local_address (struct gdbarch *gdbarch, ptid_t ptid, + CORE_ADDR lm_addr, CORE_ADDR offset) +{ + svr4_tls_gdbarch_data *gdbarch_data = get_svr4_tls_gdbarch_data (gdbarch); + + /* Use the target's get_thread_local_address method when: + + - No method has been provided for finding the TLS DTV. + + or + + - The thread stratum has been pushed (at some point) onto the + target stack, except when 'force_internal_tls_address_lookup' + has been set. + + The idea here is to prefer use of of the target's thread_stratum + method since it should be more accurate. */ + if (gdbarch_data->get_tls_dtv_addr == nullptr + || (find_target_at (thread_stratum) != nullptr + && !force_internal_tls_address_lookup)) + { + struct target_ops *target = current_inferior ()->top_target (); + return target->get_thread_local_address (ptid, lm_addr, offset); + } + else + { + /* Details, found below, regarding TLS layout is for the GNU C + library (glibc) and the MUSL C library (musl), circa 2024. + While some of this layout is defined by the TLS ABI, some of + it, such as how/where to find the DTV pointer in the TCB, is + not. A good source of ABI info for some architectures can be + found in "ELF Handling For Thread-Local Storage" by Ulrich + Drepper. That document is worth consulting even for + architectures not described there, since the general approach + and terminology is used regardless. + + Some architectures, such as aarch64, are not described in + that document, so some details had to ferreted out using the + glibc source code. Likewise, the MUSL source code was + consulted for details which differ from GLIBC. */ + enum svr4_tls_libc libc = libc_tls_sniffer (gdbarch); + int mod_id; + if (libc == svr4_tls_libc_glibc) + mod_id = glibc_link_map_to_tls_module_id (lm_addr); + else /* Assume MUSL. */ + mod_id = musl_link_map_to_tls_module_id (lm_addr); + if (mod_id == 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to determine TLS module id")); + + /* Use the architecture specific DTV fetcher to obtain the DTV. */ + CORE_ADDR dtv_addr = gdbarch_data->get_tls_dtv_addr (gdbarch, ptid, libc); + + /* In GLIBC, The DTV (dynamic thread vector) is an array of + structs consisting of two fields, the first of which is a + pointer to the TLS block of interest. (The second field is a + pointer that assists with memory management, but that's not + of interest here.) Also, the 0th entry is the generation + number, but although it's a single scalar, the 0th entry is + padded to be the same size as all the rest. Thus each + element of the DTV array is two pointers in size. + + In MUSL, the DTV is simply an array of pointers. The 0th + entry is still the generation number, but contains no padding + aside from that which is needed to make it pointer sized. */ + int m; /* Multiplier, for size of DTV entry. */ + switch (libc) + { + case svr4_tls_libc_glibc: + m = 2; + break; + default: + m = 1; + break; + } + + /* Obtain TLS block address. Module ids start at 1, so there's + no need to adjust it to skip over the 0th entry of the DTV, + which is the generation number. */ + CORE_ADDR dtv_elem_addr + = dtv_addr + mod_id * m * (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + gdb::byte_vector buf (gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT); + if (target_read_memory (dtv_elem_addr, buf.data (), buf.size ()) != 0) + throw_error (TLS_GENERIC_ERROR, _("Unable to fetch TLS block address")); + const struct builtin_type *builtin = builtin_type (gdbarch); + CORE_ADDR tls_block_addr = gdbarch_pointer_to_address + (gdbarch, builtin->builtin_data_ptr, + buf.data ()); + + /* When the TLS block addr is 0 or -1, this usually indicates that + the TLS storage hasn't been allocated yet. (In GLIBC, some + architectures use 0 while others use -1.) */ + if (tls_block_addr == 0 || tls_block_addr == (CORE_ADDR) -1) + throw_error (TLS_NOT_ALLOCATED_YET_ERROR, _("TLS not allocated yet")); + + /* MUSL (and perhaps other C libraries, though not GLIBC) have + TLS implementations for some architectures which, for some + reason, have DTV entries which must be negatively offset by + DTP_OFFSET in order to obtain the TLS block address. + DTP_OFFSET is a constant in the MUSL sources - these offsets, + when they're non-zero, seem to be either 0x800 or 0x8000, + and are present for riscv[32/64], powerpc[32/64], m68k, and + mips. + + Use the architecture specific get_tls_dtp_offset method, if + present, to obtain this offset. */ + ULONGEST dtp_offset + = gdbarch_data->get_tls_dtp_offset == nullptr + ? 0 + : gdbarch_data->get_tls_dtp_offset (gdbarch, ptid, libc); + + return tls_block_addr - dtp_offset + offset; + } +} + +/* See svr4-tls-tdep.h. */ + +void +svr4_tls_register_tls_methods (struct gdbarch_info info, struct gdbarch *gdbarch, + get_tls_dtv_addr_ftype *get_tls_dtv_addr, + get_tls_dtp_offset_ftype *get_tls_dtp_offset) +{ + gdb_assert (get_tls_dtv_addr != nullptr); + + svr4_tls_gdbarch_data *gdbarch_data = get_svr4_tls_gdbarch_data (gdbarch); + gdbarch_data->get_tls_dtv_addr = get_tls_dtv_addr; + gdbarch_data->get_tls_dtp_offset = get_tls_dtp_offset; +} + +void _initialize_svr4_tls_tdep (); +void +_initialize_svr4_tls_tdep () +{ + add_setshow_boolean_cmd ("force-internal-tls-address-lookup", class_obscure, + &force_internal_tls_address_lookup, _("\ +Set to force internal TLS address lookup."), _("\ +Show whether GDB is forced to use internal TLS address lookup."), _("\ +When resolving addresses for TLS (Thread Local Storage) variables,\n\ +GDB will attempt to use facilities provided by the thread library (i.e.\n\ +libthread_db). If those facilities aren't available, GDB will fall\n\ +back to using some internal (to GDB), but possibly less accurate\n\ +mechanisms to resolve the addresses for TLS variables. When this flag\n\ +is set, GDB will force use of the fall-back TLS resolution mechanisms.\n\ +This flag is used by some GDB tests to ensure that the internal fallback\n\ +code is exercised and working as expected. The default is to not force\n\ +the internal fall-back mechanisms to be used."), + NULL, NULL, + &maintenance_set_cmdlist, + &maintenance_show_cmdlist); +} diff --git a/gdb/svr4-tls-tdep.h b/gdb/svr4-tls-tdep.h new file mode 100644 index 0000000..73efc02 --- /dev/null +++ b/gdb/svr4-tls-tdep.h @@ -0,0 +1,59 @@ +/* Target-dependent code for GNU/Linux, architecture independent. + + Copyright (C) 2025 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#ifndef GDB_SVR4_TLS_TDEP_H +#define GDB_SVR4_TLS_TDEP_H + +/* C library variants for TLS lookup. */ + +enum svr4_tls_libc +{ + svr4_tls_libc_unknown, + svr4_tls_libc_musl, + svr4_tls_libc_glibc +}; + +/* Function type for "get_tls_dtv_addr" method. */ + +typedef CORE_ADDR (get_tls_dtv_addr_ftype) (struct gdbarch *gdbarch, + ptid_t ptid, + enum svr4_tls_libc libc); + +/* Function type for "get_tls_dtp_offset" method. */ + +typedef CORE_ADDR (get_tls_dtp_offset_ftype) (struct gdbarch *gdbarch, + ptid_t ptid, + enum svr4_tls_libc libc); + +/* Register architecture specific methods for fetching the TLS DTV + and TLS DTP, used by linux_get_thread_local_address. */ + +extern void svr4_tls_register_tls_methods + (struct gdbarch_info info, struct gdbarch *gdbarch, + get_tls_dtv_addr_ftype *get_tls_dtv_addr, + get_tls_dtp_offset_ftype *get_tls_dtp_offset = nullptr); + +/* Used as a gdbarch method for get_thread_local_address when the tdep + file also defines a suitable method for obtaining the TLS DTV. + See linux_init_abi(), above. */ +CORE_ADDR +svr4_tls_get_thread_local_address (struct gdbarch *gdbarch, ptid_t ptid, + CORE_ADDR lm_addr, CORE_ADDR offset); + +#endif /* GDB_SVR4_TLS_TDEP_H */ diff --git a/gdb/syscalls/riscv-canonicalize-syscall-gen.py b/gdb/syscalls/riscv-canonicalize-syscall-gen.py new file mode 100755 index 0000000..40039bb --- /dev/null +++ b/gdb/syscalls/riscv-canonicalize-syscall-gen.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +# pylint: disable=invalid-name + +# Copyright (C) 2024-2025 Free Software Foundation, Inc. +# Contributed by Timur Golubovich + +# This file is part of GDB. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. + +# This program 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 General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + + +# To get help message for this script, run: +# ./gdb/syscalls/riscv-canonicalize-syscall-gen.py --help + +# Execution result: + +# usage: riscv-canonicalize-syscall-gen.py [-h] -i INPUT +# +# Generate file gdb/riscv-canonicalize-syscall-gen.c from path to riscv linux syscalls. +# +# options: +# -h, --help show this help message and exit +# -i INPUT, --input INPUT +# path to riscv linux syscalls (glibc/sysdeps/unix/sysv/linux/riscv/rv64/arch-syscall.h) + +import argparse +import re +import sys +from pathlib import Path as _Path + +head = """\ +/* DO NOT EDIT: Autogenerated by riscv-canonicalize-syscall-gen.py + + Copyright (C) 2024-2025 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#include "defs.h" +#include "riscv-linux-tdep.h" + +/* riscv64_canonicalize_syscall maps from the native riscv 64 Linux set + of syscall ids into a canonical set of syscall ids used by + process record. */ + +enum gdb_syscall +riscv64_canonicalize_syscall (int syscall) +{ + switch (syscall) + { +""" + +tail = """\ + default: + return gdb_sys_no_syscall; + } +} +""" + + +class Generator: + def _get_gdb_syscalls(self, gdb_syscalls_path: _Path) -> list[str]: + gdb_syscalls: list[str] = [] + with open(gdb_syscalls_path, "r", encoding="UTF-8") as file: + lines = file.readlines() + for line in lines: + match = re.search(r"\s*(?P<name>gdb_sys_[^S]+)\S*=", line) + if match: + gdb_syscalls.append(match.group("name").strip()) + return gdb_syscalls + + def _get_canon_syscalls_lines( + self, syscalls_path: _Path, gdb_syscalls: list[str] + ) -> list[str]: + canon_syscalls: dict[int, str] = {} + with open(syscalls_path, "r", encoding="UTF-8") as file: + lines = file.readlines() + for line in lines: + match = re.match( + r"#define\s+__NR_(?P<name>[^\s]+)\s+(?P<number>\d+)", line + ) + if match: + syscall_name = match.group("name") + syscall_num = int(match.group("number")) + gdb_syscall_name = f"gdb_sys_{syscall_name}" + if gdb_syscall_name in gdb_syscalls: + value = f" case {syscall_num}: return {gdb_syscall_name};\n" + canon_syscalls[syscall_num] = value + # this is a place for corner cases + elif syscall_name == "mmap": + gdb_old_syscall_name = "gdb_sys_old_mmap" + value = ( + f" case {syscall_num}: return {gdb_old_syscall_name};\n" + ) + canon_syscalls[syscall_num] = value + else: + value = f" /* case {syscall_num}: return {gdb_syscall_name}; */\n" + canon_syscalls[syscall_num] = value + return [canon_syscalls[syscall_num] for syscall_num in sorted(canon_syscalls)] + + def generate(self, syscalls_path: _Path) -> None: + repo_path = _Path(__file__).parent.parent.parent + gdb_syscalls_path = repo_path / "gdb" / "linux-record.h" + canon_syscalls_path = repo_path / "gdb" / "riscv-canonicalize-syscall-gen.c" + + gdb_syscalls = self._get_gdb_syscalls(gdb_syscalls_path) + canon_syscalls_lines = self._get_canon_syscalls_lines( + syscalls_path, gdb_syscalls + ) + + with open(canon_syscalls_path, "w", encoding="UTF-8") as file: + file.writelines(head) + file.writelines(canon_syscalls_lines) + file.writelines(tail) + + +help_message = """\ +Generate file gdb/riscv-canonicalize-syscall-gen.c +from path to riscv linux syscalls. +""" + + +def setup_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=help_message) + parser.add_argument( + "-i", + "--input", + type=_Path, + required=True, + help="path to riscv linux syscalls (glibc/sysdeps/unix/sysv/linux/riscv/rv64/arch-syscall.h)", + ) + return parser + + +def main(argv: list[str]) -> int: + try: + parser = setup_parser() + args = parser.parse_args(argv) + generator = Generator() + generator.generate(args.input) + return 0 + except RuntimeError as e: + print(str(e)) + return -1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/gdb/target.c b/gdb/target.c index 4a1964e..522bed8 100644 --- a/gdb/target.c +++ b/gdb/target.c @@ -1250,11 +1250,21 @@ generic_tls_error (void) _("Cannot find thread-local variables on this target")); } -/* Using the objfile specified in OBJFILE, find the address for the - current thread's thread-local storage with offset OFFSET. */ +/* See target.h. */ + CORE_ADDR -target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset) +target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset, + const char *name) { + if (!target_has_registers ()) + { + if (name == nullptr) + error (_("Cannot translate TLS address without registers")); + else + error (_("Cannot find address of TLS symbol `%s' without registers"), + name); + } + volatile CORE_ADDR addr = 0; struct target_ops *target = current_inferior ()->top_target (); gdbarch *gdbarch = current_inferior ()->arch (); diff --git a/gdb/target.h b/gdb/target.h index 004494d..2d3bac7 100644 --- a/gdb/target.h +++ b/gdb/target.h @@ -2472,8 +2472,14 @@ extern void target_pre_inferior (); extern void target_preopen (int); +/* Using the objfile specified in OBJFILE, find the address for the + current thread's thread-local storage with offset OFFSET. If it's + provided, NAME might be used to indicate the relevant variable + in an error message. */ + extern CORE_ADDR target_translate_tls_address (struct objfile *objfile, - CORE_ADDR offset); + CORE_ADDR offset, + const char *name = nullptr); /* Return the "section" containing the specified address. */ const struct target_section *target_section_by_addr (struct target_ops *target, diff --git a/gdb/testsuite/boards/cc-with-dwz-5.exp b/gdb/testsuite/boards/cc-with-dwz-5.exp new file mode 100644 index 0000000..b254f91 --- /dev/null +++ b/gdb/testsuite/boards/cc-with-dwz-5.exp @@ -0,0 +1,28 @@ +# Copyright 2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# This file is a dejagnu "board file" and is used to run the testsuite +# with contrib/cc-with-tweaks.sh -5. +# +# NOTE: We assume dwz is in $PATH. +# +# Example usage: +# bash$ cd $objdir +# bash$ make check-gdb \ +# RUNTESTFLAGS='--target_board=cc-with-dwz-5' +# + +set CC_WITH_TWEAKS_FLAGS "-5" +load_board_description "cc-with-tweaks" diff --git a/gdb/testsuite/gdb.base/bg-execution-repeat.c b/gdb/testsuite/gdb.base/bg-execution-repeat.c index 8e9bae4..3c0cc76 100644 --- a/gdb/testsuite/gdb.base/bg-execution-repeat.c +++ b/gdb/testsuite/gdb.base/bg-execution-repeat.c @@ -37,9 +37,9 @@ main (void) { alarm (60); + do_wait = 1; foo (); - do_wait = 1; wait (); /* do_wait set to 0 externally. */ diff --git a/gdb/testsuite/gdb.base/bg-execution-repeat.exp b/gdb/testsuite/gdb.base/bg-execution-repeat.exp index b1496ee..d5580fb 100644 --- a/gdb/testsuite/gdb.base/bg-execution-repeat.exp +++ b/gdb/testsuite/gdb.base/bg-execution-repeat.exp @@ -67,6 +67,17 @@ proc test {continue_cmd} { # enable the "set var" command with an interrupt / continue& pair. gdb_test -no-prompt-anchor "interrupt" + set test "interrupt received" + set re [string_to_regexp "Program received signal SIGINT, Interrupt."] + gdb_expect { + -re $re { + pass $test + } + timeout { + fail "$test (timeout)" + } + } + # Allow the breakpoint to trigger. gdb_test -no-prompt-anchor "set var do_wait=0" diff --git a/gdb/testsuite/gdb.base/break1.c b/gdb/testsuite/gdb.base/break1.c index 110341c..26c4663 100644 --- a/gdb/testsuite/gdb.base/break1.c +++ b/gdb/testsuite/gdb.base/break1.c @@ -23,7 +23,13 @@ struct some_struct { int a_field; int b_field; - union { int z_field; }; + union + { + struct + { + int z_field; + }; + }; }; struct some_struct values[50]; diff --git a/gdb/testsuite/gdb.base/default.exp b/gdb/testsuite/gdb.base/default.exp index d4d6b20..3abd049 100644 --- a/gdb/testsuite/gdb.base/default.exp +++ b/gdb/testsuite/gdb.base/default.exp @@ -699,6 +699,8 @@ set show_conv_list \ {$_gdb_minor = 1} \ {$_shell_exitsignal = void} \ {$_shell_exitcode = 0} \ + {$_active_linker_namespaces = 1} \ + {$_current_linker_namespace = <error: No registers.>}\ } if [allow_python_tests] { append show_conv_list \ diff --git a/gdb/testsuite/gdb.base/dlmopen-ns-ids-main.c b/gdb/testsuite/gdb.base/dlmopen-ns-ids-main.c index 3bcd819..c7c038a 100644 --- a/gdb/testsuite/gdb.base/dlmopen-ns-ids-main.c +++ b/gdb/testsuite/gdb.base/dlmopen-ns-ids-main.c @@ -41,6 +41,12 @@ main (void) handle[2] = dlmopen (LM_ID_NEWLM, DSO_NAME, RTLD_LAZY | RTLD_LOCAL); assert (handle[2] != NULL); + for (dl = 2; dl >= 0; dl--) + { + fun = dlsym (handle[dl], "inc"); + fun (dl); + } + dlclose (handle[0]); /* TAG: first dlclose */ dlclose (handle[1]); /* TAG: second dlclose */ dlclose (handle[2]); /* TAG: third dlclose */ diff --git a/gdb/testsuite/gdb.base/dlmopen-ns-ids.exp b/gdb/testsuite/gdb.base/dlmopen-ns-ids.exp index 3ddc07e..8f52199 100644 --- a/gdb/testsuite/gdb.base/dlmopen-ns-ids.exp +++ b/gdb/testsuite/gdb.base/dlmopen-ns-ids.exp @@ -105,4 +105,137 @@ proc test_info_shared {} { "after unloading everything" } +# Run all tests related to the linkage namespaces convenience +# variables, _active_namespaces and _current_namespaces. +proc_with_prefix test_conv_vars {} { + clean_restart $::binfile + + gdb_test "print \$_active_linker_namespaces" "1" \ + "1 namespace before starting inferior" + gdb_test "print \$_current_linker_namespace" "No registers." \ + "No current namespace before starting inferior" + + if { ![runto_main] } { + return + } + + gdb_test "print \$_active_linker_namespaces" "1" \ + "Before activating namespaces" + gdb_test "print \$_current_linker_namespace" ".*\"\\\[\\\[0\\\]\\\]\"" \ + "Still in the default namespace" + + gdb_breakpoint "inc" allow-pending + gdb_breakpoint [gdb_get_line_number "TAG: first dlclose"] + + foreach_with_prefix dl {3 2 1} { + gdb_continue_to_breakpoint "inc" + + gdb_test "print \$_current_linker_namespace" ".*\"\\\[\\\[$dl\\\]\\\]\"" \ + "Verify we're in namespace $dl" + } + + gdb_continue_to_breakpoint "first dlclose" + gdb_test "print \$_active_linker_namespaces" "4" "all SOs loaded" + + gdb_test "next" ".*second dlclose.*" "close one SO" + gdb_test "print \$_active_linker_namespaces" "3" "one SOs unloaded" + gdb_test "next" ".*third dlclose.*" "close another SO" + gdb_test "print \$_active_linker_namespaces" "2" "two SOs unloaded" + + # Restarting GDB so that we can test setting a breakpoint + # using the convenience variable, while a proper bp syntax + # isn't implemented for namespaces + clean_restart $::binfile + if {![runto_main]} { + return + } + + # We need to load one SO because you can't have confitional + # breakpoints and pending breakpoints at the same time with + # gdb_breakpoint. + gdb_test "next" ".*assert.*" "load the first SO" + gdb_breakpoint "inc if \$_streq(\$_current_linker_namespace, \"\[\[2\]\]\")" + gdb_continue_to_breakpoint "inc" + gdb_continue_to_end "" continue 1 +} + +# Run several tests relating to the command "info namespaces". +proc test_info_linker_namespaces {} { + clean_restart $::binfile + + if { ![runto_main] } { + return + } + + with_test_prefix "info linker-namespaces" { + gdb_breakpoint [gdb_get_line_number "TAG: first dlclose"] + gdb_continue_to_breakpoint "TAG: first dlclose" + } + + # First, test printing a single namespace, and ensure all of + # them are correct, using both syntaxes. + set found_all_libs false + gdb_test_multiple "info linker-namespaces \[\[0\]\]" "print namespace 0" -lbl { + -re "^\r\nThere are ($::decimal) libraries loaded in linker namespace \\\[\\\[0\\\]\\\]" { + # Some systems may add libc and libm to every loaded namespace, + # others may load only one or neither, because the SO doesn't + # actually use either library. The best we can do is check if + # we found the dynamic linker, and up to 2 more libraries. + set libs $expect_out(1,string) + set found_all_libs [expr $libs - 1 <= 2] + exp_continue + } + -re "^\r\n$::gdb_prompt $" { + gdb_assert $found_all_libs "the correct number of libraries was reported" + } + -re "(^\r\n)?\[^\r\n\]+(?=\r\n)" { + exp_continue + } + } + foreach_with_prefix ns {1 2 3} { + set found_test_so false + set found_all_libs false + gdb_test_multiple "info linker-namespaces $ns" "print namespace $ns" -lbl { + -re "^\r\nThere are ($::decimal) libraries loaded in linker namespace \\\[\\\[$ns\\\]\\\]" { + set libs $expect_out(1,string) + # Some systems may add libc and libm to every loaded namespace, + # others may load only one or neither, because the SO doesn't + # actually use either library. The best we can do is check if + # we found the dynamic linker, the test SO, and maybe up to 2 + # more libraries. + set found_all_libs [expr $libs - 2 <= 2] + exp_continue + } + -re "^\r\n\[^\r\n\]+${::binfile_lib}\[^\r\n\]*(?=\r\n)" { + set found_test_so true + exp_continue + } + -re "^\r\n$::gdb_prompt $" { + gdb_assert $found_test_so "this testfle's SO was reported" + gdb_assert $found_all_libs "the correct number of libraries was reported" + } + -re "(^\r\n)?\[^\r\n\]+(?=\r\n)" { + exp_continue + } + } + } + + # These patterns are simpler, and purposefully glob multiple lines. + # The point is to ensure that we find and display all the namespaces, + # without worrying about the libraries printed, since that was tested + # above. + gdb_test "info linker-namespaces" \ + [multi_line "There are 4 linker namespaces loaded" \ + "There are $::decimal libraries loaded in linker namespace ..0.." \ + ".*" \ + "There are $::decimal libraries loaded in linker namespace ..1.." \ + ".*" \ + "There are $::decimal libraries loaded in linker namespace ..2.." \ + ".*" \ + "There are $::decimal libraries loaded in linker namespace ..3.." \ + ".*" ] "print namespaces with no argument" +} + test_info_shared +test_conv_vars +test_info_linker_namespaces diff --git a/gdb/testsuite/gdb.base/tls-common.exp.tcl b/gdb/testsuite/gdb.base/tls-common.exp.tcl new file mode 100644 index 0000000..7aa7f46 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-common.exp.tcl @@ -0,0 +1,50 @@ +# Copyright 2024 Free Software Foundation, Inc. +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +# Require statement, variables and procs used by tls-nothreads.exp, +# tls-multiobj.exp, and tls-dlobj.exp. + +# The tests listed above are known to work for the targets listed on +# the 'require' line, below. +# +# At the moment, only the Linux target is listed, but, ideally, these +# tests should be run on other targets too. E.g, testing on FreeBSD +# shows many failures which should be addressed in some fashion before +# enabling it for that target. + +require {is_any_target "*-*-linux*"} + +# These are the targets which have support for internal TLS lookup: + +set internal_tls_linux_targets {"x86_64-*-linux*" "aarch64-*-linux*" + "riscv*-*-linux*" "powerpc64*-*-linux*" + "s390x*-*-linux*"} + +# The "maint set force-internal-tls-address-lookup" command is only +# available for certain Linux architectures. Don't attempt to force +# use of internal TLS support for architectures which don't support +# it. + +if [is_any_target {*}$internal_tls_linux_targets] { + set internal_tls_iters { false true } +} else { + set internal_tls_iters { false } +} + +# Set up a kfail with message KFAIL_MSG when KFAIL_COND holds, then +# issue gdb_test with command CMD and regular expression RE. + +proc gdb_test_with_kfail {cmd re kfail_cond kfail_msg} { + if [uplevel 1 [list expr $kfail_cond]] { + setup_kfail $kfail_msg *-*-* + } + gdb_test $cmd $re +} diff --git a/gdb/testsuite/gdb.base/tls-dlobj-lib.c b/gdb/testsuite/gdb.base/tls-dlobj-lib.c new file mode 100644 index 0000000..c69bab7 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-dlobj-lib.c @@ -0,0 +1,87 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +/* This program needs to be compiled with preprocessor symbol set to + a small integer, e.g. "gcc -DN=1 ..." With N defined, the CONCAT2 + and CONCAT3 macros will construct suitable names for the global + variables and functions. */ + +#define CONCAT2(a,b) CONCAT2_(a,b) +#define CONCAT2_(a,b) a ## b + +#define CONCAT3(a,b,c) CONCAT3_(a,b,c) +#define CONCAT3_(a,b,c) a ## b ## c + +/* For N=1, this ends up being... + __thread int tls_lib1_tbss_1; + __thread int tls_lib1_tbss_2; + __thread int tls_lib1_tdata_1 = 196; + __thread int tls_lib1_tdata_2 = 197; */ + +__thread int CONCAT3(tls_lib, N, _tbss_1); +__thread int CONCAT3(tls_lib, N, _tbss_2); +__thread int CONCAT3(tls_lib, N, _tdata_1) = CONCAT2(N, 96); +__thread int CONCAT3(tls_lib, N, _tdata_2) = CONCAT2(N, 97); + +/* Substituting for N, define function: + + int get_tls_libN_var (int which) . */ + +int +CONCAT3(get_tls_lib, N, _var) (int which) +{ + switch (which) + { + case 0: + return -1; + case 1: + return CONCAT3(tls_lib, N, _tbss_1); + case 2: + return CONCAT3(tls_lib, N, _tbss_2); + case 3: + return CONCAT3(tls_lib, N, _tdata_1); + case 4: + return CONCAT3(tls_lib, N, _tdata_2); + } + return -1; +} + +/* Substituting for N, define function: + + void set_tls_libN_var (int which, int val) . */ + +void +CONCAT3(set_tls_lib, N, _var) (int which, int val) +{ + switch (which) + { + case 0: + break; + case 1: + CONCAT3(tls_lib, N, _tbss_1) = val; + break; + case 2: + CONCAT3(tls_lib, N, _tbss_2) = val; + break; + case 3: + CONCAT3(tls_lib, N, _tdata_1) = val; + break; + case 4: + CONCAT3(tls_lib, N, _tdata_2) = val; + break; + } +} diff --git a/gdb/testsuite/gdb.base/tls-dlobj.c b/gdb/testsuite/gdb.base/tls-dlobj.c new file mode 100644 index 0000000..322bdda --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-dlobj.c @@ -0,0 +1,311 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#include <dlfcn.h> +#include <assert.h> +#include <stdlib.h> +#include <stdio.h> + +typedef void (*setter_ftype) (int which, int val); + +__thread int tls_main_tbss_1; +__thread int tls_main_tbss_2; +__thread int tls_main_tdata_1 = 96; +__thread int tls_main_tdata_2 = 97; + +extern void set_tls_lib10_var (int which, int val); +extern void set_tls_lib11_var (int which, int val); + +volatile int data; + +static void +set_tls_main_var (int which, int val) +{ + switch (which) + { + case 1: + tls_main_tbss_1 = val; + break; + case 2: + tls_main_tbss_2 = val; + break; + case 3: + tls_main_tdata_1 = val; + break; + case 4: + tls_main_tdata_2 = val; + break; + } +} + +void +use_it (int a) +{ + data = a; +} + +static void * +load_dso (char *dso_name, int n, setter_ftype *setterp) +{ + char buf[80]; + void *sym; + void *handle = dlopen (dso_name, RTLD_NOW | RTLD_GLOBAL); + if (handle == NULL) + { + fprintf (stderr, "dlopen of DSO '%s' failed: %s\n", dso_name, dlerror ()); + exit (1); + } + sprintf (buf, "set_tls_lib%d_var", n); + sym = dlsym (handle, buf); + assert (sym != NULL); + *setterp = sym; + + /* Some libc implementations (for some architectures) refuse to + initialize TLS data structures (specifically, the DTV) without + first calling dlsym on one of the TLS symbols. */ + sprintf (buf, "tls_lib%d_tdata_1", n); + assert (dlsym (handle, buf) != NULL); + + return handle; +} + +int +main (int argc, char **argv) +{ + int i, status; + setter_ftype s0, s1, s2, s3, s4, s10, s11; + void *h1 = load_dso (OBJ1, 1, &s1); + void *h2 = load_dso (OBJ2, 2, &s2); + void *h3 = load_dso (OBJ3, 3, &s3); + void *h4 = load_dso (OBJ4, 4, &s4); + s0 = set_tls_main_var; + s10 = set_tls_lib10_var; + s11 = set_tls_lib11_var; + + use_it (0); /* main-breakpoint-1 */ + + /* Set TLS variables in main program and all libraries. */ + for (i = 1; i <= 4; i++) + s0 (i, 10 + i); + for (i = 1; i <= 4; i++) + s1 (i, 110 + i); + for (i = 1; i <= 4; i++) + s2 (i, 210 + i); + for (i = 1; i <= 4; i++) + s3 (i, 310 + i); + for (i = 1; i <= 4; i++) + s4 (i, 410 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1010 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1110 + i); + + use_it (0); /* main-breakpoint-2 */ + + /* Unload lib2 and lib3. */ + status = dlclose (h2); + assert (status == 0); + status = dlclose (h3); + assert (status == 0); + + /* Set TLS variables in main program and in libraries which are still + loaded. */ + for (i = 1; i <= 4; i++) + s0 (i, 20 + i); + for (i = 1; i <= 4; i++) + s1 (i, 120 + i); + for (i = 1; i <= 4; i++) + s4 (i, 420 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1020 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1120 + i); + + use_it (0); /* main-breakpoint-3 */ + + /* Load lib3. */ + h3 = load_dso (OBJ3, 3, &s3); + + /* Set TLS vars again; currently, only lib2 is not loaded. */ + for (i = 1; i <= 4; i++) + s0 (i, 30 + i); + for (i = 1; i <= 4; i++) + s1 (i, 130 + i); + for (i = 1; i <= 4; i++) + s3 (i, 330 + i); + for (i = 1; i <= 4; i++) + s4 (i, 430 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1030 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1130 + i); + + use_it (0); /* main-breakpoint-4 */ + + /* Unload lib1 and lib4; load lib2. */ + status = dlclose (h1); + assert (status == 0); + status = dlclose (h4); + assert (status == 0); + h2 = load_dso (OBJ2, 2, &s2); + + /* Set TLS vars; currently, lib2 and lib3 are loaded, + lib1 and lib4 are not. */ + for (i = 1; i <= 4; i++) + s0 (i, 40 + i); + for (i = 1; i <= 4; i++) + s2 (i, 240 + i); + for (i = 1; i <= 4; i++) + s3 (i, 340 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1040 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1140 + i); + + use_it (0); /* main-breakpoint-5 */ + + /* Load lib4 and lib1. Unload lib2. */ + h4 = load_dso (OBJ4, 4, &s4); + h1 = load_dso (OBJ1, 1, &s1); + status = dlclose (h2); + assert (status == 0); + + /* Set TLS vars; currently, lib1, lib3, and lib4 are loaded; + lib2 is not loaded. */ + for (i = 1; i <= 4; i++) + s0 (i, 50 + i); + for (i = 1; i <= 4; i++) + s1 (i, 150 + i); + for (i = 1; i <= 4; i++) + s3 (i, 350 + i); + for (i = 1; i <= 4; i++) + s4 (i, 450 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1050 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1150 + i); + + use_it (0); /* main-breakpoint-6 */ + + /* Load lib2, unload lib1, lib3, and lib4; then load lib3 again. */ + h2 = load_dso (OBJ2, 2, &s2); + status = dlclose (h1); + assert (status == 0); + status = dlclose (h3); + assert (status == 0); + status = dlclose (h4); + assert (status == 0); + h3 = load_dso (OBJ3, 3, &s3); + + /* Set TLS vars; currently, lib2 and lib3 are loaded; + lib1 and lib4 are not loaded. */ + for (i = 1; i <= 4; i++) + s0 (i, 60 + i); + for (i = 1; i <= 4; i++) + s2 (i, 260 + i); + for (i = 1; i <= 4; i++) + s3 (i, 360 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1060 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1160 + i); + + use_it (0); /* main-breakpoint-7 */ + + /* Unload lib3 and lib2, then (re)load lib4, lib3, lib2, and lib1, + in that order. */ + status = dlclose (h3); + assert (status == 0); + status = dlclose (h2); + assert (status == 0); + h4 = load_dso (OBJ4, 4, &s4); + h3 = load_dso (OBJ3, 3, &s3); + h2 = load_dso (OBJ2, 2, &s2); + h1 = load_dso (OBJ1, 1, &s1); + + /* Set TLS vars; currently, lib1, lib2, lib3, and lib4 are all + loaded. */ + for (i = 1; i <= 4; i++) + s0 (i, 70 + i); + for (i = 1; i <= 4; i++) + s1 (i, 170 + i); + for (i = 1; i <= 4; i++) + s2 (i, 270 + i); + for (i = 1; i <= 4; i++) + s3 (i, 370 + i); + for (i = 1; i <= 4; i++) + s4 (i, 470 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1070 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1170 + i); + + use_it (0); /* main-breakpoint-8 */ + + /* Unload lib3, lib1, and lib4. */ + status = dlclose (h3); + assert (status == 0); + status = dlclose (h1); + assert (status == 0); + status = dlclose (h4); + assert (status == 0); + + /* Set TLS vars; currently, lib2 is loaded; lib1, lib3, and lib4 are + not. */ + for (i = 1; i <= 4; i++) + s0 (i, 80 + i); + for (i = 1; i <= 4; i++) + s2 (i, 280 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1080 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1180 + i); + + use_it (0); /* main-breakpoint-9 */ + + /* Load lib3, unload lib2, load lib4. */ + h3 = load_dso (OBJ3, 3, &s3); + status = dlclose (h2); + assert (status == 0); + h4 = load_dso (OBJ4, 4, &s4); + + /* Set TLS vars; currently, lib3 and lib4 are loaded; lib1 and lib2 + are not. */ + for (i = 1; i <= 4; i++) + s0 (i, 90 + i); + for (i = 1; i <= 4; i++) + s3 (i, 390 + i); + for (i = 1; i <= 4; i++) + s4 (i, 490 + i); + for (i = 1; i <= 4; i++) + s10 (i, 1090 + i); + for (i = 1; i <= 4; i++) + s11 (i, 1190 + i); + + use_it (0); /* main-breakpoint-10 */ + + /* Attempt to keep variables in the main program from being optimized + away. */ + use_it (tls_main_tbss_1); + use_it (tls_main_tbss_2); + use_it (tls_main_tdata_1); + use_it (tls_main_tdata_2); + + use_it (100); /* main-breakpoint-last */ + + return 0; +} diff --git a/gdb/testsuite/gdb.base/tls-dlobj.exp b/gdb/testsuite/gdb.base/tls-dlobj.exp new file mode 100644 index 0000000..02f2ff8 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-dlobj.exp @@ -0,0 +1,378 @@ +# Copyright 2024 Free Software Foundation, Inc. +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +# Test that the GDB-internal TLS link map to module id mapping code +# works correctly when debugging a program which is linked against +# shared objects and which also loads and unloads other shared objects +# in different orders. For targets which have GDB-internal TLS +# support, it'll check both GDB-internal TLS support as well as that +# provided by a helper library such as libthread_db. + +source $srcdir/$subdir/tls-common.exp.tcl + +require allow_shlib_tests + +standard_testfile + +set libsrc "${srcdir}/${subdir}/${testfile}-lib.c" + +# These will be dlopen'd: +set lib1obj [standard_output_file "${testfile}1-lib.so"] +set lib2obj [standard_output_file "${testfile}2-lib.so"] +set lib3obj [standard_output_file "${testfile}3-lib.so"] +set lib4obj [standard_output_file "${testfile}4-lib.so"] + +# These will be dynamically linked with the main program: +set lib10obj [standard_output_file "${testfile}10-lib.so"] +set lib11obj [standard_output_file "${testfile}11-lib.so"] + +# Due to problems with some versions of glibc, we expect some tests to +# fail due to TLS storage not being allocated/initialized. Test +# command CMD using regular expression RE, and use XFAIL instead of +# FAIL when the relevant RE is matched and COND is true when evaluated +# in the upper level. + +proc gdb_test_with_xfail { cmd re cond} { + gdb_test_multiple $cmd $cmd { + -re -wrap $re { + pass $gdb_test_name + } + -re -wrap "The inferior has not yet allocated storage for thread-local variables.*" { + if [ uplevel 1 [list expr $cond]] { + xfail $gdb_test_name + } else { + fail $gdb_test_name + } + } + } +} + +proc do_tests {force_internal_tls} { + clean_restart $::binfile + if ![runto_main] { + return + } + + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-1"] + gdb_continue_to_breakpoint "main-breakpoint-1" + + with_test_prefix "before assignments" { + gdb_test "print tls_main_tbss_1" ".* = 0" + gdb_test "print tls_main_tbss_2" ".* = 0" + gdb_test "print tls_main_tdata_1" ".* = 96" + gdb_test "print tls_main_tdata_2" ".* = 97" + + # For these tests, where we're attempting to access TLS vars + # in a dlopen'd library, but before assignment to any of the + # vars, so it could happen that storage hasn't been allocated + # yet. But it might also work. (When testing against MUSL, + # things just work; GLIBC ends to produce the TLS error.) So + # accept either the right answer or a TLS error message. + + set tlserr "The inferior has not yet allocated storage for thread-local variables.*" + foreach n {1 2 3 4} { + gdb_test "print tls_lib${n}_tbss_1" \ + "0|${tlserr}" + gdb_test "print tls_lib${n}_tbss_2" \ + "0|${tlserr}" + gdb_test "print tls_lib${n}_tdata_1" \ + "96|${tlserr}" + gdb_test "print tls_lib${n}_tdata_2" \ + "97|${tlserr}" + } + foreach n {10 11} { + gdb_test "print tls_lib${n}_tbss_1" ".* = 0" + gdb_test "print tls_lib${n}_tbss_2" ".* = 0" + gdb_test "print tls_lib${n}_tdata_1" ".* = ${n}96" + gdb_test "print tls_lib${n}_tdata_2" ".* = ${n}97" + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-2"] + gdb_continue_to_breakpoint "main-breakpoint-2" + + with_test_prefix "at main-breakpoint-2" { + gdb_test "print tls_main_tbss_1" ".* = 11" + gdb_test "print tls_main_tbss_2" ".* = 12" + gdb_test "print tls_main_tdata_1" ".* = 13" + gdb_test "print tls_main_tdata_2" ".* = 14" + + foreach n {1 2 3 4 10 11} { + gdb_test "print tls_lib${n}_tbss_1" ".* = ${n}11" + gdb_test "print tls_lib${n}_tbss_2" ".* = ${n}12" + gdb_test "print tls_lib${n}_tdata_1" ".* = ${n}13" + gdb_test "print tls_lib${n}_tdata_2" ".* = ${n}14" + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-3"] + gdb_continue_to_breakpoint "main-breakpoint-3" + + # At this point lib2 and lib3 have been unloaded. Also, TLS vars + # in remaining libraries have been changed. + + with_test_prefix "at main-breakpoint-3" { + gdb_test "print tls_main_tbss_1" ".* = 21" + gdb_test "print tls_main_tbss_2" ".* = 22" + gdb_test "print tls_main_tdata_1" ".* = 23" + gdb_test "print tls_main_tdata_2" ".* = 24" + + foreach n {1 4 10 11} { + gdb_test "print tls_lib${n}_tbss_1" ".* = ${n}21" + gdb_test "print tls_lib${n}_tbss_2" ".* = ${n}22" + gdb_test "print tls_lib${n}_tdata_1" ".* = ${n}23" + gdb_test "print tls_lib${n}_tdata_2" ".* = ${n}24" + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-4"] + gdb_continue_to_breakpoint "main-breakpoint-4" + + # lib3 has been loaded again; lib2 is the only one not loaded. + + with_test_prefix "at main-breakpoint-4" { + gdb_test "print tls_main_tbss_1" ".* = 31" + gdb_test "print tls_main_tbss_2" ".* = 32" + gdb_test "print tls_main_tdata_1" ".* = 33" + gdb_test "print tls_main_tdata_2" ".* = 34" + + set cond { $n == 3 } + foreach n {1 3 4 10 11} { + gdb_test_with_xfail "print tls_lib${n}_tbss_1" ".* = ${n}31" $cond + gdb_test_with_xfail "print tls_lib${n}_tbss_2" ".* = ${n}32" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_1" ".* = ${n}33" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_2" ".* = ${n}34" $cond + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-5"] + gdb_continue_to_breakpoint "main-breakpoint-5" + + # lib2 and lib3 are loaded; lib1 and lib4 are not. + + with_test_prefix "at main-breakpoint-5" { + gdb_test "print tls_main_tbss_1" ".* = 41" + gdb_test "print tls_main_tbss_2" ".* = 42" + gdb_test "print tls_main_tdata_1" ".* = 43" + gdb_test "print tls_main_tdata_2" ".* = 44" + + set cond { $n == 2 || $n == 3 } + foreach n {2 3 10 11} { + gdb_test_with_xfail "print tls_lib${n}_tbss_1" ".* = ${n}41" $cond + gdb_test_with_xfail "print tls_lib${n}_tbss_2" ".* = ${n}42" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_1" ".* = ${n}43" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_2" ".* = ${n}44" $cond + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-6"] + gdb_continue_to_breakpoint "main-breakpoint-6" + + # lib1, lib3 and lib4 are loaded; lib2 is not loaded. + + with_test_prefix "at main-breakpoint-6" { + gdb_test "print tls_main_tbss_1" ".* = 51" + gdb_test "print tls_main_tbss_2" ".* = 52" + gdb_test "print tls_main_tdata_1" ".* = 53" + gdb_test "print tls_main_tdata_2" ".* = 54" + + set cond { $n == 1 || $n == 3 || $n == 4} + foreach n {1 3 4 10 11} { + gdb_test_with_xfail "print tls_lib${n}_tbss_1" ".* = ${n}51" $cond + gdb_test_with_xfail "print tls_lib${n}_tbss_2" ".* = ${n}52" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_1" ".* = ${n}53" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_2" ".* = ${n}54" $cond + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-7"] + gdb_continue_to_breakpoint "main-breakpoint-7" + + # lib2 and lib3 are loaded; lib1 and lib4 are not. + + with_test_prefix "at main-breakpoint-7" { + gdb_test "print tls_main_tbss_1" ".* = 61" + gdb_test "print tls_main_tbss_2" ".* = 62" + gdb_test "print tls_main_tdata_1" ".* = 63" + gdb_test "print tls_main_tdata_2" ".* = 64" + + set cond { $n == 2 || $n == 3 } + foreach n {2 3 10 11} { + gdb_test_with_xfail "print tls_lib${n}_tbss_1" ".* = ${n}61" $cond + gdb_test_with_xfail "print tls_lib${n}_tbss_2" ".* = ${n}62" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_1" ".* = ${n}63" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_2" ".* = ${n}64" $cond + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-8"] + gdb_continue_to_breakpoint "main-breakpoint-8" + + # lib1, lib2, lib3, and lib4 are all loaded. + + with_test_prefix "at main-breakpoint-8" { + gdb_test "print tls_main_tbss_1" ".* = 71" + gdb_test "print tls_main_tbss_2" ".* = 72" + gdb_test "print tls_main_tdata_1" ".* = 73" + gdb_test "print tls_main_tdata_2" ".* = 74" + + foreach n {1 2 3 4 10 11} { + gdb_test "print tls_lib${n}_tbss_1" ".* = ${n}71" + gdb_test "print tls_lib${n}_tbss_2" ".* = ${n}72" + gdb_test "print tls_lib${n}_tdata_1" ".* = ${n}73" + gdb_test "print tls_lib${n}_tdata_2" ".* = ${n}74" + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-9"] + gdb_continue_to_breakpoint "main-breakpoint-9" + + # lib2 is loaded; lib1, lib3, and lib4 are not. + + with_test_prefix "at main-breakpoint-9" { + gdb_test "print tls_main_tbss_1" ".* = 81" + gdb_test "print tls_main_tbss_2" ".* = 82" + gdb_test "print tls_main_tdata_1" ".* = 83" + gdb_test "print tls_main_tdata_2" ".* = 84" + + foreach n {2 10 11} { + gdb_test "print tls_lib${n}_tbss_1" ".* = ${n}81" + gdb_test "print tls_lib${n}_tbss_2" ".* = ${n}82" + gdb_test "print tls_lib${n}_tdata_1" ".* = ${n}83" + gdb_test "print tls_lib${n}_tdata_2" ".* = ${n}84" + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-10"] + gdb_continue_to_breakpoint "main-breakpoint-10" + + # lib3 and lib4 are loaded; lib1 and lib2 are not. + + with_test_prefix "at main-breakpoint-10" { + gdb_test "print tls_main_tbss_1" ".* = 91" + gdb_test "print tls_main_tbss_2" ".* = 92" + gdb_test "print tls_main_tdata_1" ".* = 93" + gdb_test "print tls_main_tdata_2" ".* = 94" + + set cond { $n == 3 || $n == 4 } + foreach n {3 4 10 11} { + gdb_test_with_xfail "print tls_lib${n}_tbss_1" ".* = ${n}91" $cond + gdb_test_with_xfail "print tls_lib${n}_tbss_2" ".* = ${n}92" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_1" ".* = ${n}93" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_2" ".* = ${n}94" $cond + } + } + + # gdb_interact + + set corefile ${::binfile}.core + set core_supported 0 + if { ![is_remote host] } { + set core_supported [gdb_gcore_cmd $corefile "save corefile"] + } + + # Finish test early if no core file was made. + if !$core_supported { + return + } + + clean_restart $::binfile + + set core_loaded [gdb_core_cmd $corefile "load corefile"] + if { $core_loaded == -1 } { + return + } + + with_test_prefix "core file" { + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + gdb_test "print tls_main_tbss_1" ".* = 91" + gdb_test "print tls_main_tbss_2" ".* = 92" + gdb_test "print tls_main_tdata_1" ".* = 93" + gdb_test "print tls_main_tdata_2" ".* = 94" + + set cond { $n == 3 || $n == 4 } + foreach n {3 4 10 11} { + gdb_test_with_xfail "print tls_lib${n}_tbss_1" ".* = ${n}91" $cond + gdb_test_with_xfail "print tls_lib${n}_tbss_2" ".* = ${n}92" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_1" ".* = ${n}93" $cond + gdb_test_with_xfail "print tls_lib${n}_tdata_2" ".* = ${n}94" $cond + } + } +} + +# Build shared objects for dlopen: +if { [gdb_compile_shlib $libsrc $lib1obj [list debug additional_flags=-DN=1]] != "" } { + untested "failed to compile shared object" + return -1 +} +if { [gdb_compile_shlib $libsrc $lib2obj [list debug additional_flags=-DN=2]] != "" } { + untested "failed to compile shared object" + return -1 +} +if { [gdb_compile_shlib $libsrc $lib3obj [list debug additional_flags=-DN=3]] != "" } { + untested "failed to compile shared object" + return -1 +} +if { [gdb_compile_shlib $libsrc $lib4obj [list debug additional_flags=-DN=4]] != "" } { + untested "failed to compile shared object" + return -1 +} + +# Build shared objects to link against main program: +if { [gdb_compile_shlib $libsrc $lib10obj [list debug additional_flags=-DN=10]] != "" } { + untested "failed to compile shared object" + return -1 +} +if { [gdb_compile_shlib $libsrc $lib11obj [list debug additional_flags=-DN=11]] != "" } { + untested "failed to compile shared object" + return -1 +} + +# Use gdb_compile_pthreads to build and link the main program for +# testing. It's also possible to run the tests using plain old +# gdb_compile, but this adds complexity with setting up additional +# KFAILs. (When run using GLIBC versions earlier than 2.34, a program +# that's not dynamically linked against libpthread will lack a working +# libthread_db, and, therefore, won't be able to access thread local +# storage without GDB-internal TLS support. Additional complications +# arise from when testing on x86_64 with -m32, which tends to work +# okay on GLIBC 2.34 and newer, but not older versions. It gets messy +# to properly sort out all of these cases.) +# +# This test was originally written to do it both ways, i.e. with both +# both gdb_compile and gdb_compile_pthreads, but the point of this +# test is to check that the link map address to TLS module id mapping +# code works correctly in programs which use lots of dlopen and +# dlclose calls in various orders - and that can be done using just +# gdb_compile_pthreads. + +if { [gdb_compile_pthreads "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable \ + [list debug shlib_load \ + shlib=${lib10obj} \ + shlib=${lib11obj} \ + additional_flags=-DOBJ1=\"${lib1obj}\" \ + additional_flags=-DOBJ2=\"${lib2obj}\" \ + additional_flags=-DOBJ3=\"${lib3obj}\" \ + additional_flags=-DOBJ4=\"${lib4obj}\" \ + ]] != "" } { + untested "failed to compile" +} else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + do_tests $force_internal_tls + } +} diff --git a/gdb/testsuite/gdb.base/tls-multiobj.c b/gdb/testsuite/gdb.base/tls-multiobj.c new file mode 100644 index 0000000..10e67da --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-multiobj.c @@ -0,0 +1,89 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +__thread int tls_main_tbss_1; +__thread int tls_main_tbss_2; +__thread int tls_main_tdata_1 = 96; +__thread int tls_main_tdata_2 = 97; + +extern __thread int tls_lib1_tbss_1; +extern __thread int tls_lib1_tbss_2; +extern __thread int tls_lib1_tdata_1; +extern __thread int tls_lib1_tdata_2; + +extern __thread int tls_lib2_tbss_1; +extern __thread int tls_lib2_tbss_2; +extern __thread int tls_lib2_tdata_1; +extern __thread int tls_lib2_tdata_2; + +extern __thread int tls_lib3_tbss_1; +extern __thread int tls_lib3_tbss_2; +extern __thread int tls_lib3_tdata_1; +extern __thread int tls_lib3_tdata_2; + +extern void lib1_func (); +extern void lib2_func (); +extern void lib3_func (); + +volatile int data; + +void +use_it (int a) +{ + data = a; +} + +int +main (int argc, char **argv) +{ + use_it (-1); + + tls_main_tbss_1 = 51; /* main-breakpoint-1 */ + tls_main_tbss_2 = 52; + tls_main_tdata_1 = 53; + tls_main_tdata_2 = 54; + + tls_lib1_tbss_1 = 151; + tls_lib1_tbss_2 = 152; + tls_lib1_tdata_1 = 153; + tls_lib1_tdata_2 = 154; + + tls_lib2_tbss_1 = 251; + tls_lib2_tbss_2 = 252; + tls_lib2_tdata_1 = 253; + tls_lib2_tdata_2 = 254; + + tls_lib3_tbss_1 = 351; + tls_lib3_tbss_2 = 352; + tls_lib3_tdata_1 = 353; + tls_lib3_tdata_2 = 354; + + lib1_func (); + lib2_func (); + lib3_func (); + + /* Attempt to keep variables in the main program from being optimized + away. */ + use_it (tls_main_tbss_1); + use_it (tls_main_tbss_2); + use_it (tls_main_tdata_1); + use_it (tls_main_tdata_2); + + use_it (100); /* main-breakpoint-2 */ + + return 0; +} diff --git a/gdb/testsuite/gdb.base/tls-multiobj.exp b/gdb/testsuite/gdb.base/tls-multiobj.exp new file mode 100644 index 0000000..97acb33 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-multiobj.exp @@ -0,0 +1,230 @@ +# Copyright 2024 Free Software Foundation, Inc. +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +# Using different compilation/linking scenarios, attempt to access +# thread-local variables in a non-threaded program using multiple +# shared objects. + +source $srcdir/$subdir/tls-common.exp.tcl + +standard_testfile + +set lib1src "${srcdir}/${subdir}/${testfile}1.c" +set lib2src "${srcdir}/${subdir}/${testfile}2.c" +set lib3src "${srcdir}/${subdir}/${testfile}3.c" + +set lib1obj [standard_output_file "${testfile}1-lib.so"] +set lib2obj [standard_output_file "${testfile}2-lib.so"] +set lib3obj [standard_output_file "${testfile}3-lib.so"] + +proc do_tests {force_internal_tls {do_kfail_tls_access 0}} { + clean_restart $::binfile + if ![runto_main] { + return + } + + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + if { $do_kfail_tls_access && [istarget "*-*-linux*"] } { + # Turn off do_kfail_tls_access when libthread_db is loaded. + # This can happen for the default case when testing x86_64 + # w/ -m32 using glibc versions 2.34 or newer. + gdb_test_multiple "maint check libthread-db" "Check for loaded libthread_db" { + -re -wrap "libthread_db integrity checks passed." { + set do_kfail_tls_access 0 + pass $gdb_test_name + } + -re -wrap "No libthread_db loaded" { + pass $gdb_test_name + } + } + # Also turn off do_kfail_tls_access when connected to a + # gdbserver and we observe that accessing a TLS variable + # works. + if [target_is_gdbserver] { + gdb_test_multiple "print tls_main_tbss_1" \ + "Check TLS accessibility when connected to a gdbserver" { + -re -wrap "= 0" { + set do_kfail_tls_access 0 + pass $gdb_test_name + } + -re -wrap "Remote target failed to process qGetTLSAddr request" { + pass $gdb_test_name + } + } + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-1"] + gdb_continue_to_breakpoint "main-breakpoint-1" + + set t $do_kfail_tls_access + set m "tls not available" + with_test_prefix "before assignments" { + gdb_test_with_kfail "print tls_main_tbss_1" ".* = 0" $t $m + gdb_test_with_kfail "print tls_main_tbss_2" ".* = 0" $t $m + gdb_test_with_kfail "print tls_main_tdata_1" ".* = 96" $t $m + gdb_test_with_kfail "print tls_main_tdata_2" ".* = 97" $t $m + + gdb_test_with_kfail "print tls_lib1_tbss_1" ".* = 0" $t $m + gdb_test_with_kfail "print tls_lib1_tbss_2" ".* = 0" $t $m + gdb_test_with_kfail "print tls_lib1_tdata_1" ".* = 196" $t $m + gdb_test_with_kfail "print tls_lib1_tdata_2" ".* = 197" $t $m + + gdb_test_with_kfail "print tls_lib2_tbss_1" ".* = 0" $t $m + gdb_test_with_kfail "print tls_lib2_tbss_2" ".* = 0" $t $m + gdb_test_with_kfail "print tls_lib2_tdata_1" ".* = 296" $t $m + gdb_test_with_kfail "print tls_lib2_tdata_2" ".* = 297" $t $m + + gdb_test_with_kfail "print tls_lib3_tbss_1" ".* = 0" $t $m + gdb_test_with_kfail "print tls_lib3_tbss_2" ".* = 0" $t $m + gdb_test_with_kfail "print tls_lib3_tdata_1" ".* = 396" $t $m + gdb_test_with_kfail "print tls_lib3_tdata_2" ".* = 397" $t $m + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-2"] + gdb_continue_to_breakpoint "main-breakpoint-2" + + with_test_prefix "after assignments" { + gdb_test_with_kfail "print tls_main_tbss_1" ".* = 51" $t $m + gdb_test_with_kfail "print tls_main_tbss_2" ".* = 52" $t $m + gdb_test_with_kfail "print tls_main_tdata_1" ".* = 53" $t $m + gdb_test_with_kfail "print tls_main_tdata_2" ".* = 54" $t $m + + gdb_test_with_kfail "print tls_lib1_tbss_1" ".* = 151" $t $m + gdb_test_with_kfail "print tls_lib1_tbss_2" ".* = 152" $t $m + gdb_test_with_kfail "print tls_lib1_tdata_1" ".* = 153" $t $m + gdb_test_with_kfail "print tls_lib1_tdata_2" ".* = 154" $t $m + + gdb_test_with_kfail "print tls_lib2_tbss_1" ".* = 251" $t $m + gdb_test_with_kfail "print tls_lib2_tbss_2" ".* = 252" $t $m + gdb_test_with_kfail "print tls_lib2_tdata_1" ".* = 253" $t $m + gdb_test_with_kfail "print tls_lib2_tdata_2" ".* = 254" $t $m + + gdb_test_with_kfail "print tls_lib3_tbss_1" ".* = 351" $t $m + gdb_test_with_kfail "print tls_lib3_tbss_2" ".* = 352" $t $m + gdb_test_with_kfail "print tls_lib3_tdata_1" ".* = 353" $t $m + gdb_test_with_kfail "print tls_lib3_tdata_2" ".* = 354" $t $m + } + + set corefile ${::binfile}.core + set core_supported 0 + if { ![is_remote host] } { + set core_supported [gdb_gcore_cmd $corefile "save corefile"] + } + + # Finish test early if no core file was made. + if !$core_supported { + return + } + + clean_restart $::binfile + + set core_loaded [gdb_core_cmd $corefile "load corefile"] + if { $core_loaded == -1 } { + return + } + + with_test_prefix "core file" { + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + gdb_test_with_kfail "print tls_main_tbss_1" ".* = 51" $t $m + gdb_test_with_kfail "print tls_main_tbss_2" ".* = 52" $t $m + gdb_test_with_kfail "print tls_main_tdata_1" ".* = 53" $t $m + gdb_test_with_kfail "print tls_main_tdata_2" ".* = 54" $t $m + + gdb_test_with_kfail "print tls_lib1_tbss_1" ".* = 151" $t $m + gdb_test_with_kfail "print tls_lib1_tbss_2" ".* = 152" $t $m + gdb_test_with_kfail "print tls_lib1_tdata_1" ".* = 153" $t $m + gdb_test_with_kfail "print tls_lib1_tdata_2" ".* = 154" $t $m + + gdb_test_with_kfail "print tls_lib2_tbss_1" ".* = 251" $t $m + gdb_test_with_kfail "print tls_lib2_tbss_2" ".* = 252" $t $m + gdb_test_with_kfail "print tls_lib2_tdata_1" ".* = 253" $t $m + gdb_test_with_kfail "print tls_lib2_tdata_2" ".* = 254" $t $m + + gdb_test_with_kfail "print tls_lib3_tbss_1" ".* = 351" $t $m + gdb_test_with_kfail "print tls_lib3_tbss_2" ".* = 352" $t $m + gdb_test_with_kfail "print tls_lib3_tdata_1" ".* = 353" $t $m + gdb_test_with_kfail "print tls_lib3_tdata_2" ".* = 354" $t $m + } +} + +if { [gdb_compile_shlib $lib1src $lib1obj {debug}] != "" } { + untested "failed to compile shared object" + return -1 +} +if { [gdb_compile_shlib $lib2src $lib2obj {debug}] != "" } { + untested "failed to compile shared object" + return -1 +} +if { [gdb_compile_shlib $lib3src $lib3obj {debug}] != "" } { + untested "failed to compile shared object" + return -1 +} + +# Certain linux target architectures implement support for internal +# TLS lookup which is used when thread stratum support (via +# libthread_db) is missing or when the linux-only GDB maintenance +# setting 'force-internal-tls-address-lookup' is 'on'. Thus for some +# of the testing scenarios, such as statically linked executables, +# this internal support will be used. Set 'do_kfail_tls_access' to 1 +# for those architectures which don't implement internal tls support. +if {[istarget *-*-linux*] + && ![is_any_target {*}$internal_tls_linux_targets]} { + set do_kfail_tls_access 1 +} elseif {[istarget *-*-linux*] && [is_x86_like_target]} { + # This covers the case of x86_64 with -m32: + set do_kfail_tls_access 1 +} else { + set do_kfail_tls_access 0 +} + +set binprefix $binfile + +with_test_prefix "default" { + set binfile $binprefix-default + if { [gdb_compile "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable \ + [list debug shlib=${lib1obj} \ + shlib=${lib2obj} \ + shlib=${lib3obj}]] != "" } { + untested "failed to compile" + } else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + # Depending on glibc version, it might not be appropriate + # for do_kfail_tls_access to be set here. That will be + # handled in 'do_tests', disabling it if necessary. + # + # Specifically, glibc versions 2.34 and later have the + # thread library (and libthread_db availability) in + # programs not linked against libpthread.so + do_tests $force_internal_tls $do_kfail_tls_access + } + } +} + +with_test_prefix "pthreads" { + set binfile $binprefix-pthreads + if { [gdb_compile_pthreads "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable \ + [list debug shlib=${lib1obj} \ + shlib=${lib2obj} \ + shlib=${lib3obj}]] != "" } { + untested "failed to compile" + } else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + do_tests $force_internal_tls + } + } +} diff --git a/gdb/testsuite/gdb.base/tls-multiobj1.c b/gdb/testsuite/gdb.base/tls-multiobj1.c new file mode 100644 index 0000000..86e7222 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-multiobj1.c @@ -0,0 +1,26 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +__thread int tls_lib1_tbss_1; +__thread int tls_lib1_tbss_2; +__thread int tls_lib1_tdata_1 = 196; +__thread int tls_lib1_tdata_2 = 197; + +void +lib1_func () +{ +} diff --git a/gdb/testsuite/gdb.base/tls-multiobj2.c b/gdb/testsuite/gdb.base/tls-multiobj2.c new file mode 100644 index 0000000..cea0709 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-multiobj2.c @@ -0,0 +1,26 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +__thread int tls_lib2_tbss_1; +__thread int tls_lib2_tbss_2; +__thread int tls_lib2_tdata_1 = 296; +__thread int tls_lib2_tdata_2 = 297; + +void +lib2_func () +{ +} diff --git a/gdb/testsuite/gdb.base/tls-multiobj3.c b/gdb/testsuite/gdb.base/tls-multiobj3.c new file mode 100644 index 0000000..bb0f239 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-multiobj3.c @@ -0,0 +1,26 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +__thread int tls_lib3_tbss_1; +__thread int tls_lib3_tbss_2; +__thread int tls_lib3_tdata_1 = 396; +__thread int tls_lib3_tdata_2 = 397; + +void +lib3_func () +{ +} diff --git a/gdb/testsuite/gdb.base/tls-nothreads.c b/gdb/testsuite/gdb.base/tls-nothreads.c new file mode 100644 index 0000000..b3aaa33 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-nothreads.c @@ -0,0 +1,57 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2024 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +__thread int tls_tbss_1; +__thread int tls_tbss_2; +__thread int tls_tbss_3; + +__thread int tls_tdata_1 = 21; +__thread int tls_tdata_2 = 22; +__thread int tls_tdata_3 = 23; + +volatile int data; + +void +use_it (int a) +{ + data = a; +} + +int +main (int argc, char **argv) +{ + use_it (-1); + + tls_tbss_1 = 24; /* main-breakpoint-1 */ + tls_tbss_2 = 25; + tls_tbss_3 = 26; + + tls_tdata_1 = 42; + tls_tdata_2 = 43; + tls_tdata_3 = 44; + + use_it (tls_tbss_1); + use_it (tls_tbss_2); + use_it (tls_tbss_3); + use_it (tls_tdata_1); + use_it (tls_tdata_2); + use_it (tls_tdata_3); + + use_it (100); /* main-breakpoint-2 */ + + return 0; +} diff --git a/gdb/testsuite/gdb.base/tls-nothreads.exp b/gdb/testsuite/gdb.base/tls-nothreads.exp new file mode 100644 index 0000000..92a5cd9 --- /dev/null +++ b/gdb/testsuite/gdb.base/tls-nothreads.exp @@ -0,0 +1,248 @@ +# Copyright 2024 Free Software Foundation, Inc. +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. + +# Using different compilation/linking scenarios, attempt to access +# thread-local variables in a non-threaded program. Also test that +# GDB internal TLS lookup works correctly. + +source $srcdir/$subdir/tls-common.exp.tcl + +standard_testfile + +proc do_tests {force_internal_tls {do_kfail_tls_access 0}} { + clean_restart $::binfile + if ![runto_main] { + return + } + + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + if { $do_kfail_tls_access && [istarget "*-*-linux*"] } { + # Turn off do_kfail_tls_access when libthread_db is loaded. + # This can happen for the default case when testing x86_64 + # w/ -m32 using glibc versions 2.34 or newer. + gdb_test_multiple "maint check libthread-db" "Check for loaded libthread_db" { + -re -wrap "libthread_db integrity checks passed." { + set do_kfail_tls_access 0 + pass $gdb_test_name + } + -re -wrap "No libthread_db loaded" { + pass $gdb_test_name + } + } + # Also turn off do_kfail_tls_access when connected to a + # gdbserver and we observe that accessing a TLS variable + # works. + if [target_is_gdbserver] { + gdb_test_multiple "print tls_tbss_1" "Check TLS accessibility when connected to a gdbserver" { + -re -wrap "= 0" { + set do_kfail_tls_access 0 + pass $gdb_test_name + } + -re -wrap "Remote target failed to process qGetTLSAddr request" { + pass $gdb_test_name + } + } + } + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-1"] + gdb_continue_to_breakpoint "main-breakpoint-1" + + set t $do_kfail_tls_access + set m "tls not available" + with_test_prefix "before assignments" { + gdb_test_with_kfail "print tls_tbss_1" ".* = 0" $t $m + gdb_test_with_kfail "print tls_tbss_2" ".* = 0" $t $m + gdb_test_with_kfail "print tls_tbss_3" ".* = 0" $t $m + + gdb_test_with_kfail "print tls_tdata_1" ".* = 21" $t $m + gdb_test_with_kfail "print tls_tdata_2" ".* = 22" $t $m + gdb_test_with_kfail "print tls_tdata_3" ".* = 23" $t $m + } + + gdb_breakpoint [gdb_get_line_number "main-breakpoint-2"] + gdb_continue_to_breakpoint "main-breakpoint-2" + + with_test_prefix "after assignments" { + gdb_test_with_kfail "print tls_tbss_1" ".* = 24" $t $m + gdb_test_with_kfail "print tls_tbss_2" ".* = 25" $t $m + gdb_test_with_kfail "print tls_tbss_3" ".* = 26" $t $m + + gdb_test_with_kfail "print tls_tdata_1" ".* = 42" $t $m + gdb_test_with_kfail "print tls_tdata_2" ".* = 43" $t $m + gdb_test_with_kfail "print tls_tdata_3" ".* = 44" $t $m + } + + # Make a core file now, but save testing using it until the end + # in case core files are not supported. + set corefile ${::binfile}.core + set core_supported 0 + if { ![is_remote host] } { + set core_supported [gdb_gcore_cmd $corefile "save corefile"] + } + + # Now continue to end and see what happens when attempting to + # access a TLS variable when the program is no longer running. + gdb_continue_to_end + with_test_prefix "after exit" { + gdb_test "print tls_tbss_1" \ + "Cannot (?:read|find address of TLS symbol) `tls_tbss_1' without registers" + } + + with_test_prefix "stripped" { + set binfile_stripped "${::binfile}.stripped" + set objcopy [gdb_find_objcopy] + set cmd "$objcopy --strip-debug ${::binfile} $binfile_stripped" + if ![catch "exec $cmd" cmd_output] { + clean_restart $binfile_stripped + if ![runto_main] { + return + } + + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + # While there are no debug (e.g. DWARF) symbols, there + # are minimal symbols, so we should be able to place a + # breakpoint in use_it and continue to it. Continuing + # twice should put us past the assignments, at which point + # we can see if the TLS variables are still accessible. + gdb_test "break use_it" "Breakpoint 2 at $::hex" + gdb_test "continue" "Breakpoint 2, $::hex in use_it.*" + gdb_test "continue" "Breakpoint 2, $::hex in use_it.*" "continue 2" + + # Note that a cast has been added in order to avoid the + # "...has unknown type; cast it to its declared type" + # problem. + gdb_test_with_kfail "print (int) tls_tbss_1" ".* = 24" $t $m + gdb_test_with_kfail "print (int) tls_tbss_2" ".* = 25" $t $m + gdb_test_with_kfail "print (int) tls_tbss_3" ".* = 26" $t $m + + gdb_test_with_kfail "print (int) tls_tdata_1" ".* = 42" $t $m + gdb_test_with_kfail "print (int) tls_tdata_2" ".* = 43" $t $m + gdb_test_with_kfail "print (int) tls_tdata_3" ".* = 44" $t $m + + # Get rid of the "use_it" breakpoint + gdb_test_no_output "del 2" + + # Continue to program exit + gdb_continue_to_end + + # TLS variables should not be accessible after program exit + # (This case initially caused GDB to crash during development + # of GDB-internal TLS lookup support.) + with_test_prefix "after exit" { + gdb_test "print (int) tls_tbss_1" \ + "Cannot find address of TLS symbol `tls_tbss_1' without registers" + } + } + } + + # Finish test early if no core file was made. + if !$core_supported { + return + } + + clean_restart $::binfile + + set core_loaded [gdb_core_cmd $corefile "load corefile"] + if { $core_loaded == -1 } { + return + } + + with_test_prefix "core file" { + if $force_internal_tls { + gdb_test_no_output "maint set force-internal-tls-address-lookup on" + } + + gdb_test_with_kfail "print tls_tbss_1" ".* = 24" $t $m + gdb_test_with_kfail "print tls_tbss_2" ".* = 25" $t $m + gdb_test_with_kfail "print tls_tbss_3" ".* = 26" $t $m + + gdb_test_with_kfail "print tls_tdata_1" ".* = 42" $t $m + gdb_test_with_kfail "print tls_tdata_2" ".* = 43" $t $m + gdb_test_with_kfail "print tls_tdata_3" ".* = 44" $t $m + } +} + +# Certain linux target architectures implement support for internal +# TLS lookup which is used when thread stratum support (via +# libthread_db) is missing or when the linux-only GDB maintenance +# setting 'force-internal-tls-address-lookup' is 'on'. Thus for some +# of the testing scenarios, such as statically linked executables, +# this internal support will be used. Set 'do_kfail_tls_access' to 1 +# for those architectures which don't implement internal TLS support. +if {[istarget *-*-linux*] + && ![is_any_target {*}$internal_tls_linux_targets]} { + set do_kfail_tls_access 1 +} elseif {[istarget *-*-linux*] && [is_x86_like_target]} { + # This covers the case of x86_64 with -m32: + set do_kfail_tls_access 1 +} else { + set do_kfail_tls_access 0 +} + +set binprefix $binfile + +with_test_prefix "default" { + set binfile $binprefix-default + if { [gdb_compile "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable {debug}] != "" } { + untested "failed to compile" + } else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + # Depending on glibc version, it might not be appropriate + # for do_kfail_tls_access to be set here. That will be + # handled in 'do_tests', disabling it if necessary. + # + # Specifically, glibc versions 2.34 and later have the + # thread library (and libthread_db availability) in + # programs not linked against libpthread.so + do_tests $force_internal_tls $do_kfail_tls_access + } + } +} + +with_test_prefix "static" { + set binfile $binprefix-static + if { [gdb_compile "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable {debug "additional_flags=-static"}] != "" } { + untested "failed to compile" + } else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + do_tests $force_internal_tls $do_kfail_tls_access + } + } +} + +with_test_prefix "pthreads" { + set binfile $binprefix-pthreads + if { [gdb_compile_pthreads "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable {debug}] != "" } { + untested "failed to compile" + } else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + do_tests $force_internal_tls + } + } +} + +with_test_prefix "pthreads-static" { + set binfile $binprefix-pthreads-static + if { [gdb_compile_pthreads "${srcdir}/${subdir}/${srcfile}" "${binfile}" executable {debug "additional_flags=-static"}] != "" } { + untested "failed to compile" + } else { + foreach_with_prefix force_internal_tls $internal_tls_iters { + do_tests $force_internal_tls $do_kfail_tls_access + } + } +} diff --git a/gdb/testsuite/gdb.cp/cplusfuncs.exp b/gdb/testsuite/gdb.cp/cplusfuncs.exp index 94d9df3..e785909 100644 --- a/gdb/testsuite/gdb.cp/cplusfuncs.exp +++ b/gdb/testsuite/gdb.cp/cplusfuncs.exp @@ -579,7 +579,8 @@ proc do_tests {} { gdb_test_no_output "set width 0" - runto_main + # Don't run to main, to avoid loading and expanding debug info for + # libstdc++. gdb_test_no_output "set language c++" probe_demangler diff --git a/gdb/testsuite/gdb.debuginfod/fetch_src_and_symbols.exp b/gdb/testsuite/gdb.debuginfod/fetch_src_and_symbols.exp index 7b36f65..4b3894e 100644 --- a/gdb/testsuite/gdb.debuginfod/fetch_src_and_symbols.exp +++ b/gdb/testsuite/gdb.debuginfod/fetch_src_and_symbols.exp @@ -152,7 +152,7 @@ proc_with_prefix no_url { } { # Test that GDB cannot find dwz without debuginfod. clean_restart gdb_test "file ${binfile}_alt.o" \ - ".*could not find '.gnu_debugaltlink'.*" \ + ".*could not find supplementary DWARF file .*" \ "file [file tail ${binfile}_alt.o]" # Generate a core file and test that GDB cannot find the diff --git a/gdb/testsuite/gdb.dwarf2/dwzbuildid.exp b/gdb/testsuite/gdb.dwarf2/dwzbuildid.exp index 055e69c..080e999 100644 --- a/gdb/testsuite/gdb.dwarf2/dwzbuildid.exp +++ b/gdb/testsuite/gdb.dwarf2/dwzbuildid.exp @@ -13,160 +13,5 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -load_lib dwarf.exp - -# This test can only be run on targets which support DWARF-2 and use gas. -require dwarf2_support - -# No remote host testing either. -require {!is_remote host} - - -# Lots of source files since we test a few cases and make new files -# for each. -# The tests are: -# ok - the main file refers to a dwz and the buildids match -# mismatch - the buildids do not match -# fallback - the buildids do not match but a match is found via buildid -standard_testfile main.c \ - dwzbuildid-ok-base.S dwzbuildid-ok-sep.S \ - dwzbuildid-mismatch-base.S dwzbuildid-mismatch-sep.S \ - dwzbuildid-fallback-base.S dwzbuildid-fallback-sep.S \ - dwzbuildid-fallback-ok.S - -# Write some assembly that just has a .gnu_debugaltlink section. -proc write_just_debugaltlink {filename dwzname buildid} { - set asm_file [standard_output_file $filename] - - Dwarf::assemble $asm_file { - upvar dwzname dwzname - upvar buildid buildid - - gnu_debugaltlink $dwzname $buildid - - # Only the DWARF reader checks .gnu_debugaltlink, so make sure - # there is a bit of DWARF in here. - cu { label cu_start } { - compile_unit {{language @DW_LANG_C}} { - } - } - aranges {} cu_start { - arange {} 0 0 - } - } -} - -# Write some DWARF that also sets the buildid. -proc write_dwarf_file {filename buildid {value 99}} { - set asm_file [standard_output_file $filename] - - Dwarf::assemble $asm_file { - declare_labels int_label int_label2 - - upvar buildid buildid - upvar value value - - build_id $buildid - - cu { label cu_start } { - compile_unit {{language @DW_LANG_C}} { - int_label2: base_type { - {name int} - {byte_size 4 sdata} - {encoding @DW_ATE_signed} - } - - constant { - {name the_int} - {type :$int_label2} - {const_value $value data1} - } - } - } - - aranges {} cu_start { - arange {} 0 0 - } - } -} - -if { [gdb_compile ${srcdir}/${subdir}/${srcfile} ${binfile}1.o \ - object {nodebug}] != "" } { - return -1 -} - -# The values don't really matter, just whether they are equal. -set ok_prefix 01 -set ok_suffix 02030405060708091011121314151617181920 -set ok_suffix2 020304050607080910111213141516171819ff -set ok_buildid ${ok_prefix}${ok_suffix} -set ok_buildid2 ${ok_prefix}${ok_suffix2} -set bad_buildid [string repeat ff 20] - -set debugdir [standard_output_file {}] -set basedir $debugdir/.build-id -file mkdir $basedir $basedir/$ok_prefix - -# Test where the separate debuginfo's buildid matches. -write_just_debugaltlink $srcfile2 ${binfile}3.o $ok_buildid -write_dwarf_file $srcfile3 $ok_buildid - -# Test where the separate debuginfo's buildid does not match. -write_just_debugaltlink $srcfile4 ${binfile}5.o $ok_buildid -write_dwarf_file $srcfile5 $bad_buildid - -# Test where the separate debuginfo's buildid does not match, but then -# we find a match in the .build-id directory. -write_just_debugaltlink $srcfile6 ${binfile}7.o $ok_buildid2 -# Use 77 as the value so that if we load the bad debuginfo, we will -# see the wrong result. -write_dwarf_file $srcfile7 $bad_buildid 77 -write_dwarf_file $srcfile8 $ok_buildid2 - -# Compile everything. -for {set i 2} {$i <= 8} {incr i} { - if {[gdb_compile [standard_output_file [set srcfile$i]] \ - ${binfile}$i.o object nodebug] != ""} { - return -1 - } -} - -# Copy a file into the .build-id place for the "fallback" test. -file copy -force -- ${binfile}8.o $basedir/$ok_prefix/$ok_suffix2.debug - -proc do_test {} { - clean_restart - - gdb_test_no_output "set debug-file-directory $::debugdir" \ - "set debug-file-directory" - - gdb_load ${::binfile}-${::testname} - - if {![runto_main]} { - return - } - - if {$::testname == "mismatch"} { - gdb_test "print the_int" \ - "(No symbol table is loaded|No symbol \"the_int\" in current context).*" - } else { - gdb_test "print the_int" " = 99" - } -} - -foreach_with_prefix testname { ok mismatch fallback } { - if { $testname == "ok" } { - set objs [list ${binfile}1.o ${binfile}2.o] - } elseif { $testname == "mismatch" } { - set objs [list ${binfile}1.o ${binfile}4.o] - } elseif { $testname == "fallback" } { - set objs [list ${binfile}1.o ${binfile}6.o] - } - - if {[gdb_compile $objs ${binfile}-$testname executable {quiet}] != ""} { - unsupported "compilation failed" - continue - } - - do_test -} +set scenario gnu +source $srcdir/$subdir/dwzbuildid.tcl diff --git a/gdb/testsuite/gdb.dwarf2/dwzbuildid.tcl b/gdb/testsuite/gdb.dwarf2/dwzbuildid.tcl new file mode 100644 index 0000000..a9077eb --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/dwzbuildid.tcl @@ -0,0 +1,184 @@ +# Copyright 2013-2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +load_lib dwarf.exp + +# This test can only be run on targets which support DWARF-2 and use gas. +require dwarf2_support + +# No remote host testing either. +require {!is_remote host} + + +# Lots of source files since we test a few cases and make new files +# for each. +# The tests are: +# ok - the main file refers to a dwz and the buildids match +# mismatch - the buildids do not match +# fallback - the buildids do not match but a match is found via buildid +standard_testfile main.c \ + dwzbuildid-ok-base.S dwzbuildid-ok-sep.S \ + dwzbuildid-mismatch-base.S dwzbuildid-mismatch-sep.S \ + dwzbuildid-fallback-base.S dwzbuildid-fallback-sep.S \ + dwzbuildid-fallback-ok.S + +# Write some assembly that just has a .gnu_debugaltlink section. +proc write_just_debugaltlink {filename dwzname buildid} { + set asm_file [standard_output_file $filename] + + Dwarf::assemble $asm_file { + upvar dwzname dwzname + upvar buildid buildid + + if {$::scenario == "gnu"} { + gnu_debugaltlink $dwzname $buildid + } else { + debug_sup 0 $dwzname $buildid + } + + # Only the DWARF reader checks .gnu_debugaltlink, so make sure + # there is a bit of DWARF in here. + cu { label cu_start } { + compile_unit {{language @DW_LANG_C}} { + } + } + aranges {} cu_start { + arange {} 0 0 + } + } +} + +# Write some DWARF that also sets the buildid. +proc write_dwarf_file {filename buildid {value 99}} { + set asm_file [standard_output_file $filename] + + Dwarf::assemble $asm_file { + declare_labels int_label int_label2 + + upvar buildid buildid + upvar value value + + if {$::scenario == "gnu"} { + build_id $buildid + } else { + debug_sup 1 "" $buildid + } + + cu { label cu_start } { + compile_unit {{language @DW_LANG_C}} { + int_label2: base_type { + {name int} + {byte_size 4 sdata} + {encoding @DW_ATE_signed} + } + + constant { + {name the_int} + {type :$int_label2} + {const_value $value data1} + } + } + } + + aranges {} cu_start { + arange {} 0 0 + } + } +} + +if { [gdb_compile ${srcdir}/${subdir}/${srcfile} ${binfile}1.o \ + object {nodebug}] != "" } { + return -1 +} + +# The values don't really matter, just whether they are equal. +set ok_prefix 01 +set ok_suffix 02030405060708091011121314151617181920 +set ok_suffix2 020304050607080910111213141516171819ff +set ok_buildid ${ok_prefix}${ok_suffix} +set ok_buildid2 ${ok_prefix}${ok_suffix2} +set bad_buildid [string repeat ff 20] + +set debugdir [standard_output_file {}] +set basedir $debugdir/.build-id +file mkdir $basedir $basedir/$ok_prefix + +# Test where the separate debuginfo's buildid matches. +write_just_debugaltlink $srcfile2 ${binfile}3.o $ok_buildid +write_dwarf_file $srcfile3 $ok_buildid + +# Test where the separate debuginfo's buildid does not match. +write_just_debugaltlink $srcfile4 ${binfile}5.o $ok_buildid +write_dwarf_file $srcfile5 $bad_buildid + +# Test where the separate debuginfo's buildid does not match, but then +# we find a match in the .build-id directory. +write_just_debugaltlink $srcfile6 ${binfile}7.o $ok_buildid2 +# Use 77 as the value so that if we load the bad debuginfo, we will +# see the wrong result. +write_dwarf_file $srcfile7 $bad_buildid 77 +write_dwarf_file $srcfile8 $ok_buildid2 + +# Compile everything. +for {set i 2} {$i <= 8} {incr i} { + if {[gdb_compile [standard_output_file [set srcfile$i]] \ + ${binfile}$i.o object nodebug] != ""} { + return -1 + } +} + +# Copy a file into the .build-id place for the "fallback" test. +file copy -force -- ${binfile}8.o $basedir/$ok_prefix/$ok_suffix2.debug + +proc do_test {} { + clean_restart + + gdb_test_no_output "set debug-file-directory $::debugdir" \ + "set debug-file-directory" + + gdb_load ${::binfile}-${::testname} + + if {![runto_main]} { + return + } + + if {$::testname == "mismatch"} { + gdb_test "print the_int" \ + "(No symbol table is loaded|No symbol \"the_int\" in current context).*" + } else { + gdb_test "print the_int" " = 99" + } +} + +set tests {ok mismatch} +if {$scenario == "gnu"} { + lappend tests fallback +} +foreach_with_prefix testname $tests { + if { $testname == "ok" } { + set objs [list ${binfile}1.o ${binfile}2.o] + } elseif { $testname == "mismatch" } { + set objs [list ${binfile}1.o ${binfile}4.o] + } elseif { $testname == "fallback" } { + set objs [list ${binfile}1.o ${binfile}6.o] + } + + if {[gdb_compile $objs ${binfile}-$testname executable {quiet}] != ""} { + unsupported "compilation failed" + continue + } + + do_test +} diff --git a/gdb/testsuite/gdb.dwarf2/dwzbuildid5.exp b/gdb/testsuite/gdb.dwarf2/dwzbuildid5.exp new file mode 100644 index 0000000..047626c --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/dwzbuildid5.exp @@ -0,0 +1,17 @@ +# Copyright 2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +set scenario dwarf5 +source $srcdir/$subdir/dwzbuildid.tcl diff --git a/gdb/testsuite/gdb.dwarf2/dwznolink.exp b/gdb/testsuite/gdb.dwarf2/dwznolink.exp index 91fe369..0c486ea 100644 --- a/gdb/testsuite/gdb.dwarf2/dwznolink.exp +++ b/gdb/testsuite/gdb.dwarf2/dwznolink.exp @@ -49,5 +49,5 @@ if {[build_executable $testfile.exp $testfile \ clean_restart gdb_test "file -readnow $binfile" \ - "could not read '.gnu_debugaltlink' section" \ + "could not find supplementary DWARF file" \ "file $testfile" diff --git a/gdb/testsuite/gdb.dwarf2/macro-source-path-clang14-dw4.exp b/gdb/testsuite/gdb.dwarf2/macro-source-path-clang14-dw4.exp new file mode 100644 index 0000000..c0c2635 --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/macro-source-path-clang14-dw4.exp @@ -0,0 +1,71 @@ +# This testcase is part of GDB, the GNU debugger. + +# Copyright 2022-2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Generate binaries imitating different ways source file paths can be passed to +# compilers. Test printing macros from those binaries. + +# The do_test proc comes from macro-source-path.exp.tcl. +source $srcdir/$subdir/macro-source-path.exp.tcl + +# When adding a test here, please consider adding an equivalent case to +# `gdb.base/macro-source-path.exp`. + +# The following tests are based on the output of `clang-14 -gdwarf-4 +# -fdebug-macro -g3 <file>` (using its built-in assembler). With -gdwarf-4, +# clang produces a .debug_macinfo section, not a .debug_macro section. But +# this test still creates a .debug_macro section, that's good enough for what +# we want to test. + +## test.c +do_test filename 4 "test.c" 1 { +} { + {"test.c" 0} +} + +## ./test.c +do_test dot-filename 4 "test.c" 1 { + "." +} { + {"test.c" 1} +} + +## ../cwd/test.c +do_test dot-dot-cwd 4 "../cwd/test.c" 1 { + "../cwd" +} { + {"test.c" 1} +} + +## /tmp/cwd/test.c +do_test absolute-cwd 4 "/tmp/cwd/test.c" 1 { +} { + {"test.c" 0} +} + +## ../other/test.c +do_test dot-dot-other 4 "../other/test.c" 1 { + "../other" +} { + {"test.c" 1} +} + +## /tmp/other/test.c +do_test absolute-other 4 "/tmp/other/test.c" 1 { + "/tmp" +} { + {"other/test.c" 1} +} diff --git a/gdb/testsuite/gdb.dwarf2/macro-source-path-clang14-dw5.exp b/gdb/testsuite/gdb.dwarf2/macro-source-path-clang14-dw5.exp new file mode 100644 index 0000000..0b3239e --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/macro-source-path-clang14-dw5.exp @@ -0,0 +1,75 @@ +# This testcase is part of GDB, the GNU debugger. + +# Copyright 2022-2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Generate binaries imitating different ways source file paths can be passed to +# compilers. Test printing macros from those binaries. + +# The do_test proc comes from macro-source-path.exp.tcl. +source $srcdir/$subdir/macro-source-path.exp.tcl + +# When adding a test here, please consider adding an equivalent case to +# `gdb.base/macro-source-path.exp`. + +# The following tests are based on the output of `clang-14 -gdwarf-5 +# -fdebug-macro -g3 <file>` (using its built-in assembler) + +## test.c +do_test filename 5 "test.c" 0 { + "/tmp/cwd" +} { + {"test.c" 0} +} + +## ./test.c +do_test dot-filename 5 "test.c" 1 { + "/tmp/cwd" + "." +} { + {"test.c" 0} + {"test.c" 1} +} + +## ../cwd/test.c +do_test dot-dot-cwd 5 "../cwd/test.c" 0 { + "/tmp/cwd" +} { + {"../cwd/test.c" 0} +} + +## /tmp/cwd/test.c +do_test absolute-cwd 5 "/tmp/cwd/test.c" 1 { + "/tmp/cwd" +} { + {"/tmp/cwd/test.c" 0} + {"test.c" 0} +} + +## ../other/test.c +do_test dot-dot-other 5 "../other/test.c" 0 { + "/tmp/cwd" +} { + {"../other/test.c" 0} +} + +## /tmp/other/test.c +do_test absolute-other 5 "/tmp/other/test.c" 1 { + "/tmp/cwd" + "/tmp" +} { + {"/tmp/other/test.c" 0} + {"other/test.c" 1} +} diff --git a/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld234-dw5.exp b/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld234-dw5.exp new file mode 100644 index 0000000..940f997 --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld234-dw5.exp @@ -0,0 +1,70 @@ +# This testcase is part of GDB, the GNU debugger. + +# Copyright 2022-2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Generate binaries imitating different ways source file paths can be passed to +# compilers. Test printing macros from those binaries. + +# The do_test proc comes from macro-source-path.exp.tcl. +source $srcdir/$subdir/macro-source-path.exp.tcl + +# When adding a test here, please consider adding an equivalent case to +# `gdb.base/macro-source-path.exp`. + +# The following tests are based on the output of `gcc -gdwarf-5 -g3 <file>`, +# gcc 11 paired with gas from binutils 2.34 (Ubuntu 20.04). It generates a v5 +# .debug_macro section, but a v3 .debug_line section. + +## test.c +do_test filename 3 "test.c" 1 { +} { + {"test.c" 0} +} + +## ./test.c +do_test dot-filename 3 "./test.c" 1 { + "." +} { + {"test.c" 1} +} + +## ../cwd/test.c +do_test dot-dot-cwd 3 "../cwd/test.c" 1 { + "../cwd" +} { + {"test.c" 1} +} + +## /tmp/cwd/test.c +do_test absolute-cwd 3 "/tmp/cwd/test.c" 1 { + "/tmp/cwd" +} { + {"test.c" 1} +} + +## ../other/test.c +do_test dot-dot-other 3 "../other/test.c" 1 { + "../other" +} { + {"test.c" 1} +} + +## /tmp/other/test.c +do_test absolute-other 3 "/tmp/other/test.c" 1 { + "/tmp/other" +} { + {"test.c" 1} +} diff --git a/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld238-dw4.exp b/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld238-dw4.exp new file mode 100644 index 0000000..dea0308 --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld238-dw4.exp @@ -0,0 +1,70 @@ +# This testcase is part of GDB, the GNU debugger. + +# Copyright 2022-2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Generate binaries imitating different ways source file paths can be passed to +# compilers. Test printing macros from those binaries. + +# The do_test proc comes from macro-source-path.exp.tcl. +source $srcdir/$subdir/macro-source-path.exp.tcl + +# When adding a test here, please consider adding an equivalent case to +# `gdb.base/macro-source-path.exp`. + +# The following tests are based on the output of `gcc -gdwarf-4 -g3 <file>`, +# gcc 11 paired with gas from binutils 2.38. With -gdwarf-4, gcc generates a +# v4 (pre-standard) .debug_macro section. + +## test.c +do_test filename 4 "test.c" 1 { +} { + {"test.c" 0} +} + +## ./test.c +do_test dot-filename 4 "./test.c" 1 { + "." +} { + {"test.c" 1} +} + +## ../cwd/test.c +do_test dot-dot-cwd 4 "../cwd/test.c" 1 { + "../cwd" +} { + {"test.c" 1} +} + +## /tmp/cwd/test.c +do_test absolute-cwd 4 "/tmp/cwd/test.c" 1 { + "/tmp/cwd" +} { + {"test.c" 1} +} + +## ../other/test.c +do_test dot-dot-other 4 "../other/test.c" 1 { + "../other" +} { + {"test.c" 1} +} + +## /tmp/other/test.c +do_test absolute-other 4 "/tmp/other/test.c" 1 { + "/tmp/other" +} { + {"test.c" 1} +} diff --git a/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld238-dw5.exp b/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld238-dw5.exp new file mode 100644 index 0000000..98a278e --- /dev/null +++ b/gdb/testsuite/gdb.dwarf2/macro-source-path-gcc11-ld238-dw5.exp @@ -0,0 +1,81 @@ +# This testcase is part of GDB, the GNU debugger. + +# Copyright 2022-2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Generate binaries imitating different ways source file paths can be passed to +# compilers. Test printing macros from those binaries. + +# The do_test proc comes from macro-source-path.exp.tcl. +source $srcdir/$subdir/macro-source-path.exp.tcl + +# When adding a test here, please consider adding an equivalent case to +# `gdb.base/macro-source-path.exp`. + +# The following tests are based on the output of `gcc -gdwarf-5 -g3 <file>`, +# gcc 11 paired with gas from binutils 2.38. + +## test.c +do_test filename 5 "test.c" 1 { + "/tmp/cwd" +} { + {"test.c" 0} + {"test.c" 0} +} + +## ./test.c +do_test dot-filename 5 "./test.c" 1 { + "/tmp/cwd" + "." +} { + {"test.c" 1} + {"test.c" 1} +} + +## ../cwd/test.c +do_test dot-dot-cwd 5 "../cwd/test.c" 1 { + "/tmp/cwd" + "../cwd" +} { + {"test.c" 1} + {"test.c" 1} +} + +## /tmp/cwd/test.c +do_test absolute-cwd 5 "/tmp/cwd/test.c" 1 { + "/tmp/cwd" + "/tmp/cwd" +} { + {"test.c" 1} + {"test.c" 0} +} + +## ../other/test.c +do_test dot-dot-other 5 "../other/test.c" 1 { + "/tmp/cwd" + "../other" +} { + {"test.c" 1} + {"test.c" 1} +} + +## /tmp/other/test.c +do_test absolute-other 5 "/tmp/other/test.c" 1 { + "/tmp/cwd" + "/tmp/other" +} { + {"test.c" 1} + {"test.c" 1} +} diff --git a/gdb/testsuite/gdb.dwarf2/macro-source-path.exp b/gdb/testsuite/gdb.dwarf2/macro-source-path.exp.tcl index 1318f8e..ecaf685 100644 --- a/gdb/testsuite/gdb.dwarf2/macro-source-path.exp +++ b/gdb/testsuite/gdb.dwarf2/macro-source-path.exp.tcl @@ -17,12 +17,15 @@ # Generate binaries imitating different ways source file paths can be passed to # compilers. Test printing macros from those binaries. +# +# The entry points for this test are in the various +# gdb.dwarf2/macro-source-path-*.exp files. load_lib dwarf.exp require dwarf2_support -standard_testfile .c +standard_testfile macro-source-path.c lassign [function_range main $srcdir/$subdir/$srcfile] \ main_start main_len @@ -160,248 +163,3 @@ proc do_test { test_name lines_version DW_AT_name main_file_idx directories } } } - -# When adding a test here, please consider adding an equivalent case to the test -# of the same name in gdb.base. - -# The following tests are based on the output of `gcc -gdwarf-5 -g3 <file>`, -# gcc 11 paired with gas from binutils 2.38. - -## test.c -do_test gcc11-ld238-dw5-filename 5 "test.c" 1 { - "/tmp/cwd" -} { - {"test.c" 0} - {"test.c" 0} -} - -## ./test.c -do_test gcc11-ld238-dw5-dot-filename 5 "./test.c" 1 { - "/tmp/cwd" - "." -} { - {"test.c" 1} - {"test.c" 1} -} - -## ../cwd/test.c -do_test gcc11-ld238-dw5-dot-dot-cwd 5 "../cwd/test.c" 1 { - "/tmp/cwd" - "../cwd" -} { - {"test.c" 1} - {"test.c" 1} -} - -## /tmp/cwd/test.c -do_test gcc11-ld238-dw5-absolute-cwd 5 "/tmp/cwd/test.c" 1 { - "/tmp/cwd" - "/tmp/cwd" -} { - {"test.c" 1} - {"test.c" 0} -} - -## ../other/test.c -do_test gcc11-ld238-dw5-dot-dot-other 5 "../other/test.c" 1 { - "/tmp/cwd" - "../other" -} { - {"test.c" 1} - {"test.c" 1} -} - -## /tmp/other/test.c -do_test gcc11-ld238-dw5-absolute-other 5 "/tmp/other/test.c" 1 { - "/tmp/cwd" - "/tmp/other" -} { - {"test.c" 1} - {"test.c" 1} -} - -# The following tests are based on the output of `gcc -gdwarf-4 -g3 <file>`, -# gcc 11 paired with gas from binutils 2.38. With -gdwarf-4, gcc generates a -# v4 (pre-standard) .debug_macro section. - -## test.c -do_test gcc11-ld238-dw4-filename 4 "test.c" 1 { -} { - {"test.c" 0} -} - -## ./test.c -do_test gcc11-ld238-dw4-dot-filename 4 "./test.c" 1 { - "." -} { - {"test.c" 1} -} - -## ../cwd/test.c -do_test gcc11-ld238-dw4-dot-dot-cwd 4 "../cwd/test.c" 1 { - "../cwd" -} { - {"test.c" 1} -} - -## /tmp/cwd/test.c -do_test gcc11-ld238-dw4-absolute-cwd 4 "/tmp/cwd/test.c" 1 { - "/tmp/cwd" -} { - {"test.c" 1} -} - -## ../other/test.c -do_test gcc11-ld238-dw4-dot-dot-other 4 "../other/test.c" 1 { - "../other" -} { - {"test.c" 1} -} - -## /tmp/other/test.c -do_test gcc11-ld238-dw4-absolute-other 4 "/tmp/other/test.c" 1 { - "/tmp/other" -} { - {"test.c" 1} -} - -# The following tests are based on the output of `clang-14 -gdwarf-5 -# -fdebug-macro -g3 <file>` (using its built-in assembler) - -## test.c -do_test clang14-dw5-filename 5 "test.c" 0 { - "/tmp/cwd" -} { - {"test.c" 0} -} - -## ./test.c -do_test clang14-dw5-dot-filename 5 "test.c" 1 { - "/tmp/cwd" - "." -} { - {"test.c" 0} - {"test.c" 1} -} - -## ../cwd/test.c -do_test clang14-dw5-dot-dot-cwd 5 "../cwd/test.c" 0 { - "/tmp/cwd" -} { - {"../cwd/test.c" 0} -} - -## /tmp/cwd/test.c -do_test clang14-dw5-absolute-cwd 5 "/tmp/cwd/test.c" 1 { - "/tmp/cwd" -} { - {"/tmp/cwd/test.c" 0} - {"test.c" 0} -} - -## ../other/test.c -do_test clang14-dw5-dot-dot-other 5 "../other/test.c" 0 { - "/tmp/cwd" -} { - {"../other/test.c" 0} -} - -## /tmp/other/test.c -do_test clang14-dw5-absolute-other 5 "/tmp/other/test.c" 1 { - "/tmp/cwd" - "/tmp" -} { - {"/tmp/other/test.c" 0} - {"other/test.c" 1} -} - -# The following tests are based on the output of `clang-14 -gdwarf-4 -# -fdebug-macro -g3 <file>` (using its built-in assembler). With -gdwarf-4, -# clang produces a .debug_macinfo section, not a .debug_macro section. But -# this test still creates a .debug_macro section, that's good enough for what -# we want to test. - -## test.c -do_test clang14-dw4-filename 4 "test.c" 1 { -} { - {"test.c" 0} -} - -## ./test.c -do_test clang14-dw4-dot-filename 4 "test.c" 1 { - "." -} { - {"test.c" 1} -} - -## ../cwd/test.c -do_test clang14-dw4-dot-dot-cwd 4 "../cwd/test.c" 1 { - "../cwd" -} { - {"test.c" 1} -} - -## /tmp/cwd/test.c -do_test clang14-dw4-absolute-cwd 4 "/tmp/cwd/test.c" 1 { -} { - {"test.c" 0} -} - -## ../other/test.c -do_test clang14-dw4-dot-dot-other 4 "../other/test.c" 1 { - "../other" -} { - {"test.c" 1} -} - -## /tmp/other/test.c -do_test clang14-dw4-absolute-other 4 "/tmp/other/test.c" 1 { - "/tmp" -} { - {"other/test.c" 1} -} - -# The following tests are based on the output of `gcc -gdwarf-5 -g3 <file>`, -# gcc 11 paired with gas from binutils 2.34 (Ubuntu 20.04). It generates a v5 -# .debug_macro section, but a v3 .debug_line section. - -## test.c -do_test gcc11-ld234-dw5-filename 3 "test.c" 1 { -} { - {"test.c" 0} -} - -## ./test.c -do_test gcc11-ld234-dw5-dot-filename 3 "./test.c" 1 { - "." -} { - {"test.c" 1} -} - -## ../cwd/test.c -do_test gcc11-ld234-dw5-dot-dot-cwd 3 "../cwd/test.c" 1 { - "../cwd" -} { - {"test.c" 1} -} - -## /tmp/cwd/test.c -do_test gcc11-ld234-dw5-absolute-cwd 3 "/tmp/cwd/test.c" 1 { - "/tmp/cwd" -} { - {"test.c" 1} -} - -## ../other/test.c -do_test gcc11-ld234-dw5-dot-dot-other 3 "../other/test.c" 1 { - "../other" -} { - {"test.c" 1} -} - -## /tmp/other/test.c -do_test gcc11-ld234-dw5-absolute-other 3 "/tmp/other/test.c" 1 { - "/tmp/other" -} { - {"test.c" 1} -} diff --git a/gdb/testsuite/gdb.dwarf2/no-gnu-debuglink.exp b/gdb/testsuite/gdb.dwarf2/no-gnu-debuglink.exp index 7475d7a..05e625f 100644 --- a/gdb/testsuite/gdb.dwarf2/no-gnu-debuglink.exp +++ b/gdb/testsuite/gdb.dwarf2/no-gnu-debuglink.exp @@ -38,7 +38,7 @@ if { [build_executable $testfile.exp $testfile [list $srcfile $asm_file]] } { clean_restart gdb_test_no_output "maint set dwarf synchronous on" -set msg "\r\nwarning: could not find '\.gnu_debugaltlink' file for \[^\r\n\]*" +set msg "\r\nwarning: could not find supplementary DWARF file \[^\r\n\]*" gdb_test "file $binfile" "$msg" "file command" set question "Load new symbol table from .*\? .y or n. " diff --git a/gdb/testsuite/gdb.python/gdb_leak_detector.py b/gdb/testsuite/gdb.python/gdb_leak_detector.py new file mode 100644 index 0000000..8f74b67 --- /dev/null +++ b/gdb/testsuite/gdb.python/gdb_leak_detector.py @@ -0,0 +1,121 @@ +# Copyright (C) 2021-2025 Free Software Foundation, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# Defines a base class, which can be sub-classed, in order to run +# memory leak tests on some aspects of GDB's Python API. See the +# comments on the gdb_leak_detector class for more details. + +import os +import tracemalloc + +import gdb + + +# This class must be sub-classed to create a memory leak test. The +# sub-classes __init__ method should call the parent classes __init__ +# method, and the sub-class should override allocate() and +# deallocate(). See the comments on the various methods below for +# more details of required arguments and expected usage. +class gdb_leak_detector: + + # Class initialisation. FILENAME is the file in which the + # sub-class is defined, usually passed as just '__file__'. This + # is used when looking for memory allocations; only allocations in + # FILENAME are considered. + def __init__(self, filename): + self.filters = [tracemalloc.Filter(True, "*" + os.path.basename(filename))] + + # Internal helper function to actually run the test. Calls the + # allocate() method to allocate an object from GDB's Python API. + # When CLEAR is True the object will then be deallocated by + # calling deallocate(), otherwise, deallocate() is not called. + # + # Finally, this function checks for any memory allocatios + # originating from 'self.filename' that have not been freed, and + # returns the total (in bytes) of the memory that has been + # allocated, but not freed. + def _do_test(self, clear): + # Start tracing, and take a snapshot of the current allocations. + tracemalloc.start() + snapshot1 = tracemalloc.take_snapshot() + + # Generate the GDB Python API object by calling the allocate + # method. + self.allocate() + + # Possibly clear the reference to the allocated object. + if clear: + self.deallocate() + + # Now grab a second snapshot of memory allocations, and stop + # tracing memory allocations. + snapshot2 = tracemalloc.take_snapshot() + tracemalloc.stop() + + # Filter the snapshots; we only care about allocations originating + # from this file. + snapshot1 = snapshot1.filter_traces(self.filters) + snapshot2 = snapshot2.filter_traces(self.filters) + + # Compare the snapshots, this leaves only things that were + # allocated, but not deallocated since the first snapshot. + stats = snapshot2.compare_to(snapshot1, "traceback") + + # Total up all the allocated things. + total = 0 + for stat in stats: + total += stat.size_diff + return total + + # Run the memory leak test. Prints 'PASS' if successful, + # otherwise, raises an exception (of type GdbError). + def run(self): + # The first time we run this some global state will be allocated which + # shows up as memory that is allocated, but not released. So, run the + # test once and discard the result. + self._do_test(True) + + # Now run the test twice, the first time we clear our global reference + # to the allocated object, which should allow Python to deallocate the + # object. The second time we hold onto the global reference, preventing + # Python from performing the deallocation. + bytes_with_clear = self._do_test(True) + bytes_without_clear = self._do_test(False) + + # If there are any allocations left over when we cleared the reference + # (and expected deallocation) then this indicates a leak. + if bytes_with_clear > 0: + raise gdb.GdbError("memory leak when object reference was released") + + # If there are no allocations showing when we hold onto a reference, + # then this likely indicates that the testing infrastructure is broken, + # and we're no longer spotting the allocations at all. + if bytes_without_clear == 0: + raise gdb.GdbError("object is unexpectedly not showing as allocated") + + # Print a PASS message that the TCL script can see. + print("PASS") + + # Sub-classes must override this method. Allocate an object (or + # multiple objects) from GDB's Python API. Store references to + # these objects within SELF. + def allocate(self): + raise NotImplementedError("allocate() not implemented") + + # Sub-classes must override this method. Deallocate the object(s) + # allocated by the allocate() method. All that is required is for + # the references created in allocate() to be set to None. + def deallocate(self): + raise NotImplementedError("allocate() not implemented") diff --git a/gdb/testsuite/gdb.python/py-breakpoint.exp b/gdb/testsuite/gdb.python/py-breakpoint.exp index 1b9c05f..9a901a3 100644 --- a/gdb/testsuite/gdb.python/py-breakpoint.exp +++ b/gdb/testsuite/gdb.python/py-breakpoint.exp @@ -707,7 +707,7 @@ proc_with_prefix test_bkpt_explicit_loc {} { delete_breakpoints gdb_test "python bp1 = gdb.Breakpoint (line=bp1)" \ - "RuntimeError.*: Line keyword should be an integer or a string.*" \ + "RuntimeError.*: Line keyword should be an integer or a string\\.\r\n.*" \ "set explicit breakpoint by invalid line type" delete_breakpoints diff --git a/gdb/testsuite/gdb.python/py-color-leak.exp b/gdb/testsuite/gdb.python/py-color-leak.exp new file mode 100644 index 0000000..6d7fa7c --- /dev/null +++ b/gdb/testsuite/gdb.python/py-color-leak.exp @@ -0,0 +1,28 @@ +# Copyright (C) 2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +# This file is part of the GDB testsuite. It checks for memory leaks +# associated with allocating gdb.Color objects. + +load_lib gdb-python.exp + +require allow_python_tests + +standard_testfile + +clean_restart + +gdb_py_run_memory_leak_test ${srcdir}/${subdir}/${testfile}.py \ + "gdb.Color object deallocates correctly" diff --git a/gdb/testsuite/gdb.python/py-color-leak.py b/gdb/testsuite/gdb.python/py-color-leak.py new file mode 100644 index 0000000..50dc315 --- /dev/null +++ b/gdb/testsuite/gdb.python/py-color-leak.py @@ -0,0 +1,31 @@ +# Copyright (C) 2025 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import gdb_leak_detector + + +class color_leak_detector(gdb_leak_detector.gdb_leak_detector): + def __init__(self): + super().__init__(__file__) + self.color = None + + def allocate(self): + self.color = gdb.Color("red") + + def deallocate(self): + self.color = None + + +color_leak_detector().run() diff --git a/gdb/testsuite/gdb.python/py-color.exp b/gdb/testsuite/gdb.python/py-color.exp index c6f1041..3563d22 100644 --- a/gdb/testsuite/gdb.python/py-color.exp +++ b/gdb/testsuite/gdb.python/py-color.exp @@ -13,8 +13,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -# This file is part of the GDB testsuite. -# It tests gdb.parameter and gdb.Parameter. +# This file is part of the GDB testsuite. It tests gdb.Color. load_lib gdb-python.exp @@ -23,7 +22,10 @@ require allow_python_tests # Start with a fresh gdb. clean_restart -gdb_test_no_output "python print_color_attrs = lambda c: print (c, c.colorspace, c.is_none, c.is_indexed, c.is_direct)" \ +gdb_test_no_output "python get_color_attrs = lambda c: \"%s %s %s %s %s\" % (str(c), c.colorspace, c.is_none, c.is_indexed, c.is_direct)" \ + "get_color_attrs helper" + +gdb_test_no_output "python print_color_attrs = lambda c: print (get_color_attrs (c))" \ "print_color_attrs helper" gdb_test_no_output "python c = gdb.Color ()" \ @@ -59,6 +61,15 @@ gdb_test "python print_color_attrs (c)" "green 1 False True False" \ gdb_test "python print (c.index)" "2" \ "print index of a basic color with ansi colorspace" +# Create a color using keyword arguments, and check it matches the +# non-keyword color. +gdb_test_no_output "python c2 = gdb.Color (color_space = gdb.COLORSPACE_ANSI_8COLOR, value = 2)" \ + "create color from basic index and ansi colorspace using keywords" +gdb_test "python print(get_color_attrs (c) == get_color_attrs (c2))" "True" \ + "check attributes match" +gdb_test "python print(c.index == c2.index)" "True" \ + "check index matches" + gdb_test_no_output "python c = gdb.Color (2, gdb.COLORSPACE_XTERM_256COLOR)" \ "create color from basic index and xterm256 colorspace" gdb_test "python print_color_attrs (c)" "2 3 False True False" \ @@ -97,4 +108,48 @@ gdb_test [concat "python print (c_red.escape_sequence (True) + " \ "c_none.escape_sequence (True))"] \ "\033\\\[31m\033\\\[42mred on green\033\\\[49m red on default\033\\\[39m" \ "escape sequences" - +gdb_test [concat "python print (c_red.escape_sequence (is_foreground = True) + " \ + "c_green.escape_sequence (is_foreground = False) + 'red on green' + " \ + "c_none.escape_sequence (is_foreground = False) + ' red on default' + " \ + "c_none.escape_sequence (is_foreground = True))"] \ + "\033\\\[31m\033\\\[42mred on green\033\\\[49m red on default\033\\\[39m" \ + "escape sequences using keyword arguments" + +gdb_test_multiline "Try to sub-class gdb.Color" \ + "python" "" \ + "class my_color(gdb.Color):" "" \ + " def __init__(self):" "" \ + " super().__init__('red')" "" \ + "end" \ + [multi_line \ + "Python Exception <class 'TypeError'>: type 'gdb\\.Color' is not an acceptable base type" \ + "Error occurred in Python: type 'gdb\\.Color' is not an acceptable base type"] + +gdb_test_multiline "Setup a color parameter and non gdb.Color object" \ + "python" "" \ + "class my_param(gdb.Parameter):" "" \ + " def __init__(self):" "" \ + " super().__init__('color-param', gdb.COMMAND_NONE, gdb.PARAM_COLOR)" "" \ + " self.value = gdb.Color('red')" "" \ + "color_param = my_param()" "" \ + " " "" \ + "class bad_type:" "" \ + " @property" "" \ + " def __class__(self):" "" \ + " raise RuntimeError('__class__ error for bad_type')" "" \ + "bad_obj = bad_type()" "" \ + "end" "" + +gdb_test_no_output "python color_param.value = gdb.Color('blue')" \ + "set color parameter to blue" + +gdb_test "python color_param.value = bad_obj" \ + [multi_line \ + "Python Exception <class 'RuntimeError'>: color argument must be a gdb\\.Color object\\." \ + "Error occurred in Python: color argument must be a gdb\\.Color object\\."] \ + "set color parameter to a non-color type" + +gdb_test "python c_none.escape_sequence(c_red)" \ + [multi_line \ + "Python Exception <class 'TypeError'>: argument 1 must be bool, not gdb.Color" \ + "Error occurred in Python: argument 1 must be bool, not gdb.Color"] diff --git a/gdb/testsuite/gdb.python/py-disasm.exp.tcl b/gdb/testsuite/gdb.python/py-disasm.exp.tcl index 938326d..c5099ba 100644 --- a/gdb/testsuite/gdb.python/py-disasm.exp.tcl +++ b/gdb/testsuite/gdb.python/py-disasm.exp.tcl @@ -152,7 +152,10 @@ set test_plans \ "Buffer returned from read_memory is sized $decimal instead of the expected $decimal"]] \ [list "ResultOfWrongType" \ [make_exception_pattern "TypeError" \ - "Result is not a DisassemblerResult."]] \ + "Result from Disassembler must be gdb.DisassemblerResult, not Blah."]] \ + [list "ResultOfVeryWrongType" \ + [make_exception_pattern "TypeError" \ + "Result from Disassembler must be gdb.DisassemblerResult, not Blah."]] \ [list "ErrorCreatingTextPart_NoArgs" \ [make_exception_pattern "TypeError" \ [missing_arg_pattern "style" 1]]] \ diff --git a/gdb/testsuite/gdb.python/py-disasm.py b/gdb/testsuite/gdb.python/py-disasm.py index 32d6aa7..9761337 100644 --- a/gdb/testsuite/gdb.python/py-disasm.py +++ b/gdb/testsuite/gdb.python/py-disasm.py @@ -294,6 +294,24 @@ class ResultOfWrongType(TestDisassembler): return self.Blah(1, "ABC") +class ResultOfVeryWrongType(TestDisassembler): + """Return something that is not a DisassemblerResult from disassemble + method. The thing returned will raise an exception if used in an + isinstance() call, or in PyObject_IsInstance from C++. + """ + + class Blah: + def __init__(self): + pass + + @property + def __class__(self): + raise RuntimeError("error from __class__ in Blah") + + def disassemble(self, info): + return self.Blah() + + class TaggingDisassembler(TestDisassembler): """A simple disassembler that just tags the output.""" diff --git a/gdb/testsuite/gdb.python/py-frame.exp b/gdb/testsuite/gdb.python/py-frame.exp index 5668807..c1e3e33 100644 --- a/gdb/testsuite/gdb.python/py-frame.exp +++ b/gdb/testsuite/gdb.python/py-frame.exp @@ -188,6 +188,21 @@ gdb_test "python print(gdb.selected_frame().read_register(list()))" \ ".*Invalid type for register.*" \ "test Frame.read_register with list" +gdb_test_multiline "setup a bad object" \ + "python" "" \ + "class bad_type:" "" \ + " def __init__ (self):" "" \ + " pass" "" \ + " @property" "" \ + " def __class__(self):" "" \ + " raise RuntimeError('error from __class in bad_type')" "" \ + "bad_object = bad_type()" "" \ + "end" "" + +gdb_test "python print(gdb.selected_frame().read_register(bad_object))" \ + ".*Invalid type for register.*" \ + "test Frame.read_register with bad_type object" + # Compile again without debug info. gdb_exit if { [prepare_for_testing "failed to prepare" ${testfile} ${srcfile} {}] } { diff --git a/gdb/testsuite/gdb.python/py-inferior-leak.exp b/gdb/testsuite/gdb.python/py-inferior-leak.exp index 6710f59..15216ee 100644 --- a/gdb/testsuite/gdb.python/py-inferior-leak.exp +++ b/gdb/testsuite/gdb.python/py-inferior-leak.exp @@ -24,15 +24,5 @@ standard_testfile clean_restart -# Skip this test if the tracemalloc module is not available. -if { ![gdb_py_module_available "tracemalloc"] } { - unsupported "tracemalloc module not available" - return -} - -set pyfile [gdb_remote_download host ${srcdir}/${subdir}/${testfile}.py] - -# Source the Python script, this runs the test (which is written -# completely in Python), and either prints PASS, or throws an -# exception. -gdb_test "source ${pyfile}" "PASS" "source python script" +gdb_py_run_memory_leak_test ${srcdir}/${subdir}/${testfile}.py \ + "gdb.Inferior object deallocates correctly" diff --git a/gdb/testsuite/gdb.python/py-inferior-leak.py b/gdb/testsuite/gdb.python/py-inferior-leak.py index 97837dc..f764688 100644 --- a/gdb/testsuite/gdb.python/py-inferior-leak.py +++ b/gdb/testsuite/gdb.python/py-inferior-leak.py @@ -14,99 +14,32 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. import re -import tracemalloc -import gdb +import gdb_leak_detector -# A global variable in which we store a reference to the gdb.Inferior -# object sent to us in the new_inferior event. -inf = None +class inferior_leak_detector(gdb_leak_detector.gdb_leak_detector): + def __init__(self): + super().__init__(__file__) + self.inferior = None + self.__handler = lambda event: setattr(self, "inferior", event.inferior) + gdb.events.new_inferior.connect(self.__handler) -# Register the new_inferior event handler. -def new_inferior_handler(event): - global inf - inf = event.inferior + def __del__(self): + gdb.events.new_inferior.disconnect(self.__handler) + def allocate(self): + output = gdb.execute("add-inferior", False, True) + m = re.search(r"Added inferior (\d+)", output) + if m: + num = int(m.group(1)) + else: + raise RuntimeError("no match") -gdb.events.new_inferior.connect(new_inferior_handler) + gdb.execute("remove-inferiors %s" % num) -# A global filters list, we only care about memory allocations -# originating from this script. -filters = [tracemalloc.Filter(True, "*py-inferior-leak.py")] + def deallocate(self): + self.inferior = None -# Add a new inferior, and return the number of the new inferior. -def add_inferior(): - output = gdb.execute("add-inferior", False, True) - m = re.search(r"Added inferior (\d+)", output) - if m: - num = int(m.group(1)) - else: - raise RuntimeError("no match") - return num - - -# Run the test. When CLEAR is True we clear the global INF variable -# before comparing the before and after memory allocation traces. -# When CLEAR is False we leave INF set to reference the gdb.Inferior -# object, thus preventing the gdb.Inferior from being deallocated. -def test(clear): - global filters, inf - - # Start tracing, and take a snapshot of the current allocations. - tracemalloc.start() - snapshot1 = tracemalloc.take_snapshot() - - # Create an inferior, this triggers the new_inferior event, which - # in turn holds a reference to the new gdb.Inferior object in the - # global INF variable. - num = add_inferior() - gdb.execute("remove-inferiors %s" % num) - - # Possibly clear the global INF variable. - if clear: - inf = None - - # Now grab a second snapshot of memory allocations, and stop - # tracing memory allocations. - snapshot2 = tracemalloc.take_snapshot() - tracemalloc.stop() - - # Filter the snapshots; we only care about allocations originating - # from this file. - snapshot1 = snapshot1.filter_traces(filters) - snapshot2 = snapshot2.filter_traces(filters) - - # Compare the snapshots, this leaves only things that were - # allocated, but not deallocated since the first snapshot. - stats = snapshot2.compare_to(snapshot1, "traceback") - - # Total up all the deallocated things. - total = 0 - for stat in stats: - total += stat.size_diff - return total - - -# The first time we run this some global state will be allocated which -# shows up as memory that is allocated, but not released. So, run the -# test once and discard the result. -test(True) - -# Now run the test twice, the first time we clear our global reference -# to the gdb.Inferior object, which should allow Python to deallocate -# the object. The second time we hold onto the global reference, -# preventing Python from performing the deallocation. -bytes_with_clear = test(True) -bytes_without_clear = test(False) - -# The bug that used to exist in GDB was that even when we released the -# global reference the gdb.Inferior object would not be deallocated. -if bytes_with_clear > 0: - raise gdb.GdbError("memory leak when gdb.Inferior should be released") -if bytes_without_clear == 0: - raise gdb.GdbError("gdb.Inferior object is no longer allocated") - -# Print a PASS message that the test script can see. -print("PASS") +inferior_leak_detector().run() diff --git a/gdb/testsuite/gdb.python/py-read-memory-leak.exp b/gdb/testsuite/gdb.python/py-read-memory-leak.exp index 0015a57..9ae5eb8 100644 --- a/gdb/testsuite/gdb.python/py-read-memory-leak.exp +++ b/gdb/testsuite/gdb.python/py-read-memory-leak.exp @@ -30,15 +30,5 @@ if ![runto_main] { return -1 } -# Skip this test if the tracemalloc module is not available. -if { ![gdb_py_module_available "tracemalloc"] } { - unsupported "tracemalloc module not available" - return -} - -set pyfile [gdb_remote_download host ${srcdir}/${subdir}/${testfile}.py] - -# Source the Python script, this runs the test (which is written -# completely in Python), and either prints PASS, or throws an -# exception. -gdb_test "source ${pyfile}" "PASS" "source python script" +gdb_py_run_memory_leak_test ${srcdir}/${subdir}/${testfile}.py \ + "buffers returned by read_memory() deallocates correctly" diff --git a/gdb/testsuite/gdb.python/py-read-memory-leak.py b/gdb/testsuite/gdb.python/py-read-memory-leak.py index 348403d..71edf47 100644 --- a/gdb/testsuite/gdb.python/py-read-memory-leak.py +++ b/gdb/testsuite/gdb.python/py-read-memory-leak.py @@ -13,81 +13,21 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -import os -import tracemalloc +import gdb_leak_detector -import gdb -# A global variable in which we store a reference to the memory buffer -# returned from gdb.Inferior.read_memory(). -mem_buf = None +class read_leak_detector(gdb_leak_detector.gdb_leak_detector): + def __init__(self): + super().__init__(__file__) + self.mem_buf = None + self.addr = gdb.parse_and_eval("px") + self.inf = gdb.inferiors()[0] + def allocate(self): + self.mem_buf = self.inf.read_memory(self.addr, 4096) -# A global filters list, we only care about memory allocations -# originating from this script. -filters = [tracemalloc.Filter(True, "*" + os.path.basename(__file__))] + def deallocate(self): + self.mem_buf = None -# Run the test. When CLEAR is True we clear the global INF variable -# before comparing the before and after memory allocation traces. -# When CLEAR is False we leave INF set to reference the gdb.Inferior -# object, thus preventing the gdb.Inferior from being deallocated. -def test(clear): - global filters, mem_buf - - addr = gdb.parse_and_eval("px") - inf = gdb.inferiors()[0] - - # Start tracing, and take a snapshot of the current allocations. - tracemalloc.start() - snapshot1 = tracemalloc.take_snapshot() - - # Read from the inferior, this allocate a memory buffer object. - mem_buf = inf.read_memory(addr, 4096) - - # Possibly clear the global INF variable. - if clear: - mem_buf = None - - # Now grab a second snapshot of memory allocations, and stop - # tracing memory allocations. - snapshot2 = tracemalloc.take_snapshot() - tracemalloc.stop() - - # Filter the snapshots; we only care about allocations originating - # from this file. - snapshot1 = snapshot1.filter_traces(filters) - snapshot2 = snapshot2.filter_traces(filters) - - # Compare the snapshots, this leaves only things that were - # allocated, but not deallocated since the first snapshot. - stats = snapshot2.compare_to(snapshot1, "traceback") - - # Total up all the allocated things. - total = 0 - for stat in stats: - total += stat.size_diff - return total - - -# The first time we run this some global state will be allocated which -# shows up as memory that is allocated, but not released. So, run the -# test once and discard the result. -test(True) - -# Now run the test twice, the first time we clear our global reference -# to the memory buffer object, which should allow Python to deallocate -# the object. The second time we hold onto the global reference, -# preventing Python from performing the deallocation. -bytes_with_clear = test(True) -bytes_without_clear = test(False) - -# The bug that used to exist in GDB was that even when we released the -# global reference the gdb.Inferior object would not be deallocated. -if bytes_with_clear > 0: - raise gdb.GdbError("memory leak when memory buffer should be released") -if bytes_without_clear == 0: - raise gdb.GdbError("memory buffer object is no longer allocated") - -# Print a PASS message that the test script can see. -print("PASS") +read_leak_detector().run() diff --git a/gdb/testsuite/gdb.python/py-unwind.exp b/gdb/testsuite/gdb.python/py-unwind.exp index 80eac28..b416c2f 100644 --- a/gdb/testsuite/gdb.python/py-unwind.exp +++ b/gdb/testsuite/gdb.python/py-unwind.exp @@ -245,6 +245,13 @@ with_test_prefix "frame-id 'pc' is invalid" { "Python Exception <class 'ValueError'>: invalid literal for int\\(\\) with base 10: 'xyz'\r\n.*" } +with_test_prefix "bad object unwinder" { + gdb_test_no_output "python obj = bad_object_unwinder(\"bad-object\")" + gdb_test_no_output "python gdb.unwinder.register_unwinder(None, obj, replace=True)" + gdb_test "backtrace" \ + "Python Exception <class 'gdb.error'>: an Unwinder should return gdb.UnwindInfo, not Blah\\.\r\n.*" +} + # Gather information about every frame. gdb_test_no_output "python capture_all_frame_information()" gdb_test_no_output "python gdb.newest_frame().select()" diff --git a/gdb/testsuite/gdb.python/py-unwind.py b/gdb/testsuite/gdb.python/py-unwind.py index 8e65a1a..0faccf2 100644 --- a/gdb/testsuite/gdb.python/py-unwind.py +++ b/gdb/testsuite/gdb.python/py-unwind.py @@ -267,4 +267,24 @@ class validating_unwinder(Unwinder): return None +class bad_object_unwinder(Unwinder): + def __init__(self, name): + super().__init__(name) + + def __call__(self, pending_frame): + + if pending_frame.level() != 1: + return None + + class Blah: + def __init__(self): + pass + + @property + def __class__(self): + raise RuntimeError("error in Blah.__class__") + + return Blah() + + print("Python script imported") diff --git a/gdb/testsuite/gdb.server/no-thread-db.exp b/gdb/testsuite/gdb.server/no-thread-db.exp index cc24708..9fd2090 100644 --- a/gdb/testsuite/gdb.server/no-thread-db.exp +++ b/gdb/testsuite/gdb.server/no-thread-db.exp @@ -57,6 +57,8 @@ gdb_breakpoint ${srcfile}:[gdb_get_line_number "after tls assignment"] gdb_continue_to_breakpoint "after tls assignment" # Printing a tls variable should fail gracefully without a libthread_db. +# Alternately, the correct answer might be printed due GDB's internal +# TLS support for some targets. set re_exec "\[^\r\n\]*[file tail $binfile]" gdb_test "print foo" \ - "Cannot find thread-local storage for Thread \[^,\]+, executable file $re_exec:\[\r\n\]+Remote target failed to process qGetTLSAddr request" + "= 1|(?:Cannot find thread-local storage for Thread \[^,\]+, executable file $re_exec:\[\r\n\]+Remote target failed to process qGetTLSAddr request)" diff --git a/gdb/testsuite/gdb.threads/clone-attach-detach.exp b/gdb/testsuite/gdb.threads/clone-attach-detach.exp index 0ae4281..3da2c3e 100644 --- a/gdb/testsuite/gdb.threads/clone-attach-detach.exp +++ b/gdb/testsuite/gdb.threads/clone-attach-detach.exp @@ -74,7 +74,7 @@ set attempts 3 for {set attempt 1} {$attempt <= $attempts} {incr attempt} { with_test_prefix "bg attach $attempt" { - gdb_test "attach $testpid &" \ + gdb_test -no-prompt-anchor "attach $testpid &" \ "Attaching to program.*process $testpid.*" \ "attach" diff --git a/gdb/testsuite/gdb.threads/tls.exp b/gdb/testsuite/gdb.threads/tls.exp index 1bc5df2..73fada7 100644 --- a/gdb/testsuite/gdb.threads/tls.exp +++ b/gdb/testsuite/gdb.threads/tls.exp @@ -159,7 +159,7 @@ gdb_test_multiple "print a_thread_local" "" { -re -wrap "Cannot find thread-local variables on this target" { kfail "gdb/25807" $gdb_test_name } - -re -wrap "Cannot read .a_thread_local. without registers" { + -re -wrap "Cannot (?:read|find address of TLS symbol) .a_thread_local. without registers" { pass $gdb_test_name } } diff --git a/gdb/testsuite/lib/dwarf.exp b/gdb/testsuite/lib/dwarf.exp index 46b39a1..7e8778a 100644 --- a/gdb/testsuite/lib/dwarf.exp +++ b/gdb/testsuite/lib/dwarf.exp @@ -3068,6 +3068,24 @@ namespace eval Dwarf { } } + # Emit a .debug_sup section with the given file name and build-id. + # The buildid should be represented as a hexadecimal string, like + # "ffeeddcc". + proc debug_sup {is_sup filename buildid} { + _defer_output .debug_sup { + # The version. + _op .2byte 0x5 + # Supplementary marker. + _op .byte $is_sup + _op .ascii [_quote $filename] + set len [expr {[string length $buildid] / 2}] + _op .uleb128 $len + foreach {a b} [split $buildid {}] { + _op .byte 0x$a$b + } + } + } + proc _note {type name hexdata} { set namelen [expr [string length $name] + 1] set datalen [expr [string length $hexdata] / 2] diff --git a/gdb/testsuite/lib/gdb-python.exp b/gdb/testsuite/lib/gdb-python.exp index b4eb40d..e026c1b 100644 --- a/gdb/testsuite/lib/gdb-python.exp +++ b/gdb/testsuite/lib/gdb-python.exp @@ -77,3 +77,24 @@ proc gdb_py_module_available { name } { return ${available} } + +# Run a memory leak test within the Python script FILENAME. This proc +# checks that the required Python modules are available, sets up the +# syspath so that the helper module can be found (in the same +# directory as FILENAME), then loads FILENAME to run the test. +proc gdb_py_run_memory_leak_test { filename testname } { + if { ![gdb_py_module_available "tracemalloc"] } { + unsupported "$testname (tracemalloc module not available)" + } + + gdb_test_no_output -nopass "python import sys" + gdb_test_no_output -nopass \ + "python sys.path.insert(0, \"[file dirname $filename]\")" \ + "setup sys.path" + + set pyfile [gdb_remote_download host ${filename}] + + # Source the Python script, this runs the test, and either prints + # PASS, or throws an exception. + gdb_test "source ${pyfile}" "^PASS" $testname +} diff --git a/gdb/testsuite/lib/gdb.exp b/gdb/testsuite/lib/gdb.exp index c37cc89..ead14bd 100644 --- a/gdb/testsuite/lib/gdb.exp +++ b/gdb/testsuite/lib/gdb.exp @@ -3758,7 +3758,8 @@ proc supports_reverse {} { || [istarget "aarch64*-*-linux*"] || [istarget "loongarch*-*-linux*"] || [istarget "powerpc*-*-linux*"] - || [istarget "s390*-*-linux*"] } { + || [istarget "s390*-*-linux*"] + || [istarget "riscv*-*-*"] } { return 1 } diff --git a/gdb/ui-file.c b/gdb/ui-file.c index 09e8b0b..f86b6b1 100644 --- a/gdb/ui-file.c +++ b/gdb/ui-file.c @@ -88,18 +88,6 @@ ui_file::emit_style_escape (const ui_file_style &style) /* See ui-file.h. */ void -ui_file::reset_style () -{ - if (can_emit_style_escape ()) - { - m_applied_style = ui_file_style (); - this->puts (m_applied_style.to_ansi ().c_str ()); - } -} - -/* See ui-file.h. */ - -void ui_file::printchar (int c, int quoter, bool async_safe) { char buf[4]; diff --git a/gdb/ui-file.h b/gdb/ui-file.h index 351cf1f..3919e52 100644 --- a/gdb/ui-file.h +++ b/gdb/ui-file.h @@ -123,9 +123,6 @@ public: /* Emit an ANSI style escape for STYLE. */ virtual void emit_style_escape (const ui_file_style &style); - /* Rest the current output style to the empty style. */ - virtual void reset_style (); - /* Print STR, bypassing any paging that might be done by this ui_file. Note that nearly no code should call this -- it's intended for use by gdb_printf, but nothing else. */ @@ -353,12 +350,6 @@ public: m_two->emit_style_escape (style); } - void reset_style () override - { - m_one->reset_style (); - m_two->reset_style (); - } - void puts_unfiltered (const char *str) override { m_one->puts_unfiltered (str); @@ -389,10 +380,6 @@ public: void emit_style_escape (const ui_file_style &style) override { } - - void reset_style () override - { - } }; /* A base class for ui_file types that wrap another ui_file. */ @@ -419,10 +406,6 @@ public: void emit_style_escape (const ui_file_style &style) override { m_stream->emit_style_escape (style); } - /* Rest the current output style to the empty style. */ - void reset_style () override - { m_stream->reset_style (); } - int fd () const override { return m_stream->fd (); } diff --git a/gdb/ui-style.c b/gdb/ui-style.c index b8321c5..b8d73ab 100644 --- a/gdb/ui-style.c +++ b/gdb/ui-style.c @@ -45,7 +45,8 @@ static const char ansi_regex_text[] = /* The compiled form of ansi_regex_text. */ -static regex_t ansi_regex; +static compiled_regex ansi_regex (ansi_regex_text, REG_EXTENDED, + _("Error in ANSI terminal escape sequences regex")); /* This maps 8-color palette to RGB triples. The values come from plain linux terminal. */ @@ -364,7 +365,7 @@ ui_file_style::parse (const char *buf, size_t *n_read) { regmatch_t subexps[NUM_SUBEXPRESSIONS]; - int match = regexec (&ansi_regex, buf, ARRAY_SIZE (subexps), subexps, 0); + int match = ansi_regex.exec (buf, ARRAY_SIZE (subexps), subexps, 0); if (match == REG_NOMATCH) { *n_read = 0; @@ -531,7 +532,7 @@ skip_ansi_escape (const char *buf, int *n_read) { regmatch_t subexps[NUM_SUBEXPRESSIONS]; - int match = regexec (&ansi_regex, buf, ARRAY_SIZE (subexps), subexps, 0); + int match = ansi_regex.exec (buf, ARRAY_SIZE (subexps), subexps, 0); if (match == REG_NOMATCH || buf[subexps[FINAL_SUBEXP].rm_so] != 'm') return false; @@ -539,16 +540,6 @@ skip_ansi_escape (const char *buf, int *n_read) return true; } -void _initialize_ui_style (); -void -_initialize_ui_style () -{ - int code = regcomp (&ansi_regex, ansi_regex_text, REG_EXTENDED); - /* If the regular expression was incorrect, it was a programming - error. */ - gdb_assert (code == 0); -} - /* See ui-style.h. */ const std::vector<color_space> & diff --git a/gdb/unittests/remote-arg-selftests.c b/gdb/unittests/remote-arg-selftests.c new file mode 100644 index 0000000..70f8a39 --- /dev/null +++ b/gdb/unittests/remote-arg-selftests.c @@ -0,0 +1,166 @@ +/* Self tests for GDB's argument splitting and merging. + + Copyright (C) 2023-2025 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. */ + +#include "defs.h" +#include "gdbsupport/selftest.h" +#include "gdbsupport/buildargv.h" +#include "gdbsupport/common-inferior.h" +#include "gdbsupport/remote-args.h" +#include "gdbsupport/gdb_argv_vec.h" + +namespace selftests { +namespace remote_args_tests { + +/* The data needed to perform a single remote argument test. */ +struct arg_test_desc +{ + /* The original inferior argument string. */ + std::string input; + + /* The individual arguments once they have been split. */ + std::vector<std::string> split; + + /* The new inferior argument string, created by joining SPLIT. */ + std::string joined; +}; + +/* The list of tests. */ +arg_test_desc desc[] = { + { "abc", { "abc" }, "abc" }, + { "a b c", { "a", "b", "c" }, "a b c" }, + { "\"a b\" 'c d'", { "a b", "c d" }, "a\\ b c\\ d" }, + { "\\' \\\"", { "'", "\"" }, "\\' \\\"" }, + { "'\\'", { "\\" }, "\\\\" }, + { "\"\\\\\" \"\\\\\\\"\"", { "\\", "\\\"" }, "\\\\ \\\\\\\"" }, + { "\\ \" \" ' '", { " ", " ", " "}, "\\ \\ \\ " }, + { "\"'\"", { "'" }, "\\'" }, + { "'\"' '\\\"'", { "\"", "\\\"" } , "\\\" \\\\\\\""}, + { "\"first arg\" \"\" \"third-arg\" \"'\" \"\\\"\" \"\\\\\\\"\" \" \" \"\"", + { "first arg", "", "third-arg", "'", "\"", "\\\""," ", "" }, + "first\\ arg '' third-arg \\' \\\" \\\\\\\" \\ ''"}, + { "\"\\a\" \"\\&\" \"\\#\" \"\\<\" \"\\^\"", + { "\\a", "\\&", "\\#" , "\\<" , "\\^"}, + "\\\\a \\\\\\& \\\\\\# \\\\\\< \\\\\\^" }, + { "1 '\n' 3", { "1", "\n", "3" }, "1 '\n' 3" }, +}; + +/* Run the remote argument passing self tests. */ + +static void +self_test () +{ + int failure_count = 0; + for (const auto &d : desc) + { + if (run_verbose ()) + { + if (&d != &desc[0]) + debug_printf ("------------------------------\n"); + debug_printf ("Input (%s)\n", d.input.c_str ()); + } + + /* Split argument string into individual arguments. */ + std::vector<std::string> split_args = gdb::remote_args::split (d.input); + + if (run_verbose ()) + { + debug_printf ("Split:\n"); + + size_t len = std::max (split_args.size (), d.split.size ()); + for (size_t i = 0; i < len; ++i) + { + const char *got = "N/A"; + const char *expected = got; + + if (i < split_args.size ()) + got = split_args[i].c_str (); + + if (i < d.split.size ()) + expected = d.split[i].c_str (); + + debug_printf (" got (%s), expected (%s)\n", got, expected); + } + } + + if (split_args != d.split) + { + ++failure_count; + if (run_verbose ()) + debug_printf ("FAIL\n"); + continue; + } + + /* Now join the arguments. */ + gdb::argv_vec split_args_c_str; + for (const std::string &s : split_args) + split_args_c_str.push_back (xstrdup (s.c_str ())); + std::string joined_args + = gdb::remote_args::join (split_args_c_str.get ()); + + if (run_verbose ()) + debug_printf ("Joined (%s), expected (%s)\n", + joined_args.c_str (), d.joined.c_str ()); + + if (joined_args != d.joined) + { + ++failure_count; + if (run_verbose ()) + debug_printf ("FAIL\n"); + continue; + } + + /* The contents of JOINED_ARGS will not be identical to D.INPUT. + There are multiple ways that an argument can be escaped, and our + join function just picks one. However, if we split JOINED_ARGS + again then each individual argument should be the same as those in + SPLIT_ARGS. So test that next. */ + std::vector<std::string> split_args_v2 + = gdb::remote_args::split (joined_args); + + if (split_args_v2 != split_args) + { + ++failure_count; + if (run_verbose ()) + { + debug_printf ("Re-split:\n"); + for (const auto &a : split_args_v2) + debug_printf (" got (%s)\n", a.c_str ()); + debug_printf ("FAIL\n"); + } + continue; + } + + if (run_verbose ()) + debug_printf ("PASS\n"); + } + + SELF_CHECK (failure_count == 0); +} + +} /* namespace remote_args_tests */ +} /* namespace selftests */ + +void _initialize_remote_arg_selftests (); + +void +_initialize_remote_arg_selftests () +{ + selftests::register_test ("remote-args", + selftests::remote_args_tests::self_test); +} diff --git a/gdb/utils.c b/gdb/utils.c index 986b906..ce3c26e 100644 --- a/gdb/utils.c +++ b/gdb/utils.c @@ -1407,18 +1407,6 @@ pager_file::emit_style_escape (const ui_file_style &style) } } -/* See pager.h. */ - -void -pager_file::reset_style () -{ - if (can_emit_style_escape ()) - { - m_applied_style = ui_file_style (); - m_wrap_buffer.append (m_applied_style.to_ansi ()); - } -} - /* Wait, so the user can read what's on the screen. Prompt the user to continue by pressing RETURN. 'q' is also provided because telling users what to do in the prompt is more user-friendly than diff --git a/gdb/valops.c b/gdb/valops.c index 1b63343..94f908d 100644 --- a/gdb/valops.c +++ b/gdb/valops.c @@ -2420,47 +2420,42 @@ value_struct_elt (struct value **argp, return v; } -/* Given *ARGP, a value of type structure or union, or a pointer/reference +/* Given VAL, a value of type structure or union, or a pointer/reference to a structure or union, extract and return its component (field) of type FTYPE at the specified BITPOS. Throw an exception on error. */ struct value * -value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype, - const char *err) +value_struct_elt_bitpos (struct value *val, int bitpos, struct type *ftype) { struct type *t; int i; - *argp = coerce_array (*argp); + val = coerce_array (val); - t = check_typedef ((*argp)->type ()); + t = check_typedef (val->type ()); while (t->is_pointer_or_reference ()) { - *argp = value_ind (*argp); - if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC) - *argp = coerce_array (*argp); - t = check_typedef ((*argp)->type ()); + val = value_ind (val); + if (check_typedef (val->type ())->code () != TYPE_CODE_FUNC) + val = coerce_array (val); + t = check_typedef (val->type ()); } if (t->code () != TYPE_CODE_STRUCT && t->code () != TYPE_CODE_UNION) - error (_("Attempt to extract a component of a value that is not a %s."), - err); + error (_("Attempt to extract a component of non-aggregate value.")); for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++) { if (!t->field (i).is_static () && bitpos == t->field (i).loc_bitpos () && types_equal (ftype, t->field (i).type ())) - return (*argp)->primitive_field (0, i, t); + return val->primitive_field (0, i, t); } error (_("No field with matching bitpos and type.")); - - /* Never hit. */ - return NULL; } /* Search through the methods of an object (and its bases) to find a diff --git a/gdb/value.h b/gdb/value.h index 0cbcfca..71d0ba1 100644 --- a/gdb/value.h +++ b/gdb/value.h @@ -1297,10 +1297,9 @@ extern struct value *value_struct_elt (struct value **argp, const char *name, int *static_memfuncp, const char *err); -extern struct value *value_struct_elt_bitpos (struct value **argp, +extern struct value *value_struct_elt_bitpos (struct value *val, int bitpos, - struct type *field_type, - const char *err); + struct type *field_type); extern struct value *value_aggregate_elt (struct type *curtype, const char *name, |