Commit Graph

31215 Commits

Author SHA1 Message Date
Luis Machado
1b6b755e91 Print bfloat16 DWARF types correctly
Even if the DWARF information contains a bfloat16 base type (__bf16), a
variable of such type will still be printed using the IEEE half float format,
which is wrong.

This patch teaches GDB how to pick the bfloat16 format for __bf16 types in
DWARF (based on the base type name) and uses IEEE half float for all the other
16-bit float formats.

Tested on aarch64-linux/x86_64-linux.

OK?

gdb/ChangeLog:

2021-04-16  Luis Machado  <luis.machado@linaro.org>

	* arch-utils.c (default_floatformat_for_type): Handle bfloat16.

gdb/testsuite:

2021-04-16  Luis Machado  <luis.machado@linaro.org>

	* gdb.dwarf2/dw2-bfloat16.exp: New file.
2021-04-16 11:14:16 -03:00
John Baldwin
c45ecc9d16 gdb fbsd-nat: Use new-style debug macros
gdb/ChangeLog:

	* fbsd-nat.c (fbsd_lwp_debug_printf, fbsd_nat_debug_printf): New,
	use throughout file.
2021-04-15 15:40:12 -07:00
Tom Tromey
a15a276b46 Avoid crash in Ada value printing with optimized-out array
The Ada value-printing code could crash when printing an array which
had been optimized out.

The crash is difficult to reproduce, but I did manage to write a test
that at least shows that the previous behavior was incorrect -- before
the patch, the array is printed as if it is valid and every value is 0.

gdb/ChangeLog
2021-04-15  Tom Tromey  <tromey@adacore.com>

	* ada-valprint.c (ada_value_print_array): Handle optimized-out
	arrays.

gdb/testsuite/ChangeLog
2021-04-15  Tom Tromey  <tromey@adacore.com>

	* gdb.dwarf2/arr-stride.exp: Add test.
2021-04-15 10:14:11 -06:00
Tom Tromey
644a2e75ac Use common_val_print_checked in print_variable_and_value
GDB was crashing in "bt full" for a large Ada program.  I tracked this
down to a combination of bugs.

The first bug, fixed here, is that print_variable_and_value calls
common_val_print.  Normally only the value-printing implementation
should call this; from the top level, common_val_print_checked is
preferred, because it correctly handles values that are wholly
optimized out.

I wasn't able to write a test case for this.

gdb/ChangeLog
2021-04-15  Tom Tromey  <tromey@adacore.com>

	* printcmd.c (print_variable_and_value): Use
	common_val_print_checked.
2021-04-15 10:14:11 -06:00
Tom Tromey
9e5e03df52 Use block_symbol in var_value_operation
I noticed that var_value_operation takes a block and a symbol, and
most callers destructure a block_symbol to pass in.  It seems better
for this class to simply hold a block_symbol instead.

Tested on x86-64 Fedora 32.

gdb/ChangeLog
2021-04-15  Tom Tromey  <tromey@adacore.com>

	* rust-exp.y (rust_parser::convert_ast_to_expression): Update.
	* parse.c (parser_state::push_symbol, parser_state::push_dollar):
	Update.
	* p-exp.y (variable): Update.
	* m2-exp.y (variable): Update.
	* go-exp.y (variable): Update.
	* expprint.c (dump_for_expression): New overload.
	* expop.h (check_objfile): New overload.
	(check_constant): New overload.
	(class var_value_operation): Use block_symbol.
	<get_symbol>: Rewrite.
	* eval.c (var_value_operation::evaluate)
	(var_value_operation::evaluate_funcall)
	(var_value_operation::evaluate_for_address)
	(var_value_operation::evaluate_for_address)
	(var_value_operation::evaluate_with_coercion)
	(var_value_operation::evaluate_for_sizeof)
	(var_value_operation::evaluate_for_cast): Update.
	* d-exp.y (PrimaryExpression): Update.
	* c-exp.y (variable): Update.
	* ax-gdb.c (var_value_operation::do_generate_ax): Update.
	* ada-lang.c (ada_var_value_operation::evaluate_for_cast)
	(ada_var_value_operation::evaluate)
	(ada_var_value_operation::resolve)
	(ada_funcall_operation::resolve): Update.
	* ada-exp.y (write_var_from_sym, write_object_renaming)
	(write_ambiguous_var, write_var_or_type, write_name_assoc)
	(maybe_overload): Update.
	* ada-exp.h (class ada_var_value_operation) <get_block>: Rewrite.
2021-04-15 10:05:00 -06:00
Tom Tromey
5809fbf2e2 gdb: add "set startup-quietly" command
This adds a new command to change GDB to behave as though "-quiet"
were always given.  This new command can be added to the gdbearlyinit
file to affect future GDB sessions.

gdb/ChangeLog:

	* NEWS: Add entry.
	* main.c (captured_main_1): Call check_quiet_mode.
	* top.c (startup_quiet): New global.
	(check_quiet_mode): New function.
	(show_startup_quiet): New function.
	(init_main): Register new command.
	* top.h (check_quiet_mode): Declare.

gdb/doc/ChangeLog:

	* gdb.texinfo (Mode Options): Mention "set startup-quietly".

gdb/testsuite/ChangeLog:

	* gdb.base/startup-file.exp: Add more tests.
2021-04-15 10:34:09 +01:00
Andrew Burgess
92e4e97a9f gdb: process early initialization files and command line options
Adds the ability to process commands at a new phase during GDB's
startup.  This phase is earlier than the current initialisation file
processing, before GDB has produced any output.

The number of commands that can be processed at this early stage will
be limited, and it is expected that the only commands that would be
processed at this stage will relate to some of the fundamentals of how
GDB starts up.

Currently the only commands that it makes sense to add to this early
initialization file are those like 'set style version ....' as the
version string is displayed during startup before the standard
initialization files are parsed.  As such this commit fully resolved
bug cli/25956.

This commit adds a mechanism to execute these early initialization
files from a users HOME directory, as well as some corresponding
command line flags for GDB.

The early initialization files that GDB will currently check for are
~/.config/gdb/gdbearlyinit (on Linux like systems) or ~/.gdbearlyinit
if the former is not found.

The output of 'gdb --help' has been extended to include a list of the
early initialization files being processed.

gdb/ChangeLog:

	PR cli/25956
	* NEWS: Mention new early init files and command line options.
	* config.in: Regenerate.
	* configure: Regenerate.
	* configure.ac: Define GDBEARLYINIT.
	* main.c (get_earlyinit_files): New function.
	(enum cmdarg_kind): Add CMDARG_EARLYINIT_FILE and
	CMDARG_EARLYINIT_COMMAND.
	(captured_main_1): Add support for new command line flags, and for
	processing startup files.
	(print_gdb_help): Include startup files in the output.

gdb/doc/ChangeLog:

	PR cli/25956
	* gdb.texinfo (File Options): Mention new command line options.
	(Startup): Discuss when early init files are processed.
	(Initialization Files): Add description of early init files.
	(Output Styling): Update description of 'version' style.
	(gdb man): Mention early init files.

gdb/testsuite/ChangeLog:

	PR cli/25956
	* gdb.base/early-init-file.c: New file.
	* gdb.base/early-init-file.exp: New file.
	* lib/gdb-utils.exp (style): Handle style 'none'.
2021-04-15 10:34:09 +01:00
Andrew Burgess
54b4dcc530 gdb: refactor the initialization file lookup code
In preparation for the next patch, which adds startup files, this
commit refactors the code for looking up the initialization files so
that the code can be more easily reused in the next commit.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* main.c (relocate_gdbinit_path_maybe_in_datadir): Rename to...
	(relocate_file_path_maybe_in_datadir): ...this.
	(class gdb_initfile_finder): New class.
	(get_init_files): Now uses gdb_initfile_finder.
	(print_gdb_help): Print 'None found' when there are no init files.
2021-04-15 10:34:09 +01:00
Tankut Baris Aktemur
34dc0f9596 gdb/dwarf2: fix "info locals" for clang-compiled inlined functions
GDB reports duplicate local vars with "<optimized out>" values for
inlined functions that are compiled with Clang.

Suppose we have

  __attribute__((always_inline))
  static void aFunction() {
    int a = 42;
    if(a > 2) {
      int value = a;
      value += 10; /* break here */
    }
  }

The "info locals" command at the "break here" line gives the following
output:

  ...
  Breakpoint 1, aFunction () at test.c:6
  6           value += 10; /* break here */
  (gdb) info locals
  value = 42
  a = 42
  value = <optimized out>
  (gdb)

The reason is, inlined functions that are compiled by Clang do not
contain DW_AT_abstract_origin attributes in the DW_TAG_lexical_block
entries.  See

  https://bugs.llvm.org/show_bug.cgi?id=49953

E.g. the DIE of the inlined function above is

0x00000087:     DW_TAG_inlined_subroutine
                  DW_AT_abstract_origin (0x0000002a "aFunction")
                  DW_AT_low_pc  (0x00000000004004b2)
                  DW_AT_high_pc (0x00000000004004d2)
                  DW_AT_call_file       ("/tmp/test.c")
                  DW_AT_call_line       (11)
                  DW_AT_call_column     (0x03)

0x0000009b:       DW_TAG_variable
                    DW_AT_location      (DW_OP_fbreg -4)
                    DW_AT_abstract_origin       (0x00000032 "a")

0x000000a3:       DW_TAG_lexical_block
                    DW_AT_low_pc        (0x00000000004004c3)
                    DW_AT_high_pc       (0x00000000004004d2)

0x000000b0:         DW_TAG_variable
                      DW_AT_location    (DW_OP_fbreg -8)
                      DW_AT_abstract_origin     (0x0000003e "value")

This causes GDB to fail matching the concrete lexical scope with the
corresponding abstract entry.  Hence, the local vars of the abstract
function that are contained in the lexical scope are read separately
(and thus, in addition to) the local vars of the concrete scope.
Because the abstract definitions of the vars do not contain location
information, we see the extra 'value = <optimized out>' above.

This bug is highly related to PR gdb/25695, but the root cause is not
exactly the same.  In PR gdb/25695, GCC emits an extra
DW_TAG_lexical_block without an DW_AT_abstract_origin that wraps the
body of the inlined function.  That is, the trees of the abstract DIE
for the function and its concrete instance are structurally not the
same.  In the case of using Clang, the trees have the same structure.

To tackle the Clang case, when traversing the children of the concrete
instance root, keep a reference to the child of the abstract DIE that
corresponds to the concrete child, so that we can match the two DIEs
heuristically in case of missing DW_AT_abstract_origin attributes.

The updated gdb.opt/inline-locals.exp test has been checked with GCC
5-10 and Clang 5-11.

gdb/ChangeLog:
2021-04-14  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* dwarf2/read.c (inherit_abstract_dies): Keep a reference to the
	corresponding child of the abstract DIE when iterating the
	children of the concrete DIE.

gdb/testsuite/ChangeLog:
2021-04-14  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* gdb.opt/inline-locals.c (scoped): New function.
	(main): Call 'scoped'.
	* gdb.opt/inline-locals.exp: Update with "info locals" tests
	for scoped variables.
	* gdb.dwarf2/dw2-inline-with-lexical-scope.c: New file.
	* gdb.dwarf2/dw2-inline-with-lexical-scope.exp: New file.
2021-04-14 18:55:36 +02:00
Tom de Vries
329534fda7 [gdb] Fix regoff_t incompatibility
I did an experiment with importing the regex module in gnulib, and trying to
build gdb.

The first problem I ran into was that:
- regoff_t was defined as long int, and
- the address of a regoff_t variable i in ui_file_style::parse was passed
  as int * to function extended_color.

Fix this by changing the types of some function parameters of functions
read_semi_number and extended_color from int * to regoff_t *.

Tested on x86_64-linux.

gdb/ChangeLog:

2021-04-13  Tom de Vries  <tdevries@suse.de>

	* ui-style.c (read_semi_number, extended_color): Change idx parameter
	type to regoff_t *.
2021-04-13 17:38:53 +02:00
Luis Machado
d9d2ef05f1 Fix build failure for 32-bit targets with --enable-targets=all
Replace use of %lx with %s.

gdb/ChangeLog:

2021-04-13  Luis Machado  <luis.machado@linaro.org>

	* rs6000-tdep.c (ppc_displaced_step_fixup): Use %s to print
	hex values.
2021-04-13 10:49:57 -03:00
Will Schmidt
c8a379440e [PATCH] gdb-power10-single-step
Hi,
  This is based on a patch originally written by Alan Modra.
Powerpc / Power10 ISA 3.1 adds prefixed instructions, which
are 8 bytes in length.  This is in contrast to powerpc previously
always having 4 byte instruction length.  This patch implements
changes to allow GDB to better detect prefixed instructions, and
handle single stepping across the 8 byte instructions.

Added #defines to help test for PNOP and prefix instructions.
Update ppc_displaced_step_copy_insn() to handle pnop and prefixed
instructions whem R=0 (non-pc-relative).

Updated ppc_displaced_step_fixup() to properly handle the offset
value matching the current instruction size

Updated the for-loop within ppc_deal_with_atomic_sequence() to
count instructions properly in case we have a mix of 4-byte and
8-byte instructions within the atomic_sequence_length.

Added testcase and harness to exercise pc-relative load/store
instructions with R=0.

2021-04-12  Will Schmidt  <will_schmidt@vnet.ibm.com>

        gdb/ChangeLog:
        * rs6000-tdep.c:  Add support for single-stepping of
        prefixed instructions.

        gdb/testsuite/ChangeLog:
        * gdb.arch/powerpc-plxv-nonrel.s:  Testcase using
        non-relative plxv instructions.
        * gdb.arch/powerpc-plxv-nonrel.exp: Testcase harness.
2021-04-12 14:11:02 -05:00
Will Schmidt
e3d528d7e6 [PATCH, rs6000, v3][PR gdb/27525] displaced stepping across addpcis/lnia.
This addresses PR gdb/27525.     The lnia and other variations
of the addpcis instruction write the value of the NIA into a target register.
If we are single-stepping across a breakpoint, the instruction is executed
from a displaced location, and thusly the written value of the PC/NIA
will be incorrect.   The changes here will measure the displacement
offset, and adjust the target register value to compensate.

YYYY-MM-DD  Will Schmidt  <will_schmidt@vnet.ibm.com>

gdb/ChangeLog:

        * rs6000-tdep.c (ppc_displaced_step_fixup): Update to handle
        the addpcis/lnia instruction.

gdb/testsuite/ChangeLog:

        * gdb.arch/powerpc-addpcis.exp: Testcase harness to
        exercise single-stepping over subpcis,lnia,addpcis instructions
        with displacement.
        * gdb.arch/powerpc-addpcis.s: Testcase with stream
        of addpcis/lnia/subpcis instructions.
        * gdb.arch/powerpc-lnia.exp: Testcase harness to exercise
        single-stepping over lnia instructions with displacement.
        * gdb.arch/powerpc-lnia.s: Testcase with stream of
        lnia instructions.
2021-04-12 13:35:54 -05:00
Will Schmidt
b722acca42 Add myself to gdb/MAINTAINERS
gdb/ChangeLog:

        * MAINTAINERS (Write After Approval): Add myself.
2021-04-12 12:17:52 -05:00
Carl Love
6ba4cb845b RS6000 Add support to print vector register contents as float128
This patch adds a floating point 128-bit composite field to the vsx
register type.  When printing the register with p/f the float128 field will
be printed as a 128-bit floating point value.  A test case to verify the new
vsx register field is visible and correctly prints out the value of a 128-bit
floating point value is also added.

gdb/ChangeLog:

	* rs6000-tdep.c (rs6000_builtin_type_vec128): Add t_float128 variable.
	(rs6000_builtin_type_vec128): Add append_composite_type_field for
	float128.

gdb/testsuite/ChangeLog:

	* gdb.arch/vsx-vsr-float128.c: New test file.
	* gdb.arch/vsx-vsr-float128.exp: New expect file.
2021-04-12 10:36:10 -05:00
Simon Marchi
d471748373 gdb, gdbserver: remove WinCE support code
The support for WinCE was removed with commit 84b300de36 ("gdbserver:
remove support for ARM/WinCE").  There is some leftover code for WinCE
support, guarded by the _WIN32_WCE macro, which I didn't know of at the
time.

I didn't remove the _WIN32_WCE references in the tests, because in
theory we still support the WinCE architecture in GDB (when debugging
remotely).  So someone could run a test with that (although I'd be
really surprised).

gdb/ChangeLog:

	* nat/windows-nat.c: Remove all code guarded by _WIN32_WCE.
	* nat/windows-nat.h: Likewise.

gdbserver/ChangeLog:

	* win32-low.cc: Remove all code guarded by _WIN32_WCE.
	* win32-low.h: Likewise.

Change-Id: I7a871b897e2135dc195b10690bff2a01d9fac05a
2021-04-12 11:10:57 -04:00
Eli Zaretskii
b3885679dd Fix handling DLL loads at run time
This patch makes handling a DLL load at run time (using LoadLibrary)
much more reliable when its file name cannot be obtained using the
lpImageName pointer provided by the DLL load debug event.  The
solution is to enumerate all the DLLs loaded by the inferior, looking
for the DLL that's loaded at base address provided by the lpBaseOfDll
pointer of the debug event.  Correctly resolving the DLL file name is
important, because without that GDB doesn't record the DLL in the list
of solibs, and then later is unable to show functions in that DLL in
the backtraces, which produces corrupted and truncated backtraces.
See this thread for the problems that causes:

  https://sourceware.org/pipermail/gdb-patches/2021-March/177022.html

gdb/ChangeLog:

2021-04-10  Eli Zaretskii  <eliz@gnu.org>

	* windows-nat.c (windows_nat::handle_load_dll): Call
	windows_add_dll if get_image_name failed to glean the name of the
	DLL by using the lpImageName pointer.
	(windows_add_all_dlls): Now a thin wrapper around windows_add_dll.
	(windows_add_dll): Now does what windows_add_all_dlls did before,
	but also accepts an argument LOAD_ADDR, which, if non-NULL,
	specifies the address where the DLL was loaded into the inferior,
	and looks for the single DLL loaded at that address.
2021-04-10 11:42:54 +03:00
Luis Machado
1ef6a59696 [AArch64] Fix include order for MTE
Similarly to commit 665af52ec2, fix a build
failure seen with an updated glibc, due to the enum/constant mismatch.

The old include file order eventually makes asm/ptrace.h get included before
sys/ptrace.h.

This patch fixes it. Seems fairly obvious and I'll push it shortly.

gdb/ChangeLog:

2021-04-09  Luis Machado  <luis.machado@linaro.org>

	* nat/aarch64-mte-linux-ptrace.c: Update include file order.
2021-04-09 11:36:55 -03:00
Dominique Quatravaux
83a559f7b9 Remove unused variable un darwin_nat_target::resume
gdb/ChangeLog:

	* darwin-nat.c (darwin_nat_target::resume): Remove status
	variable.

Change-Id: Ibcbdd6641a12252840c7dea9f388f4f8ce265e3d
2021-04-08 15:22:49 -04:00
Felix Willgerodt
16e311ab6d gdb: Allow prologue detection via symbols for Intel compilers.
The next-gen Intel Fortran compiler isn't flang-based, but emits
prologue_end in the same manner.  As do the newer Intel C/C++ compilers.
This allows prologue detection based on dwarf for all newer Intel compilers.
The cut-off version was not chosen for any specific reason other than the
effort to test this.

gdb/Changelog:
2021-04-08  Felix Willgerodt  <felix.willgerodt@intel.com>

    	* i386-tdep.c (i386_skip_prologue): Use symbol table to find the
    	prologue end for Intel compilers.
    	* amd64-tdep.c (amd64_skip_prologue): Likewise.
    	* producer.c (producer_is_icc_ge_19): New function.
    	* producer.h (producer_is_icc_ge_19): New declaration.
2021-04-08 09:19:57 +02:00
Felix Willgerodt
fbb3bcfcd8 gdb: Update producer check for Intel compilers.
The main goal of this patch is to get rid of a warning for the new Fortran
compiler:

(gdb) b 9
warning: Could not recognize version of Intel Compiler in: "Intel(R) Fortran 21.0-2087b"
Breakpoint 1 at 0x4048cf: file comp.f90, line 9.

While trying to fix this I analyzed DW_AT_producer of all latest Intel
compilers for C, C++ and Fortran.  They do no longer necessarily start with
"Intel (R)" nor do they follow the internal and external version number
scheme that the original patch for this check assumed.  Some newer compilers
even contradict the "intermediate" digit in the old version scheme and have
the MINOR number as the second digit, even when having 3 or 4 digits overall.

Therefore I rewrote the check to consider the first MAJOR.MINOR string found
as the version number.  This might not be 100% correct for some older
internal compilers, but the only current user of this function is only
checking for the major version anyway.  Hence this should be reliable enough
and extendable enough going forward.

gdb/ChangeLog:
2021-04-08  Felix Willgerodt  <felix.willgerodt@intel.com>

    	* producer.c: (producer_is_icc): Update for new version scheme.
    	(producer_parsing_tests): Update names and expected results.
    	* producer.h: (producer_is_icc): Update comment accordingly.
2021-04-08 09:18:55 +02:00
Simon Marchi
e97007b64a gdb: make target_ops::follow_fork return void
I noticed that all implementations return false, so
target_ops::follow_fork doesn't really need to return a value.  Change
it to return void.

gdb/ChangeLog:

	* target.h (struct target_ops) <follow_fork>: Return void.
	(target_follow_fork): Likewise.
	* target.c (default_follow_fork): Likewise.
	(target_follow_fork): Likewise.
	* infrun.c (follow_fork_inferior): Adjust.
	* fbsd-nat.h (class fbsd_nat_target) <follow_fork>: Return void.
	* fbsd-nat.c (fbsd_nat_target:::follow_fork): Likewise.
	* linux-nat.h (class linux_nat_target) <follow_fork>: Likewise.
	* linux-nat.c (linux_nat_target::follow_fork): Return void.
	* obsd-nat.h (class obsd_nat_target) <follow_fork>: Return void.
	* obsd-nat.c (obsd_nat_target::follow_fork): Likewise.
	* remote.c (class remote_target) <follow_fork>: Likewise.
	(remote_target::follow_fork): Likewise.
	* target-delegates.c: Re-generate.

Change-Id: If908c2f68b29fa275be2b0b9deb41e4c6a1b7879
2021-04-07 16:57:29 -04:00
Weimin Pan
dc2b480f3d CTF: handle forward reference type
Added function fetch_tid_type which calls get_tid_type and will set up
the type, associated with a tid, if it is not read in yet. Also implement
function read_forward_type which handles the CTF_K_FORWARD kind.

Expanded gdb.base/ctf-ptype.exp to add cases with forward references.

gdb/ChangeLog:
       * ctfread.c (fetch_tid_type): New function, use throughout file.
       (read_forward_type): New function.
       (read_type_record): Call read_forward_type.

gdb/testsuite/ChangeLog:
       * gdb.base/ctf-ptype.c: Add struct link containing a forward
       reference type.
       * gdb.base/ctf-ptype.exp: Add "ptype struct link".
2021-04-07 14:07:48 -04:00
Andrew Burgess
0a703a4ced gdb/fortran: handle dynamic types within arrays and structures
This commit replaces this patch:

  https://sourceware.org/pipermail/gdb-patches/2021-January/174933.html

which was itself a replacement for this patch:

  https://sourceware.org/pipermail/gdb-patches/2020-July/170335.html

The motivation behind the original patch can be seen in the new test,
which currently gives a GDB session like this:

  (gdb) ptype var8
  type = Type type6
      PTR TO -> ( Type type2 :: ptr_1 )
      PTR TO -> ( Type type2 :: ptr_2 )
  End Type type6
  (gdb) ptype var8%ptr_2
  type = PTR TO -> ( Type type2
      integer(kind=4) :: spacer
      Type type1, allocatable :: t2_array(:)	<------ Issue #1
  End Type type2 )
  (gdb) ptype var8%ptr_2%t2_array
  Cannot access memory at address 0x38		<------ Issue #2
  (gdb)

Issue #1: Here we see the abstract dynamic type, rather than the
resolved concrete type.  Though in some cases the user might be
interested in the abstract dynamic type, I think that in most cases
showing the resolved concrete type will be of more use.  Plus, the
user can always figure out the dynamic type (by source code inspection
if nothing else) given the concrete type, but it is much harder to
figure out the concrete type given only the dynamic type.

Issue #2: In this example, GDB evaluates the expression in
EVAL_AVOID_SIDE_EFFECTS mode (due to ptype).  The value returned for
var8%ptr_2 will be a non-lazy, zero value of the correct dynamic
type.  However, when GDB asks about the type of t2_array this requires
GDB to access the value of var8%ptr_2 in order to read the dynamic
properties.  As this value was forced to zero (thanks to the use of
EVAL_AVOID_SIDE_EFFECTS) then GDB ends up accessing memory at a base
of zero plus some offset.

Both this patch, and my previous two attempts, have all tried to
resolve this problem by stopping EVAL_AVOID_SIDE_EFFECTS replacing the
result value with a zero value in some cases.

This new patch is influenced by how Ada handles its tagged typed.
There are plenty of examples in ada-lang.c, but one specific case is
ada_structop_operation::evaluate.  When GDB spots that we are dealing
with a tagged (dynamic) type, and we're in EVAL_AVOID_SIDE_EFFECTS
mode, then GDB re-evaluates the child operation in EVAL_NORMAL mode.

This commit handles two cases like this specifically for Fortran, a
new fortran_structop_operation, and the already existing
fortran_undetermined, which is where we handle array accesses.

In these two locations we spot when we are dealing with a dynamic type
and re-evaluate the child operation in EVAL_NORMAL mode so that we
are able to access the dynamic properties of the type.

The rest of this commit message is my attempt to record why my
previous patches failed.

To understand my second patch, and why it failed lets consider two
expressions, this Fortran expression:

  (gdb) ptype var8%ptr_2%t2_array	--<A>
  Operation: STRUCTOP_STRUCT		--(1)
   Operation: STRUCTOP_STRUCT		--(2)
    Operation: OP_VAR_VALUE		--(3)
     Symbol: var8
     Block: 0x3980ac0
    String: ptr_2
   String: t2_array

And this C expression:

  (gdb) ptype ptr && ptr->a == 3	--<B>
  Operation: BINOP_LOGICAL_AND		--(4)
   Operation: OP_VAR_VALUE		--(5)
    Symbol: ptr
    Block: 0x45a2a00
   Operation: BINOP_EQUAL		--(6)
    Operation: STRUCTOP_PTR		--(7)
     Operation: OP_VAR_VALUE		--(8)
      Symbol: ptr
      Block: 0x45a2a00
     String: a
    Operation: OP_LONG			--(9)
     Type: int
     Constant: 0x0000000000000003

In expression <A> we should assume that t2_array is of dynamic type.
Nothing has dynamic type in expression <B>.

This is how GDB currently handles expression <A>, in all cases,
EVAL_AVOID_SIDE_EFFECTS or EVAL_NORMAL, an OP_VAR_VALUE operation
always returns the real value of the symbol, this is not forced to a
zero value even in EVAL_AVOID_SIDE_EFFECTS mode.  This means that (3),
(5), and (8) will always return a real lazy value for the symbol.

However a STRUCTOP_STRUCT will always replace its result with a
non-lazy, zero value with the same type as its result.  So (2) will
lookup the field ptr_2 and create a zero value with that type.  In
this case the type is a pointer to a dynamic type.

Then, when we evaluate (1) to figure out the resolved type of
t2_array, we need to read the types dynamic properties.  These
properties are stored in memory relative to the objects base address,
and the base address is in var8%ptr_2, which we already figured out
has the value zero.  GDB then evaluates the DWARF expressions that
take the base address, add an offset and dereference.  GDB then ends
up trying to access addresses like 0x16, 0x8, etc.

To fix this, I proposed changing STRUCTOP_STRUCT so that instead of
returning a zero value we instead returned the actual value
representing the structure's field in the target.  My thinking was
that GDB would not try to access the value's contents unless it needed
it to resolve a dynamic type.  This belief was incorrect.

Consider expression <B>.  We already know that (5) and (8) will return
real values for the symbols being referenced.  The BINOP_LOGICAL_AND,
operation (4) will evaluate both of its children in
EVAL_AVOID_SIDE_EFFECTS in order to get the types, this is required
for C++ operator lookup.  This means that even if the value of (5)
would result in the BINOP_LOGICAL_AND returning false (say, ptr is
NULL), we still evaluate (6) in EVAL_AVOID_SIDE_EFFECTS mode.

Operation (6) will evaluate both children in EVAL_AVOID_SIDE_EFFECTS
mode, operation (9) is easy, it just returns a value with the constant
packed into it, but (7) is where the problem lies.  Currently in GDB
this STRUCTOP_STRUCT will always return a non-lazy zero value of the
correct type.

When the results of (7) and (9) are back in the BINOP_LOGICAL_AND
operation (6), the two values are passed to value_equal which performs
the comparison and returns a result.  Note, the two things compared
here are the immediate value (9), and a non-lazy zero value from (7).

However, with my proposed patch operation (7) no longer returns a zero
value, instead it returns a lazy value representing the actual value
in target memory.  When we call value_equal in (6) this code causes
GDB to try and fetch the actual value from target memory.  If `ptr` is
NULL then this will cause GDB to access some invalid address at an
offset from zero, this will most likely fail, and cause GDB to throw
an error instead of returning the expected type.

And so, we can now describe the problem that we're facing.  The way
GDB's expression evaluator is currently written we assume, when in
EVAL_AVOID_SIDE_EFFECTS mode, that any value returned from a child
operation can safely have its content read without throwing an
error.  If child operations start returning real values (instead of
the fake zero values), then this is simply not true.

If we wanted to work around this then we would need to rewrite almost
all operations (I would guess) so that EVAL_AVOID_SIDE_EFFECTS mode
does not cause evaluation of an operation to try and read the value of
a child operation.  As an example, consider this current GDB code from
eval.c:

  struct value *
  eval_op_equal (struct type *expect_type, struct expression *exp,
  	       enum noside noside, enum exp_opcode op,
  	       struct value *arg1, struct value *arg2)
  {
    if (binop_user_defined_p (op, arg1, arg2))
      {
        return value_x_binop (arg1, arg2, op, OP_NULL, noside);
      }
    else
      {
        binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
        int tem = value_equal (arg1, arg2);
        struct type *type = language_bool_type (exp->language_defn,
  					      exp->gdbarch);
        return value_from_longest (type, (LONGEST) tem);
      }
  }

We could change this function to be this:

  struct value *
  eval_op_equal (struct type *expect_type, struct expression *exp,
  	       enum noside noside, enum exp_opcode op,
  	       struct value *arg1, struct value *arg2)
  {
    if (binop_user_defined_p (op, arg1, arg2))
      {
        return value_x_binop (arg1, arg2, op, OP_NULL, noside);
      }
    else
      {
        struct type *type = language_bool_type (exp->language_defn,
  					      exp->gdbarch);
        if (noside == EVAL_AVOID_SIDE_EFFECTS)
  	  return value_zero (type, VALUE_LVAL (arg1));
        else
  	{
  	  binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
  	  int tem = value_equal (arg1, arg2);
  	  return value_from_longest (type, (LONGEST) tem);
  	}
      }
  }

Now we don't call value_equal unless we really need to.  However, we
would need to make the same, or similar change to almost all
operations, which would be a big task, and might not be a direction we
wanted to take GDB in.

So, for now, I'm proposing we go with the more targeted, Fortran
specific solution, that does the minimal required in order to
correctly resolve the dynamic types.

gdb/ChangeLog:

	* f-exp.h (class fortran_structop_operation): New class.
	* f-exp.y (exp): Create fortran_structop_operation instead of the
	generic structop_operation.
	* f-lang.c (fortran_undetermined::evaluate): Re-evaluate
	expression as EVAL_NORMAL if the result type was dynamic so we can
	extract the actual array bounds.
	(fortran_structop_operation::evaluate): New function.

gdb/testsuite/ChangeLog:

	* gdb.fortran/dynamic-ptype-whatis.exp: New file.
	* gdb.fortran/dynamic-ptype-whatis.f90: New file.
2021-04-07 17:19:46 +01:00
Andrew Burgess
30ab358668 gdb: allow casting to rvalue reference in more cases
It is not currently possible to cast some values to an rvaule
reference.  This happens when simple scalar values are cast to an
rvalue reference of the same type, e.g.:

  int global_var;

Then in GDB:

  (gdb) p static_cast<int&&> (global_var)
  Attempt to take address of value not located in memory.

Which is clearly silly.

The problem is that as part of the cast an intermediate value is
created within GDB that becomes an lval_none rather than the original
lval_memory.  The casting logic basically goes like this:

The call tree that leads to the error looks like this:

  value_cast
    value_cast
    value_ref
      value_addr
        error

The first value_cast call is casting the value for 'global_var' to
type 'int&&'.  GDB spots that the target type is a reference, and so
calls value_cast again, this time casting 'global_var' to type 'int'.
We then call value_ref to convert the result of the second value_cast
into a reference.

Unfortunately, the second cast results in the value (for global_var)
changing from an lval_memory to an lval_none.  This is because int to
int casting calls extract_unsigned_integer and then
value_from_longest.

In theory value_cast has a check at its head that should help in this
case, the code is:

  if (value_type (arg2) == type)
    return arg2;

However, this only works in some cases.  In our case
'value_type (arg2)' will be an objfile owned type, while the type from
the expression parser 'int&&' will be gdbarch owned.  The pointers
will not be equal, but the meaning of the type will be equal.

I did consider making the int to int casting case smarter, but this
obviously is only one example.  We must also consider things like
float to float, or pointer to pointer....

So, I instead decided to try and make the initial check smarter.
Instead of a straight pointer comparison, I now propose that we use
types_deeply_equal.  If this is true then we are casting something
back to its current type, in which case we can preserve the lval
setting by using value_copy.

gdb/ChangeLog:

	* valops.c (value_cast): Call value_deeply_equal before performing
	any cast.

gdb/testsuite/ChangeLog:

	* gdb.cp/rvalue-ref-params.cc (f3): New function.
	(f4): New function.
	(global_int): New global variable.
	(global_float): Likeiwse.
	(main): Call both new functions.
	* gdb.cp/rvalue-ref-params.exp: Add new tests.
2021-04-07 12:49:12 +01:00
Andrew Burgess
5e18990f1f gdb: move cheap pointer equality check earlier in types_equal
I noticed that in types equal we start with a cheap pointer equality
check, then resolve typedefs, then do a series of (semi-)expensive
checks, including checking type names, before, finally performing
another pointer equality check.

We should hoist the second pointer equality check to immediately after
we have resolved typedefs.  This would save performing the more
expensive checks.

This isn't going to give any noticable performance improvement, I just
spotted this in passing and figured I might as well commit the fix.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* gdbtypes.c (types_equal): Move pointer equality check earlier in
	the function.
2021-04-07 12:49:12 +01:00
Caroline Tice
56d467f4ee gdb: handle relative paths to DWO files
DWARF allows .dwo file paths to be relative rather than absolute.

When they are relative, DWARF uses DW_AT_comp_dir to find the .dwo
file.  DW_AT_comp_dir can also be relative, making the entire search
patch for the .dwo file relative.

In this case, GDB currently searches relative to its current working
directory, i.e. the directory from which the debugger was launched,
but not relative to the directory containing the built binary.  This
cannot be right, as the compiler, when generating the relative paths,
knows where it's building the binary but can have no idea where the
debugger will be launched.

The correct thing is to add the directory containing the binary to the
search paths used for resolving relative locations of dwo files. That
is what this patch does.

gdb/ChangeLog:

	* dwarf2/read.c (try_open_dwop_file): Add path for the binary to
	the search paths used resolve relative location of .dwo file.

gdb/testsuite/ChangeLog:

	* gdb.dwarf2/fission-relative-dwo.c: New file.
	* gdb.dwarf2/fission-relative-dwo.exp: New file.
2021-04-07 11:41:50 +01:00
Andrew Burgess
1fd999d909 gdb: Handle missing .debug_str section
While messing with the Dwarf assembler (gdb/testsuite/lib/dwarf.exp) I
managed to create an ELF which made use of DW_FORM_strp, but didn't
include a .debug_str section.

When I started GDB on this ELF, GDB crashed.  I would have expected to
get an error instead.

I tracked this down to an unfortunate design choice in
dwarf2_section_info, a class which wraps around a bfd section, and is
used for reading in debug information.  GBB creates many
dwarf2_section_info objects, one for each debug section that might
need to be read, then as we find the input bfd sections we associate
them with the corresponding dwarf2_section_info.

If no matching input bfd section is found then the dwarf2_section_info
is left in an unassociated state, its internal bfd section pointer is
null.

If later GDB tries to read content from the dwarf2_section_info, for
example, which trying to read the string associated with DW_FORM_strp,
we spot that there is no associated bfd section and issue an error
message.

To make the users life easier, the error message includes the section
name being looked for, and the bfd from which the section was
obtained.

However, we get the section name by calling bfd_section_name on the
associated section, and we get the bfd filename by calling
bfd_get_filename on the owner of the associated section.

Of course, if there is no associated section then both the calls
bfd_section_name and dwarf2_section_info::get_bfd_owner will result in
undefined behaviour (e.g. a crash).

The solution I propose in this patch is, I know, not ideal.  I simply
spot the case where there is no associated section, and print a
simpler error message, leaving out the section name and filename.

A better solution would involve redesigning dwarf2_section_info, we
could associate each dwarf2_section_info with the initial bfd being
parsed.  We would then display this filename if there's nothing better
to display (e.g. if we find a section in a dwo/dwp split dwarf file
then we would probably use that filename in preference).

Each dwarf2_section_info could also have the concept of the default
section name that would be read for that section, for example, string
data might appear in ".debug_str" or ".zdebug_str", but if neither is
found, then it would probably be OK to just say ".debug_str" is
missing.

Anyway, I didn't do any of that redesign, I just wanted to stop GDB
crashing for now, so instead we get this:

  Dwarf Error: DW_FORM_strp used without required section

Which isn't the best, but in context, isn't too bad:

  Reading symbols from /path/to/executable...
  Dwarf Error: DW_FORM_strp used without required section
  (No debugging symbols found in /path/to/executable)

I also added some asserts into dwarf2_section_info which should
trigger before GDB crashes in future, if we trigger any other bad
paths through this code.

And there's a test for the specific issue I hit.

gdb/ChangeLog:

	* dwarf2/section.c (dwarf2_section_info::get_bfd_owner): Add an
	assert.
	(dwarf2_section_info::get_file_name): Add an assert.
	(dwarf2_section_info::read_string): Display a minimal, sane error
	when the dwarf2_section_info is not associated with a bfd section.

gdb/testsuite/ChangeLog:

	* gdb.dwarf2/dw2-using-debug-str.exp: Add an additional test.
2021-04-07 11:31:30 +01:00
Andrew Burgess
79c024436b gdb/py: fix gdb.parameter('data-directory')
It was reported on IRC that using gdb.parameter('data-directory')
doesn't work correctly.

The problem is that the data directory is stored in 'gdb_datadir',
however the set/show command is associated with a temporary
'staged_gdb_datadir'.

When the user does 'set data-directory VALUE', the VALUE is stored in
'staged_gdb_datadir' by GDB, then set_gdb_datadir is called.  This in
turn calls set_gdb_data_directory to copy the value from
staged_gdb_datadir into gdb_datadir.

However, set_gdb_data_directory will resolve relative paths, so the
value stored in gdb_datadir might not match the value in
staged_gdb_datadir.

The Python gdb.parameter API fetches the parameter values by accessing
the variable associated with the show command, so in this case
staged_gdb_datadir.  This causes two problems:

1. Initially staged_gdb_datadir is NULL, and remains as such until the
user does 'set data-directory VALUE' (which might never happen), but
gdb_datadir starts with GDB's default data-directory value.  So
initially from Python gdb.parameter('data-directory') will return the
empty string, even though at GDB's CLI 'show data-directory' prints a
real path.

2. If the user does 'set data-directory ./some/relative/path', GDB
will resolve the relative path, thus, 'show data-directory' at the CLI
will print an absolute path.  However, the value is staged_gdb_datadir
will still be the relative path, and gdb.parameter('data-directory')
from Python will return the relative path.

In this commit I fix both of these issues by:

1. Initialising the value in staged_gdb_datadir based on the initial
value in gdb_datadir, and

2. In set_gdb_datadir, after calling set_gdb_data_directory, I copy
the value in gdb_datadir back into staged_gdb_datadir.

With these two changes in place the value in staged_gdb_datadir should
always match the value in gdb_datadir, and accessing data-directory
from Python should now work correctly.

gdb/ChangeLog:

	* top.c (staged_gdb_datadir): Update comment.
	(set_gdb_datadir): Copy the value of gdb_datadir back into
	staged_datadir.
	(init_main): Initialise staged_gdb_datadir.

gdb/testsuite/ChangeLog:

	* gdb.python/py-parameter.exp: Add test for reading data-directory
	using gdb.parameter API.
2021-04-07 11:14:26 +01:00
Tom de Vries
340d00fb78 [gdb/breakpoints] Workaround missing line-table entry
When running test-case gdb.opt/inline-cmds.exp, we run into this KFAIL with
gcc:
...
Breakpoint 7, main () at gdb.opt/inline-cmds.c:71^M
71        result = 0; /* set breakpoint 3 here */^M
(gdb) PASS: gdb.opt/inline-cmds.exp: continue to breakpoint: consecutive func1
next^M
73        func1 (); /* first call */^M
(gdb) PASS: gdb.opt/inline-cmds.exp: next to first func1
next^M
75        marker ();^M
(gdb) KFAIL: gdb.opt/inline-cmds.exp: next to second func1 (PRMS: gdb/25884)
...
while with clang we have instead:
...
next^M
74        func1 (); /* second call */^M
(gdb) PASS: gdb.opt/inline-cmds.exp: next to second func1
...

The relevant bit of the test source is here in inline-cmds.c:
...
    71    result = 0; /* set breakpoint 3 here */
    72
    73    func1 (); /* first call */
    74    func1 (); /* second call */
    75    marker ();
...
with func1 defined as:
...
    33  inline __attribute__((always_inline)) int func1(void)
    34  {
    35    bar ();
    36    return x * y;
    37  }
...

The corresponding insns are:
...
  40050b:       movl   $0x0,0x200b1f(%rip)        # 601034 <result>
  400515:       callq  40057b <bar>
  40051a:       callq  40057b <bar>
  40051f:       callq  400596 <marker>
...
and the line number info is:
...
Line number    Starting address    View    Stmt
         71            0x40050b               x
         35            0x400515               x
         75            0x40051f               x
...

The line number info is missing an entry for the insn at 40051a, and that is
causing the FAIL.  This is a gcc issue, filed as PR gcc/98780 -" Missing line
table entry for inlined stmt at -g -O0".

[ For contrast, with clang we have an extra entry:
...
Line number    Starting address    View    Stmt
         71            0x40050b               x
         35            0x400515               x
         35            0x40051a
         75            0x40051f               x
...
though it appears to be missing the start-of-statement marker. ]

However, there is debug info that indicates that the insn at 40051a is not
part of the line table entry for the insn at 400515:
...
<2><1c4>: Abbrev Number: 8 (DW_TAG_inlined_subroutine)
    <1c5>   DW_AT_abstract_origin: <0x2a2>
    <1c9>   DW_AT_low_pc      : 0x400515
    <1d1>   DW_AT_high_pc     : 0x5
    <1d9>   DW_AT_call_file   : 1
    <1da>   DW_AT_call_line   : 73
 <2><1db>: Abbrev Number: 8 (DW_TAG_inlined_subroutine)
    <1dc>   DW_AT_abstract_origin: <0x2a2>
    <1e0>   DW_AT_low_pc      : 0x40051a
    <1e8>   DW_AT_high_pc     : 0x5
    <1f0>   DW_AT_call_file   : 1
    <1f1>   DW_AT_call_line   : 74
...
and indeed lldb manages to "next" from line 73 to line 74.

Work around the missing line table entry, by using the inline frame info to
narrow the stepping range in prepare_one_step.

Tested on x86_64-linux.

gdb/ChangeLog:

2021-04-06  Tom de Vries  <tdevries@suse.de>

	PR breakpoints/25884
	* infcmd.c (prepare_one_step): Using inline frame info to narrow
	stepping range.

gdb/testsuite/ChangeLog:

2021-04-06  Tom de Vries  <tdevries@suse.de>

	PR breakpoints/25884
	* gdb.opt/inline-cmds.exp: Remove kfail.
2021-04-06 15:12:38 +02:00
Tom de Vries
d811a7cf74 [gdb/tui] Fix len_without_escapes in tui-disasm.c
On openSUSE Tumbleweed I run into:
...
FAIL: gdb.tui/basic.exp: asm window shows main
ERROR: invalid command name "_csi_L"
...

Using a minimal example, we get:
...
$ gdb -q outputs/gdb.tui/basic/basic -ex "tui enable" -ex "layout asm"
<TUI output>
src/gdb/ui-style.c:243: internal-error: bool \
  ui_file_style::parse(const char*, size_t*): Assertion `match == 0' failed.
...

The problem is in len_without_escapes, where we detect the start of an escape
sequence, but then pass ptr to style.parse while ptr no longer points to the
escape due to the ptr++ in the while condition:
...
  while ((c = *ptr++) != '\0')
     {
      if (c == '\033')
        {
          ui_file_style style;
          size_t n_read;
          if (style.parse (ptr, &n_read))
...

Fix this by removing the ++ in the while condition, and adding ptr++ in the
loop body where appropriate.

Tested on x86_64-linux.

gdb/ChangeLog:

2021-04-06  Tom de Vries  <tdevries@suse.de>

	PR tui/27680
	* tui/tui-disasm.c (len_without_escapes): Pass ptr pointing at escape
	to style.parse.
2021-04-06 10:40:11 +02:00
Simon Marchi
306b445a6d gdb: fix internal error in avr_frame_unwind_cache
When trying to do pretty much anything that requires unwinding a frame
on AVR, we get

    /home/simark/src/wt/avr/gdb/trad-frame.h:143: internal-error: LONGEST trad_frame_saved_reg::addr() const: Assertion `m_kind == trad_frame_saved_reg_kind::ADDR' failed.

This is likely coming from the trad-frame refactor in 098caef485
("Refactor struct trad_frame_saved_regs").  Here's an example of how to
reproduce it:

In one terminal:

    $ cat test.c
    int foo(int x)
    {
      return x * 7;
    }

    int main() {
        return foo(2);
    }
    $ avr-gcc -gdwarf-4 -mmcu=atmega2560 test.c
    $ /tmp/simavr/bin/simavr --mcu atmega2560 -g a.out
    Loaded 330 .text at address 0x0
    Loaded 0 .data

And in another one:

    $ ./gdb -q -nx --data-directory=data-directory a.out -ex "tar rem :1234" -ex "b foo" -ex c -ex bt
    Reading symbols from a.out...
    Remote debugging using :1234
    0x00000000 in __vectors ()
    Breakpoint 1 at 0x110: file test.c, line 3.
    Note: automatically using hardware breakpoints for read-only addresses.
    Continuing.

    Breakpoint 1, foo (x=2) at test.c:3
    3         return x * 7;
    #0  foo (x=2) at test.c:3
    /home/simark/src/wt/avr/gdb/trad-frame.h:143: internal-error: LONGEST trad_frame_saved_reg::addr() const: Assertion `m_kind == trad_frame_saved_reg_kind::ADDR' failed.

What the AVR code does is:

1. In avr_scan_prologue, in the block that says "First stage of the
   prologue scanning.", look for "push rX" instructions and note that rX
   is saved on the stack.  But instead of putting the actual stack
   address directly, it puts an offset (from the previous frame's sp).
2. Back in avr_frame_unwind_cache, in the block that says "Adjust all
   the saved registers", adjust all these values to be real stack
   addresses.

To check whether a register was assigned an address (and therefore if it
needs adjustment), the code does:

    if (info->saved_regs[i].addr () > 0)

Since commit 098caef485, it's invalid to call the `addr` getter of
trad_frame_saved_reg if the register hasn't been assigned an address.
Instead, the code could use the `is_addr` getter to verify if the
register has been assigned an address.  This is what this patch does.

gdb/ChangeLog:

	* avr-tdep.c (avr_frame_unwind_cache): Use
	trad_frame_saved_reg::is_addr.

Change-Id: I5803089160b829400178746c5e3bca0c1cd11c00
2021-04-04 22:29:34 -04:00
Simon Marchi
9161c89ad8 gdb: remove objfile parameter from get_objfile_bfd_data
I noticed it was unused.  I think that makes sense, as it shows that
objfile_per_bfd_storage is not specific to one objfile (it can be shared
by multiple objfiles that have the same bfd).

There is one thing I wonder though, maybe I'm missing something.  If
the BFD doesn't require relocation, get_objfile_bfd_data stores the
newly allocated object in objfiles_bfd_data, so we can assume that
objfiles_bfd_data is the owner of the object.  When the bfd's refcount
drops to 0, the corresponding objfile_per_bfd_storage object in
objfiles_bfd_data is deleted.

But if the BFD requires relocation, get_objfile_bfd_data returns a newly
allocated object that isn't kept anywhere else (and isn't shared).  So
the objfile becomes the owner of the objfile_per_bfd_storage object.  In
objfile::~objfile, we have this:

    if (obfd)
      gdb_bfd_unref (obfd);
    else
      delete per_bfd;

I'm thinking that obfd could be non-nullptr, and it could require
relocation.  In that case, it would never be freed.  Anyway, that's not
really connected to this patch.

gdb/ChangeLog:

	* objfiles.c (get_objfile_bfd_data): Remove objfile parameter,
	adjust callers.

Change-Id: Ifa3158074ea6b42686780ba09d0c964b0cf14cf1
2021-04-02 11:51:45 -04:00
Simon Marchi
0072c87379 gdb: pass objfile_per_bfd_storage instead of objfile to partial_symtab
Since partial_symtab is supposed to be objfile-independent (since series
[1]), I think it would make sense for partial_symtab to not take an
objfile as a parameter in its constructor.

This patch replaces that parameter with an objfile_per_bfd_storage
parameter.

The objfile is used for two things:

 - to get the objfile_name, for debug messages.  We can get that name
   from the bfd instead.
 - to intern the partial symtab filename.  Even though it goes through
   an objfile method, the request is actually forwarded to the
   underlying objfile_per_bfd_storage.  So we can ask the new
   objfile_per_bfd_storage instead.

In order to get a reference to the BFD from the objfile_per_bfd_storage,
the BFD is saved in the objfile_per_bfd_storage object.

[1] https://sourceware.org/pipermail/gdb-patches/2021-February/176625.html

gdb/ChangeLog:

	* psympriv.h (struct partial_symtab) <partial_symtab>: Change
	objfile parameter for objfile_per_bfd_storage, adjust callers.
	(struct standard_psymtab) <standard_psymtab>: Likewise.
	(struct legacy_psymtab) <legacy_psymtab>: Likewise.
	* psymtab.c (partial_symtab::partial_symtab): Likewise.
	* ctfread.c (struct ctf_psymtab): Likewise.
	* dwarf2/read.h (struct dwarf2_psymtab): Likewise.
	* dwarf2/read.c (struct dwarf2_include_psymtab): Likewise.
	(dwarf2_create_include_psymtab): Likewise.
	* objfiles.h (struct objfile_per_bfd_storage)
	<objfile_per_bfd_storage>: Add bfd parameter, adjust callers.
	<get_bfd>: New method.
	<m_bfd>: New field.
	* objfiles.c (get_objfile_bfd_data): Adjust.

Change-Id: I2ed3ab5d2e6f27d034bd4dc26ae2fae7b0b8a2b9
2021-04-02 11:45:37 -04:00
Simon Marchi
9984dd9994 gdb: use std::string in partial_symtab::partial_symtab / allocate_symtab
This simplifies the code a bit.

gdb/ChangeLog:

	* psymtab.c (partial_symtab::partial_symtab): Change
	last_objfile_name to be an std::string.
	* symfile.c (allocate_symtab): Likewise.

Change-Id: I3dfe217233ed9346c2abc04a9b1be0df69a90af8
2021-04-02 11:39:55 -04:00
Simon Marchi
4a4f97c129 gdb: add intern methods to objfile_per_bfd_storage
This allows keeping the objfile_per_bfd_storage implementation details
into objfile_per_bfd_storage, instead of into objfile.  And this makes
the intern methods usable for code that only has an
objfile_per_bfd_storage to work with.

gdb/ChangeLog:

	* objfiles.h (struct objfile_per_bfd_storage) <intern>: New
	methods.
	(struct objfile) <intern>: Use
	objfile::objfile_per_bfd_storage::intern.

Change-Id: Ifd54026c5efaeffafac9b84ff84c199acc7ce78a
2021-04-02 11:35:29 -04:00
Simon Marchi
0672875f3c gdb: remove TYPE_FLAG_ENUM
gdb/ChangeLog:

	* gdbtypes.h (TYPE_FLAG_ENUM): Remove, replace all uses
	with type::is_flag_enum.

Change-Id: I74e23893066eecd6df641045b859a6d6ebb13dd0
2021-04-01 21:10:09 -04:00
Simon Marchi
9902b32793 gdb: add type::is_flag_enum / type::set_is_flag_enum
Add the `is_flag_enum` and `set_is_flag_enum` methods on `struct type`,
in order to remove the `TYPE_FLAG_ENUM` macro.  In this patch, the macro
is changed to use the getter, so all the call sites of the macro that
are used as a setter are changed to use the setter method directly.  The
next patch will remove the macro completely.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <is_flag_enum,
	set_is_flag_enum>: New methods.
	(TYPE_FLAG_ENUM): Use type::is_flag_enum, change all
	write call sites to use type::set_is_flag_enum.

Change-Id: I9c56c91626c8d784947ba94fcb97818526b81d1c
2021-04-01 21:10:09 -04:00
Simon Marchi
3bc440a2c4 gdb: remove TYPE_DECLARED_CLASS
gdb/ChangeLog:

	* gdbtypes.h (TYPE_DECLARED_CLASS): Remove, replace all uses
	with type::is_declared_class.

Change-Id: Ifecb2342417ecd7bf570c3205344b09d706daab2
2021-04-01 21:10:09 -04:00
Simon Marchi
aa70e35c71 gdb: add type::is_declared_class / type::set_is_declared_class
Add the `is_declared_class` and `set_is_declared_class` methods on
`struct type`, in order to remove the `TYPE_DECLARED_CLASS` macro.  In
this patch, the macro is changed to use the getter, so all the call
sites of the macro that are used as a setter are changed to use the
setter method directly.  The next patch will remove the macro
completely.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <is_declared_class,
	set_is_declared_class>: New methods.
	(TYPE_DECLARED_CLASS): Use type::is_declared_class, change all
	write call sites to use type::set_is_declared_class.

Change-Id: Idf08d32e137c885a0aba0a18f556a899c1cbfd68
2021-04-01 21:10:08 -04:00
Boris Staletic
bfb9f5dcfe Use importlib instead of imp module on python 3.4+
Python 3.4 has deprecated the imp module in favour of importlib. This
patch avoids the DeprecationWarning. This warning is visible to users
whose libpython.so has been compiled with --with-pydebug.

Considering that even python 3.5 has reached end of life, would it be
better to just use importlib and drop support for python 3.0 to 3.3?

2021-02-28  Boris Staletic  <boris.staletic@gmail.com>

	* gdb/python/lib/gdb/__init__.py: Use importlib on python 3.4+
	to avoid deprecation warnings.
2021-04-01 12:26:52 -06:00
Martin Liska
733f5eea6b Use startswith in gdb subfolder.
gdb/ChangeLog:

	* cp-name-parser.y: Use startswith instead of strncmp.
	* m2-exp.y: Likewise.
	* macroexp.c (substitute_args): Likewise.
	* mi/mi-main.c (command_notifies_uscc_observer): Likewise.
	* rust-exp.y: Likewise.
2021-04-01 06:29:59 +02:00
Tom Tromey
af82f89db0 Remove two trivial functions from dwarf2/read.c
This removes dw2_map_matching_symbols and dw2_expand_symtabs_matching,
merging them with their sole trivial callers.

gdb/ChangeLog
2021-03-31  Tom Tromey  <tom@tromey.com>

	* dwarf2/read.c (dwarf2_gdb_index::map_matching_symbols): Merge
	with dw2_map_matching_symbols.
	(dwarf2_gdb_index::expand_symtabs_matching): Merge with
	dw2_expand_symtabs_matching.
2021-03-31 18:28:30 -06:00
Tom Tromey
3570682a2c Fix typo in dwarf2/stringify.h
Pedro pointed out a typo in a comment in dwarf2/stringify.h.  This
fixes it.

gdb/ChangeLog
2021-03-31  Tom Tromey  <tromey@adacore.com>

	* dwarf2/stringify.h: Fix typo.
2021-03-31 09:48:56 -06:00
Simon Marchi
8a91fbdf3b gdb/dwarf: disable per-BFD resource sharing for -readnow objfiles
New in v2:

  - Disable sharing only for -readnow objfiles, not all objfiles.

As described in PR 27541, we hit an internal error when loading a binary
the standard way and then loading it with the -readnow option:

    $ ./gdb -nx -q --data-directory=data-directory ~/a.out -ex "set confirm off" -ex "file -readnow ~/a.out"
    Reading symbols from /home/simark/a.out...
    Reading symbols from ~/a.out...
    /home/simark/src/binutils-gdb/gdb/dwarf2/read.c:8098: internal-error: void create_all_comp_units(dwarf2_per_objfile*): Assertion `per_objfile->per_bfd->all_comp_units.empty ()' failed.

This is a recurring problem that exposes a design issue in the DWARF
per-BFD sharing feature.  Things work well when loading a binary with
the same method (with/without index, with/without readnow) twice in a
row.  But they don't work so well when loading a binary with different
methods.  See this previous fix, for example:

    efb763a5ea ("gdb: check for partial symtab presence in dwarf2_initialize_objfile")

That one handled the case where the first load is normal (uses partial
symbols) and the second load uses an index.

The problem is that when loading an objfile with a method A, we create a
dwarf2_per_bfd and some dwarf2_per_cu_data and initialize them with the
data belonging to that method.  When loading another obfile sharing the
same BFD but with a different method B, it's not clear how to re-use the
dwarf2_per_bfd/dwarf2_per_cu_data previously created, because they
contain the data specific to method A.

I think the most sensible fix would be to not share a dwarf2_per_bfd
between two objfiles loaded with different methods.  That means that two
objfiles sharing the same BFD and loaded the same way would share a
dwarf2_per_bfd.  Two objfiles sharing the same BFD but loaded with
different methods would use two different dwarf2_per_bfd structures.

However, this isn't a trivial change.  So to fix the known issue quickly
(including in the gdb 10 branch), this patch just disables all
dwarf2_per_bfd sharing for objfiles using READNOW.

Generalize the gdb.base/index-cache-load-twice.exp test to test all
the possible combinations of loading a file with partial symtabs, index
and readnow.  Move it to gdb.dwarf2, since it really exercises features
of the DWARF reader.

gdb/ChangeLog:

	PR gdb/27541
	* dwarf2/read.c (dwarf2_has_info): Don't share dwarf2_per_bfd
	with objfiles using READNOW.

gdb/testsuite/ChangeLog:

	PR gdb/27541
	* gdb.base/index-cache-load-twice.exp: Remove.
	* gdb.base/index-cache-load-twice.c: Remove.
	* gdb.dwarf2/per-bfd-sharing.exp: New.
	* gdb.dwarf2/per-bfd-sharing.c: New.

Change-Id: I9ffcf1e136f3e75242f70e4e58e4ba1fd3083389
2021-03-30 13:37:11 -04:00
Tom Tromey
9f67fc596b Remove parameter from language_info
I noticed that language_info is only ever called with a value of '1'.
This patch removes the parameter.

2021-03-29  Tom Tromey  <tromey@adacore.com>

	* top.c (check_frame_language_change): Update.
	* language.c (language_info): Remove parameter.
	* language.h (language_info): Remove parameter.
2021-03-29 09:36:11 -06:00
Luis Machado
9b8ffbf410 Don't pass empty options to GCC
On aarch64-linux, I noticed the compile command didn't work at all.  It
always gave the following error:

aarch64-linux-gnu-g++: error: : No such file or directory

Turns out we're passing an empty argv entry to GCC (because aarch64 doesn't
have a -m64 option), and GCC's behavior is to think that is a file it needs
to open.  One can reproduce it like so:

gcc "" "" "" ""
gcc: error: : No such file or directory
gcc: error: : No such file or directory
gcc: error: : No such file or directory
gcc: error: : No such file or directory
gcc: fatal error: no input files
compilation terminated.

The solution is to check for an empty string and skip adding that to argv.

Regression tested on aarch64-linux/Ubuntu 18.04/20.04.

gdb/ChangeLog:

2021-03-29  Luis Machado  <luis.machado@linaro.org>

	* compile/compile.c (get_args): Don't add empty argv entries.
2021-03-29 11:59:50 -03:00
Rainer Orth
25b48839b3 Restore procfs.c compilation
Since c8fbd44a01 (gdb: remove
target_is_pushed free function), procfs.c compilation is broken, which
went unnoticed for lack of functioning buildbots:

/vol/src/gnu/gdb/hg/master/dist/gdb/procfs.c: In member function 'virtual void procfs_target::attach(const char*, int)':
/vol/src/gnu/gdb/hg/master/dist/gdb/procfs.c:1772:8: error: 'inf' was not declared in this scope; did you mean 'info'?
 1772 |   if (!inf->target_is_pushed (this))
      |        ^~~
      |        info
/vol/src/gnu/gdb/hg/master/dist/gdb/procfs.c: In member function 'virtual void procfs_target::create_inferior(const char*, const string&, char**, int)':
/vol/src/gnu/gdb/hg/master/dist/gdb/procfs.c:2865:8: error: 'inf' was not declared in this scope; did you mean 'info'?
 2865 |   if (!inf->target_is_pushed (this))
      |        ^~~
      |        info

Fixed by defining inf.  Tested on amd64-pc-solaris2.11 and
sparcv9-sun-solaris2.11.

2021-03-29  Rainer Orth  <ro@CeBiTec.Uni-Bielefeld.DE>

	gdb:
	* procfs.c (procfs_target::attach): Define inf.
	Use it.
	(procfs_target::create_inferior): Likewise.
2021-03-29 13:26:35 +02:00
Tom Tromey
edc02ceb97 Simplify DWARF reader initialization
Now that the quick functions are separate from the object file format,
there's no need to have elfread.c push a new entry on the objfile 'qf'
list.  Instead, this detail can be pushed into the DWARF reader.  That
is what this patch implements.

I wasn't sure whether lazy reading still makes sense or not.  It's
still only used by ELF, and only in certain situations (like vfork, I
think).  It may not be carrying its weight, so we may want to consider
removing this in the future.

Also, I'm unclear on why the various indices are only used for ELF.
This seems sub-optimal.  However, I haven't tried to address that
here.

gdb/ChangeLog
2021-03-28  Tom Tromey  <tom@tromey.com>

	* elfread.c (can_lazily_read_symbols): Move to dwarf2/read.c.
	(elf_symfile_read): Simplify.
	* dwarf2/read.c (struct lazy_dwarf_reader): Move from elfread.c.
	(make_lazy_dwarf_reader): New function.
	(make_dwarf_gdb_index, make_dwarf_debug_names): Now static.
	(dwarf2_initialize_objfile): Return void.  Remove index_kind
	parameter.  Push on 'qf' list.
	* dwarf2/public.h (dwarf2_initialize_objfile): Change return
	type.  Remove 'index_kind' parameter.
	(make_dwarf_gdb_index, make_dwarf_debug_names): Don't declare.
2021-03-28 10:43:15 -06:00
Tom Tromey
6e23d91aa7 Don't declare elf_sym_fns_lazy_psyms
An earlier patch neglected to delete a forward declaration of
elf_sym_fns_lazy_psyms.  This is no longer defined.  This patch
removes it.

gdb/ChangeLog
2021-03-27  Tom Tromey  <tom@tromey.com>

	* elfread.c (elf_sym_fns_lazy_psyms): Don't declare.
2021-03-27 16:48:36 -06:00