Commit Graph

29894 Commits

Author SHA1 Message Date
Samuel Thibault c6887cfb4f hurd: add missing awk script dependency
To make sure the *_reply_S.[ch] files get regenerated whenever we change
the awk script.

gdb/ChangeLog:

	* config/i386/i386gnu.mn (%_reply_S.c): Add dependency on
	$(srcdir)/reply_mig_hack.awk.
2020-05-30 18:40:29 +00:00
Samuel Thibault 6930bffe33 hurd: fix gnu_debug_flag type
Fixes

../../gdb/gnu-nat.c:96:6: error: conflicting declaration ‘bool gnu_debug_flag’
   96 | bool gnu_debug_flag = false;
../../gdb/gnu-nat.c: In function ‘void _initialize_gnu_nat()’:
../../gdb/gnu-nat.c:3511:7: error: cannot

gdb/ChangeLog:

	* gnu-nat.h (gnu_debug_flag): Set type to bool.
2020-05-30 18:40:25 +00:00
Jonny Grant 112c22ed1f gdb: change bug URL to https
gdb/ChangeLog:

	* configure.ac (ACX_BUGURL): change bug URL to https.

Signed-off-by: Jonny Grant <jg@jguk.org>
Change-Id: If8d939e50c830e3e452c3e8f7a7aee06d9c96645
2020-05-30 11:18:53 -04:00
Pedro Alves f68f85b52b replace_typedefs: handle templates in namespaces
GDB currently crashes with infinite recursion, if you set a breakpoint
on a function inside a namespace that includes a template on its fully
qualified name, and, the template's name is also used as typedef in
the global scope that expands to a name that includes the template
name in its qualified name.  For example, from the testcase added by
this commit:

 namespace NS1 { namespace NS2 {

 template<typename T> struct Templ1
 {
   T x;

   Templ1 (object_p) {}
 }} // namespace NS1::NS2

 using Templ1 = NS1::NS2::Templ1<unsigned>;

Setting a breakpoint like so:

(gdb) break NS1::NS2::Templ1<int>::Templ1(NS1::NS2::object*)

Results in infinite recursion, with this cycle (started by
cp_canonicalize_string_full) repeating until the stack is exhausted:

 ...
 #1709 0x000000000055533c in inspect_type (info=0x38ff720, ret_comp=0xd83be10, finder=0x0, data=0x0) at /home/pedro/gdb/mygit/src/gdb/cp-support.c:267
 #1710 0x0000000000555a6f in replace_typedefs (info=0x38ff720, ret_comp=0xd83be10, finder=0x0, data=0x0) at /home/pedro/gdb/mygit/src/gdb/cp-support.c:475
 #1711 0x0000000000555a36 in replace_typedefs (info=0x38ff720, ret_comp=0xd83be70, finder=0x0, data=0x0) at /home/pedro/gdb/mygit/src/gdb/cp-support.c:470
 #1712 0x0000000000555800 in replace_typedefs_qualified_name (info=0x38ff720, ret_comp=0xd839470, finder=0x0, data=0x0) at /home/pedro/gdb/mygit/src/gdb/cp-support.c:389
 #1713 0x0000000000555a8c in replace_typedefs (info=0x38ff720, ret_comp=0xd839470, finder=0x0, data=0x0) at /home/pedro/gdb/mygit/src/gdb/cp-support.c:479
 ...

The demangle component tree for that symbol name looks like this:

d_dump tree for NS1::NS2::Templ1<int>::Templ1(NS1::NS2::object*):
typed name
  qualified name
    name 'NS1'
    qualified name
      name 'NS2'
      qualified name
        template                  <<<<<<<<<<
          name 'Templ1'
          template argument list
            builtin type int
        name 'Templ1'
  function type
    argument list
      pointer
        qualified name
          name 'NS1'
          qualified name
            name 'NS2'
            name 'object'

The recursion starts at replace_typedefs_qualified_name, which doesn't
handle the "template" node, and thus doesn't realize that the template
name actually has the fully qualified name NS1::NS2::Templ1.
replace_typedefs_qualified_name calls into replace_typedefs on the
template node, and that ends up in inspect_type looking up for a
symbol named "Templ1", which finds the global namespace typedef, which
itself expands to NS1::NS2::Templ1.  GDB then tries replacing typedefs
in that newly expanded name, which ends up again in
replace_typedefs_qualified_name, trying to expand a fully qualified
name with "NS::NS2::Templ1<unsigned>" in its name, which results in
recursion whenever the template node is reached.

Fix this by teaching replace_typedefs_qualified_name how to handle
template nodes.  It needs handling in two places: the first spot
handles the symbol above; the second spot handles a symbol like this,
from the new test:

(gdb) b NS1::NS2::grab_it(NS1::NS2::Templ1<int>*)
d_dump tree for NS1::NS2::grab_it(NS1::NS2::Templ1<int>*):
typed name
  qualified name
    name 'NS1'
    qualified name
      name 'NS2'
      name 'grab_it'
  function type
    argument list
      pointer
        qualified name
          name 'NS1'
          qualified name
            name 'NS2'
            template             <<<<<<<<
              name 'Templ1'
              template argument list
                builtin type int

What's different in this case is that the template node appears on the
right child node of a qualified name, instead of on the left child.

The testcase includes a test that checks whether template aliases are
correctly replaced by GDB too.  That fails with GCC due to GCC PR
95437, which makes GDB not know about a typedef for
"NS1::NS2::AliasTempl<int>".  GCC emits a typedef named
"NS1::NS2::AliasTempl" instead, with no template parameter info.  The
test passes with Clang (5.0.2 at least).  See more details here:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95437

gdb/ChangeLog:
2020-05-30  Pedro Alves  <palves@redhat.com>

	* cp-support.c (replace_typedefs_template): New.
	(replace_typedefs_qualified_name): Handle
	DEMANGLE_COMPONENT_TEMPLATE.

gdb/testsuite/ChangeLog:
2020-05-30  Pedro Alves  <palves@redhat.com>

	* gdb.linespec/cp-replace-typedefs-ns-template.cc: New.
	* gdb.linespec/cp-replace-typedefs-ns-template.exp: New.
2020-05-30 14:20:10 +01:00
Simon Marchi 976ca31673 gdb: rename dwarf2_per_objfile variables/fields to per_objfile
While doing the psymtab-sharing patchset, I avoided renaming variables
unnecessarily to avoid adding noise to patches, but I'd like to do it
now.  Basically, we have these dwarf2 per-something structures:

  - dwarf2_per_objfile
  - dwarf2_per_bfd
  - dwarf2_per_cu_data

I named the instances of dwarf2_per_bfd `per_bfd` and most of instances
of dwarf2_per_cu_data are called `per_cu`.  Most pre-existing instances
of dwarf2_per_objfile are named `dwarf2_per_objfile`.  For consistency
with the other type, I'd like to rename them to just `per_objfile`.  The
`dwarf2_` prefix is superfluous, since it's already clear we are in
dwarf2 code.  It also helps reducing the line wrapping by saving 7
precious columns.

gdb/ChangeLog:

	* dwarf2/comp-unit.c, dwarf2/comp-unit.h, dwarf2/index-cache.c,
	dwarf2/index-cache.h, dwarf2/index-write.c,
	dwarf2/index-write.h, dwarf2/line-header.c,
	dwarf2/line-header.h, dwarf2/macro.c, dwarf2/macro.h,
	dwarf2/read.c, dwarf2/read.h: Rename struct dwarf2_per_objfile
	variables and fields from `dwarf2_per_objfile` to just
	`per_objfile` throughout.

Change-Id: I3c45cdcc561265e90df82cbd36b4b4ef2fa73aef
2020-05-29 15:15:10 -04:00
Simon Marchi 989ade0552 gdb: add comment in dwarf_evaluate_loc_desc::push_dwarf_reg_entry_value
Add a comment to clarify why we temporarily override some of the
context's fields, and especially the per_objfile field.  A longer
explanation can be found in this previous commit

    44486dcf19 ("gdb: use caller objfile in dwarf_evaluate_loc_desc::push_dwarf_reg_entry_value")

gdb/ChangeLog:

	* dwarf2/loc.c (class dwarf_evaluate_loc_desc)
	<push_dwarf_reg_entry_value>: Add comment.

Change-Id: I60c6e1062799f729b30a9db78bcb6448783324b4
2020-05-28 15:47:53 -04:00
Kevin Buettner c47bae859a Fix Python3.9 related runtime problems
Python3.9b1 is now available on Rawhide.  GDB w/ Python 3.9 support
can be built using the configure switch -with-python=/usr/bin/python3.9.

Attempting to run gdb/Python3.9 segfaults on startup:

    #0  0x00007ffff7b0582c in PyEval_ReleaseLock () from /lib64/libpython3.9.so.1.0
    #1  0x000000000069ccbf in do_start_initialization ()
	at worktree-test1/gdb/python/python.c:1789
    #2  _initialize_python ()
	at worktree-test1/gdb/python/python.c:1877
    #3  0x00000000007afb0a in initialize_all_files () at init.c:237
    ...

Consulting the the documentation...

https://docs.python.org/3/c-api/init.html

...we find that PyEval_ReleaseLock() has been deprecated since version
3.2.  It recommends using PyEval_SaveThread or PyEval_ReleaseThread()
instead.  In do_start_initialization, in gdb/python/python.c, we
can replace the calls to PyThreadState_Swap() and PyEval_ReleaseLock()
with a single call to PyEval_SaveThread.   (Thanks to Keith Seitz
for working this out.)

With that in place, GDB gets a little bit further.  It still dies
on startup, but the backtrace is different:

    #0  0x00007ffff7b04306 in PyOS_InterruptOccurred ()
       from /lib64/libpython3.9.so.1.0
    #1  0x0000000000576e86 in check_quit_flag ()
	at worktree-test1/gdb/extension.c:776
    #2  0x0000000000576f8a in set_active_ext_lang (now_active=now_active@entry=0x983c00 <extension_language_python>)
	at worktree-test1/gdb/extension.c:705
    #3  0x000000000069d399 in gdbpy_enter::gdbpy_enter (this=0x7fffffffd2d0,
	gdbarch=0x0, language=0x0)
	at worktree-test1/gdb/python/python.c:211
    #4  0x0000000000686e00 in python_new_inferior (inf=0xddeb10)
	at worktree-test1/gdb/python/py-inferior.c:251
    #5  0x00000000005d9fb9 in std::function<void (inferior*)>::operator()(inferior*) const (__args#0=<optimized out>, this=0xccad20)
	at /usr/include/c++/10/bits/std_function.h:617
    #6  gdb::observers::observable<inferior*>::notify (args#0=0xddeb10,
	this=<optimized out>)
	at worktree-test1/gdb/../gdbsupport/observable.h:106
    #7  add_inferior_silent (pid=0)
	at worktree-test1/gdb/inferior.c:113
    #8  0x00000000005dbcb8 in initialize_inferiors ()
	at worktree-test1/gdb/inferior.c:947
    ...

We checked with some Python Developers and were told that we should
acquire the GIL prior to calling any Python C API function.  We
definitely don't have the GIL for calls of PyOS_InterruptOccurred().

I moved class_gdbpy_gil earlier in the file and use it in
gdbpy_check_quit_flag() to acquire (and automatically release) the
GIL.

With those changes in place, I was able to run to a GDB prompt.  But,
when trying to quit, it segfaulted again due to due to some other
problems with gdbpy_check_quit_flag():

    Thread 1 "gdb" received signal SIGSEGV, Segmentation fault.
    0x00007ffff7bbab0c in new_threadstate () from /lib64/libpython3.9.so.1.0
    (top-gdb) bt 8
    #0  0x00007ffff7bbab0c in new_threadstate () from /lib64/libpython3.9.so.1.0
    #1  0x00007ffff7afa5ea in PyGILState_Ensure.cold ()
       from /lib64/libpython3.9.so.1.0
    #2  0x000000000069b58c in gdbpy_gil::gdbpy_gil (this=<synthetic pointer>)
	at worktree-test1/gdb/python/python.c:278
    #3  gdbpy_check_quit_flag (extlang=<optimized out>)
	at worktree-test1/gdb/python/python.c:278
    #4  0x0000000000576e96 in check_quit_flag ()
	at worktree-test1/gdb/extension.c:776
    #5  0x000000000057700c in restore_active_ext_lang (previous=0xe9c050)
	at worktree-test1/gdb/extension.c:729
    #6  0x000000000088913a in do_my_cleanups (
	pmy_chain=0xc31870 <final_cleanup_chain>,
	old_chain=0xae5720 <sentinel_cleanup>)
	at worktree-test1/gdbsupport/cleanups.cc:131
    #7  do_final_cleanups ()
	at worktree-test1/gdbsupport/cleanups.cc:143

In this case, we're trying to call a Python C API function after
Py_Finalize() has been called from finalize_python().  I made
finalize_python set gdb_python_initialized to false and then cause
check_quit_flag() to return early when it's false.

With these changes in place, GDB seems to be working again with
Python3.9b1.  I think it likely that there are other problems lurking.
I wouldn't be surprised to find that there are other calls into Python
where we don't first make sure that we have the GIL.  Further changes
may well be needed.

I see no regressions testing on Rawhide using a GDB built with the
default Python version (3.8.3) versus one built using Python 3.9b1.

I've also tested on Fedora 28, 29, 30, 31, and 32 (all x86_64) using
the default (though updated) system installed versions of Python on
those OSes.  This means that I've tested against Python versions
2.7.15, 2.7.17, 2.7.18, 3.7.7, 3.8.2, and 3.8.3.  In each case GDB
still builds without problem and shows no regressions after applying
this patch.

gdb/ChangeLog:

2020-MM-DD  Kevin Buettner  <kevinb@redhat.com>
	    Keith Seitz  <keiths@redhat.com>

	* python/python.c (do_start_initialization): For Python 3.9 and
	later, call PyEval_SaveThread instead of PyEval_ReleaseLock.
	(class gdbpy_gil): Move to earlier in file.
	(finalize_python): Set gdb_python_initialized.
	(gdbpy_check_quit_flag): Acquire GIL via gdbpy_gil.  Return early
	when not initialized.
2020-05-28 12:46:16 -07:00
Simon Marchi 44486dcf19 gdb: use caller objfile in dwarf_evaluate_loc_desc::push_dwarf_reg_entry_value
In commit

    89b07335fe ("Add dwarf2_per_objfile to dwarf_expr_context and dwarf2_frame_cache")

I replaced the offset property of dwarf_expr_context by a per_objfile
property (since we can get the text offset from the objfile).  The
previous code in dwarf_evaluate_loc_desc::push_dwarf_reg_entry_value
(dwarf_evaluate_loc_desc derives from dwarf_expr_context) did
temporarily override the offset property while evaluating a DWARF
sub-expression.  I speculated that this sub-expression always came from
the same objfile as the outer expression, so I didn't see the need to
temporarily override the per_objfile property in the new code.  A later
commit:

    9f47c70716 ("Remove dwarf2_per_cu_data::objfile ()")

added the following assertion to verify this:

    gdb_assert (this->per_objfile == caller_per_objfile);

It turns out that this is not true.  Call sites can refer to function in
another objfile, and therefore the caller's objfile can be different
from the callee's objfile.  This can happen when the call site DIE in the
DWARF represents a function call done through a function pointer.  The
DIE can't describe statically which function is being called, since it's
variable and not known at compile time.  Instead, it provides an
expression that evaluates to the address of the function being called.
In this case, the called function can very well be in a separate
objfile.

Fix this by overriding the per_objfile property while evaluating the
sub-expression.

This was exposed by the gdb.base/catch-load.exp test failing on openSUSE
Tumbleweed with the glibc debug info installed.  It was also reported to
fail on Fedora.

When I investigated the problem, the particular call site on which we
did hit the assert was coming from this DIE, in
/usr/lib/debug/lib64/libc-2.31.so-2.31-5.1.x86_64.debug on openSUSE
Tumbleweed:

    0x0091aa10:     DW_TAG_GNU_call_site
                      DW_AT_low_pc [DW_FORM_addr]   (0x00000000001398e0)
                      DW_AT_GNU_call_site_target [DW_FORM_exprloc]  (DW_OP_fbreg -272, DW_OP_deref)
                      DW_AT_sibling [DW_FORM_ref4]  (0x0091aa2b)

And for you curious out there, this call site is found in this function:

    0x0091a91d:   DW_TAG_subprogram
                    DW_AT_external [DW_FORM_flag_present]   (true)
                    DW_AT_name [DW_FORM_strp]       ("_dl_catch_exception")
                    DW_AT_decl_file [DW_FORM_data1] ("/usr/src/debug/glibc-2.31-5.1.x86_64/elf/dl-error-skeleton.c")
                    ...

Which is a function that indeed uses a function pointer.

gdb/ChangeLog:

	* dwarf2/loc.c (class dwarf_evaluate_loc_desc)
	<push_dwarf_reg_entry_value>: Remove assert.  Override
	per_objfile with caller_per_objfile.

Change-Id: Ib227d767ce525c10607ab6621a373aaae982c67a
2020-05-28 11:31:00 -04:00
Tom de Vries f030440daa [gdb/symtab] Make gold index workaround more precise
There's a PR gold/15646 - "gold-generated .gdb_index has duplicated
symbols that gdb-generated index doesn't", that causes gold to generate
duplicate symbols in the index.

F.i., a namespace N1 declared in a header file can be listed for two CUs that
include the header file:
...
[759] N1:
        2 [global type]
        3 [global type]
...

This causes a gdb performance problem: f.i. when attempting to set a
breakpoint on a non-existing function N1::misspelled, the symtab for both CUs
will be expanded.

Gdb contains a workaround for this, added in commit 8943b87476 "Work around
gold/15646", that skips duplicate global symbols in the index.

However, the workaround does not check for the symbol kind ("type" in the
example above).

Make the workaround more precise by limiting it to symbol kind "type".

Tested on x86_64-linux, with target boards cc-with-gdb-index and
gold-gdb-index.

gdb/ChangeLog:

2020-05-28  Tom de Vries  <tdevries@suse.de>

	* dwarf2/read.c	(dw2_symtab_iter_next, dw2_expand_marked_cus): Limit
	PR gold/15646 workaround to symbol kind "type".
2020-05-28 17:26:22 +02:00
Tom Tromey f0fbb768c2 Use add_partial_symbol in load_partial_dies
An earlier patch added the add_partial_symbol helper function to
dwarf2/read.c.  However, a couple of calls to add_psymbol_to_list were
left in place.  It turns out that these calls slow down partial symbol
reading, because they still go via the path that tries to needlessly
demangle already-demangled names.

This patch improves the performance of partial symbol reading by
changing this code to use add_partial_symbol instead.

The run previous to this had times of (see the first patch in the
series for an explanation):

gdb    1.64
libxul 1.99
Ada    2.47

This patch improves the times to:

gdb    1.47
libxul 1.89
Ada    2.39

gdb/ChangeLog
2020-05-27  Tom Tromey  <tromey@adacore.com>

	* dwarf2/read.c (load_partial_dies): Use add_partial_symbol.
2020-05-27 11:48:19 -06:00
Tom Tromey af0b2a3e85 Inline abbrev lookup
Profiling showed that calls to abbrev_table::lookup_abbrev were "too
visible".  As these are just forwarding calls to the hash table, this
patch inlines the lookup.  Also, htab_find_with_hash is used, avoiding
another call.

The run previous to this had times of (see the first patch in the
series for an explanation):

gdb    1.69
libxul 2.02
Ada    2.52

This patch improves the times to:

gdb    1.64
libxul 1.99
Ada    2.47

gdb/ChangeLog
2020-05-27  Tom Tromey  <tromey@adacore.com>

	* dwarf2/abbrev.h (struct abbrev_table) <lookup_abbrev>: Inline.
	Use htab_find_with_hash.
	<add_abbrev>: Remove "abbrev_number" parameter.
	* dwarf2/abbrev.c (abbrev_table::add_abbrev): Remove
	"abbrev_number" parameter.  Use htab_find_slot_with_hash.
	(hash_abbrev): Add comment.
	(abbrev_table::lookup_abbrev): Move to header file.
	(abbrev_table::read): Update.
2020-05-27 11:48:19 -06:00
Tom Tromey 7d00ffecd2 Lazily compute partial DIE name
Currently the name of a partial DIE is computed eagerly.  However, the
name is not always needed.  This patch changes partial DIEs to compute
their name lazily, improving performance by avoiding unnecessary name
computations.

The run previous to this had times of (see the first patch in the
series for an explanation):

gdb    1.88
libxul 2.11
Ada    2.60

This patch improves the times to:

gdb    1.69
libxul 2.02
Ada    2.52

gdb/ChangeLog
2020-05-27  Tom Tromey  <tromey@adacore.com>

	* dwarf2/read.c (struct partial_die_info) <name>: Declare new
	method.
	<canonical_name>: New member.
	<raw_name>: Rename from "name".
	(partial_die_info): Initialize canonical_name.
	(scan_partial_symbols): Check raw_name.
	(partial_die_parent_scope, partial_die_full_name)
	(add_partial_symbol, add_partial_subprogram)
	(add_partial_enumeration, load_partial_dies): Use "name" method.
	(partial_die_info::name): New method.
	(partial_die_info::read, guess_partial_die_structure_name)
	(partial_die_info::fixup): Update.
2020-05-27 11:48:19 -06:00
Tom Tromey 697bba1827 Attribute method inlining
This inlines a couple of methods on struct attribute, improving the
performance of DWARF partial symbol reading.  These methods were
discovered as hot spots using callgrind.

For this patch, and for all the patches in this series, I tested gdb's
performance on three programs:

1. gdb itself -- I built gdb and copied it to /tmp, ensuring that the
   same version was used in all tests.

2. The system libxul.so, the main library of Firefox.  I installed the
   separate debuginfo and ensured that gdb read it.

3. A large-ish Ada program that I happen to have.

I ran gdb 10 times like:

	  /bin/time -f %e \
		    ./gdb/gdb --data-directory ./gdb/data-directory -nx \
		    -iex 'set debug-file-directory /usr/lib/debug' \
		    -batch $X

... where $X was the test executable.  Then I computed the mean time.
This was all done with a standard (-g -O2) build of gdb.

The baseline times were

gdb    1.90
libxul 2.12
Ada    2.61

This patch brings the numbers down to

gdb    1.88
libxul 2.11
Ada    2.60

Not a huge change, but still visible in the results.

gdb/ChangeLog
2020-05-27  Tom Tromey  <tromey@adacore.com>

	* dwarf2/attribute.h (struct attribute) <form_is_ref>: Inline.
	<get_ref_die_offset>: Inline.
	<get_ref_die_offset_complaint>: New method.
	* dwarf2/attribute.c (attribute::form_is_ref): Move to header.
	(attribute::get_ref_die_offset_complaint): Rename from
	get_ref_die_offset.  Just issue complaint.
2020-05-27 11:48:18 -06:00
Hannes Domani c17ace4397 Move exit_status_set_internal_vars out of GLOBAL_CURDIR
Fixes these testsuite fails on Windows:
FAIL: gdb.base/shell.exp: shell success exitcode
FAIL: gdb.base/shell.exp: shell fail exitcode

The convenience variables $_shell_exitcode and $_shell_exitsignal don't
depend on the GLOBAL_CURDIR define.

gdb/ChangeLog:

2020-05-27  Hannes Domani  <ssbssa@yahoo.de>

	* cli/cli-cmds.c (shell_escape): Move exit_status_set_internal_vars.
2020-05-27 19:42:53 +02:00
Hannes Domani 96445f0b66 Use errno value of first openp failure
Fixes this testsuite fail on Windows:
FAIL: gdb.base/bad-file.exp: directory

If both tries to open the file fail (without and with ".exe"), use the
errno value of the first try.

gdb/ChangeLog:

2020-05-27  Hannes Domani  <ssbssa@yahoo.de>

	* exec.c (exec_file_attach): Use errno value of first openp failure.
2020-05-27 19:41:07 +02:00
Hannes Domani ac637ec30d Don't close thread handles provided by WaitForDebugEvent
I sometimes encountered a weird breakpoint failure when using start:

(gdb) start
Temporary breakpoint 2 at 0x40162d: file gdb-25911.c, line 4.
Starting program: C:\src\tests\gdb-25911.exe
Warning:
Cannot insert breakpoint 2.
Cannot access memory at address 0x401628

After trying a lot of combinations, I found a way to reproduce it:

(gdb) file gdb-25987.exe
Reading symbols from gdb-25987.exe...
(gdb) start
Temporary breakpoint 1 at 0x401638: file gdb-25987.cpp, line 13.
Starting program: C:\src\tests\gdb-25987.exe

Temporary breakpoint 1, main () at gdb-25987.cpp:13
13      int main() {
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
MyClass::call (this=0x3d20d0) at gdb-25987.cpp:8
8           *(char*)(nullptr) = 1;
(gdb) kill
Kill the program being debugged? (y or n) y
[Inferior 1 (process 1140) killed]
(gdb) file gdb-25911.exe
Load new symbol table from "gdb-25911.exe"? (y or n) y
Reading symbols from gdb-25911.exe...
(gdb) start
Temporary breakpoint 2 at 0x40162d: file gdb-25911.c, line 4.
Starting program: C:\src\tests\gdb-25911.exe
Warning:
Cannot insert breakpoint 2.
Cannot access memory at address 0x401628

Command aborted.

The actual failure was that ReadProcessMemory used a process handle that
was no longer valid.
And the underlying reason was that the windows_thread_info destructor
closes a thread handle that was provided earlier by WaitForDebugEvent.

But since this is not allowed (and it was actually already closed at this
point, and the handle value reused), this closed another still-needed handle.

gdb/ChangeLog:

2020-05-27  Hannes Domani  <ssbssa@yahoo.de>

	* nat/windows-nat.c (windows_thread_info::~windows_thread_info):
	Don't close thread handle.
2020-05-27 19:15:53 +02:00
Tom Tromey 17ee85fc2a Share DWARF partial symtabs
This changes the DWARF reader to share partial symtabs (or indices if
they are available) across objfiles.  This has a few parts.

* If multiple objfiles backed by the same BFD can share partial symtabs
  (see below), a single dwarf2_per_bfd is created.  It is stored in the
  per-bfd `dwarf2_per_bfd_bfd_data_key` registry.  Multiple
  dwarf2_per_objfile objects will point to the same instance.  The
  lifetime of these dwarf2_per_bfd objects is naturally handled.  When
  all the objfiles using the BFD are destroyed, the BFD's refount drops
  to 0, which triggers the removal of the corresponding dwarf2_per_bfd
  object from the registry and its destruction.

* If multiple objfiles backed by the same BFD can't share partial
  symtabs (see below), one dwarf2_per_bfd object is created for each
  objfile.  Each dwarf2_per_objfile will point to their own instance of
  dwarf2_per_bfd.  These instances of dwarf2_per_bfd are kept in a
  per-objfile registry, meaning that when the objfile gets destroyed,
  the dwarf2_per_bfd instance gets destroyed as well.

* objfile::partial_symtabs is changed to be a shared_ptr again.  This
  lets us stash a second reference in dwarf2_per_bfd; if the DWARF
  data is being shared, we can simply copy this value to the new
  objfile.

* Two dwarf2_per_objfile objects backed by the same BFD may share a
  dwarf2_per_bfd instance if:

  * No other symbol reader has found symbols, and
  * No BFD section rqeuires relocation

gdb/ChangeLog:

YYYY-MM-DD  Tom Tromey  <tom@tromey.com>
YYYY-MM-DD  Simon Marchi  <simon.marchi@efficios.com>

	* objfiles.h (struct objfile) <partial_symtabs>: Now a
	shared_ptr.
	* dwarf2/read.h (struct dwarf2_per_objfile) <partial_symtabs>: New
	member.
	* dwarf2/read.c (dwarf2_per_bfd_bfd_data_key,
	dwarf2_per_bfd_objfile_data_key>: New globals.
	(dwarf2_has_info): Use shared dwarf2_per_bfd if possible.
	(dwarf2_get_section_info): Use get_dwarf2_per_objfile.
	(dwarf2_initialize_objfile): Consider cases where per_bfd can be
	shared.
	(dwarf2_build_psymtabs): Set objfile::partial_symtabs and
	short-circuit when sharing.
	(dwarf2_build_psymtabs): Set dwarf2_per_objfile::partial_symtabs.
	(dwarf2_psymtab::expand_psymtab): Use free_cached_comp_units.

Change-Id: I868c64448589102ab8cbb8f06c31a8de50a14004
2020-05-27 11:20:15 -04:00
Simon Marchi 39b16f87f7 Move line_header_hash to dwarf2_per_objfile
The `line_header_hash` field of `struct dwarf2_per_bfd` contains some
`struct line_header` objects.  A `struct line_header` objects contains
some `file_entry` objects.  A `file_entry` object contains a pointer to
the `symtab` object created from it.  The `line_header_hash` is
therefore ultimately objfile-dependent and can't be shared as-is between
objfiles.

Move it from `dwarf2_per_bfd` to `dwarf2_per_objfile`.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_bfd) <line_header_hash>: Move
	to...
	(struct dwarf2_per_objfile) <line_header_hash>: ... here.
	* dwarf2/read.c (handle_DW_AT_stmt_list): Update.

Change-Id: I8d2ee04df4f4847c2db99061fc976c35af98ac71
2020-05-27 11:19:41 -04:00
Simon Marchi fcf23d5b65 Make mapped_debug_names independent of objfile
mapped_debug_names currently has a dwarf2_per_objfile field.  Since we
want it to become objfile-independent, this field must be removed.

This patch removes it, and then arranges for all methods that needed it
to accept a dwarf2_per_objfile parameter.  This trickles down at various
places, like the dw2_debug_names_iterator type.

Ultimately, the objfile only seems to be needed because we might need to
read a string from the string section.  For that, we might need to read
in the section, and if it's a relocatable section, the objfile is needed
in order to do the relocation.  This pattern happens often (that we to
pass an objfile only because a section might be read).  I think it's a
bit ugly, but I don't have a good alternative right now.

gdb/ChangeLog:

	* dwarf2/read.c (struct mapped_index_base) <symbol_name_at,
	build_name_components, find_name_components_bounds>:
	Add per_objfile parameter.
	(struct mapped_index) <symbol_name_at>: Likewise.
	(struct mapped_debug_names): Remove constructor.
	<dwarf2_per_objfile>: Remove field.
	<namei_to_name, symbol_name_at>: Add per_objfile parameter.
	(mapped_index_base::find_name_components_bounds,
	mapped_index_base::build_name_components,
	dw2_expand_symtabs_matching_symbol): Likewise.
	(class mock_mapped_index) <symbol_name_at>: Likewise.
	(check_match): Likewise.
	(check_find_bounds_finds): Likewise.
	(test_mapped_index_find_name_component_bounds): Update.
	(CHECK_MATCH): Update.
	(dw2_expand_symtabs_matching): Update.
	(class dw2_debug_names_iterator) <dw2_debug_names_iterator>: Add
	per_objfile parameter.
	<find_vec_in_debug_names>: Likewise.
	<m_per_objfile>: New field.
	(mapped_debug_names::namei_to_name): Add dwarf2_per_objfile
	parameter.
	(dw2_debug_names_iterator::find_vec_in_debug_names): Likewise.
	(dw2_debug_names_iterator::next): Update.
	(dw2_debug_names_lookup_symbol): Update.
	(dw2_debug_names_expand_symtabs_for_function): Update.
	(dw2_debug_names_map_matching_symbols): Update.
	(dw2_debug_names_expand_symtabs_matching): Update.
	(dwarf2_read_debug_names): Update.

Change-Id: I00ee0d939390d353442675c7d400a261307c57a1
2020-05-27 11:19:41 -04:00
Simon Marchi 7188ed02d2 Replace dwarf2_per_cu_data::cu backlink with per-objfile map
The dwarf2_per_cu_data type is going to become objfile-independent,
while the dwarf2_cu type will stay object-dependent.  This patch removes
the backlink from dwarf2_per_cu_data to dwarf2_cu, in favor of the
dwarf2_per_objfile::m_dwarf2_cus map.  It maps dwarf2_per_cu_data
objects to the corresponding dwarf2_cu objects for this objfile.  If a
CU has been read in in the context of this objfile, then an entry will
be present in the map.

The dwarf2_cu objects that are read in are currently kept in a linked
list rooted in the dwarf2_per_bfd.  Except that the dwarf2_cu objects
are not simply linked together, they are interleaved with their
corresponding dwarf2_per_cu_data objects.  So if we have CUs A and B
read in, the dwarf2_per_bfd::read_in_chain will point to a chain like
this (DPCD == dwarf2_per_cu_data, DC == dwarf2_cu):

 DPCD A -> DC A -> DPCD B -> DC B

Obviously, this can't stay as is, since a same CU can be read in for an
objfile but not read in for another objfile sharing the same BFD, and
the dwarf2_per_cu_data::cu link is removed.   This is all replaced by
the dwarf2_per_objfile::m_dwarf2_cus map.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_cu): Forward-declare.
	(struct dwarf2_per_bfd) <free_cached_comp_units>: Remove,
	move to dwarf2_per_objfile.
	<read_in_chain>: Remove.
	(struct dwarf2_per_objfile) <get_cu, set_cu, remove_cu,
	remove_all_cus, age_comp_units>: New methods.
	<m_dwarf2_cus>: New member.
	(struct dwarf2_per_cu_data) <cu>: Remove.
	* dwarf2/read.c (struct dwarf2_cu) <read_in_chain>: Remove.
	(age_cached_comp_units, free_one_cached_comp_unit): Remove,
	moved to methods of dwarf2_per_objfile.
	(dwarf2_clear_marks): Remove.
	(dwarf2_queue_item::~dwarf2_queue_item): Update.
	(dwarf2_per_bfd::~dwarf2_per_bfd): Don't free dwarf2_cus.
	(dwarf2_per_bfd::free_cached_comp_units): Remove.
	(dwarf2_per_objfile::remove_all_cus): New.
	(class free_cached_comp_units) <~free_cached_comp_units>:
	Update.
	(load_cu): Update.
	(dw2_do_instantiate_symtab): Adjust.
	(fill_in_sig_entry_from_dwo_entry): Adjust.
	(cutu_reader::init_tu_and_read_dwo_dies): Update.
	(cutu_reader::cutu_reader): Likewise.
	(cutu_reader::keep): Use dwarf2_per_objfile::set_cu.
	(cutu_reader::cutu_reader): Use dwarf2_per_objfile::get_cu.
	(process_psymtab_comp_unit): Use dwarf2_per_objfile::remove_cu
	and dwarf2_per_objfile::age_comp_units.
	(load_partial_comp_unit): Update.
	(maybe_queue_comp_unit): Use dwarf2_per_objfile::get_cu.
	(process_queue): Likewise.
	(find_partial_die): Use dwarf2_per_objfile::get_cu instead of cu
	backlink.
	(dwarf2_read_addr_index): Likewise.
	(follow_die_offset): Likewise.
	(dwarf2_fetch_die_loc_sect_off): Likewise.
	(dwarf2_fetch_constant_bytes): Likewise.
	(dwarf2_fetch_die_type_sect_off): Likewise.
	(follow_die_sig_1): Likewise.
	(load_full_type_unit): Likewise.
	(read_signatured_type): Likewise.
	(dwarf2_cu::dwarf2_cu): Don't set cu field.
	(dwarf2_cu::~dwarf2_cu): Remove.
	(dwarf2_per_objfile::get_cu): New.
	(dwarf2_per_objfile::set_cu): New.
	(age_cached_comp_units): Rename to...
	(dwarf2_per_objfile::age_comp_units): ... this.  Adjust
	to std::unordered_map.
	(free_one_cached_comp_unit): Rename to...
	(dwarf2_per_objfile::remove_cu): ... this.  Adjust
	to std::unordered_map.
	(dwarf2_per_objfile::~dwarf2_per_objfile): New.
	(dwarf2_mark_helper): Use dwarf2_per_objfile::get_cu, expect
	a dwarf2_per_objfile in data.
	(dwarf2_mark): Pass dwarf2_per_objfile in data to htab_traverse.
	(dwarf2_clear_marks): Remove.

Change-Id: Ia33ac71c79b2de4710569008e22a6563a1505cde
2020-05-27 11:19:40 -04:00
Simon Marchi 2e6711003b Pass existing_cu object to cutu_reader
It is possible, seemingly for a special case described in
find_partial_die, for cutu_reader to re-use an existing dwarf2_cu
instead of creating a new one.  This happens when running this test, for
example:

    make check TESTS="gdb.dwarf2/fission-reread.exp"

Right now the, `use_existing_cu` flag tells cutu_reader to use the
dwarf2_cu object at dwarf2_per_cu_data::cu.  However, we'll remove that
field, so we need to find another solution.

This situation arises when some caller up the stack has already created
the dwarf2_cu to read a dwarf2_per_cu_data, but needs to re-read it with
some other parameters.  Therefore, it's possible to just have that
caller pass down the dwarf2_cu object to use as a `existing_cu`
parameter.  If `existing_cu` is NULL, it tells cutu_reader that it needs
to instantiate a new one.

gdb/ChangeLog:

	* dwarf2/read.c (class cutu_reader) <cutu_reader>: Replace
	`int use_existing_cu` parameter with `dwarf2_cu *existing_cu`.
	(init_tu_and_read_dwo_dies): Likewise.
	(cutu_reader::init_tu_and_read_dwo_dies): Likewise.
	(cutu_reader::cutu_reader): Likewise.
	(load_partial_comp_unit): Likewise.
	(process_psymtab_comp_unit): Update.
	(build_type_psymtabs_1): Update.
	(process_skeletonless_type_unit): Update.
	(load_full_comp_unit): Update.
	(find_partial_die): Update.
	(dwarf2_read_addr_index): Update.
	(read_signatured_type): Update.

Change-Id: Id03e3bc3de3cf99d9e4b4080ad83b029c93bf434
2020-05-27 11:19:40 -04:00
Simon Marchi 2e6a9f7959 Add comp_unit_head to dwarf2_per_cu_data
The per_cu_header_read_in function allows obtaining a filled
comp_unit_head object for a given dwarf2_per_cu_data object.  If a
dwarf2_cu object exists for this dwarf2_per_cu_data, then it just
returns a pointer to the comp_unit_head from that dwarf2_cu.  Otherwise,
it reads the header into a temporary buffer provided by the caller, and
returns a pointer to that.

Since the dwarf2_per_cu_data::cu link is going to be removed
(dwarf2_per_cu_data will become objfile-independent while dwarf2_cu
stays objfile-dependent), we cannot rely anymore on returning the header
from the dwarf2_cu object.

The not too complex solution implemented by this patch is to keep a copy
of the header in the dwarf2_per_cu_data object, independent from the
copy in dwarf2_cu.  The new copy is only used in the addr_size,
offset_size and ref_addr_size methods of dwarf2_per_cu_data.

There's nothing intrinsic to the comp_unit_head object that prevents it
to be shared between two dwarf2_cu objects (belonging to different
objfiles) representing the same CU.  In other words, I think we could
eventually get rid of the copy in dwarf2_cu to only keep the one in
dwarf2_per_cu_data.  It is not trivial, however, so I have decided not
to do it for the moment.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_cu_data) <m_header,
	m_header_read_in>: New fields.
	<get_header>: New method.
	* dwarf2/read.c (per_cu_header_read_in): Remove.
	(dwarf2_per_cu_data::get_header): New.
	(dwarf2_per_cu_data::addr_size): Update.
	(dwarf2_per_cu_data::offset_size): Update.
	(dwarf2_per_cu_data::ref_addr_size): Update.

Change-Id: Id7541fca7562843eba110ece21c4df38d45fca23
2020-05-27 11:19:40 -04:00
Simon Marchi 1b555f1747 Make load_cu return the loaded dwarf2_cu
In a subsequent patch, the dwarf2_per_cu_data::cu link will be removed.
dwarf2_cu objects will instead need to be looked up from a per-objfile
map, using the dwarf2_per_cu_data object as the key.

To make it easier for some callers, this patch makes load_cu return the
dwarf2_cu it creates.  If the caller needs to use the created dwarf2_cu,
it will have it available right away, rather than having to do a map
lookup.

At the same time, this allows changing queue_and_load_all_dwo_tus to
take a dwarf2_cu instead of a dwarf2_per_cu_data.

gdb/ChangeLog:

	* dwarf2/read.c (load_cu): Return dwarf2_cu.
	(dw2_do_instantiate_symtab): Update.
	(queue_and_load_all_dwo_tus): Change parameter from
	dwarf2_per_cu_data to dwarf2_cu.
	(dwarf2_fetch_die_loc_sect_off): Update.
	(dwarf2_fetch_constant_bytes): Update.
	(dwarf2_fetch_die_type_sect_off): Update.

Change-Id: I8a04c5d1b8cc661b8203f97999258ba8e04e1765
2020-05-27 11:19:40 -04:00
Simon Marchi 8fc0b21da6 Pass dwarf2_cu to process_full_{comp,type}_unit
These two functions work on a dwarf2_cu.  It is currently obtained from
the per_cu->cu link, which we want to remove.  Make them accept the
dwarf2_cu directly as a parameter.  This moves the per_cu->cu references
one level up, but that one will be removed too in a subsequent patch.

gdb/ChangeLog:

	* dwarf2/read.c (process_full_comp_unit,
	process_full_type_unit): Remove per_cu, per_objfile paramters.
	Add dwarf2_cu parameter.
	(process_queue): Update.

Change-Id: I1027d36986073ac991e198e06f9d51341dc19c6e
2020-05-27 11:19:40 -04:00
Simon Marchi 168c9250f2 Pass dwarf2_per_bfd instead of dwarf2_per_objfile to some index-related functions
All these functions actually only need to receive a dwarf2_per_bfd, pass
that instead of dwarf2_per_objfile.

gdb/ChangeLog:

	* dwarf2/read.c (create_cu_from_index_list): Replace
	dwarf2_per_objfile parameter with dwarf2_per_bfd.
	(create_cus_from_index_list): Likewise.
	(create_cus_from_index): Likewise.
	(create_signatured_type_table_from_index): Likewise.
	(create_cus_from_debug_names_list): Likewise.
	(create_cus_from_debug_names): Likewise.
	(dwarf2_read_gdb_index): Update.
	(dwarf2_read_debug_names): Update.

Change-Id: I8cd7dc04bf815723a48745e7e9b283663dccc1ac
2020-05-27 11:19:40 -04:00
Tom Tromey e286671bf9 Move signatured_type::type to unshareable object
signatured_type has a link to the "struct type".  However, types are
inherently objfile-specific, so once sharing is implemented, this will
be incorrect.

This patch moves the type to a new map in the DWARF unshareable
object.

gdb/ChangeLog:

YYYY-MM-DD  Tom Tromey  <tom@tromey.com>
YYYY-MM-DD  Simon Marchi  <simon.marchi@efficios.com>

	* dwarf2/read.h (struct dwarf2_per_objfile)
	<get_type_for_signatured_type, set_type_for_signatured_type>:
	New methods.
	<m_type_map>: New member.
	(struct signatured_type) <type>: Remove.
	* dwarf2/read.c
	(dwarf2_per_objfile::get_type_for_signatured_type,
	dwarf2_per_objfile::set_type_for_signatured_type): New.
	(get_signatured_type): Use new methods.

Change-Id: I765ae3c43fae1064f51ced352167a57638609f02
2020-05-27 11:19:35 -04:00
Tom Tromey 8adb84872b Split type_unit_group
type_unit_group has links to the compunit_symtab and other symtabs.
However, once this object is shared across objfiles, this will no
longer be ok.

This patch introduces a new type_unit_group_unshareable and arranges to
store a map from type unit groups to type_unit_group_unshareable objects
in dwarf2_per_objfile.

gdb/ChangeLog:

YYYY-MM-DD  Tom Tromey  <tom@tromey.com>
YYYY-MM-DD  Simon Marchi  <simon.marchi@efficios.com>

	* dwarf2/read.h (struct type_unit_group_unshareable): New.
	(struct dwarf2_per_objfile) <type_units>: New member.
	<get_type_unit_group_unshareable>: New method.
	* dwarf2/read.c (struct type_unit_group) <compunit_symtab,
	num_symtabs, symtabs>: Remove; move to
	type_unit_group_unshareable.
	(dwarf2_per_objfile::get_type_unit_group_unshareable): New.
	(process_full_type_unit, dwarf2_cu::setup_type_unit_groups)
	(dwarf2_cu::setup_type_unit_groups): Use type_unit_group_unshareable.

Change-Id: I1fec2fab59e0ec40fee3614fc821172a469c0e41
2020-05-27 11:19:09 -04:00
Simon Marchi 127bbf4b50 Remove dwarf2_per_cu_data::dwarf2_per_objfile
Nothing references this field anymore, remove it.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_cu_data):
	<dwarf2_per_objfile>: Remove.
	* dwarf2/read.c (create_cu_from_index_list): Don't assign
	dwarf2_per_objfile.
	(create_signatured_type_table_from_index): Likewise.
	(create_signatured_type_table_from_debug_names): Likewise.
	(create_debug_type_hash_table): Likewise.
	(fill_in_sig_entry_from_dwo_entry): Likewise.
	(create_type_unit_group): Likewise.
	(read_comp_units_from_section): Likewise.
	(create_cus_hash_table): Likewise.

Change-Id: Icf0b657a6beec953fe17cbe0fb2ae2c6e744d3ed
2020-05-27 11:15:58 -04:00
Simon Marchi f6e649ddaf Remove leftover references to dwarf2_per_cu_data::dwarf2_per_objfile
This patch removes the remaining references to that field in obvious
ways (the same object is already available some other way in these
contexts).

gdb/ChangeLog:

	* dwarf2/read.c (process_psymtab_comp_unit): Remove reference to
	dwarf2_per_cu_data::dwarf2_per_objfile.
	(compute_compunit_symtab_includes): Likewise.
	(dwarf2_cu::start_symtab): Likewise.

Change-Id: I965700fa793d8457711a2d6ae448aaefd779eb96
2020-05-27 11:15:58 -04:00
Simon Marchi aa66c37944 Add dwarf2_per_objfile parameter to get_die_type_at_offset
This allows removing some dwarf2_per_cu_data::dwarf2_per_objfile
references.

gdb/ChangeLog:

	* dwarf2/read.h (dwarf2_get_die_type): Add dwarf2_per_objfile
	parameter.
	* dwarf2/read.c (get_die_type_at_offset): Likewise.
	(read_namespace_alias): Update.
	(lookup_die_type): Update.
	(dwarf2_get_die_type): Add dwarf2_per_objfile parameter.
	* dwarf2/loc.c (class dwarf_evaluate_loc_desc) <get_base_type>:
	Update.
	(disassemble_dwarf_expression): Update.

Change-Id: Ibaf5b684cb0a8eb8f0b23e62bd0283c295410aa5
2020-05-27 11:15:58 -04:00
Simon Marchi 120ce1b5b2 Add dwarf2_per_objfile parameter to free_one_cached_comp_unit
This allows removing some references to
dwarf2_per_cu_data::dwarf2_per_objfile.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_queue_item): Add
	dwarf2_per_objfile parameter, assign new parameter.
	<per_objfile>: New field.
	* dwarf2/read.c (free_one_cached_comp_unit): Add
	dwarf2_per_objfile parameter.
	(queue_comp_unit): Likewise.
	(dw2_do_instantiate_symtab): Update.
	(process_psymtab_comp_unit): Update.
	(maybe_queue_comp_unit): Add dwarf2_per_objfile parameter.
	(process_imported_unit_die): Update.
	(queue_and_load_dwo_tu): Update.
	(follow_die_offset): Update.
	(follow_die_sig_1): Update.

Change-Id: Ibb4a4ea28eeac5ebcbf73c0d2a13f9391e15c235
2020-05-27 11:15:57 -04:00
Simon Marchi 9f47c70716 Remove dwarf2_per_cu_data::objfile ()
Since dwarf2_per_cu_data objects are going to become
objfile-independent, the backlink from dwarf2_per_cu_data to one
particular objfile must be removed.  Instead, users of
dwarf2_per_cu_data that need an objfile must know from somewhere else in
the context of which objfile they are using this CU.

This also helps remove a dwarf2_per_cu_data::dwarf2_per_objfile
reference (from where the objfile was obtained).

Note that the dwarf2_per_cu_data::objfile method has a special case to
make sure to return the main objfile, if the objfile associated to the
dwarf2_per_cu_data is a separate debug objfile.  I don't really know if
this is necessary: I ignored that, and didn't see any regression when
testing with the various Dejagnu boards with separate debug info, so I
presume it wasn't needed.  If it turns out this was needed, then we can
have a helper method on the objfile type for that.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_cu_data) <objfile>: Remove.
	* dwarf2/read.c (dwarf2_compute_name): Pass per_objfile down.
	(read_call_site_scope): Assign per_objfile.
	(dwarf2_per_cu_data::objfile): Remove.
	* gdbtypes.h (struct call_site) <per_objfile>: New member.
	* dwarf2/loc.h (dwarf2_evaluate_loc_desc): Add
	dwarf2_per_objfile parameter.
	* dwarf2/loc.c (dwarf2_evaluate_loc_desc_full): Add
	dwarf2_per_objfile parameter.
	(dwarf_expr_reg_to_entry_parameter): Add output
	dwarf2_per_objfile parameter.
	(locexpr_get_frame_base): Update.
	(class dwarf_evaluate_loc_desc) <get_tls_address>: Update.
	<push_dwarf_reg_entry_value>: Update.
	<call_site_to_target_addr>: Update.
	(dwarf_entry_parameter_to_value): Add dwarf2_per_objfile
	parameter.
	(value_of_dwarf_reg_entry): Update.
	(rw_pieced_value): Update.
	(indirect_synthetic_pointer): Update.
	(dwarf2_evaluate_property): Update.
	(dwarf2_loc_desc_get_symbol_read_needs): Add dwarf2_per_objfile
	parameter.
	(locexpr_read_variable): Update.
	(locexpr_get_symbol_read_needs): Update.
	(loclist_read_variable): Update.

Change-Id: Idb40d1a94995af305054d463967bb6ce11a08f25
2020-05-27 11:15:57 -04:00
Simon Marchi 14095eb326 Add dwarf2_per_objfile parameters to dwarf2_fetch_* functions
This allows removing dwarf2_per_cu_data references.

gdb/ChangeLog:

	* dwarf2/read.h (dwarf2_fetch_die_loc_sect_off,
	dwarf2_fetch_die_loc_cu_off, dwarf2_fetch_constant_bytes,
	dwarf2_fetch_die_type_sect_off): Add dwarf2_per_objfile
	parameter.
	* dwarf2/read.c (dwarf2_fetch_die_loc_sect_off,
	dwarf2_fetch_die_loc_cu_off, dwarf2_fetch_constant_bytes,
	dwarf2_fetch_die_type_sect_off): Add dwarf2_per_objfile
	parameter.
	* dwarf2/loc.c (indirect_synthetic_pointer, per_cu_dwarf_call,
	sect_variable_value): Add dwarf2_per_objfile parameter.
	(class dwarf_evaluate_loc_desc) <dwarf_call,
	dwarf_variable_value>: Update.
	(fetch_const_value_from_synthetic_pointer): Add
	dwarf2_per_objfile parameter.
	(fetch_const_value_from_synthetic_pointer): Update.
	(coerced_pieced_ref): Update.
	(class symbol_needs_eval_context) <dwarf_call,
	dwarf_variable_value>: Update.
	(dwarf2_compile_expr_to_ax): Update.

Change-Id: I07cf1806380633d0572304cea049a1fa5e9ea67f
2020-05-27 11:15:57 -04:00
Simon Marchi 3c3cd3d4d7 Add dwarf2_per_objfile parameter to allocate_piece_closure
This allows removing a dwarf2_per_cu_data::dwarf2_per_objfile reference.

gdb/ChangeLog:

	* dwarf2/loc.c (allocate_piece_closure): Add dwarf2_per_objfile
	parameter.
	(dwarf2_evaluate_loc_desc_full): Update.

Change-Id: Ic4a694a3fc763360a131ee4e3aaf5a5b4735c813
2020-05-27 11:15:57 -04:00
Simon Marchi 82ca3f5189 Add dwarf2_per_objfile parameter to dwarf2_read_addr_index
Pass it all the way from the symbol batons.  This allows removing a
dwarf2_per_cu_data::dwarf2_per_objfile reference.

gdb/ChangeLog:

	* dwarf2/read.h (dwarf2_read_addr_index): Add dwarf2_per_objfile
	parameter.
	* dwarf2/read.c (dwarf2_read_addr_index): Likewise.
	* dwarf2/loc.c (decode_debug_loclists_addresses): Add
	dwarf2_per_objfile parameter.
	(decode_debug_loc_dwo_addresses): Likewise.
	(dwarf2_find_location_expression): Update.
	(class dwarf_evaluate_loc_desc) <get_addr_index>: Update.
	(locexpr_describe_location_piece): Add dwarf2_per_objfile
	parameter.
	(disassemble_dwarf_expression): Add dwarf2_per_objfile
	parameter.
	(locexpr_describe_location_1): Likewise.
	(locexpr_describe_location): Update.

Change-Id: I8414755e41a87c92f96e408524cc7aaccf086cda
2020-05-27 11:15:57 -04:00
Simon Marchi 4b167ea1a0 Remove dwarf2_per_cu_data::text_offset
This method simply returns the text offset of the objfile associated to
the dwarf2_per_cu_data object.  Since dwarf2_per_cu_data objects are
going to become objfile-independent, we can't keep this method.  This
patch removes it.

Existing callers need to figure out the in the context of which objfile
this is being used, and call text_offset on it.  Typically, this comes
from a symbol baton, where we store the corresponding
dwarf2_per_objfile.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_cu_data) <text_offset>:
	Remove.
	* dwarf2/read.c (dwarf2_per_cu_data::text_offset): Remove.
	* dwarf2/loc.c (dwarf2_find_location_expression): Update.
	(dwarf2_compile_property_to_c): Update.
	(dwarf2_compile_expr_to_ax): Add dwarf2_per_objfile parameter,
	use text offset from objfile.
	(locexpr_tracepoint_var_ref): Update.
	(locexpr_generate_c_location): Update.
	(loclist_describe_location): Update.
	(loclist_tracepoint_var_ref): Update.
	* dwarf2/compile.h (compile_dwarf_bounds_to_c): Add
	dwarf2_per_objfile parameter.
	* dwarf2/loc2c.c (do_compile_dwarf_expr_to_c): Likewise,
	use text offset from objfile.
	(compile_dwarf_expr_to_c): Add dwarf2_per_objfile parameter.

Change-Id: I56b01ba294733362a3562426a96d48ae051a776f
2020-05-27 11:15:57 -04:00
Simon Marchi 89b07335fe Add dwarf2_per_objfile to dwarf_expr_context and dwarf2_frame_cache
Evaluating DWARF expressions (such as location expressions) requires
knowing about the current objfile.  For example, it may call functions
like dwarf2_fetch_die_loc_sect_off, which currently obtain the
dwarf2_per_objfile object it needs from the dwarf2_per_cu_data object.
However, since we are going to remove this
dwarf2_per_cu_data::dwarf2_per_objfile link, these functions will need
to obtain the current dwarf2_per_objfile by parmeter.

If we go up the stack, we see that the DWARF expression contexts
(dwarf_expr_context and the classes that derive from it) need to store
the dwarf2_per_objfile, to be able to pass it to those functions that
will need it.

This patch adds a constructor to all these dwarf_expr_context variants,
accepting a dwarf2_per_objfile parameter.  This dwarf2_per_objfile
generally comes from a symbol baton created earlier.

For frame-related expressions, the dwarf2_per_objfile object must be
passed through the dwarf2_frame_cache object.  This lead to the
dwarf2_frame_find_fde function returning (by parameter) a
dwarf2_per_objfile object.  I then realized that this made the existing
"out_offset" parameter redundant.  This offset is
`objfile->text_section_offset ()`, so it can be recomputed from the
dwarf2_per_objfile object at any time.  I therefore opted to remove this
output parameter, as well as the offset field of dwarf2_frame_cache.

*Note*, there's one spot I'm particularly unsure about.  In
dwarf_evaluate_loc_desc::push_dwarf_reg_entry_value, we would save and
overwrite the offset value in the context, along with a bunch of other
state.  This is because we might be about to evaluate something in a
different CU that the current one.  If the two CUs are in the same
objfile, then the text_offset is the same, as it's a property of the
objfile.  However, if the two CUs are possibly in different objfiles,
then it means the text_offsets are different.  It would also mean we
would need to save and restore the dwarf2_per_objfile in the context.
Is that even possible?

gdb/ChangeLog:

	* dwarf2/expr.h (struct dwarf_expr_context)
	<dwarf_expr_context>: Add dwarf2_per_objfile parameter.
	<offset>: Remove.
	<per_objfile>: New member.
	* dwarf2/expr.c (dwarf_expr_context::dwarf_expr_context): Add
	dwarf2_per_objfile parameter.  Don't set offset, set
	per_objfile.
	(dwarf_expr_context::execute_stack_op): Use offset from objfile.
	* dwarf2/frame.c (dwarf2_frame_find_fde): Return (by parameter)
	a dwarf2_per_objfile object instead of an offset.
	(class dwarf_expr_executor) <dwarf_expr_executor>: Add
	constructor.
	(execute_stack_op): Add dwarf2_per_objfile parameter, pass it
	to dwarf2_expr_executor constructor.  Don't set offset.
	(dwarf2_fetch_cfa_info): Update.
	(struct dwarf2_frame_cache) <text_offset>: Remove.
	<per_objfile>: New field.
	(dwarf2_frame_cache): Update.
	(dwarf2_frame_prev_register): Update.
	* dwarf2/loc.c (class dwarf_evaluate_loc_desc)
	<dwarf_evaluate_loc_desc>: Add constructor.
	(dwarf2_evaluate_loc_desc_full): Update.
	(dwarf2_locexpr_baton_eval): Update.
	(class symbol_needs_eval_context) <symbol_needs_eval_context>:
	Add constructor.
	(dwarf2_loc_desc_get_symbol_read_needs): Update.

Change-Id: I14df060669cc36ad04759f1708c6d7b1fda77727
2020-05-27 11:15:56 -04:00
Simon Marchi 293e7e5114 Move int type methods out of dwarf2_per_cu_data
These methods rely on the current objfile to create types based on it.
Since dwarf2_per_cu_data is to become objfile-independent, these methods
need to mvoe.

int_type can be in dwarf2_per_objfile, as it only requires knowing about
the objfile.

addr_sized_int_type and addr_type also need to know about the DWARF
address type size, which is CU-specific.  The dwarf2_cu objects seems
like a good place for it, as it knows both about the current objfile and
the current CU.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_cu_data) <addr_type,
	addr_sized_int_type>: Move to dwarf2_cu.
	<int_type>: Move to dwarf2_per_objfile.
	(struct dwarf2_per_objfile) <int_type>: Move here.
	* dwarf2/read.c (struct dwarf2_cu) <addr_type,
	addr_sized_int_type>: Move here.
	(read_func_scope): Update.
	(read_array_type): Update.
	(read_tag_string_type): Update.
	(attr_to_dynamic_prop): Update.
	(dwarf2_per_cu_data::int_type): Rename to...
	(dwarf2_per_objfile::int_type): ... this.
	(dwarf2_per_cu_data::addr_sized_int_type): Rename to...
	(dwarf2_cu::addr_sized_int_type): ... this.
	(read_subrange_type): Update.
	(dwarf2_per_cu_data::addr_type): Rename to...
	(dwarf2_cu::addr_type): ... this.
	(set_die_type): Update.

Change-Id: Ic4708ef99d43a8d99325ff91dee59b2eb706cb8f
2020-05-27 11:15:56 -04:00
Simon Marchi 64874a4030 Remove reference to dwarf2_per_cu_data::dwarf2_per_objfile in queue_and_load_all_dwo_tus
In this context, we know that per_cu->cu will be set, as there is this
assertion:

    gdb_assert (per_cu->cu != NULL)

So in order to remove the dwarf2_per_cu_data::dwarf2_per_objfile
reference in queue_and_load_all_dwo_tus, we can go through per_cu->cu.
This adds a reference to dwarf2_per_cu_data::cu, but it will get removed
eventually, in a subsequent patch.

gdb/ChangeLog:

	* dwarf2/read.c (queue_and_load_all_dwo_tus): Access per_objfile
	data through per_cu->cu.

Change-Id: Id4662828ac3c5bc93fe221df3c9bd9a36a8427ad
2020-05-27 11:15:56 -04:00
Simon Marchi 4ab09049d6 Pass dwarf2_cu objects to dwo-related functions, instead of dwarf2_per_cu_data
This allows removing references to the
dwarf2_per_cu_data::dwarf2_per_objfile field.

I am not too sure of the code flow here, but ultimately
open_and_init_dwo_file calls create_cus_hash_table, and passes it
per_cu->cu.  create_cus_hash_table requires a dwarf2_cu to pass to
cutu_reader, as the "parent_cu".

The dwarf2_per_cu_data::cu link is only set when in a certain context.
It's not easy to convince myself in which situations it's safe to use
it.  Instead, if a function is going to use a dwarf2_cu, I think it's
simpler if it takes that object directly.  If it needs access to the
corresponding dwarf2_per_cu_data object, then it can used the
dwarf2_cu::per_cu field, which we know is always set.

This patch adds some references to dwarf2_per_cu_data::cu in the
cutu_reader context.  In this context, we know this field will be set,
as it's cutu_reader that is responsible for instantiating the dwarf2_cu
and assigning the field.

gdb/ChangeLog:

	* dwarf2/read.c (lookup_dwo_comp_unit): Change
	dwarf2_per_cu_data parameter fo dwarf2_cu.
	(lookup_dwo_type_unit): Likewise.
	(read_cutu_die_from_dwo): Likewise.
	(lookup_dwo_unit): Likewise.
	(open_and_init_dwo_file): Likewise.
	(lookup_dwo_cutu): Likewise.
	(lookup_dwo_comp_unit): Likewise.
	(lookup_dwo_type_unit): Likewise.
	(cutu_reader::init_tu_and_read_dwo_dies): Update.
	(cutu_reader::cutu_reader): Update.

Change-Id: I0406a715b0797963bde2bd86237f159cbece5839
2020-05-27 11:15:56 -04:00
Simon Marchi 47b14e8676 Add dwarf2_per_objfile parameter to process_full_{comp,type}_unit
This allows removing the dwarf2_per_cu_data::dwarf2_per_objfile
references in them.

gdb/ChangeLog:

	* dwarf2/read.c (process_full_comp_unit): Add dwarf2_per_objfile
	parameter.
	(process_full_type_unit): Likewise.
	(process_queue): Update.

Change-Id: Ie68baa8cc4bf1f81cc67d4ad13a59881b4c3feb6
2020-05-27 11:15:56 -04:00
Simon Marchi 43182c09c6 Add dwarf2_per_objfile parameter to recursively_compute_inclusions
This allows removing dwarf2_per_cu_data::dwarf2_per_objfile references
in recursively_compute_inclusions and compute_compunit_symtab_includes.

gdb/ChangeLog:

	* dwarf2/read.c (recursively_compute_inclusions): Add
	dwarf2_per_objfile parameter.
	(compute_compunit_symtab_includes): Likewise.
	(process_cu_includes): Update.

Change-Id: I1ee7f8dfc07b39763985e6764e8ce04dcc943ec5
2020-05-27 11:15:55 -04:00
Simon Marchi 7aa104c423 Add dwarf2_per_objfile parameter to create_partial_symtab
This allows removing a dwarf2_per_cu_data::dwarf2_per_objfile reference.

gdb/ChangeLog:

	* dwarf2/read.c (create_partial_symtab): Add dwarf2_per_objfile
	parameter.
	(create_type_unit_group): Update.
	(process_psymtab_comp_unit_reader): Update.
	(build_type_psymtabs_reader): Update.

Change-Id: I72e3a8fce8022943ce6992fb623e05636cd0e3a5
2020-05-27 11:15:55 -04:00
Simon Marchi e3beb21d35 Remove dwarf2_per_cu_data::dwarf2_per_objfile reference in cutu_reader::keep
Here, it should be safe to use dwarf2_per_cu_data->cu->per_objfile, as
we know that dwarf2_per_cu_data->cu will be set at this point.

Note that this adds a reference to dwarf2_per_cu_data::cu, which we'll
want to remove later, but the current focus is to remove references to
dwarf2_per_cu_data::dwarf2_per_objfile.  We'll deal with that in a
subsequent patch.

gdb/ChangeLog:

	* dwarf2/read.c (cutu_reader::keep): Access dwarf2_per_objfile
	object through m_this_cu->cu.

Change-Id: I8dc26d4db021e0b9e9306eb033965b2704bba87c
2020-05-27 11:15:55 -04:00
Simon Marchi d460f6600a Make queue_and_load_dwo_tu receive a dwarf2_cu
queue_and_load_dwo_tu, used as a callback for htab_traverse_noresize,
currently receives a dwarf2_per_cu_data as its `info` user data.  It
accesses the current dwarf2_cu object through the dwarf2_per_cu_data::cu field.
This field will be removed, because the dwarf2_per_cu_data will become
objfile-independent, while dwarf_cu will remain objfile-dependent.

To remove references to this field, change queue_and_load_dwo_tu so
that it expects to receive a pointer to the dwarf2_cu as its info
parameter.

A reference to dwarf2_per_cu_data::cu needs to be added, but it will get
removed in a subsequent patch, when this function gets re-worked.

I kept this as a separate patch, because since there's no strong typing
here, it's easy to miss something.

gdb/ChangeLog:

	* dwarf2/read.c (queue_and_load_dwo_tu): Expect a dwarf2_cu as
	the info parameter.
	(queue_and_load_all_dwo_tus): Pass per_cu->cu.

Change-Id: I3db2a780f0e2157d52ce6939f478558ffe20abcf
2020-05-27 11:15:55 -04:00
Simon Marchi ab43249077 Add dwarf2_per_objfile parameter to cutu_reader's constructors
The cutu_reader type is used for reading the CU represented by the
passed dwarf2_per_cu_data object.  This reading is done in the context
of a given obfile, which is currently the one associated to the passed
dwarf2_per_cu_data object.  Since the dwarf2_per_cu_data type will
become objfile-independent, we will need to pass the objfile separately.

This patch therefore adds a dwarf2_per_objfile parameter to the
cutu_reader constructors, as well as to their callers, up until the
point where we can get the dwarf2_per_objfile object from somewhere
else.  In the end, this allows removing the reference to
dwarf2_per_cu_data::dwarf2_per_objfile in cutu_reader::cutu_reader.

A few dwarf2_per_cu_data::dwarf2_per_objfile references are added (e.g.
in dwarf2_fetch_die_type_sect_off).  This is temporary, this will be
removed once these functions will get re-worked in subsequent patches.

gdb/ChangeLog:

	* dwarf2/read.c (class cutu_reader) <cutu_reader>: Add
	per_objfile parameter.
	(load_full_type_unit): Add per_objfile parameter.
	(read_signatured_type): Likewise.
	(load_full_comp_unit): Likewise.
	(load_cu): Likewise.
	(dw2_do_instantiate_symtab): Likewise.
	(dw2_get_file_names): Likewise.
	(dw2_map_symtabs_matching_filename): Update.
	(dw_expand_symtabs_matching_file_matcher): Update.
	(dw2_map_symbol_filenames): Update.
	(process_psymtab_comp_unit): Add per_objfile parameter.
	(build_type_psymtabs_1): Update.
	(process_skeletonless_type_unit): Update.
	(dwarf2_build_psymtabs_hard): Update.
	(load_partial_comp_unit): Add per_objfile parameter.
	(scan_partial_symbols): Update.
	(load_full_comp_unit): Add per_objfile parameter.
	(process_imported_unit_die): Update.
	(create_cus_hash_table): Update.
	(find_partial_die): Update.
	(dwarf2_read_addr_index): Update.
	(follow_die_offset): Update.
	(dwarf2_fetch_die_loc_sect_off): Update.
	(dwarf2_fetch_constant_bytes): Update.
	(dwarf2_fetch_die_type_sect_off): Update.
	(follow_die_sig_1): Update.
	(load_full_type_unit): Add per_objfile parameter.
	(read_signatured_type): Likewise.

Change-Id: Ibd7bbc443df8b9b8b6f96ff18e93a60ee721b85f
2020-05-27 11:15:55 -04:00
Simon Marchi 313bad1bc6 Use bfd_get_filename instead of objfile_name in lookup_dwo_unit
There should be no functional difference, as objfile_name defers to
bfd_get_filename if objfile::obfd is non-NULL, which should be the case
here.  This allows to remove a reference to
dwarf2_per_cu_data::dwarf2_per_objfile.

gdb/ChangeLog:

	* dwarf2/read.c (lookup_dwo_unit): Use bfd_get_filename instead
	of objfile_name.

Change-Id: I1e1c1870820aec23701edc9c3994612da5781c23
2020-05-27 11:15:55 -04:00
Simon Marchi c3699833af Make dwarf2_get_dwz_file take a dwarf2_per_bfd
This allows removing a per_bfd->dwarf2_per_objfile reference in
get_abbrev_section_for_cu.

This requires saving the bfd in dwarf2_per_bfd.  The constructor of
dwarf2_per_bfd already accepts the bfd, so it's just a matter of saving
it in a field.

I replaced uses of objfile_name with bfd_get_filename, which should be
equivalent in this case.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_bfd) <obfd>: New member.
	(dwarf2_get_dwz_file): Replace parameter with dwarf2_per_bfd.
	* dwarf2/read.c (dwarf2_per_bfd::dwarf2_per_bfd): Assign obfd
	field.
	(dwarf2_get_dwz_file): Replace parameter with dwarf2_per_bfd.
	(create_cus_from_index): Update.
	(dwarf2_read_gdb_index): Update.
	(create_cus_from_debug_names): Update.
	(dwarf2_read_debug_names): Update.
	(get_abbrev_section_for_cu): Update.
	(create_all_comp_units): Update.
	(read_attribute_value): Update.
	(get_debug_line_section): Update.
	* dwarf2/index-cache.c (index_cache::store): Update.
	* dwarf2/index-write.c (save_gdb_index_command): Update.
	* dwarf2/macro.c (dwarf_decode_macro_bytes): Update.

Change-Id: Ifb23f55dda93c499aae57b6a9aff9c6ff9d2f45f
2020-05-27 11:15:54 -04:00
Simon Marchi 1859c670e9 Add dwarf2_per_bfd field to dwarf2_per_cu_data
Some code using dwarf2_per_cu_data objects accesses the corresponding
dwarf2_per_bfd using the following pattern:

    per_cu->dwarf2_per_objfile->per_bfd

Since dwarf2_per_cu_data objects are going to become
objfile-independent, the dwarf2_per_objfile link must go.  To replace
it, add a dwarf2_per_cu_data->per_bfd link.  It makes sense to have it
there because the dwarf2_per_cu_data objects belong to the
dwarf2_per_bfd, so this is essentially just a backlink to their owner.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_cu_data) <per_bfd>: New
	member.
	* dwarf2/read.c (dwarf2_per_bfd::allocate_per_cu): Initialize
	dwarf2_per_cu_data::per_bfd.
	(dwarf2_per_bfd::allocate_signatured_type): Likewise.
	(create_type_unit_group): Likewise.
	(queue_comp_unit): Remove reference to
	per_cu->dwarf2_per_objfile.
	(maybe_queue_comp_unit): Likewise.
	(fill_in_sig_entry_from_dwo_entry): Assign new field.
	(create_cus_hash_table): Assign new field.

Change-Id: I4ba0a393e64a14489ef061261a3dede1509d055b
2020-05-27 11:15:54 -04:00
Simon Marchi 5e22e966a0 Remove dwarf2_cu->per_cu->dwarf2_per_objfile references
Change spots that access the dwarf2_per_objfile object through this
pattern:

  dwarf2_cu->per_cu->dwarf2_per_objfile

to

  dwarf2_cu->per_objfile

This allows removing many references to
dwarf2_per_cu_data::dwarf2_per_objfile.

Again, I hope the following ChangeLog entry will be fine.  I'd rather not
list all the affected functions, as it would be time-consuming and a bit
pointless.

gdb/ChangeLog:

	* dwarf2/read.c: Replace
	dwarf2_cu->per_cu->dwarf2_per_objfile references with
	dwarf2_cu->per_objfile throughout.

Change-Id: I00f44e88295f70ae805a4b18e8144ca92154612e
2020-05-27 11:15:54 -04:00
Simon Marchi 97a1449a95 Remove reference to dwarf2_per_cu_data::dwarf2_per_objfile in dw2_do_instantiate_symtab
This patch begins by removing the per_cu->dwarf2_per_objfile reference
in dw2_do_instantiate_symtab, instead accepting a dwarf2_per_objfile
object as a parameter.  It then fixes the fallouts.  In this context,
the dwarf2_per_objfile is generally derived from an objfile passed to a
quick_symbol_functions callback.

gdb/ChangeLog:

	* dwarf2/read.c (dw2_do_instantiate_symtab): Add per_objfile
	parameter, don't use per_cu->dwarf2_per_objfile.
	(dw2_instantiate_symtab): Likewise.
	(dw2_find_last_source_symtab): Update.
	(dw2_map_expand_apply): Update.
	(dw2_lookup_symbol): Update.
	(dw2_expand_symtabs_for_function): Update.
	(dw2_expand_all_symtabs): Update.
	(dw2_expand_symtabs_with_fullname): Update.
	(dw2_expand_symtabs_matching_one): Add per_objfile parameter,
	don't use per_cu->dwarf2_per_objfile.
	(dw2_expand_marked_cus): Update.
	(dw2_find_pc_sect_compunit_symtab): Update.
	(dw2_debug_names_lookup_symbol): Update.
	(dw2_debug_names_expand_symtabs_for_function): Update.
	(dw2_debug_names_map_matching_symbols): Update.
	(dwarf2_psymtab::expand_psymtab): Update.

Change-Id: I248300822a09bae8470b65a7122d04fb9cb2b5bc
2020-05-27 11:15:54 -04:00
Simon Marchi 9e021579fa Add dwarf2_per_objfile field to dwarf2_cu
Subsequent patches will make dwarf2_per_cu_data objfile-independent.
This means that the dwarf2_per_cu_data::dwarf2_per_objfile field must
go.

The code using a dwarf2_cu structure currently accesses the current
dwarf2_per_objfile object through dwarf2_cu->per_cu->dwarf2_per_objfile.
Since it's ok for the dwarf2_cu to know about the current objfile (a
dwarf2_cu is always used in the context of a particular objfile), add a
dwarf2_per_objfile field to dwarf2_cu.  Upcoming patches will gradually
remove uses of dwarf2_per_cu_data::dwarf2_per_objfile in favor of
dwarf2_cu::dwarf2_per_objfile, until the former can be removed.

gdb/ChangeLog:

	* dwarf2/read.c (struct dwarf2_cu) <dwarf2_cu>: Add parameter.
	<per_objfile>: New member.
	(class cutu_reader) <init_tu_and_read_dwo_dies>: Add parameter.
	(cutu_reader::init_tu_and_read_dwo_dies): Add parameter, update
	call to dwarf2_cu.
	(cutu_reader::cutu_reader): Update.
	(dwarf2_cu::dwarf2_cu): Add parameter, initialize per_objfile.

Change-Id: I8fd0da7371f65baea1ea7787aad08e10453bc565
2020-05-27 11:15:54 -04:00
Simon Marchi ae090bdbf8 Move die_type_hash to dwarf2_per_objfile
The die_type_hash field can't be shared between multiple obfiles, as it
holds `struct type` objects, which are objfile-specific.  Move it from
dwarf2_per_bfd to dwarf2_per_objfile and update all references.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_bfd) <die_type_hash>: Move to
	struct dwarf2_per_objfile.
	(struct dwarf2_per_objfile) <die_type_hash>: Move from struct
	dwarf2_per_bfd.
	* dwarf2/read.c (set_die_type): Update.
	(get_die_type_at_offset): Update.

Change-Id: I3589777ed3579bcabafd2ba859d27babe4502bfb
2020-05-27 11:15:54 -04:00
Simon Marchi af758d117e Remove symtab links from dwarf2_psymtab and dwarf2_per_cu_quick_data
The dwarf2_psymtab and dwarf2_per_cu_quick_data types contain a pointer
to a compunit_symtab, which is a pointer to the corresponding full
symtab.  The dwarf2_psymtab and dwarf2_per_cu_quick_data objects are
going to become objfile-independent, and possibly shared by multiple
objfiles, whereas compunit_symtab will stay objfile-dependent.  This
backlink to the compunit_symtab must therefore be removed.

This patch replaces them with a vector in the dwarf2_per_objfile type,
that serves as a mapping from dwarf2_per_cu_data objects to
compunit_symtab objects, for this particular objfile.  The vector is
indexed using the index assigned to the dwarf2_per_cu_data at its
creation.

I removed the get_compunit_symtab, as it appears to bring not much value
over calling dwarf2_per_objfile::get_symtab directly.

gdb/ChangeLog:

YYYY-MM-DD  Tom Tromey  <tom@tromey.com>
YYYY-MM-DD  Simon Marchi  <simon.marchi@efficios.com>

	* dwarf2/read.h (struct dwarf2_per_bfd) <num_psymtabs>: New
	method.
	(struct dwarf2_per_objfile) <resize_symtabs, symtab_set_p,
	get_symtab, set_symtab>: New methods.
	<m_symtabs>: New field.
	(struct dwarf2_psymtab): Derive from partial_symtab.
	<readin_p, get_compunit_symtab>: Declare methods.
	* dwarf2/read.c (dwarf2_per_objfile::symtab_set_p,
	dwarf2_per_objfile::get_symtab, dwarf2_per_objfile::set_symtab):
	New methods.
	(struct dwarf2_per_cu_quick_data) <compunit_symtab>: Remove.
	(dw2_do_instantiate_symtab, dw2_instantiate_symtab)
	(dw2_map_expand_apply, dw2_map_symtabs_matching_filename)
	(dw2_symtab_iter_next, dw2_print_stats)
	(dw2_expand_symtabs_with_fullname)
	(dw2_expand_symtabs_matching_one)
	(dw_expand_symtabs_matching_file_matcher)
	(dw2_find_pc_sect_compunit_symtab, dw2_map_symbol_filenames)
	(dw2_debug_names_iterator::next)
	(dw2_debug_names_map_matching_symbols)
	(fill_in_sig_entry_from_dwo_entry, dwarf2_psymtab::read_symtab)
	(process_queue, dwarf2_psymtab::expand_psymtab): Update.
	(dwarf2_psymtab::readin_p, dwarf2_psymtab::get_compunit_symtab):
	New methods.
	(get_compunit_symtab, process_full_comp_unit)
	(process_full_type_unit): Update.
	(dwarf2_build_psymtabs, dwarf2_initialize_objfile, add_type_unit): Call

Change-Id: Iec53d96e0b70a57d8b68408febdac3c6c3d4854b
2020-05-27 11:15:47 -04:00
Simon Marchi 5989a64ed5 Split dwarf2_per_objfile into dwarf2_per_objfile and dwarf2_per_bfd
This is the first step of splitting dwarf2_per_objfile in two, one
structure for objfile-independent data (dwarf2_per_bfd) and one for
objfile-dependent data (dwarf2_per_objfile).

The existing dwarf2_per_objfile is renamed dwarf2_per_bfd, and a new
dwarf2_per_objfile type is introduced, which sits "in between" the
objfile and dwarf2_per_bfd.

So where we had this before:

  objfile -> dwarf2_per_objfile (*)

we now have this:

  objfile -> dwarf2_per_objfile -> dwarf2_per_bfd (*)

(*) Note that the dwarf2_per_objfile in the former corresponds to
the dwarf2_per_bfd in the latter.

I've done the minimal amount of changes in this patch: following patches
will incrementally move things that are not actually shareable between
objfiles from dwarf2_per_bfd to dwarf2_per_objfile.

Most references to dwarf2_per_objfile objects are changed to
dwarf2_per_objfile->per_bfd.  To avoid many of these replacements, which
would have to be reverted later anyway, I've moved right away the
objfile backlink to the new dwarf2_per_objfile structure in this patch.
I've also moved the read_line_string method, since it references the
objfile backlink, and it's actually not difficult to move.

Once the moves are completed, multiple dwarf2_per_objfile sharing the
same BFD will point to the same single instance of dwarf2_per_bfd (as
long as they don't require relocation).

dwarf2_has_info, where we create these objects, is updated to the new
architecture.

I've had to change the get_gdb_index_contents_ftype typedef and related
functions.  The parameter type was changed from dwarf2_per_objfile to
dwarf2_per_bfd, otherwise the template wouldn't work.

Please excuse the terse ChangeLog entry, I have not listed all the
functions where dwarf2_per_objfile has been changed to
dwarf2_per_objfile->per_bfd.  It would take a considerable amount of
time and would not really be useful in the end.

gdb/ChangeLog:

	* dwarf2/read.h (dwarf2_per_objfile): Rename to dwarf2_per_bfd,
	then introduce a new dwarf2_per_objfile type.
	<read_line_string>: Move to the new dwarf2_per_objfile type.
	<objfile>: Likewise.
	(dwarf2_per_bfd): Rename dwarf2_per_objfile to this.
	* dwarf2/read.c: Replace references to dwarf2_per_objfile with
	dwarf2_per_objfile->per_bfd.
	(dwarf2_per_objfile::dwarf2_per_objfile): Rename to...
	(dwarf2_per_bfd::dwarf2_per_bfd): ... this.
	(dwarf2_per_objfile::free_cached_comp_units): Rename to...
	(dwarf2_per_bfd::free_cached_comp_units): ... this.
	(dwarf2_has_info): Allocate dwarf2_per_bfd.
	(dwarf2_per_objfile::locate_sections): Rename to...
	(dwarf2_per_bfd::locate_sections): ... this.
	(dwarf2_per_objfile::get_cutu): Rename to...
	(dwarf2_per_bfd::get_cutu): ... this.
	(dwarf2_per_objfile::get_cu): Rename to...
	(dwarf2_per_bfd::get_cu): ... this.
	(dwarf2_per_objfile::get_tu): Rename to...
	(dwarf2_per_bfd::get_tu): ... this.
	(dwarf2_per_objfile::allocate_per_cu): Rename to...
	(dwarf2_per_bfd::allocate_per_cu): ... this.
	(dwarf2_per_objfile::allocate_signatured_type): Rename to...
	(dwarf2_per_bfd::allocate_signatured_type): ... this.
	(get_gdb_index_contents_ftype): Change parameter from
	dwarf2_per_objfile to dwarf2_per_bfd.
	* dwarf2/macro.c, dwarf2/index-write.c: Replace references to
	dwarf2_per_objfile with dwarf2_per_objfile->per_bfd.

Change-Id: I7de7b5d1ce7494aa73bfcf15f719d3c5c46e138c
2020-05-27 11:13:50 -04:00
Tom Tromey a50264baf5 Add dwarf2_per_objfile member to DWARF batons
Various DWARF callbacks expect to be able to fetch the objfile and / or
dwarf2_per_objfile from the DWARF CU object.  However, this won't be
possible once sharing is implemented.

Because these objects are related to full symbols (e.g., they are used
to implement location expressions), they can simply store the
dwarf2_per_objfile they need.

This patch adds a per_objfile member to the various "baton" structures
and arranges to set this value when constructing the baton.

gdb/ChangeLog:

YYYY-MM-DD  Tom Tromey  <tom@tromey.com>
YYYY-MM-DD  Simon Marchi  <simon.marchi@efficios.com>

	* dwarf2/loc.c (struct piece_closure) <per_objfile>: New member.
	(allocate_piece_closure): Set "per_objfile" member.
	(dwarf2_find_location_expression, dwarf2_locexpr_baton_eval)
	(locexpr_describe_location, loclist_describe_location): Use new
	member.
	* dwarf2/read.c (read_call_site_scope)
	(mark_common_block_symbol_computed, attr_to_dynamic_prop)
	(dwarf2_const_value_attr, dwarf2_fetch_die_loc_sect_off)
	(fill_in_loclist_baton, dwarf2_symbol_mark_computed,
	handle_data_member_location): Set per_objfile member.
	* dwarf2/loc.h (struct dwarf2_locexpr_baton) <per_objfile>: New
	member.
	(struct dwarf2_loclist_baton) <per_objfile>: New member.

Change-Id: If3aaa6a0f544be86710157c3adb68fde24d80037
2020-05-27 11:13:50 -04:00
Tom Tromey d3473f0c4b Add dwarf2_per_cu_data::index
Currently, a dwarf2_per_cu_data can hold a link to the corresponding
expanded compunit_symtab.  However, the dwarf2_per_cu_data objects are
shared across objfiles, a simple pointer won't work: each objfile
sharing the dwarf2_per_cu_data instance will have a corresponding
compunit_symtab.

Instead, this link will be stored in the dwarf2_per_objfile object
(which will contain the objfile-specific data).  To enable this, we add
an index to each dwarf2_per_cu_data and signatured_type.  The data
structure in the dwarf2_per_objfile will use this new index to map a
dwarf2_per_cu_data to its corresponding compunit_symtab, for this
objfile.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_objfile) <allocate_per_cu,
	allocate_signatured_type>: Declare new methods.
	<m_num_psymtabs>: New member.
	(struct dwarf2_per_cu_data) <index>: New member.
	* dwarf2/read.c (dwarf2_per_objfile::allocate_per_cu)
	(dwarf2_per_objfile::allocate_signatured_type): New methods.
	(create_cu_from_index_list): Use allocate_per_cu.
	(create_signatured_type_table_from_index)
	(create_signatured_type_table_from_debug_names)
	(create_debug_type_hash_table, add_type_unit)
	(read_comp_units_from_section): Use allocate_signatured_type.

Change-Id: I7733479a38ce82a5015cb184c8acce5f8bbf2e69
2020-05-27 11:13:49 -04:00
Tom Tromey 5717c425a6 Add "objfile" parameter to two partial_symtab methods
This series will cause partial symtabs to be shared across objfiles.
However, full symtabs and symbols will still be objfile-dependent, so
will be expanded separately for each objfile.  So, a debug info reader
will need to know which objfile to consult when expanding a partial
symtab.

This patch adds an objfile parameter to the two relevant methods of
partial_symtab.  Current implementations simply ignore them.

gdb/ChangeLog:

	* psymtab.c (partial_map_expand_apply)
	(psym_find_pc_sect_compunit_symtab, psym_lookup_symbol)
	(psym_lookup_global_symbol_language)
	(psymtab_to_symtab, psym_find_last_source_symtab, dump_psymtab)
	(psym_print_stats, psym_expand_symtabs_for_function)
	(psym_map_symbol_filenames, psym_map_matching_symbols)
	(psym_expand_symtabs_matching)
	(partial_symtab::read_dependencies, maintenance_info_psymtabs)
	(maintenance_check_psymtabs): Update.
	* psympriv.h (struct partial_symtab) <readin_p,
	get_compunit_symtab>: Add objfile parameter.
	(struct standard_psymtab) <readin_p, get_compunit_symtab>:
	Likewise.
	* dwarf2/read.c (struct dwarf2_include_psymtab) <readin_p,
	get_compunit_symtab>: Likewise.
	(dwarf2_psymtab::expand_psymtab): Pass objfile argument.

Change-Id: I3f0b26787c3e78f7fb78b9fc011d91fb8690f3a0
2020-05-27 11:13:48 -04:00
Tom Tromey 4594094926 Introduce dwarf2_per_objfile::obstack
Currently much of the DWARF-related data is stored on the objfile
obstack.  This prevents sharing this data across objfiles, so this patch
adds a new obstack to dwarf2_per_objfile.  Note that the
dwarf2_per_objfile type is going to become "dwarf2_per_bfd" in a
subsequent patch, which is indeed going to be shared between objfiles.

One way to check whether this is correct is to look at the remaining
uses of objfile_obstack in the DWARF code and note that they all
appear in the "full CU" code paths.

The converse -- storing per-objfile data on the shared obstack -- is
not good, but it is just a memory leak, not a potential
use-after-free.  Double-checking this would also be useful, though.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_per_objfile) <obstack>: New
	member.
	* dwarf2/read.c (delete_file_name_entry): Fix comment.
	(create_cu_from_index_list)
	(create_signatured_type_table_from_index)
	(create_signatured_type_table_from_debug_names)
	(dw2_get_file_names_reader, dwarf2_initialize_objfile)
	(dwarf2_create_include_psymtab)
	(create_debug_type_hash_table, add_type_unit)
	(create_type_unit_group, read_comp_units_from_section)
	(dwarf2_compute_name, create_cus_hash_table)
	(create_dwp_hash_table, create_dwo_unit_in_dwp_v1)
	(create_dwo_unit_in_dwp_v2, open_and_init_dwp_file): Use new
	obstack.
	(dw2_get_real_path): Likewise.  Change argument to
	dwarf2_per_objfile.

Change-Id: Icdec7be7c4d9f33d1dce4f807284f3077f7d3f03
2020-05-27 11:13:48 -04:00
Luis Machado f8c6d1528c Fix PR 26000, logical bitwise error / prologue analyzer
This fixes an instruction mask typo. We should be matching only
ldrd (immediate) and not any other of its variants. As is, it never matches
anything.

With the patch, the instruction mask also allows matching of ldrd (literal),
but the check for SP discards this particular instruction pattern, as it has
a hardcoded PC register.

gdb/ChangeLog:

2020-05-27  Luis Machado  <luis.machado@linaro.org>

	PR tdep/26000
	* arm-tdep.c (thumb_analyze_prologue): Fix instruction matching
	for ldrd (immediate).
2020-05-27 09:41:53 -03:00
Philippe Waroquiers e98d2e6da4 Ensure class_tui is listed in the output of "help" giving the list of classes.
Before this change, "help" was not showing the TUI class.
With this change:
  (gdb) help
  ...
  support -- Support facilities.
  text-user-interface -- TUI is the GDB text based interface.
  tracepoints -- Tracing of program execution without stopping the program.
  ...
  (gdb) help text-user-interface
  TUI is the GDB text based interface.
  In TUI mode, GDB can display several text windows showing
  the source file, the processor registers, the program disassembly, ...

  List of commands:

  + -- Scroll window forward.
  ...

Note that we cannot use "tui" for the fake class command name, as "tui"
is a command.

gdb/ChangeLog

2020-05-26  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* command.h: Add comment giving the name of class_tui.
	* cli/cli-cmds.c (_initialize_cli_cmds): If TUI defined,
	create the fake command for the help for class_tui.
2020-05-26 22:18:42 +02:00
Tom Tromey 53a47a3e49 Handle indexing Ada arrays with enum indices
In Ada, like C, an enum can assign values to the constants.  However,
unlike C (or any other language supported by gdb), the enum type can
also be used as the range of an array.

In this case, the user's code references the enum constants, but the
compiler translates these to the position of the constant in the enum.
So for example one might write:

   type Enum_With_Gaps is
     (
      LIT0,
      LIT1,
      LIT2,
      LIT3,
      LIT4
     );

   for Enum_With_Gaps use
     (
      LIT0 => 3,
      LIT1 => 5,
      LIT2 => 8,
      LIT3 => 13,
      LIT4 => 21
     );

Then index an array like "array(LIT3)" -- but this will be the 4th
element in an array of 5 elements, not the 13th element in an array of
19 (assuming I did the math right) elements.

gdb supports this to some degree, with the only missing piece being
indexing into such an array.  This patch implements this missing
feature, and also fixes an existing bug, which is that in some
situations I believe gdb would mis-compute the resulting array's
length.

The approach taken here is to try to integrate this feature into the
core of gdb.  My view is that much of the Ada support should be better
integrated with gdb, rather than being "on the side".  This, I think,
would help avoid code duplication at least.  So, I try to take steps
toward this goal when possible.

Because other languages generally don't allow the user to specify the
index type of an array, I simply made the core of gdb unconditionally
apply discrete_position when computing the range of such an array.
This is a no-op for ordinary types, but applies the enum
value-to-position transformation for TYPE_CODE_ENUM.

gdb/ChangeLog
2020-05-26  Tom Tromey  <tromey@adacore.com>

	* ada-lang.c (ada_print_array_index): Change type.  Call val_atr.
	(ada_value_ptr_subscript): Don't call pos_atr on the lower bound.
	(val_atr): New function.
	(value_val_atr): Use it.
	* ada-valprint.c (print_optional_low_bound): Change low bound
	handling for enums.
	(val_print_packed_array_elements): Don't call discrete_position.
	* gdbtypes.c (get_discrete_bounds) <TYPE_CODE_RANGE>: Call
	discrete_position for enum types.
	* language.c (default_print_array_index): Change type.
	* language.h (struct language_defn) <la_print_array_index>: Add
	index_type parameter, change type of index_value.
	(LA_PRINT_ARRAY_INDEX): Add index_type parameter.
	(default_print_array_index): Update.
	* valprint.c (maybe_print_array_index): Don't call
	value_from_longest.  Update.
	(value_print_array_elements): Don't call discrete_position.

gdb/testsuite/ChangeLog
2020-05-26  Tom Tromey  <tromey@adacore.com>

	* gdb.ada/arr_acc_idx_w_gap.exp: Add tests.
2020-05-26 14:11:08 -06:00
Tom Tromey 0bc2354b81 Fix bugs in 'val and 'pos with range types
In Ada, the 'val and 'pos attributes can be used to map from an
enumeration constant to its position in the enum and vice versa.
These operators did not work properly when the type in question was a
subrange of an enum type with "holes".

gdb/ChangeLog
2020-05-26  Tom Tromey  <tromey@adacore.com>

	* ada-lang.c (value_val_atr): Handle TYPE_CODE_RANGE.
	* gdbtypes.c (discrete_position): Handle TYPE_CODE_RANGE.

gdb/testsuite/ChangeLog
2020-05-26  Tom Tromey  <tromey@adacore.com>

	* gdb.ada/arr_acc_idx_w_gap.exp: Add enum subrange tests.
	* gdb.ada/arr_acc_idx_w_gap/enum_with_gap.ads (Enum_Subrange): New
	type.
	* gdb.ada/arr_acc_idx_w_gap/enum_with_gap_main.adb (V): New
	variable.
2020-05-26 14:11:08 -06:00
Cristiano De Alti 1218a4bf49 gdb: make avr_integer_to_address generate code or data address based on type
The AVR architecture is a Harvard one, meaning it has different memory
spaces for code and data.  In GDB, this is dealt with by having the data
(SRAM) addresses start at 0x00800000.  When interpreting an integer as
an address (converting to a CORE_ADDR), we currently always generate a
data address.  This doesn't work for some cases described below, where
the integer is meant to represent a code address.

This patch changes avr_integer_to_address so that it generates the
correct type of address (code or data) based on the passed type.

Using the simavr.exp board, I didn't see any regressions when running
the gdb.base/*.exp tests.  A few tests go from fail to pass, but none
from pass to fail.  There are a few new fails and unresolved, but it's
just because some tests manage to make more progress before failing in a
different way.

In practice, it fixes disassembling by address, as described in the PR:

    - (gdb) disassemble 0x12a,0x12b
    - Dump of assembler code from 0x12a to 0x12b:
    -    0x0000012a <main+0>: push    r28
    - End of assembler dump.

    + (gdb) disassemble 0x12a,0x12b
    + Dump of assembler code from 0x80012a to 0x80012b:
    +    0x0080012a:  nop
    + End of assembler dump.

And also, setting a breakpoint by address:

    - (gdb) p &main
    - $1 = (int (*)(void)) 0x12a <main>
    - (gdb) b *0x12a
    - Breakpoint 1 at 0x80012a

    + (gdb) p &main
    + $1 = (int (*)(void)) 0x12a <main>
    + (gdb) b *0x12a
    + Breakpoint 1 at 0x12a: file test-avr.c, line 3.
    + Note: automatically using hardware breakpoints for read-only addresses.

gdb/ChangeLog:

	PR gdb/13519
	* avr-tdep.c (avr_integer_to_address): Return data or code
	address accordingly to the second 'type' argument of the
	function.

Change-Id: Iaea1587d053e86f4ab8aebdcabec8d31a6d262cd
2020-05-25 11:56:14 -04:00
Michael Weghorn 92651b1d91 gdb: Move construct_inferior_arguments to gdbsupport
This moves the function construct_inferior_arguments from
gdb/inferior.h and gdb/infcmd.c to gdbsupport/common-inferior.{h,cc}.
While at it, also move the function's comment to the header file
to align with current standards.

The intention is to use it from gdbserver in a follow-up commit.

gdb/ChangeLog:

	* infcmd.c, inferior.h: (construct_inferior_arguments):
	Moved function from here to gdbsupport/common-inferior.{h,cc}

gdbsupport/ChangeLog:

	* common-inferior.h, common-inferior.cc: (construct_inferior_arguments):
	Move function here from gdb/infcmd.c, gdb/inferior.h

Change-Id: Ib9290464ce8c0872f605d8829f88352d064c30d6
2020-05-25 11:38:02 -04:00
Tom Tromey 0a4f5f8cae Revert "Add completion styling"
This reverts commit eca1f90cf4.  Several
changes were requested, and it seemed simplest to revert it.

gdb/ChangeLog
2020-05-23  Tom Tromey  <tom@tromey.com>

	Revert commit eca1f90c:
	* NEWS: Remove entry for completion styling.
	* completer.c (_rl_completion_prefix_display_length): Move
	declaration later.
	(gdb_fnprint): Revert.
	(gdb_display_match_list_1): Likewise.
	* cli/cli-style.c (completion_prefix_style)
	(completion_difference_style, completion_suffix_style): Remove.
	(_initialize_cli_style): Revert.
	* cli/cli-style.h (completion_prefix_style)
	(completion_difference_style, completion_suffix_style): Don't
	declare.

gdb/doc/ChangeLog
2020-05-23  Tom Tromey  <tom@tromey.com>

	* gdb.texinfo (Output Styling): Don't mention completion styling.
	(Editing): Don't mention readline completion styling.

gdb/testsuite/ChangeLog
2020-05-23  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Remove completion styling test.
	* lib/gdb-utils.exp (style): Remove completion styles.
2020-05-24 20:27:48 -06:00
Pedro Alves e08bd6c508 Don't remove C++ aliases from completions if symbol doesn't match
completion_list_add_symbol currently tries to remove C++ function
aliases from the completions match list even if the symbol passed down
wasn't successfully added to the completion list because it didn't
match.  I.e., we call cp_canonicalize_string_no_typedefs for each and
every C++ function in the program, which is useful work.  This patch
skips that useless work.

gdb/ChangeLog:
2020-05-24  Pedro Alves  <palves@redhat.com>

	* symtab.c (completion_list_add_name): Return boolean indication
	of whether the symbol matched.
	(completion_list_add_symbol): Don't try to remove C++ aliases if
	the symbol didn't match in the first place.
	* symtab.h (completion_list_add_name): Return bool.
2020-05-24 13:32:25 +01:00
Simon Marchi ceacbf6edf gdb: remove TYPE_FIELD macro
Replace all uses of it by type::field.

Note that since type::field returns a reference to the field, some spots
are used to assign the whole field structure.  See ctfread.c, function
attach_fields_to_type, for example.  This is the same as was happening
with the macro, so I don't think it's a problem, but if anybody sees a
really nicer way to do this, now could be a good time to implement it.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_FIELD): Remove.  Replace all uses with
	type::field.
2020-05-23 17:39:54 -04:00
Joel Brobecker 26f1625454 Document the GDB 9.2 release in gdb/ChangeLog
gdb/ChangeLog:

	GDB 9.2 released.
2020-05-23 14:19:06 -07:00
Tom Tromey eca1f90cf4 Add completion styling
Readline has a styling feature for completion -- if it is enabled, the
common prefix of completions will be displayed in a different style.
This doesn't work in gdb, because gdb implements its own completer.

This patch implements the feature.  However, it doesn't directly use
the Readline feature, because gdb can do a bit better: it can let the
user control the styling using the existing mechanisms.

This version incorporates an Emacs idea, via Eli: style the prefix,
the "difference character", and the suffix differently.

gdb/ChangeLog
2020-05-23  Tom Tromey  <tom@tromey.com>

	* NEWS: Add entry for completion styling.
	* completer.c (_rl_completion_prefix_display_length): Move
	declaration earlier.
	(gdb_fnprint): Use completion_style.
	(gdb_display_match_list_1): Likewise.
	* cli/cli-style.c (completion_prefix_style)
	(completion_difference_style, completion_suffix_style): New
	globals.
	(_initialize_cli_style): Register new globals.
	* cli/cli-style.h (completion_prefix_style)
	(completion_difference_style, completion_suffix_style): Declare.

gdb/doc/ChangeLog
2020-05-23  Tom Tromey  <tom@tromey.com>

	* gdb.texinfo (Output Styling): Mention completion styling.
	(Editing): Mention readline completion styling.

gdb/testsuite/ChangeLog
2020-05-23  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Add completion styling test.
	* lib/gdb-utils.exp (style): Add completion styles.
2020-05-23 14:53:33 -06:00
Pedro Alves 51e2cfa2dc Use safe-ctype.h (ISSPACE etc.) in symbol parsing & comparison
This patch avoids depending on the current locale when parsing &
comparing symbol names, by using libiberty's safe-ctype.h uppercase
TOLOWER, ISXDIGIT, etc. macros instead of the standard ctype.h
tolower, isxdigit, etc. macros/functions.

This commit:

 commit b1b60145ae
 Author:     Pedro Alves <palves@redhat.com>
 AuthorDate: Tue May 22 17:35:38 2018 +0100

    Support UTF-8 identifiers in C/C++ expressions (PR gdb/22973)

did something similar, except in the expression parser.

This can improve GDB's symbol loading performance significantly.
Currently strcmp_iw_ordered can show up high on profiles (called from
sort_pst_symbols -> std::sort) because of the isspace and tolower
functions.  Hannes mentions seeing it as high as in ~24% of the
profiling samples on Windows
(https://sourceware.org/pipermail/gdb-patches/2020-May/168858.html).

I tested GDB's performance (built with "-g -O2") loading a "-g -O0"
build of gdb.

I ran GDB 10 times like:

	  /bin/time -f %e \
		    ./gdb/gdb --data-directory ./gdb/data-directory -nx \
		    -batch /tmp/gdb-g-O0

Then I computed the mean time.

The baseline mean time was

 gdb    2.515

This patch brings the number down to

 gdb    2.096

Which is an around 16% improvement.

gdb/ChangeLog:
2020-05-23  Pedro Alves  <palves@redhat.com>

	* utils.c: Include "gdbsupport/gdb-safe-ctype.h".
	(parse_escape): Use ISDIGIT instead of isdigit.
	(puts_debug): Use gdb_isprint instead of isprint.
	(fprintf_symbol_filtered): Use ISALNUM instead of isalnum.
	(cp_skip_operator_token, skip_ws, strncmp_iw_with_mode): Use
	ISSPACE instead of isspace.
	(strncmp_iw_with_mode): Use TOLOWER instead of tolower and ISSPACE
	instead of isspace.
	(strcmp_iw_ordered): Use ISSPACE instead of isspace.
	(string_to_core_addr): Use TOLOWER instead of tolower, ISXDIGIT
	instead of isxdigit and ISDIGIT instead of isdigit.

gdbsupport/ChangeLog:
2020-05-23  Pedro Alves  <palves@redhat.com>

	* gdb-safe-ctype.h: New.
2020-05-23 12:46:37 +01:00
Simon Marchi 80fc5e77f0 gdb: remove TYPE_FIELDS macro
Remove all uses of the `TYPE_FIELDS` macro.  Replace them with either:

1) type::fields, to obtain a pointer to the fields array (same as
   TYPE_FIELDS yields)
2) type::field, a new convenience method that obtains a reference to one
   of the type's field by index.  It is meant to replace

     TYPE_FIELDS (type)[idx]

   with

     type->field (idx)

gdb/ChangeLog:

	* gdbtypes.h (struct type) <field>: New method.
	(TYPE_FIELDS): Remove, replace all uses with either type::fields
	or type::field.

Change-Id: I49fba10114417deb502060c6156aa5f7fc62462f
2020-05-22 16:55:17 -04:00
Simon Marchi 3cabb6b069 gdb: add type::fields / type::set_fields
Add the `fields` and `set_fields` methods on `struct type`, in order to
remove the `TYPE_FIELDS` macro.  In this patch, the `TYPE_FIELDS` macro
is changed to the `type::fields`, so all the call sites that use it to
set the fields array are changed to use `type::set_fields`.  The next
patch will remove `TYPE_FIELDS` entirely.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <fields, set_fields>: New methods.
	(TYPE_FIELDS): Use type::fields.  Change all call sites that
	modify the propery to use type::set_fields instead.

Change-Id: I05174ce68f2ce3fccdf5d8b469ff141f14886b33
2020-05-22 16:55:16 -04:00
Simon Marchi 1f704f761b gdb: remove TYPE_NFIELDS macro
Remove `TYPE_NFIELDS`, changing all the call sites to use
`type::num_fields` directly.  This is quite a big diff, but this was
mostly done using sed and coccinelle.  A few call sites were done by
hand.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_NFIELDS): Remove.  Change all cal sites to use
	type::num_fields instead.

Change-Id: Ib73be4c36f9e770e0f729bac3b5257d7cb2f9591
2020-05-22 16:55:15 -04:00
Simon Marchi 5e33d5f4e1 gdb: add type::num_fields / type::set_num_fields
Add the `num_fields` and `set_num_fields` methods on `struct type`, in
order to remove the `TYPE_NFIELDS` macro.  In this patch, the
`TYPE_NFIELDS` macro is changed to use `type::num_fields`, so all the
call sites that are used to set the number of fields are changed to use
`type::set_num_fields`.  The next patch will remove `TYPE_NFIELDS`
completely.

I think that in the future, we should consider making the interface of
`struct type` better.  For example, right now it's possible for the
number of fields property and the actual number of fields set to be out
of sync.  However, I want to keep the existing behavior in this patch,
just translate from macros to methods.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <num_fields, set_num_fields>: New
	methods.
	(TYPE_NFIELDS): Use type::num_fields.  Change all call sites
	that modify the number of fields to use type::set_num_fields
	instead.

Change-Id: I5ad9de5be4097feaf942d111077434bf91d13dc5
2020-05-22 16:55:14 -04:00
Tom Tromey 9392ebb3bb Remove obsolete declaration
Commit c9e0a7e333 ("Remove munmap_listp_free_cleanup") removed
munmap_listp_free, but missed a declaration.  This patch removes that
as well.

gdb/ChangeLog
2020-05-22  Tom Tromey  <tromey@adacore.com>

	* compile/compile-object-load.h (munmap_list_free): Don't
	declare.
2020-05-22 13:35:13 -06:00
Andrew Burgess 7c13f4e875 gdb: Restore old annotations behaviour when printing frame info
This undoes most of the changes from these commits:

  commit ec8e2b6d30
  Date:   Fri Jun 14 23:43:00 2019 +0100

      gdb: Don't allow annotations to influence what else GDB prints

  commit 0d3abd8cc9
  Date:   Wed Jun 12 22:34:26 2019 +0100

      gdb: Remove an update of current_source_line and current_source_symtab

as a result of the discussion here:

  https://sourceware.org/pipermail/gdb/2020-April/048468.html

Having taken time to reflect on the discussion, and reading the
documentation again I believe we should revert GDB's behaviour back to
how it used to be.

The original concern that triggered the initial patch was that when
annotations were on the current source and line were updated (inside
the annotation code), while when annotations are off this update would
not occur.  This was incorrect, as printing the source with the call
to print_source_lines does also update the current source and line.

Further, the documentation here:
  https://sourceware.org/gdb/current/onlinedocs/gdb/Source-Annotations.html#Source-Annotations

Clearly states:

  "The following annotation is used instead of displaying source code:

   ^Z^Zsource filename:line:character:middle:addr

   ..."

So it is documented that the 'source' annotation is a replacement for,
and not in addition to, actually printing the source lie.

There are still a few issues that I can see, these are:

  1. In source.c:info_line_command, when annotations are on we call
  annotate_source_line, however, if annotations are off then there is
  no corresponding call to print the source line.  This means that a
  if a user uses 'info line ...' with annotations on, and then does a
  'list', they will get different results than if they had done this
  with annotations off.

  2. It bothers me that the call to annotate_source_line returns a
  boolean, and that this controls a call to print_source_line (in
  stack.c:print_frame_info).

  The reason for this is that the source line annotation will only
  print something if the file is found, and the line number is in
  range for the file.

  It seems to me like an annotation should always be printed, either
  one that identifies the file and line, or one that identifies the
  file and line GDB would like to access, but couldn't.

  I considered changing this, but in the end decided not too, if I
  extend the existing 'source' annotation to print something in all
  cases then I risk breaking existing UIs that rely on the file and
  line always being valid.  If I add a new annotation then this might
  also break existing UIs that rely on GDB itself printing the error
  from within print_source_line.

Given that annotations is deprecated (as I understand it) mechanism
for UIs to interact with GDB (in favour of MI) I figure we should just
restore the old behaviour, and leave the mini-bugs in until someone
actually complains.

This isn't a straight revert of the two commits mentioned above.  I've
left annotate_source_line instead of going back to the original
identify_source_line, which lived in source.c, but was really
annotation related.  The API for setting the current source and line
has changed since the original patches, so I updated for that change
too.  Finally I wrote the code in stack.c so that we avoided an extra
level of indentation, which I felt made things easier to read.

gdb/ChangeLog:

	* annotate.c (annotate_source_line): Update return type, add call
	to update current symtab and line.
	* annotate.h (annotate_source_line): Update return type, and
	extend header comment.
	* source.c (info_line_command): Check annotation_level before
	calling annotate_source_line.
	* stack.c (print_frame_info): If calling annotate_source_line
	returns true, then don't print any other source line information.

gdb/testsuite/ChangeLog:

	* gdb.base/annota1.exp: Update expected results.
	* gdb.cp/annota2.exp: Update expected results, remove duplicate
	test name.
	* gdb.cp/annota3.exp: Update expected results.
2020-05-22 13:39:50 +01:00
Simon Marchi aa370940e2 gdb: fix -Wtautological-overlap-compare error in lm32-tdep.c
Building with clang 11, we get:

    /home/smarchi/src/binutils-gdb/gdb/lm32-tdep.c:84:44: error: overlapping comparisons always evaluate to false [-Werror,-Wtautological-overlap-compare]
        return ((regnum >= SIM_LM32_EA_REGNUM) && (regnum <= SIM_LM32_BA_REGNUM))
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Indeed, this doesn't make sense, as EA_REGNUM is greater than BA_REGNUM.
I'll assume that it was just a mistake and that these two should be
swapped.

The regnums for BA and EA are contiguous, so ultimately this particular
part of the condition is only true if regnum is == EA or == BA.  These
registers are Exception Address and Breakpoint Address, so I guess it
makes sense for them to be in the system register group.

The relevant reference is here:

  https://www.latticesemi.com/-/media/LatticeSemi/Documents/UserManuals/JL/LatticeMico32ProcessorReferenceManual39.ashx?document_id=52077

gdb/ChangeLog:

	* lm32-tdep.c (lm32_register_reggroup_p): Fix condition.
2020-05-21 13:22:10 -04:00
Simon Marchi 84d53fa9d2 gdb: remove unnecessary NULL checks before xfree
I was inspired by a series of patches merged by Alan Modra in the other
projects, so I did the same in GDB with a bit of Coccinelle and grep.

This patch removes the unnecessary NULL checks before calls to xfree.
They are unnecessary because xfree already does a NULL check.  Since
free is supposed to handle NULL values correctly, the NULL check in
xfree itself is also questionable, but I've left it there for now.

gdb/ChangeLog:

	* coffread.c (patch_type): Remove NULL check before xfree.
	* corefile.c (set_gnutarget): Likewise.
	* cp-abi.c (set_cp_abi_as_auto_default): Likewise.
	* exec.c (build_section_table): Likewise.
	* remote.c (remote_target::pass_signals): Likewise.
	* utils.c (n_spaces): Likewise.
	* cli/cli-script.c (document_command): Likewise.
	* i386-windows-tdep.c (core_process_module_section): Likewise.
	* linux-fork.c (struct fork_info) <~fork_info>: Likewise.
2020-05-21 13:12:29 -04:00
Simon Marchi 9d428aae67 gdb: reset/recompute objfile section offsets in reread_symbols
This patch started as an investigation of this bug, where the program is
re-compiled between two "start" runs:

    $ ./gdb -nx --data-directory=data-directory -q a.out
    Reading symbols from a.out...
    (gdb) start
    Temporary breakpoint 1 at 0x1131: file test.c, line 1.
    Starting program: /home/smarchi/build/wt/test/gdb/a.out

    Temporary breakpoint 1, main () at test.c:1
    1       int main() { return 0; }

    *** re-compile a.out ***

    (gdb) start
    The program being debugged has been started already.
    Start it from the beginning? (y or n) y
    `/home/smarchi/build/wt/test/gdb/a.out' has changed; re-reading symbols.
    Temporary breakpoint 2 at 0x555555555129: file test.c, line 1.
    Starting program: /home/smarchi/build/wt/test/gdb/a.out
    warning: Probes-based dynamic linker interface failed.
    Reverting to original interface.

    Temporary breakpoint 2, main () at test.c:1
    1       int main() { return 0; }
    (gdb)

To reproduce the bug, a.out needs to be a position-independent
executable (PIE).

Here's what happens:

1) We first read the symbols of a.out.  The section offsets in the
   objfile are all 0, so the symbols are created unrelocated.
2) The breakpoint on main is created, as you can see the breakpoint
   address (derived from the `main` symbol with value 0x1129) is still
   unrelocated (0x1131).  Since the program is not yet started, we don't
   know at which base address the executable is going to end at.
   Everything good so far.
3) The execution starts, GDB finds out the executable's base address,
   fills the objfile's section_offsets vector with a bunch of offsets,
   and relocates the symbols with those offsets.  The latter modifies
   the symbol values (the `main` symbol is changed from 0x1129 to
   0x555555555129).
4) We `start` again, we detect that `a.out` has changed, the
   `reread_symbols` function kicks in.  It tries to reset everything
   in the `struct objfile` corresponding to `a.out`, except that it
   leaves the `section_offsets` vector there.
5) `reread_symbols` reads the debug info (calls `read_symbols`).  As the
   DWARF info is read, symbols are created using the old offsets still
   in `section_offsets`.  For example, the `main` symbol is created with
   the value 0x555555555129.  Even though at this point there is no
   process, so that address is bogus.  There's probably more that
   depends on section_offsets that is not done correctly.
6) Something in the SVR4 solib handling goes wrong, probably because
   of something that went wrong in (5).  I can't quite explain it (if
   somebody would like to provide a more complete analysis, please go
   ahead).  But this is where it takes a wrong turn:

    #0  elf_locate_base () at /home/smarchi/src/wt/test/gdb/solib-svr4.c:799
    #1  0x000055f0a5bee6d5 in locate_base (info=<optimized out>) at /home/smarchi/src/wt/test/gdb/solib-svr4.c:848
    #2  0x000055f0a5bf1771 in svr4_handle_solib_event () at /home/smarchi/src/wt/test/gdb/solib-svr4.c:1955
    #3  0x000055f0a5c0ff92 in handle_solib_event () at /home/smarchi/src/wt/test/gdb/solib.c:1258

   In the non-working case (without this patch), elf_locate_base returns
   0, whereas in the working case (with this patch) it returns a valid
   address, as we should expect.

This patch fixes this by making reread_symbols clear the
`section_offsets` vector, and re-create it by calling `sym_offsets`.
This is analogous to what syms_from_objfile_1 does.  I didn't seem
absolutely necessary, but I also made it clear the various
`sect_index_*` fields, since their values no longer make sense (they
describe the old executable, and are indices in the now cleared
sections/section_offsets arrays).

I don't really like the approach taken by reread_symbols, trying to
reset everything manually on the objfile object, instead of, for
example, creating a new one from scratch.  But I don't know enough yet
to propose a better solution.

One more reason I think this patch is needed is that the number of
sections of the new executable could be different from the number of
sections of the old executable.  So if we don't re-create the
section_offsets array, not only we'll have wrong offsets, but we could
make accesses past the array.

Something else that silently fails (but doesn't seem to have
consequences) is the prologue analysis when we try to create the
breakpoint on `main`.  Since the `main` symbol has the wrong value
0x555555555129, we try to access memory in that area, which fails.  This
can be observed by debugging gdb and using `catch throw`.  Before the
process is started, we need to access the memory at its unrelocated
address, 0x1129, which will read memory from the ELF file.  This is now
what happens, with this patch applied.

It silently fails, probably because commit 46a62268b, "Catch exceptions
thrown from gdbarch_skip_prologue", papered over the problem and added
an empty catch clause.  I'm quite sure that the root cause then was the
one fixed by this patch.

This fixes tests gdb.ada/exec_changed.exp and gdb.base/reread.exp for
me.

gdb/ChangeLog:

	* symfile.c (reread_symbols): Clear objfile's section_offsets
	vector and section indices, re-compute them by calling
	sym_offsets.
2020-05-20 15:45:03 -04:00
Tom Tromey 250106a76a Remove bound_name static from ada-lang.c
ada-lang.c has a "bound_name" static that is used when finding fields
in a structure in some cases.  This patch removes it in favor of
computing the desired field name at runtime; this avoids an artificial
limit.

I'm checking this in.  Tested on x86-64 Fedora 30, and also on the
internal AdaCore test suite.

gdb/ChangeLog
2020-05-20  Tom Tromey  <tromey@adacore.com>

	* ada-lang.c (bound_name, MAX_ADA_DIMENS): Remove.
        (desc_one_bound, desc_index_type): Compute field name.
2020-05-20 07:20:05 -06:00
Tom de Vries 9a0bacfb08 [gdb/symtab] Handle .gdb_index in ada language mode
When running test-case gdb.base/with.exp with target board cc-with-gdb-index,
we have:
...
(gdb) PASS: gdb.base/with.exp: basics: show language
with language ada -- print g_s^M
'g_s' has unknown type; cast it to its declared type^M
(gdb) FAIL: gdb.base/with.exp: basics: with language ada -- print g_s
...

This is due to this bit in dw2_map_matching_symbols:
...
  if (dwarf2_per_objfile->index_table != nullptr)
    {
      /* Ada currently doesn't support .gdb_index (see PR24713).  We can get
	 here though if the current language is Ada for a non-Ada objfile
	 using GNU index.  As Ada does not look for non-Ada symbols this
	 function should just return.  */
      return;
    }
...

While the reasoning in the comment may be sound from language perspective, it
does introduce an inconsistency in gdb behaviour between:
- having a .gdb_index section, and
- having a .gdb_names section, or a partial symtab, or -readnow.

Fix the inconsistency by completing implementation of
dw2_map_matching_symbols.

Tested on x86_64-linux, both with native and target board
cc-with-debug-index.

gdb/ChangeLog:

2020-05-20  Tom de Vries  <tdevries@suse.de>

	PR symtab/25833
	* dwarf2/read.c (dw2_map_matching_symbols): Handle .gdb_index.

gdb/testsuite/ChangeLog:

2020-05-20  Tom de Vries  <tdevries@suse.de>

	PR symtab/25833
	* gdb.base/with-mf-inc.c: New test.
	* gdb.base/with-mf-main.c: New test.
	* gdb.base/with-mf.exp: New file.
2020-05-20 11:48:39 +02:00
Alan Modra 7b958a48e1 PR25993, read of freed memory
ldmain.c:add_archive_element copies file name pointers from the bfd to
a lang_input_statement_type.
  input->filename = abfd->filename;
  input->local_sym_name = abfd->filename;
This results in stale pointers when twiddling the bfd filename in
places like the pe ld after_open.  So don't free the bfd filename,
and make copies using bfd_alloc memory that won't result in small
memory leaks that annoy memory checkers.

	PR 25993
bfd/
	* archive.c (_bfd_get_elt_at_filepos): Don't strdup filename,
	use bfd_set_filename.
	* elfcode.h (_bfd_elf_bfd_from_remote_memory): Likewise.
	* mach-o.c (bfd_mach_o_fat_member_init): Likewise.
	* opncls.c (bfd_fopen, bfd_openstreamr, bfd_openr_iovec, bfd_openw),
	(bfd_create): Likewise.
	(_bfd_delete_bfd): Don't free filename.
	(bfd_set_filename): Copy filename param to bfd_alloc'd memory,
	return pointer to the copy or NULL on alloc fail.
	* vms-lib.c (_bfd_vms_lib_get_module): Free newname and test
	result of bfd_set_filename.
	* bfd-in2.h: Regenerate.
gdb/
	* solib-darwin.c (darwin_bfd_open): Don't strdup pathname for
	bfd_set_filename.
	* solib-aix.c (solib_aix_bfd_open): Use std::string for name
	passed to bfd_set_filename.
	* symfile-mem.c (add_vsyscall_page): Likewise for string
	passed to symbol_file_add_from_memory.
	(symbol_file_add_from_memory): Make name param a const char* and
	don't strdup.
ld/
	* emultempl/pe.em (gld_${EMULATION_NAME}_after_open): Don't copy
	other_bfd_filename for bfd_set_filename, and test result of
	bfd_set_filename call.  Don't create a new is->filename, simply
	copy from bfd filename.  Free new_name after bfd_set_filename.
	* emultempl/pep.em (gld_${EMULATION_NAME}_after_open): Likewise.
2020-05-20 11:43:50 +09:30
Alan Modra c7e9767920 Use bfd_get_filename throughout gdb
This patch makes gdb use the inline accessor for all bfd->filename
read accesses.

	* coff-pe-read.c (read_pe_exported_syms): Use bfd_get_filename
	rather than accessing bfd->filename directly.
	* dtrace-probe.c (dtrace_static_probe_ops::get_probes): Likewise,
	and use bfd_section_name.
	* dwarf2/frame.c (decode_frame_entry): Likewise.
	* exec.c (exec_set_section_address): Likewise.
	* solib-aix.c (solib_aix_bfd_open): Likewise.
	* stap-probe.c (get_stap_base_address): Likewise.
	* symfile.c (reread_symbols): Likewise.
2020-05-20 07:59:00 +09:30
Tom Tromey 563c591bed Update call to target_fileio_open
An earlier patch changed target_fileio_open, but missed a caller.
This patch fixes it.

2020-05-19  Tom Tromey  <tromey@adacore.com>

	* sparc64-tdep.c (adi_tag_fd): Update call to target_fileio_open.
2020-05-19 12:35:07 -06:00
Simon Marchi f408d82c7a gdb: fix off-by-one error in quirk_rust_enum
Found by inspection, so I don't have a test for it (I don't think it
would be easy to have this bug cause a failure reliably).

We allocate space for N fields into `new_fields`, then memcpy N fields
at `new_fields + 1`.  This overflows the allocated buffer by one field.

Fix it by allocating `N + 1` fields.

gdb/ChangeLog:

	* dwarf2/read.c (quirk_rust_enum): Allocate enough fields.
2020-05-19 14:20:23 -04:00
Pedro Alves 98c59b527b Make exec-file-mismatch compare build IDs
The patch makes GDB do exec-file-mismatch validation by comparing
build IDs instead of the current method of comparing filenames.

Currently, the exec-file-mismatch feature simply compares filenames to
decide whether the exec file loaded in gdb and the exec file the
target reports is running match.  This causes false positives when
remote debugging, because it'll often be the case that the paths in
the host and the target won't match.  And of course misses the case of
the files having the same name but being actually different files
(e.g., different builds).

This also broke many testcases when running against gdbserver, causing
tests to be skipped like (here native-extended-gdbserver):

  (gdb) run
  Starting program: /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink-filelink
  warning: Mismatch between current exec-file /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink-filelink
  and automatically determined exec-file /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink
  exec-file-mismatch handling is currently "ask"
  Load new symbol table from "/home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink"? (y or n) UNTESTED: gdb.base/argv0-symlink.exp: could not run to main

or to fail like (here native-gdbserver):

 (gdb) spawn /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/../../gdbserver/gdbserver --once localhost:2346 /home/pedro/gdb/binutils-gdb/build/gdb/te
 stsuite/outputs/gdb.btrace/buffer-size/skip_btrace_tests-19968.x
 Process /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.btrace/buffer-size/skip_btrace_tests-19968.x created; pid = 20040
 Listening on port 2346
 target remote localhost:2346
 Remote debugging using localhost:2346
 warning: Mismatch between current exec-file /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/temp/19968/skip_btrace_tests-19968.x
 and automatically determined exec-file /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.btrace/buffer-size/skip_btrace_tests-19968.x
 exec-file-mismatch handling is currently "ask"
 Load new symbol table from "/home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.btrace/buffer-size/skip_btrace_tests-19968.x"? (y or n) Quit
 (gdb) UNSUPPORTED: gdb.btrace/buffer-size.exp: target does not support record-btrace

The former case is about GDB not realizing the two files are the same,
because one of the them is a symlink to the other.  The latter case is
about GDB realizing that one file is a copy of the other.

Over the years, the toolchain has settled on build ID matching being
the canonical method to match core dumps to executables, and
executables with no debug info to their debug info.

This patch makes us use build IDs to match the running image of a
binary with its version loaded in gdb, which may or may not have debug
info.  This is very much like the core dump/executable matching.

The change to gdb_bfd_open is necessary to get rid of the "transfers
from remote targets can be slow" warning when we open the remote file
to read its build ID:

 (gdb) r
 Starting program: /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/break/break
 Reading /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink from remote target...
 warning: File transfers from remote targets can be slow. Use "set sysroot" to access files locally instead.
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 warning: Mismatch between current exec-file /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/break/break
 and automatically determined exec-file /home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink
 exec-file-mismatch handling is currently "ask"
 Load new symbol table from "/home/pedro/gdb/binutils-gdb/build/gdb/testsuite/outputs/gdb.base/argv0-symlink/argv0-symlink"? (y or n)

While trying this out, I was worried that bfd would read a lot of
stuff from the binary in order to extract the build ID, making it
potentially slow, but turns out we don't read all that much.  Maybe a
couple hundred bytes, and most of it seemingly is the read-ahead
cache.  So I'm not worried about that.  Otherwise I'd consider whether
a new qXfer:buildid:read would be better.  But I'm happy that we
seemingly don't need to worry about it.

gdb/ChangeLog:
2020-05-19  Pedro Alves  <palves@redhat.com>

	* NEWS (set exec-file-mismatch): Adjust entry.
	* exec.c: Include "build-id.h".
	(validate_exec_file): Try to match build IDs instead of filenames.
	* gdb_bfd.c (struct gdb_bfd_open_closure): New.
	(gdb_bfd_iovec_fileio_open): Adjust to use gdb_bfd_open_closure
	and pass down 'warn_if_slow'.
	(gdb_bfd_open): Add 'warn_if_slow' parameter.  Use
	gdb_bfd_open_closure to pass it down.
	* gdb_bfd.h (gdb_bfd_open): Add 'warn_if_slow' parameter.

gdb/doc/ChangeLog:
2020-05-19  Pedro Alves  <palves@redhat.com>

	* gdb.texinfo (Attach): Update exec-file-mismatch description to
	mention build IDs.
	(Separate Debug Files): Add "build id" anchor.
2020-05-19 18:37:15 +01:00
Pedro Alves 4111f652f9 Eliminate target_fileio_open_warn_if_slow
This basically makes target_fileio_open_1 extern, renamed to
target_fileio_open, and eliminates the current
target_fileio_open_warn_if_slow and target_fileio_open.

A following parameter will want to change gdb_bfd_iovec_fileio_open,
the only caller of target_fileio_open_warn_if_slow, to pass down
"warn_if_slow" true/false from the caller, instead of hardcoding
"warn_if_slow" true.

gdb/ChangeLog:
2020-05-19  Pedro Alves  <palves@redhat.com>

	* gdb_bfd.c (gdb_bfd_iovec_fileio_open): Adjust.
	* target.c (target_fileio_open_1): Rename to target_fileio_open
	and make extern.  Use bool.
	(target_fileio_open, target_fileio_open_warn_if_slow): Delete.
	(target_fileio_read_alloc_1): Adjust.
	* target.h (target_fileio_open): Add 'warn_if_slow' parameter.
	(target_fileio_open_warn_if_slow): Delete declaration.
2020-05-19 18:36:51 +01:00
Pedro Alves ad80db5b9f Default gdb_bfd_open's fd parameter to -1
A following patch will add one more defaulted parameter.

gdb/ChangeLog:
2020-05-19  Pedro Alves  <palves@redhat.com>

	* gdb_bfd.h: (gdb_bfd_open): Default to 'fd' parameter to -1.
	Adjust all callers.
2020-05-19 18:36:24 +01:00
Yoshinori Sato 1d6ce4d312 gdb: fix -Wtautological-overlap-compare error in h8300-tdep.c
Compiling with clang 11 gives us:

      CXX    h8300-tdep.o
    /home/smarchi/src/binutils-gdb/gdb/h8300-tdep.c:225:21: error: overlapping comparisons always evaluate to false [-Werror,-Wtautological-overlap-compare]
                  if (disp < 0 && disp > 0xffffff)
                      ~~~~~~~~~^~~~~~~~~~~~~~~~~~
    /home/smarchi/src/binutils-gdb/gdb/h8300-tdep.c:203:17: error: overlapping comparisons always evaluate to false [-Werror,-Wtautological-overlap-compare]
              if (disp < 0 && disp > 0xffffff)
                  ~~~~~~~~~^~~~~~~~~~~~~~~~~~
    /home/smarchi/src/binutils-gdb/gdb/h8300-tdep.c:184:17: error: overlapping comparisons always evaluate to false [-Werror,-Wtautological-overlap-compare]
              if (disp < 0 && disp > 0xffffff)
                  ~~~~~~~~~^~~~~~~~~~~~~~~~~~

Indeed, disp (of type LONGEST) can't be less than 0 and greater than
0xffffff.

Fix it by changing the way we check if disp is negative.  Check the sign
bit of disp, which is a 24-bit number.

gdb/ChangeLog:

	* h8300-tdep.c (h8300_is_argument_spill): Change how we check
	whether disp is negative.
2020-05-19 13:33:52 -04:00
Simon Marchi 9005fbbb00 gdb: make symfile_segment_data::segment_info an std::vector
Change the symfile_segment_data::segment_info array to be an
std::vector.  No functional changes are expected.

gdb/ChangeLog:

	* symfile.h (struct symfile_segment_data)
	<~symfile_segment_data>: Remove.
	<segment_info>: Change to std::vector.
	* symfile.c (default_symfile_segments): Update.
	* elfread.c (elf_symfile_segments): Update.
2020-05-19 12:18:36 -04:00
Simon Marchi 68b888fff3 gdb: use std::vector to store segments in symfile_segment_data
Instead of maintaining two vectors, I added a small `segment` class
which holds both the base address and size of one segment and replaced
the two `segment_bases` and `segment_sizes` arrays with a single vector.

The rest of the changes are straightforward, no behavior changes are
expected.

gdb/ChangeLog:

	* symfile.h (struct symfile_segment_data) <struct segment>: New.
	<segments>: New.
	<segment_bases, segment_sizes>: Remove.
	* symfile.c (default_symfile_segments): Update.
	* elfread.c (elf_symfile_segments): Update.
	* remote.c (remote_target::get_offsets): Update.
	* solib-target.c (solib_target_relocate_section_addresses):
	Update.
2020-05-19 12:18:36 -04:00
Simon Marchi 62982abdee gdb: allocate symfile_segment_data with new
- Allocate this structure with new instead of XNEW, use a unique pointer
  to manage its lifetime.
- Change a few functions to return a unique   pointer instead of a
  plain pointer.
- Change free_symfile_segment_data to be symfile_segment_data's
  destructor.

gdb/ChangeLog:

	* symfile.h (struct symfile_segment_data): Initialize fields.
	<~symfile_segment_data>: Add.
	(symfile_segment_data_up): New.
	(struct sym_fns) <sym_segments>: Return a
	symfile_segment_data_up.
	(default_symfile_segments): Return a symfile_segment_data_up.
	(free_symfile_segment_data): Remove.
	(get_symfile_segment_data): Return a symfile_segment_data_up.
	* symfile.c (default_symfile_segments): Likewise.
	(get_symfile_segment_data): Likewise.
	(free_symfile_segment_data): Remove.
	(symfile_find_segment_sections): Update.
	* elfread.c (elf_symfile_segments): Return a
	symfile_segment_data_up.
	* remote.c (remote_target::get_offsets): Update.
	* solib-target.c (solib_target_relocate_section_addresses):
	Update.
	* symfile-debug.c (debug_sym_segments): Return a
	symfile_segment_data_up.
2020-05-19 12:18:36 -04:00
Rainer Orth e52a0f1bd9 Avoid short i386 register names on Solaris/x86 [PR25981]
This is the 32-bit companion to

	Remove unused ps_lgetLDT etc. on Solaris/x86 [PR25981]
        https://sourceware.org/pipermail/gdb-patches/2020-May/168713.html

A 32-bit-default gdb fails to compile with the updated <sys/regset.h>.
While it is also affected by the lack of a GS definition, which the
compantion patch above fixes, it also fails to compile i386-sol2-nat.c like
this

/vol/src/gnu/gdb/hg/master/git/gdb/i386-sol2-nat.c:181:3: error: 'EAX' was not declared in this scope
  181 |   EAX, ECX, EDX, EBX,
      |   ^~~

and several more.

While this could be fixed by either including <ucontext.h> here or
provding fallback definitions of the register macros, I chose to do what
the 64-bit-default code in the same file
(amd64_sol2_gregset32_reg_offset[]) does, namely just hardcode the
numeric values instead.  They are part of the ABI and thus guaranteed
not to change.

With this patch, a i386-pc-solaris2.11 configuration on master compiles
again, however, it doesn't work.  However, I could successfully test it
on the gdb-9 branch.

Compiling and testing proved to be messy, unfortunately:

* For one, Solaris <sys/procfs.h> and largefile support used to be
  mutually exclusive (fixed in Solaris 11.4 and Illumos), which was
  exacerbated by the fact that g++ predefines _FILE_OFFSET_BITS=64 since
  GCC 9.1.0.  For now I've worked around this by adding
  -U_FILE_OFFSET_BITS to CXXFLAGS and configuring with
  --disable-largefile.  I hope to clean this up in a future patch.

* gdb still defaults to startup-with-shell on.  However, /bin/bash is a
  64-bit executable which cannot be debugged by a 32-bit gdb.  I hacked
  around that part by pointing $SHELL at a 32-bit bash before running
  make check.

	PR build/25981
	* i386-sol2-nat.c [PR_MODEL_NATIVE != PR_MODEL_LP64] (regmap):
	Hardcode register numbers.
2020-05-18 17:59:43 +02:00
Rainer Orth 7f20433998 Remove unused ps_lgetLDT etc. on Solaris/x86 [PR25981]
As reported in PR build/25981, a future Solaris 11.4 update will soon
remove the short i386 register names like SS etc. from <sys/regset.h>.
They could leak into user code (e.g. via <signal.h> -> <sys/signal.h> ->
<sys/ucontext.h>) and pollute the user namespace.  Affected code would
have a hard time avoiding the issue: LLVM is one of those.

While the short names are required to be present by the i386 psABI, that
document only demands that they exist in <ucontext.h>, which is what the
upcoming update assures.

With this change, in a 64-bit-default configuration, procfs.c fails to
compile on Solaris/x86:

/vol/src/gnu/gdb/hg/master/git/gdb/procfs.c: In function 'ssd* procfs_find_LDT_entry(ptid_t)':
/vol/src/gnu/gdb/hg/master/git/gdb/procfs.c:1643:18: error: 'GS' was not declared in this scope
 1643 |   key = (*gregs)[GS] & 0xffff;
      |                  ^~
make[2]: *** [Makefile:1607: procfs.o] Error 1

Initially I meant to provide a definition using the planned replacement
macro, but closer inspection revealed a better way.  procfs_find_LDT_entry
and its helper proc_get_LDT_entry are only used to implement ps_lgetLDT,
one of the callback functions required by libthread_db.so.1
(cf. <proc_service.h>).  While that function is still documented as being
required even in Solaris 11.4, I found that calls to it had been removed
long ago in Solaris 9, so just removing the three functions above is the
easiest fix.

The following patch does just that.  It compiled successfully on
amd64-pc-solaris2.11, however, as reported in PR gdb/25939, master is
completely broken on Solaris since the multi-target patch.  The patch
applies cleanly to the gdb-9 branch and there I could test it
successfully.

	PR build/25981
	* procfs.c [(__i386__ || __x86_64__) && sun] (proc_get_LDT_entry,
	procfs_find_LDT_entry): Remove.
	* procfs.h [(__i386__ || __x86_64__) && sun] (struct ssd,
	procfs_find_LDT_entry): Remove.
	* sol-thread.c [(__i386__ || __x86_64__) && sun] (ps_lgetLDT):
	Remove.
2020-05-18 17:56:00 +02:00
Pedro Alves 7f32a4d5ae Stop considering hw and sw breakpoint locations duplicates (PR gdb/25741)
In the following conditions:

  - A target with hardware breakpoints available, and
  - A target that uses software single stepping,
  - An instruction at ADDRESS loops back to itself,

Now consider the following steps:

  1. The user places a hardware breakpoint at ADDRESS (an instruction
  that loops to itself),

  2. The inferior runs and hits the breakpoint at ADDRESS,

  3. The user tells GDB to 'continue'.

In #3 when the user tells GDB to continue, GDB first disables the
hardware breakpoint at ADDRESS, and then inserts a software
single-step breakpoint at ADDRESS.  The original user-created
breakpoint was a hardware breakpoint, while the single-step breakpoint
will be a software breakpoint.

GDB continues and immediately hits the software single-step
breakpoint.

GDB then deletes the software single-step breakpoint by calling
delete_single_step_breakpoints, which eventually calls
delete_breakpoint, which, once the breakpoint (and its locations) are
deleted, calls update_global_location_list.

During update_global_location_list GDB spots that we have an old
location (the software single step breakpoint location) that is
inserted, but being deleted, and a location (the original hardware
breakpoint) at the same address which we are keeping, but which is not
currently inserted, GDB then calls breakpoint_locations_match on these
two locations.

Currently the locations do match, and so GDB calls swap_insertion
which swaps the "inserted" state of the two locations.  The user
created hardware breakpoint is marked as inserted, while the GDB
internal software single step breakpoint is now marked as not
inserted.  After this GDB returns through the call stack and leaves
delete_single_step_breakpoints.

After this GDB continues with its normal "stopping" process, as part
of this stopping process GDB removes all the breakpoints from the
target.  Due to the swap it is now the user-created hardware
breakpoint that is marked as inserted, so it is this breakpoint GDB
tries to remove.

The problem is that GDB inserted the software single-step breakpoint
as a software breakpoint, but is now trying to remove the hardware
breakpoint.  The problem is removing a software breakpoint is very
different to removing a hardware breakpoint, this could result is some
undetected undefined behaviour, or as in the original bug report (PR
gdb/25741), could result in the target throwing an error.

With "set breakpoint always-inserted on", we can easily reproduce this
against GDBserver.  E.g.:

  (gdb) hbreak main
  Sending packet: $m400700,40#28...Packet received: 89e58b....
  Sending packet: $m400736,1#fe...Packet received: 48
  Hardware assisted breakpoint 1 at 0x400736: file threads.c, line 57.
  Sending packet: $Z1,400736,1#48...Packet received: OK
  Packet Z1 (hardware-breakpoint) is supported

  (gdb) b main
  Note: breakpoint 1 also set at pc 0x400736.
  Sending packet: $m400736,1#fe...Packet received: 48
  Breakpoint 2 at 0x400736: file threads.c, line 57.

  (gdb) del
  Delete all breakpoints? (y or n) y
  Sending packet: $z0,400736,1#67...Packet received: E01
  warning: Error removing breakpoint 2

This patch adds a testcase that does exactly that.

Trying to enhance GDB to handle this scenario while continuing to
avoid inserting redundant software and hardware breakpoints at the
same address turns out futile, because, given non-stop and breakpoints
always-inserted, if the user:

 #1 - inserts a hw breakpoint, then
 #2 - inserts a sw breakpoint at the same address, and then
 #3 - removes the original hw breakpoint,

GDB would have to make sure to insert the sw breakpoint before
removing the hw breakpoint, to avoid running threads missing the
breakpoint.  I.e., there's always going to be a window where a target
needs to be able to handle both sw and a hw breakpoints installed at
the same address.  You can see more detailed description of that issue
here:
https://sourceware.org/pipermail/gdb-patches/2020-April/167738.html

So the fix here is to just stop considering software breakpoints and
hw breakpoints duplicates, and let GDB insert sw and hw breakpoints at
the same address.

The central change is to make breakpoint_locations_match consider the
location's type too.  There are several other changes necessary to
actually make that that work correctly, however:

- We need to handle the duplicates detection better.  Take a look at
  the loop at the tail end of update_global_location_list.  Currently,
  because breakpoint locations aren't sorted by type, we can end up
  with, at the same address, a sw break, then a hw break, then a sw
  break, etc.  The result is that that second sw break won't be
  considered a duplicate of the first sw break.  Seems like we already
  handle that incorrectly for range breakpoints.

- The "set breakpoint auto-hw on" handling is moved out of
  insert_bp_location to update_global_location_list, before the
  duplicates determination.

  Moving "set breakpoint auto-hw off" handling as well and downgrading
  it to a warning+'disabling the location' was considered too, but in
  the end discarded, because we want to error out with internal and
  momentary breakpoints, like software single-step breakpoints.
  Disabling such locations at update_global_location_list time would
  make GDB lose control of the inferior.

- In update_breakpoint_locations, the logic of matching old locations
  with new locations, in the have_ambiguous_names case, is updated to
  still consider sw vs hw locations the same.

- Review all ALL_BP_LOCATIONS_AT_ADDR uses, and update those that
  might need to be updated, and update comments for those that don't.
  Note that that macro walks all locations at a given address, and
  doesn't call breakpoint_locations_match.

The result against GDBserver (with "set breakpoint
condition-evaluation host" to avoid seeing confusing reinsertions) is:

 (gdb) hbreak main
 Sending packet: $m400736,1#fe...Packet received: 48
 Hardware assisted breakpoint 1 at 0x400736: file main.c, line 57.
 Sending packet: $Z1,400736,1#48...Packet received: OK

 (gdb) b main
 Note: breakpoint 1 also set at pc 0x400736.
 Sending packet: $m400736,1#fe...Packet received: 48
 Breakpoint 4 at 0x400736: file main.c, line 57.
 Sending packet: $Z0,400736,1#47...Packet received: OK

 (gdb) del 3
 Sending packet: $z1,400736,1#68...Packet received: OK

gdb/ChangeLog:
2020-05-17  Pedro Alves  <palves@redhat.com>
	    Andrew Burgess  <andrew.burgess@embecosm.com>
	    Keno Fischer  <keno@juliacomputing.com>

	PR gdb/25741
	* breakpoint.c (build_target_condition_list): Update comments.
	(build_target_command_list): Update comments and skip matching
	locations.
	(insert_bp_location): Move "set breakpoint auto-hw on" handling to
	a separate function.  Simplify "set breakpoint auto-hw off"
	handling.
	(insert_breakpoints): Update comment.
	(tracepoint_locations_match): New parameter.  For breakpoints,
	compare location types too, if the caller wants to.
	(handle_automatic_hardware_breakpoints): New functions.
	(bp_location_is_less_than): Also sort by location type and
	hardware breakpoint length.
	(update_global_location_list): Handle "set breakpoint auto-hw on"
	here.
	(update_breakpoint_locations): Ask breakpoint_locations_match to
	ignore location types.

gdb/testsuite/ChangeLog:
2020-05-17  Pedro Alves  <palves@redhat.com>

	PR gdb/25741
	* gdb.base/hw-sw-break-same-address.exp: New file.
2020-05-17 19:17:56 +01:00
Simon Marchi 7d93a1e0b6 gdb: remove TYPE_NAME macro
Remove `TYPE_NAME`, changing all the call sites to use `type::name`
directly.  This is quite a big diff, but this was mostly done using sed
and coccinelle.  A few call sites were done by hand.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_NAME): Remove.  Change all cal sites to use
	type::name instead.
2020-05-16 12:36:05 -04:00
Simon Marchi d0e39ea27c gdb: add type::name / type::set_name
Add the `name` and `set_name` methods on `struct type`, in order to
remove the `TYPE_NAME` macro.  In this patch, the `TYPE_NAME` macro is
changed to use `type::name`, so all the call sites that are used to set
the type name are changed to use `type::set_name`.  The next patch will
remove `TYPE_NAME` completely.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <name, set_name>: New methods.
	(TYPE_CODE): Use type::name.  Change all call sites used to set
	the name to use type::set_name instead.
2020-05-16 12:36:05 -04:00
Tom Tromey 2dab0c7ba0 Remove ALL_UIS
Continuing my goal of removing the "ALL_*" iterator macros, this
removes ALL_UIS, replacing it with an iterator adaptor.

gdb/ChangeLog
2020-05-16  Tom Tromey  <tom@tromey.com>

	* top.c (quit_force): Update.
	* infrun.c (handle_no_resumed): Update.
	* top.h (all_uis): New function.
	(ALL_UIS): Remove.
2020-05-16 09:58:46 -06:00
Simon Marchi 59f7bd8d2b gdb: fix -Wtautological-overlap-compare warning in mips-linux-tdep.c
When building with clang 11, I get:

  CXX    mips-linux-tdep.o
/home/smarchi/src/binutils-gdb/gdb/mips-linux-tdep.c:643:30: error: overlapping comparisons always evaluate to true [-Werror,-Wtautological-overlap-compare]
      if (insn != 0x03e07821 || insn != 0x03e07825)
          ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
/home/smarchi/src/binutils-gdb/gdb/mips-linux-tdep.c:636:30: error: overlapping comparisons always evaluate to true [-Werror,-Wtautological-overlap-compare]
      if (insn != 0x03e0782d || insn != 0x03e07825)
          ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~

Indeed, given two different values, `insn` will always be different to
one of them, and these conditions always be true.

This code is meant to return if `insn` isn't one of these two values, so
the `||` should be replaced with `&&`.

gdb/ChangeLog:

	* mips-linux-tdep.c (mips_linux_in_dynsym_stub): Fix condition.
2020-05-16 11:21:41 -04:00
Pedro Alves 9bf058f094 Fix IA64 GNU/Linux build
This commit should fix:

 ../../gdb/ia64-linux-nat.c: In function ‘void enable_watchpoints_in_psr(ptid_t)’:
 ../../gdb/ia64-linux-nat.c:535:56: error: no matching function for call to ‘get_thread_regcache(ptid_t&)’
    struct regcache *regcache = get_thread_regcache (ptid);
							 ^
 In file included from ../../gdb/ia64-linux-nat.c:25:0:
 ../../gdb/regcache.h:35:25: note: candidate: regcache* get_thread_regcache(process_stratum_target*, ptid_t)
  extern struct regcache *get_thread_regcache (process_stratum_target *target,
			  ^
 ../../gdb/regcache.h:35:25: note:   candidate expects 2 arguments, 1 provided
 ../../gdb/regcache.h:39:25: note: candidate: regcache* get_thread_regcache(thread_info*)
  extern struct regcache *get_thread_regcache (thread_info *thread);
			  ^
 ../../gdb/regcache.h:39:25: note:   no known conversion for argument 1 from ‘ptid_t’ to ‘thread_info*’

gdb/ChangeLog:
2020-05-16  Pedro Alves  <palves@redhat.com>

	* ia64-linux-nat.c
	(ia64_linux_nat_target) <enable_watchpoints_in_psr(ptid_t)>:
	Declare method.
	(enable_watchpoints_in_psr): Now a method of ia64_linux_nat_target.
2020-05-16 12:26:56 +01:00
Simon Marchi 8f86ae1a18 gdb: remove unnecessary struct typedef in sparc64-tdep.c
When building with clang 11, I get:

      CXX    sparc64-tdep.o
    /home/smarchi/src/binutils-gdb/gdb/sparc64-tdep.c:89:15: error: anonymous non-C-compatible type given name for linkage purposes by typedef declaration; add a tag name here [-Werror,-Wnon-c-typedef-for-linkage]
    typedef struct
                  ^
                   adi_stat_t
    /home/smarchi/src/binutils-gdb/gdb/sparc64-tdep.c:103:16: note: type is not C-compatible due to this default member initializer
      int tag_fd = 0;
                   ^
    /home/smarchi/src/binutils-gdb/gdb/sparc64-tdep.c:111:3: note: type is given name 'adi_stat_t' for linkage purposes by this typedef declaration
    } adi_stat_t;
      ^

The typedef is not needed in C++ anyway, just remove them.

gdb/ChangeLog:

	* sparc64-tdep.c (adi_stat_t): Remove typedef (leaving struct).
	(sparc64_adi_info): Likewise.
2020-05-15 22:17:40 -04:00
Tom Tromey d6bc0792ed Remove lookup_objfile_from_block
lookup_objfile_from_block mostly duplicates the functionality of
block_objfile, but in a less efficient way.  This patch removes this
function and changes the callers to use block_objfile instead.

Tested by the buildbot.

gdb/ChangeLog
2020-05-15  Tom Tromey  <tom@tromey.com>

	* symtab.c (lookup_language_this, lookup_symbol_aux): Use
	block_objfile.
	(lookup_objfile_from_block): Remove.
	(lookup_symbol_in_block, lookup_symbol_in_static_block)
	(lookup_global_symbol): Use block_objfile.
	* symtab.h (lookup_objfile_from_block): Don't declare.
	* printcmd.c (clear_dangling_display_expressions): Use
	block_objfile.
	* parse.c (operator_check_standard): Use block_objfile.
2020-05-15 16:24:07 -06:00
Tom Tromey 8c14c3a373 Remove allocate_symbol et al
This removes allocate_symbol, allocate_template_symbol, and
initialize_objfile_symbol in favor of changing the default values for
symbol members, and updating the one per-arch caller.

gdb/ChangeLog
2020-05-15  Tom Tromey  <tom@tromey.com>

	* language.c (language_alloc_type_symbol): Set
	SYMBOL_SECTION.
	* symtab.c (initialize_objfile_symbol): Remove.
	(allocate_symbol): Remove.
	(allocate_template_symbol): Remove.
	* dwarf2/read.c (fixup_go_packaging): Use "new".
	(new_symbol): Use "new".
	(read_variable): Don't call initialize_objfile_symbol.  Use
	"new".
	(read_func_scope): Use "new".
	* xcoffread.c (process_xcoff_symbol): Don't call
	initialize_objfile_symbol.
	(SYMBOL_DUP): Remove.
	* coffread.c (process_coff_symbol, coff_read_enum_type): Use
	"new".
	* symtab.h (allocate_symbol, initialize_objfile_symbol)
	(allocate_template_symbol): Don't declare.
	(struct symbol): Add copy constructor.  Change defaults.
	* jit.c (finalize_symtab): Use "new".
	* ctfread.c (ctf_add_enum_member_cb, new_symbol, ctf_add_var_cb):
	Use "new".
	* stabsread.c (patch_block_stabs, define_symbol, read_enum_type)
	(common_block_end): Use "new".
	* mdebugread.c (parse_symbol): Use "new".
	(new_symbol): Likewise.
2020-05-15 16:11:34 -06:00
Philippe Waroquiers 5b4a1a8dbe Update NEWS and documentation for help and apropos changes.
gdb/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* NEWS: Mention changes to help and apropos.

gdb/doc/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.texinfo (Help): Document the help and apropos changes.
	(Aliases): Document new meaning of -a abbreviation flag.
2020-05-15 22:17:46 +02:00
Philippe Waroquiers 57b4f16e49 Ensure class_alias is only used for user-defined aliases.
This commit finally does the (small) change that started this patch
series.

It ensures that the class_alias is only used for user-defined aliases.
So, the few GDB pre-defined aliases that were using the 'class_alias'
class are now using a real help class, typically the class of
the aliased command.

gdb/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* command.h (enum command_class): Improve comments, document
	that class_alias is for user-defined aliases, give the class
	name for each class, remove unused class_xdb.
	* cli/cli-decode.c (add_com_alias): Document THECLASS intended usage.
	* breakpoint.c (_initialize_breakpoint): Replace class_alias
	by a precise class.
	* infcmd.c (_initialize_infcmd): Likewise.
	* reverse.c (_initialize_reverse): Likewise.
	* stack.c (_initialize_stack): Likewise.
	* symfile.c (_initialize_symfile): Likewise.
	* tracepoint.c (_initialize_tracepoint): Likewise.

gdb/testsuite/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/alias.exp: Verify 'help aliases' shows user defined aliases.
2020-05-15 22:17:46 +02:00
Philippe Waroquiers 7c05caf72d Fix/improve 'apropos' output
Similarly to 'help CLASS', apropos possibly shows several
times the same help (for the command and for each of its aliases).

This patch changes 'apropos' so that the help for a command and
all its aliases is shown once.

So, apropos_cmd now skips all aliases/abbreviations, as these are printed
as part of the help of the aliased command.

When 'apropos' prints the help of a command, function 'help_cmd' now
unconditionally print the command name and its possible aliases (as we must
indicate to the user the command/aliases for which the help is printed).

When 'help somecommand' prints the help of a command, if the command is not
aliased, the command name is not printed (to avoid a useless first line), but if
it has aliases, then the command name and all its aliases are now printed.
In addition to provide to the user the choice of the best way to
type a command, it also avoids the strange behaviour that the output
of 'help somealias' does not mention somealias.

gdb/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-decode.c (apropos_cmd): Produce output for aliases
	when their aliased command is traversed.
	(help_cmd): Add fput_command_names_styled call to
	output command name and aliases when command has an alias.

gdb/testsuite/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/help.exp: Test apropos and help for commands
	having aliases.  Fixed comments not starting with an
	upper-case letter or not finishing with a dot.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers 3b3aaacba1 Fix/improve 'help CLASS' output
Currently, help CLASS possibly shows several times the same help,
as it shows it once for the command, and once for each alias.

The final objective of this patch series is to have class_alias used only
for user defined aliases, not anymore for aliases predefined by GDB.
The command 'help aliases' will then only show the user defined aliases.
So, the idea is that GDB predefined aliases will be shown together
with their aliased command.

This commit changes 'help CLASS' so that a command is shown once in the output,
with all its aliases.
This ensures:
  * that the user has only to read once the same help text
  * and sees the command and all its aliases in a glance, a.o. allowing
    the user to choose the preferred way (e.g. the shortest one,
    or the most mnemonic one) to type the command.

For example, the old output:
   (gdb) help stack
   ...
   List of commands:

   backtrace -- Print backtrace of all stack frames, or innermost COUNT frames.
   bt -- Print backtrace of all stack frames, or innermost COUNT frames.
   ...
(note that 'where' is not shown in this output)

becomes
   (gdb) help stack
   ...
   List of commands:

   backtrace, where, bt -- Print backtrace of all stack frames, or innermost COUNT frames.
   ...

The output layout chosen is to have the command first, followed by all its
aliases separated by a comma.  Note that the command and alias names are
title-styled.  For sure, other layouts could be discussed, but this one is IMO
readable and compact.

The function 'help_cmd_list' can be simplified by removing the prefix argument,
as the prefixname of a command can now be retrieved in the GDB command tree
structure.

This also fixes the fact that 'help aliases' wrongly shows a long
list of (non-alias) when defining an alias for a prefix command.
For example, after:
    (gdb) alias montre = show
  then
    (gdb) help aliases
  shows hundreds of sub-commands starting with the non aliased command,
  such as:
    montre -- Generic command for showing things about the debugger.
    show ada -- Generic command for showing Ada-specific settings.
    show ada print-signatures -- Show whether the output of formal ...
    ....

'help_cmd_list' is also made static, as it is only used inside cli-decode.c.

Note that the 'help CLASS' is somewhat broken, in the sense that it
sometimes shows too many commands (commands not belonging to CLASS)
and sometimes shows not enough commands (not showing some commands
belonging to CLASS).
For example, 'help breakpoints' shows the command
'disable pretty-printer' and 'disable unwinder', not related to breakpoints.
On the other end, 'help stack' does not show 'disable unwinder'
while 'disable unwinder' is defined in unwinders.py as belonging to class_stack.
Fixing the missing commands is easy to do,
but fixing the excess commands is not straightforward, as many
subcommands have a class 'no_class' or 'all_class'.
Possibly, some of this might be improved/fixed in another patch series.

With this patch series, the 'abbrev flag' has as only remaining purpose
to avoid having the abbreviation alias appearing in the completion list,
so change 'help alias' accordingly.

gdb/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-decode.h (help_cmd_list): Remove declaration.
	* cli/cli-decode.c (help_cmd_list): Declare as static,
	remove prefix argument, use bool for recurse arg, rework to show the aliases of
	a command together with the command.
	(fput_command_name_styled, fput_command_names_styled): New functions.
	(print_help_for_command): Remove prefix arg, use bool for recurse arg, use
	fput_command_name_styled.
	(help_list, help_all): Update callers to remove prefix arg and use bool recurse.
	* cli/cli-cmds.c (_initialize_cli_cmds): Update alias_command doc.

gdb/testsuite/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/alias.exp: Update help output check.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers 7aa1b46f43 Fix inconsistent output of prefix and bugs in 'show' command
cmd_show_list function implements the 'show' command.

cmd_show_list output is inconsistent: it sometimes shows a prefix
and sometimes does not.
For example, in the below, you see that there is a prefix before
each value, except for 'enabled'.

    (gdb) show style
    style address background:  The "address" style background color is: none
    style address foreground:  The "address" style foreground color is: blue
    style address intensity:  The "address" style display intensity is: normal
    enabled:  CLI output styling is enabled.
    style filename background:  The "filename" style background color is: none
    ...

There are other inconsistencies or bugs e.g. in
the below we see twice insn-number-max, once with a prefix
and once without prefix : last line, just before the value of
instruction-history-size which is itself without prefix.

    (gdb) show record
    record btrace bts buffer-size:  The record/replay bts buffer size is 65536.
    record btrace cpu:  btrace cpu is 'auto'.
    record btrace pt buffer-size:  The record/replay pt buffer size is 16384.
    record btrace replay-memory-access:  Replay memory access is read-only.
    record full insn-number-max:  Record/replay buffer limit is 200000.
    record full memory-query:  Whether query if PREC cannot record memory change of next instruction is off.
    record full stop-at-limit:  Whether record/replay stops when record/replay buffer becomes full is on.
    function-call-history-size:  Number of functions to print in "record function-call-history" is 10.
    insn-number-max:  instruction-history-size:  Number of instructions to print in "record instruction-history" is 10.
    (gdb)

Also, some values are output several times due to some aliases, so avoid outputting duplicated
values by skipping all aliases.

Now that the command structure has a correct 'back-pointer' from a command
to its prefix command, we can simplify cmd_show_list by removing its prefix argument
and at the same time fix the output inconsistencies and bugs.

gdb/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-setshow.h (cmd_show_list): Remove prefix argument.
	* cli/cli-decode.c (do_show_prefix_cmd): Likewise.
	* command.h (cmd_show_list): Likewise.
	* dwarf2/index-cache.c (show_index_cache_command): Likewise.
	* cli/cli-setshow.c (cmd_show_list): Use the prefix to produce the output.  Skip aliases.

gdb/testsuite/ChangeLog

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/default.exp: Update output following fixes.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers 89bcba74f8 command-def-selftests.c: detect missing or wrong prefix cmd in subcommands.
This test revealed a number of problems that are fixed in the previous commit.

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* unittests/command-def-selftests.c (traverse_command_structure):
	Verify all commands of a list have the same prefix command and
	that only the top cmdlist commands have a null prefix.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers 3f4d92ebdf Fix the problems reported by prefix check of command-def-selftests.c
The next commit updates command-def-selftests.c to detect missing
or wrong prefix commands in a list of subcommands.
This command structure selftest detects a series of problems
that are fixed by this commit.

Many commands have a null prefix command, e.g.
    (gdb) maintenance selftest command_str
    Running selftest command_structure_invariants.
    list 0x560417949cb8 reachable via prefix 'append binary '.  command 'memory' has null prefixcmd
    list 0x560417949cb8 reachable via prefix 'append binary '.  command 'value' has null prefixcmd
    ...

Most of these are fixed by the following changes:
  * do_add_cmd searches the prefix command having the list
    in which the command is added.
    This ensures that a command defined after its prefix command
    gets the correct prefix command.
  * Due to the GDB initialization order, a GDB file can define
    a subcommand before the prefix command is defined.
    So, have add_prefix_cmd calling a new recursive function
    'update_prefix_field_of_prefix_commands' to set the prefix
    command of all sub-commands that are now reachable from
    this newly defined prefix command.  Note that this recursive
    call replaces the function 'set_prefix_cmd' that was providing
    a partial solution to this problem.

Following that, 2 python commands (defined after all the other GDB
commands) got a wrong prefix command, e.g. "info frame-filter" has
as prefix command the "i" alias of "info".  This is fixed by having
lookup_cmd_for_prefixlist returning the aliased command rather than
the alias.

After that, one remaining problem:
    (gdb) maintenance selftest command_str
    Running selftest command_structure_invariants.
    list 0x55f320272298 reachable via prefix 'set remote '.  command 'system-call-allowed' has null prefixcmd
    Self test failed: self-test failed at ../../classfix/gdb/unittests/command-def-selftests.c:196
    Ran 1 unit tests, 1 failed
    (gdb)

Caused by initialize_remote_fileio that was taking the address of
its arguments remote_set_cmdlist and remote_show_cmdlist instead
of receiving the correct values to use as list.

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-decode.c (lookup_cmd_for_prefix): Return the aliased command
	as prefix, not one of its aliases.
	(set_cmd_prefix): Remove.
	(do_add_cmd): Centralize the setting of the prefix of a command, when
	command is defined after its full chain of prefix commands.
	(add_alias_cmd): Remove call to set_cmd_prefix, as do_add_cmd does it.
	(add_setshow_cmd_full): Likewise.
	(update_prefix_field_of_prefixed_commands): New function.
	(add_prefix_cmd): Replace non working call to set_cmd_prefix by
	update_prefix_field_of_prefixed_commands.
	* gdb/remote-fileio.c (initialize_remote_fileio): Use the real
	addresses of remote_set_cmdlist and remote_show_cmdlist given
	as argument, not the address of an argument.
	* gdb/remote-fileio.h (initialize_remote_fileio): Likewise.
	* gdb/remote.c (_initialize_remote): Likewise.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers 0605465feb Fix problem that alias can be defined or not depending on the order.
When an alias name starts with the name of another alias,
GDB was accepting to define the aliases in one order (short first, long after),
but refused it the other way around.

So, fix the logic to recognise an already existing alias by using
lookup_cmd_composition.

Also, this revealed a bug in lookup_cmd_composition:
when the searched command is a prefix command, lookup_cmd_composition
was not returning the fact that a command was found even if the
TEXT to parse was fully consumed.

gdb/ChangeLog
YYYY-MM-DD  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-cmds.c (alias_command): Check for an existing alias
	using lookup_cmd_composition, as valid_command_p is too strict
	and forbids aliases that are the prefix of an existing alias
	or command.
	* cli/cli-decode.c (lookup_cmd_composition): Ensure a prefix
	command is properly recognised as a valid command.

gdb/testsuite/ChangeLog
2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/alias.exp: Test aliases starting with a prefix of
	another alias.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers 58e6ac7006 Add a selftest that detects a 'corrupted' command tree structure in GDB.
The GDB data structure that records the GDB commands is made of
'struct cmd_list_element' defined in cli-decode.h.

A cmd_list_element has various pointers to other cmd_list_element structures,
All these pointers are together building a graph of commands.

However, when following the 'next' and '*prefixlist' pointers of
cmd_list_element, the structure must better be a tree.

If such pointers do not form a tree, then some other elements of
cmd_list_element cannot get a correct semantic.  In particular, the prefixname
has no correct meaning if the same prefix command can be reached via 2 different
paths.

This commit introduces a selftest that detects (at least some cases of) errors
leading to 'next' and '*prefixlist' not giving a tree structure.

The new 'command_structure_invariants' selftest detects one single case where
the command structure is not a tree:

  (gdb) maintenance selftest command_structure_invariants
  Running selftest command_structure_invariants.
  list 0x56362e204b98 duplicated, reachable via prefix 'show ' and 'info set '.  Duplicated list first command is 'ada'
  Self test failed: self-test failed at ../../classfix/gdb/unittests/command-def-selftests.c:160
  Ran 1 unit tests, 1 failed
  (gdb)

This was fixed by the previous commit.

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* unittests/help-doc-selftests.c: Rename to
	unittests/command-def-selftests.c
	* unittests/command-def-selftests.c (help_doc_tests): Update some
	comments.
	(command_structure_tests, traverse_command_structure): New namespace
	and function.
	(command_structure_invariants_tests): New function.
	(_initialize_command_def_selftests) Renamed from
	_initialize_help_doc_selftests, register command_structure_invariants
	selftest.
2020-05-15 22:17:45 +02:00
Philippe Waroquiers a7b9ceb8b4 Fix the only incorrect case found by command_structure_invariants selftest.
The next commit introduces a selftest that detects when the GDB
command structure does not define a tree when using the pointers
'next/*prefixlist'.  This test detects one such case, fixed
by this commit.

The command 'info set' was defined as a specific prefix command,
but re-using the command list already used for the 'show' command.
This leads to the command tree 'next/*prefixlist' to not be a tree.

This change defines 'info set ' as an alias, thereby fixing the selftest.

2020-05-15  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-cmds.c (_initialize_cli_cmds): Define 'info set' as
	an alias of 'show'.
2020-05-15 22:17:45 +02:00
Joel Brobecker b2188a06e4 update name of several Ada fixed-point type handling functions
The purpose of this patch is to prepare for the future where
fixed point types become described using standard DWARF info,
rather than GNAT encodings. For that, we rename a number of
routines manipulating Ada fixed point types to make it explicit
from their new names that they rely on the GNAT encodings to work.
This will allow us, when we introduce support for fixed point types
from standard DWARF to use names that are not ambiguous with
the functions that do similar work, but only for GNAT encodings.

gdb/ChangeLog:

        * ada-lang.h: (ada_is_gnat_encoded_fixed_point_type): Renames
        ada_is_fixed_point_type.  Update all callers.
        (gnat_encoded_fixed_point_delta): Renames ada_delta.  Update
        all callers.
        * ada-lang.c (gnat_encoded_fixed_type_info): Renames fixed_type_info.
        Update all callers.
        * ada-typeprint.c (print_gnat_encoded_fixed_point_type): Renames
        print_fixed_point_type.  Update all callers.
        * ada-valprint.c (ada_value_print_num): Replace call to
        ada_is_fixed_point_type by ada_is_gnat_encoded_fixed_point_type.
2020-05-15 16:06:42 -04:00
Kevin Buettner a51951c258 Disable record btrace bts support for AMD processors
Some Intel processors implement a Branch Trace Store (BTS) which GDB
uses for reverse execution support via the "record btrace bts"
command.

I have been unable to find a description of a similar feature in a
recent (April 2020) AMD64 architecture reference:

    https://www.amd.com/system/files/TechDocs/40332.pdf

While it is the case that AMD processors have an LBR (last branch
record) bit in the DebugCtl MSR, it seems that it affects only four
MSRs when enabled.  The names of these MSRs are LastBranchToIP,
LastBranchFromIP, LastIntToIP, and LastIntFromIP.  I can find no
mention of anything more extensive.  While looking at an Intel
architecture document, I noticed that Intel's P6 family from the
mid-90s had registers of the same name.

Therefore...

This commit disables "record btrace bts" support in GDB for AMD
processors.

Using the test case from gdb.base/break.exp, the sessions
below show the expected behavior (run on a machine with an
Intel processor) versus that on a machine with an AMD processor.
The AMD processor in question is reported as follows by "lscpu":
AMD Ryzen Threadripper 2950X 16-Core Processor .  Finally, I'll
note that the AMD machine is actually a VM, but I see similar
behavior on both the virtualization host and the VM.

Intel machine - Desired behavior:

[kevinb@mohave gdb]$ ./gdb -q testsuite/outputs/gdb.base/break/break
Reading symbols from testsuite/outputs/gdb.base/break/break...
(gdb) start
Temporary breakpoint 1 at 0x401179: file /home/kevinb/sourceware-git/native-build/bld/../../binutils-gdb/gdb/testsuite/gdb.base/break.c, line 43.
Starting program: /home/kevinb/sourceware-git/native-build/bld/gdb/testsuite/outputs/gdb.base/break/break

Temporary breakpoint 1, main (argc=1, argv=0x7fffffffd748, envp=0x7fffffffd758)
    at /home/kevinb/sourceware-git/native-build/bld/../../binutils-gdb/gdb/testsuite/gdb.base/break.c:43
43	    if (argc == 12345) {  /* an unlikely value < 2^16, in case uninited */ /* set breakpoint 6 here */
(gdb) record btrace
(gdb) b factorial
Breakpoint 2 at 0x40121b: file /home/kevinb/sourceware-git/native-build/bld/../../binutils-gdb/gdb/testsuite/gdb.base/break.c, line 63.
(gdb) c
Continuing.

Breakpoint 2, factorial (value=6)
    at /home/kevinb/sourceware-git/native-build/bld/../../binutils-gdb/gdb/testsuite/gdb.base/break.c:63
63	  if (value > 1) {  /* set breakpoint 7 here */
(gdb) info record
Active record target: record-btrace
Recording format: Branch Trace Store.
Buffer size: 64kB.
Recorded 768 instructions in 22 functions (0 gaps) for thread 1 (process 19215).
(gdb) record function-call-history
13	do_lookup_x
14	_dl_lookup_symbol_x
15	_dl_fixup
16	_dl_runtime_resolve_xsavec
17	atoi
18	strtoq
19	____strtoll_l_internal
20	atoi
21	main
22	factorial
(gdb) record instruction-history
759	   0x00007ffff7ce0917 <____strtoll_l_internal+647>:	pop    %r15
760	   0x00007ffff7ce0919 <____strtoll_l_internal+649>:	retq
761	   0x00007ffff7cdd064 <atoi+20>:	add    $0x8,%rsp
762	   0x00007ffff7cdd068 <atoi+24>:	retq
763	   0x00000000004011b1 <main+75>:	mov    %eax,%edi
764	   0x00000000004011b3 <main+77>:	callq  0x401210 <factorial>
765	   0x0000000000401210 <factorial+0>:	push   %rbp
766	   0x0000000000401211 <factorial+1>:	mov    %rsp,%rbp
767	   0x0000000000401214 <factorial+4>:	sub    $0x10,%rsp
768	   0x0000000000401218 <factorial+8>:	mov    %edi,-0x4(%rbp)

AMD machine - Wrong behavior:

[kev@f32-1 gdb]$ ./gdb -q testsuite/outputs/gdb.base/break/break
Reading symbols from testsuite/outputs/gdb.base/break/break...
(gdb) start
Temporary breakpoint 1 at 0x401179: file /ironwood1/sourceware-git/f32-master/bld/../../worktree-master/gdb/testsuite/gdb.base/break.c, line 43.
Starting program: /mesquite2/sourceware-git/f32-master/bld/gdb/testsuite/outputs/gdb.base/break/break

Temporary breakpoint 1, main (argc=1, argv=0x7fffffffd5b8, envp=0x7fffffffd5c8)
    at /ironwood1/sourceware-git/f32-master/bld/../../worktree-master/gdb/testsuite/gdb.base/break.c:43
43	    if (argc == 12345) {  /* an unlikely value < 2^16, in case uninited */ /* set breakpoint 6 here */
(gdb) record btrace
(gdb) b factorial
Breakpoint 2 at 0x40121b: file /ironwood1/sourceware-git/f32-master/bld/../../worktree-master/gdb/testsuite/gdb.base/break.c, line 63.
(gdb) c
Continuing.

Breakpoint 2, factorial (value=6)
    at /ironwood1/sourceware-git/f32-master/bld/../../worktree-master/gdb/testsuite/gdb.base/break.c:63
63	  if (value > 1) {  /* set breakpoint 7 here */
(gdb) info record
Active record target: record-btrace
Recording format: Branch Trace Store.
Buffer size: 64kB.
warning: Recorded trace may be incomplete at instruction 7737 (pc = 0x405000).
warning: Recorded trace may be incomplete at instruction 7739 (pc = 0x0).
Recorded 7740 instructions in 46 functions (2 gaps) for thread 1 (process 1402911).
(gdb) record function-call-history
37	??
38	values
39	some_enum_global
40	??
41	some_union_global
42	some_variable
43	??
44	[decode error (2): unknown instruction]
45	??
46	[decode error (2): unknown instruction]
(gdb) record instruction-history
7730	   0x0000000000404ff3:	add    %al,(%rax)
7731	   0x0000000000404ff5:	add    %al,(%rax)
7732	   0x0000000000404ff7:	add    %al,(%rax)
7733	   0x0000000000404ff9:	add    %al,(%rax)
7734	   0x0000000000404ffb:	add    %al,(%rax)
7735	   0x0000000000404ffd:	add    %al,(%rax)
7736	   0x0000000000404fff:	.byte 0x0
7737	   0x0000000000405000:	Cannot access memory at address 0x405000

Lastly, I'll note that I see a lot of gdb.btrace failures without
this commit.  Worse still, the results aren't always the same which
causes a lot of noise when comparing test results.

gdbsupport/ChangeLog:

	* btrace-common.h (btrace_cpu_vendor): Add CV_AMD.

gdb/ChangeLog:

	* nat/linux-btrace.c (btrace_this_cpu): Add check for AMD
	processors.
	(cpu_supports_bts): Add CV_AMD case.
2020-05-14 17:56:33 -07:00
Laurent Morichetti 29d6859f09 gdb: infrun: consume multiple events at each pass in stop_all_threads
[Simon: I send this patch on behalf of Laurent Morichetti, I added the
 commit message and performance measurement stuff.

 Also, this patch is better viewed with "git show -w".]

stop_all_threads, in infrun.c, is used to stop all running threads on
targets that are always non-stop.  It's used, for example, when the
program hits a breakpoint while GDB is set to "non-stop off".  It sends
a stop request for each running thread, then collects one wait event for
each.

Since new threads can spawn while we are stopping the threads, it's
written in a way where it makes multiple such "send stop requests to
running threads & collect wait events" passes.  The function completes
when it has made two passes where it hasn't seen any running threads.

With the way it's written right now is, it iterates on the thread list,
sending a stop request for each running thread.  It then waits for a
single event, after which it iterates through the thread list again.  It
sends stop requests for any running threads that's been created since
the last iteration.  It then consumes another single wait event.

This makes it so we iterate on O(n^2) threads in total, where n is the
number of threads.  This patch changes the function to reduce it to
O(n).  This starts to have an impact when dealing with multiple
thousands of threads (see numbers below).  At each pass, we know the
number of outstanding stop requests we have sent, for which we need to
collect a stop event.  We can therefore loop to collect this many stop
events before proceeding to the next pass and iterate on the thread list
again.

To check the performance improvements with this patch, I made an
x86/Linux program with a large number of idle threads (varying from 1000
to 10000).  The program's main thread hits a breakpoint once all these
threads have started, which causes stop_all_threads to be called to stop
all these threads.  I measured (by patching stop_all_threads):

- the execution time of stop_all_threads
- the total number of threads we iterate on during the complete
  execution of the function (the total number of times we execute the
  "for (thread_info *t : all_non_exited_threads ())" loop)

These are the execution times, in milliseconds:

    # threads  before  after
         1000     226    106
         2000     997    919
         3000    3461   2323
         4000    4330   3570
         5000    8642   6600
         6000    9918   8039
         7000   12662  10930
         8000   16652  11222
         9000   21561  15875
        10000   26613  20019

Note that I very unscientifically executed each case only once.

These are the number of loop executions:

    # threads     before  after
         1000    1003002   3003
         2000    4006002   6003
         3000    9009002   9003
         4000   16012002  12003
         5000   25015002  15003
         6000   36018002  18003
         7000   49021002  21003
         8000   64024002  24003
         9000   81027002  27003
        10000  100030002  30003

This last table shows pretty well the O(n^2) vs O(n) behaviors.

Reg-tested on x86 GNU/Linux (Ubuntu 16.04).

gdb/ChangeLog:

YYYY-MM-DD  Laurent Morichetti  <Laurent.Morichetti@amd.com>
YYYY-MM-DD  Simon Marchi  <simon.marchi@efficios.com>

	* infrun.c (stop_all_threads): Collect multiple wait events at
	each pass.
2020-05-14 19:59:16 -04:00
Simon Marchi 7813437494 gdb: remove TYPE_CODE macro
Remove TYPE_CODE, changing all the call sites to use type::code
directly.  This is quite a big diff, but this was mostly done using sed
and coccinelle.  A few call sites were done by hand.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_CODE): Remove.  Change all call sites to use
	type::code instead.
2020-05-14 13:46:38 -04:00
Simon Marchi 67607e24d0 gdb: add type::code / type::set_code
Add the code and set_code methods on code, in order to remove the
TYPE_CODE macro.  In this patch, the TYPE_CODE macro is changed to use
type::code, so all the call sites that are used to set the type code are
changed to use type::set_code.  The next patch will remove TYPE_CODE
completely.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <code, set_code>: New methods.
	(TYPE_CODE): Use type::code.  Change all call sites used to set
	the code to use type::set_code instead.
2020-05-14 13:45:40 -04:00
Tankut Baris Aktemur a05575d39a gdb/infrun: handle already-exited threads when attempting to stop
In stop_all_threads, GDB sends signals to other threads in an attempt
to stop them.  While in a typical scenario the expected wait status is
TARGET_WAITKIND_STOPPED, it is possible that the thread GDB attempted
to stop has already terminated.  If so, a waitstatus other than
TARGET_WAITKIND_STOPPED would be received.  Handle this case
appropriately.

If a wait status that denotes thread termination is ignored, GDB goes
into an infinite loop in stop_all_threads.
E.g.:

  $ gdb ./a.out
  (gdb) start
  ...
  (gdb) add-inferior -exec ./a.out
  ...
  (gdb) inferior 2
  ...
  (gdb) start
  ...
  (gdb) set schedule-multiple on
  (gdb) set debug infrun 2
  (gdb) continue
  Continuing.
  infrun: clear_proceed_status_thread (process 10449)
  infrun: clear_proceed_status_thread (process 10453)
  infrun: proceed (addr=0xffffffffffffffff, signal=GDB_SIGNAL_DEFAULT)
  infrun: proceed: resuming process 10449
  infrun: resume (step=0, signal=GDB_SIGNAL_0), trap_expected=0, current thread [process 10449] at 0x55555555514e
  infrun: infrun_async(1)
  infrun: prepare_to_wait
  infrun: proceed: resuming process 10453
  infrun: resume (step=0, signal=GDB_SIGNAL_0), trap_expected=0, current thread [process 10453] at 0x55555555514e
  infrun: prepare_to_wait
  infrun: Found 2 inferiors, starting at #0
  infrun: target_wait (-1.0.0, status) =
  infrun:   10449.10449.0 [process 10449],
  infrun:   status->kind = exited, status = 0
  infrun: handle_inferior_event status->kind = exited, status = 0
  [Inferior 1 (process 10449) exited normally]
  infrun: stop_waiting
  infrun: stop_all_threads
  infrun: stop_all_threads, pass=0, iterations=0
  infrun:   process 10453 executing, need stop
  infrun: target_wait (-1.0.0, status) =
  infrun:   10453.10453.0 [process 10453],
  infrun:   status->kind = exited, status = 0
  infrun: stop_all_threads status->kind = exited, status = 0 process 10453
  infrun:   process 10453 executing, already stopping
  infrun: target_wait (-1.0.0, status) =
  infrun:   -1.0.0 [process -1],
  infrun:   status->kind = no-resumed
  infrun: infrun_async(0)
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  infrun: stop_all_threads status->kind = no-resumed process -1
  infrun:   process 10453 executing, already stopping
  ...

And this polling goes on forever.  This patch prevents the infinite
looping behavior.  For the same scenario above, we obtain the
following behavior:

  ...
  (gdb) continue
  Continuing.
  infrun: clear_proceed_status_thread (process 31229)
  infrun: clear_proceed_status_thread (process 31233)
  infrun: proceed (addr=0xffffffffffffffff, signal=GDB_SIGNAL_DEFAULT)
  infrun: proceed: resuming process 31229
  infrun: resume (step=0, signal=GDB_SIGNAL_0), trap_expected=0, current thread [process 31229] at 0x55555555514e
  infrun: infrun_async(1)
  infrun: prepare_to_wait
  infrun: proceed: resuming process 31233
  infrun: resume (step=0, signal=GDB_SIGNAL_0), trap_expected=0, current thread [process 31233] at 0x55555555514e
  infrun: prepare_to_wait
  infrun: Found 2 inferiors, starting at #0
  infrun: target_wait (-1.0.0, status) =
  infrun:   31229.31229.0 [process 31229],
  infrun:   status->kind = exited, status = 0
  infrun: handle_inferior_event status->kind = exited, status = 0
  [Inferior 1 (process 31229) exited normally]
  infrun: stop_waiting
  infrun: stop_all_threads
  infrun: stop_all_threads, pass=0, iterations=0
  infrun:   process 31233 executing, need stop
  infrun: target_wait (-1.0.0, status) =
  infrun:   31233.31233.0 [process 31233],
  infrun:   status->kind = exited, status = 0
  infrun: stop_all_threads status->kind = exited, status = 0 process 31233
  infrun: saving status status->kind = exited, status = 0 for 31233.31233.0
  infrun:   process 31233 not executing
  infrun: stop_all_threads, pass=1, iterations=1
  infrun:   process 31233 not executing
  infrun: stop_all_threads done
  (gdb)

The exit event from Inferior 1 is received and shown to the user.
The exit event from Inferior 2 is not displayed, but kept pending.

  (gdb) info inferiors
    Num  Description       Connection           Executable
  * 1    <null>                                 a.out
    2    process 31233     1 (native)           a.out
  (gdb) inferior 2
  [Switching to inferior 2 [process 31233] (a.out)]
  [Switching to thread 2.1 (process 31233)]
  Couldn't get registers: No such process.
  (gdb) continue
  Continuing.
  infrun: clear_proceed_status_thread (process 31233)
  infrun: clear_proceed_status_thread: thread process 31233 has pending wait status status->kind = exited, status = 0 (currently_stepping=0).
  infrun: proceed (addr=0xffffffffffffffff, signal=GDB_SIGNAL_DEFAULT)
  infrun: proceed: resuming process 31233
  infrun: resume: thread process 31233 has pending wait status status->kind = exited, status = 0 (currently_stepping=0).
  infrun: prepare_to_wait
  infrun: Using pending wait status status->kind = exited, status = 0 for process 31233.
  infrun: target_wait (-1.0.0, status) =
  infrun:   31233.31233.0 [process 31233],
  infrun:   status->kind = exited, status = 0
  infrun: handle_inferior_event status->kind = exited, status = 0
  [Inferior 2 (process 31233) exited normally]
  infrun: stop_waiting
  (gdb) info inferiors
    Num  Description       Connection           Executable
    1    <null>                                 a.out
  * 2    <null>                                 a.out
  (gdb)

When a process exits and we leave the process exit event pending, we
need to make sure that at least one thread is left listed in the
inferior's thread list.  This is necessary in order to make sure we
have a thread that we can later resume, so the process exit event can
be collected/reported.

When native debugging, the GNU/Linux back end already makes sure that
the last LWP isn't deleted.

When remote debugging against GNU/Linux GDBserver, the GNU/Linux
GDBserver backend also makes sure that the last thread isn't deleted
until the process exit event is reported to GDBserver core.

However, between the backend reporting the process exit event to
GDBserver core, and GDB consuming the event, GDB may update the thread
list and find no thread left in the process.  The process exit event
will be pending somewhere in GDBserver's stop reply queue, or
gdb/remote.c's queue, or whathever other event queue inbetween
GDBserver and infrun.c's handle_inferior_event.

This patch tweaks remote.c's target_update_thread_list implementation
to avoid deleting the last thread of an inferior.

In the past, this case of inferior-with-no-threads led to a special
case at the bottom of handle_no_resumed, where it reads:

  /* Note however that we may find no resumed thread because the whole
     process exited meanwhile (thus updating the thread list results
     in an empty thread list).  In this case we know we'll be getting
     a process exit event shortly.  */
  for (inferior *inf : all_non_exited_inferiors (ecs->target))

In current master, that code path is still reachable with the
gdb.threads/continue-pending-after-query.exp testcase, when tested
against GDBserver, with "maint set target-non-stop" forced "on".

With this patch, the scenario that loop was concerned about is still
properly handled, because the loop above it finds the process's last
thread with "executing" set to true, and thus the handle_no_resumed
function still returns true.

Since GNU/Linux native and remote are the only targets that support
non-stop mode, and with this patch, we always make sure the inferior
has at least one thread, this patch also removes that "inferior with
no threads" special case handling from handle_no_resumed.

Since remote.c now has a special case where we treat a thread that has
already exited as if it was still alive, we might need to tweak
remote.c's target_thread_alive implementation to return true for that
thread without querying the remote side (which would say "no, not
alive").  After inspecting all the target_thread_alive calls in the
codebase, it seems that only the one from prune_threads could result
in that thread being accidentally deleted.  There's only one call to
prune_threads in GDB's common code, so this patch handles this by
replacing the prune_threads call with a delete_exited_threads call.
This seems like an improvement anyway, because we'll still be doing
what the comment suggests we want to do, and, we avoid remote protocol
traffic.

Regression-tested on X86_64 Linux.

gdb/ChangeLog:
2020-05-14  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>
	    Tom de Vries  <tdevries@suse.de>
	    Pedro Alves  <palves@redhat.com>

	PR threads/25478
	* infrun.c (stop_all_threads): Do NOT ignore
	TARGET_WAITKIND_NO_RESUMED, TARGET_WAITKIND_THREAD_EXITED,
	TARGET_WAITKIND_EXITED, TARGET_WAITKIND_SIGNALLED wait statuses
	received.
	(handle_no_resumed): Remove code handling a live inferior with no
	threads.
	* remote.c (has_single_non_exited_thread): New.
	(remote_target::update_thread_list): Do not delete a thread if is
	the last thread of the process.
	* thread.c (thread_select): Call delete_exited_threads instead of
	prune_threads.

gdb/testsuite/ChangeLog:
2020-05-14  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>
	    Pedro Alves  <palves@redhat.com>

	* gdb.multi/multi-exit.c: New file.
	* gdb.multi/multi-exit.exp: New file.
	* gdb.multi/multi-kill.c: New file.
	* gdb.multi/multi-kill.exp: New file.
2020-05-14 13:59:54 +02:00
Tankut Baris Aktemur 6ad8291970 gdb/infrun: enable/disable thread events of all targets in stop_all_threads
In stop_all_threads, the thread events of the current top target are
enabled at the beginning of the function and then disabled at the end
(at scope exit time).  Because there may be multiple targets whose
thread lists will be updated and whose threads are stopped,
enable/disable thread events for all targets.

This update caused a change in the annotations.  In particular, a
"frames-invalid" annotation is printed one more time due to switching
the current inferior.  Hence, gdb.base/annota1.exp and
gdb.cp/annota2.exp tests are also updated.

Regression-tested on X86_64 Linux using the default board file and the
native-extended-gdbserver board file.

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

	* infrun.c (stop_all_threads): Enable/disable thread events of all
	targets.  Move a debug message denoting the end of the function
	into the SCOPED_EXIT block.

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

	* gdb.base/annota1.exp: Update the expected output.
	* gdb.cp/annota2.exp: Ditto.
2020-05-14 13:59:54 +02:00
Tankut Baris Aktemur d890404b63 gdb: introduce 'all_non_exited_process_targets' and 'switch_to_target_no_thread'
Introduce two new convenience functions:

1. all_non_exited_process_targets: returns a collection of all process
stratum targets that have non-exited inferiors on them.  Useful for
iterating targets.

2. switch_to_target_no_thread: switch the context to the first
inferior of the given target, and to no selected thread.

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

	* process-stratum-target.h: Include <set>.
	(all_non_exited_process_targets, switch_to_target_no_thread): New
	function declarations.
	* process-stratum-target.c (all_non_exited_process_targets)
	(switch_to_target_no_thread): New function implementations.
2020-05-14 13:59:54 +02:00
Tankut Baris Aktemur 293b3ebcba gdb/infrun: extract out a code piece into 'mark_non_executing_threads' function
This is a refactoring.  The extracted function is placed deliberately
before 'stop_all_threads' because the function will be re-used there
in a subsequent patch for handling an exit status kind received from
a thread that GDB attempted to stop.

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

	* infrun.c (handle_inferior_event): Extract out a piece of code
	into...
	(mark_non_executing_threads): ...this new function.

Change-Id: I2b088f4a724f4260cb37068264964525cf62a118
2020-05-14 13:59:53 +02:00
Tankut Baris Aktemur 7ca9b62a2b gdb/infrun: move a 'regcache_read_pc' call down to first use
In infrun.c's resume_1 function, move the definition of the local
variable PC down to its first use.  This is useful if the thread we want
to resume is already gone with a pending exit event, because we avoid
the error we would see otherwise when trying to read the PC.

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

	* infrun.c (resume_1): Move a 'regcache_read_pc' call down to first
	use.
2020-05-14 13:59:53 +02:00
Tankut Baris Aktemur fc75c28ba1 gdb: protect some 'regcache_read_pc' calls
It possible that a thread whose PC we attempt to read is already dead.
In this case, 'regcache_read_pc' errors out.  This impacts the
"proceed" execution flow, where GDB quits early before having a chance
to check if there exists a pending event.  To remedy, keep going with
a 0 value for the PC if 'regcache_read_pc' fails.  Because the value
of PC before resuming a thread is mostly used for storing and checking
the next time the thread stops, this tolerance is expected to be
harmless for a dead thread/process.

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

	* regcache.c (regcache_read_pc_protected): New function
	implementation that returns 0 if the PC cannot read via
	'regcache_read_pc'.
	* infrun.c (proceed): Call 'regcache_read_pc_protected'
	instead of 'regcache_read_pc'.
	(keep_going_pass_signal): Ditto.

gdbsupport/ChangeLog:
2020-05-14  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* common-regcache.h (regcache_read_pc_protected): New function
	declaration.
2020-05-14 13:59:53 +02:00
Tom Tromey a89febbd83 Remove ada-lang.c:align_value
I recently noticed the align_value function in ada-lang.c.  This can
be removed, in favor of align_up from gdbsupport.

gdb/ChangeLog
2020-05-13  Tom Tromey  <tromey@adacore.com>

	* ada-lang.c (align_value): Remove.
	(ada_template_to_fixed_record_type_1): Use align_up.
2020-05-13 13:15:13 -06:00
Tankut Baris Aktemur f7e23710fc gdb: update the copyright year in async-event.[ch]
The async-event.[ch] files were introduced recently as a result of
splitting the event-loop.  I believe the copyright year update was
just an oversight.  So, this patch fixes that.

gdb/ChangeLog:
2020-05-13  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* async-event.c: Update the copyright year.
	* async-event.h: Update the copyright year.
2020-05-13 16:50:58 +02:00
Simon Marchi 02ff80c296 gdb: make two objfile functions return bool
gdb/ChangeLog:

	* objfiles.h (is_addr_in_objfile,
	shared_objfile_contains_address_p): Return bool.
	* objfile.c (is_addr_in_objfile,
	shared_objfile_contains_address_p): Return bool.
2020-05-12 11:17:01 -04:00
Tom Tromey 4fd6c7e872 Restore info_command and breakpoint
As discussed on gdb-patches, this restores info_command and the
breakpoint on info_command in gdb-gdb.gdb.  This reverts a tiny part
of 0743fc83c0 ("Replace most calls to help_list and cmd_show_list"),
as well as 652fc23a30 ("Remove gdb-gdb.gdb breakpoint on disappeared
function info_command.").

gdb/ChangeLog
2020-05-11  Tom Tromey  <tromey@adacore.com>

	* cli/cli-cmds.c (info_command): Restore.
	(_initialize_cli_cmds): Use add_prefix_command for "info".
	* gdb-gdb.gdb.in: Restore breakpoint on info_command.
2020-05-11 15:30:40 -06:00
Tom Tromey 5eb68a39a2 Fix Ada value printing on PPC64
The val_print removal patches introduced an Ada regression on PPC64
(probably any big-endian system).

The issue comes because value_field does not understand that Ada
wrapper fields can be bitfields that wrap a non-scalar type.  In this
case the value is already left-justified, so the justification done
there does the wrong thing.

Perhaps it would be good, eventually, to change value_field to
understand this case.  In the meantime this implements an Ada-specific
solution.

gdb/ChangeLog
2020-05-11  Tom Tromey  <tromey@adacore.com>

	* ada-lang.c (ada_value_primitive_field): Now public.
	* ada-lang.h (ada_value_primitive_field): Declare.
	* ada-valprint.c (print_field_values): Use
	ada_value_primitive_field for wrapper fields.
2020-05-11 14:57:49 -06:00
Tom de Vries 7666722fce [gdb/symtab] Save modules in .debug_names
When running test-case gdb.fortran/info-modules.exp with target board
debug-names, I run into:
...
FAIL: gdb.fortran/info-modules.exp: info modules: check for entry \
  'info-types-2.f90', '18', 'mod2'
...

In more detail, comparing the behaviour of the executable without and with
.debug_names section, we have:
...
-$ gdb -batch info-modules -ex "info modules"
+$ gdb -batch info-modules.debugnames -ex "info modules"
 All defined modules:

-File /data/gdb_versions/devel/src/gdb/testsuite/gdb.fortran/info-types-2.f90:
-18:     mod2
-
 File /data/gdb_versions/devel/src/gdb/testsuite/gdb.fortran/info-types.f90:
 16:     mod1
...

This is due to the fact that the .debug_names section does not contain
DW_TAG_module entries.

Fix this in debug_names::psymbol_tag.

Build and tested on x86_64-linux with target board debug-names.

gdb/ChangeLog:

2020-05-11  Tom de Vries  <tdevries@suse.de>

	* dwarf2/index-write.c (debug_names::psymbol_tag): Handle
	MODULE_DOMAIN.
2020-05-11 17:13:49 +02:00
Tom de Vries 3ee6bb113a [gdb/symtab] Fix incomplete CU list assert in .debug_names
Consider the following two-file test-case:
...
$ cat main.c
extern int foo (void);

int
main (void)
{
  int sum, a, b;
  sum = a + b + foo ();
  return sum;
}
$ cat foo.c
int
foo (void)
{
  return 3;
}
...

Compiled like this:
...
$ clang-10 -gdwarf-5 -gpubnames -c main.c
$ clang-10 -gdwarf-5 -c foo.c
$ clang-10 -gdwarf-5 -gpubnames main.o foo.o
...

When loading this exec into gdb, we run into this assert:
...
$ gdb a.out
Reading symbols from a.out...

warning: Section .debug_aranges in a.out entry at offset 0 \
  debug_info_offset 0 does not exists, ignoring .debug_aranges.
src/gdb/dwarf2/read.c:6949: \
  internal-error: cutu_reader::cutu_reader(dwarf2_per_cu_data*, \
  		                           abbrev_table*, int, bool): \
  Assertion `this_cu->length == cu->header.get_length ()' failed.
...

The problem is that the determined length of the CU:
...
(gdb) p /x this_cu->length
$4 = 0x26a
...
does not match the actual length:
...
(gdb) p /x cu->header.get_length ()
$5 = 0x59
...

The length of the CU is determined in create_cus_from_debug_names_list, and
set based on this list in the .debug_names section:
...
  Compilation Unit offsets [
    CU[0]: 0x000000c7
  ]
...
and it is assumed that this is a complete list, so the size of the CU is
calculated using the end of the .debug_section at 0x331, making it 0x331 -
0xc7 == 0x26a.

However, the CU list is not complete:
...
$ llvm-dwarfdump -debug-info a.out \
  | grep "Compile Unit" \
  | sed 's/Compile Unit.*//'
0x00000000:
0x0000002e:
0x000000a5:
0x000000c7:
0x00000120:
0x00000157:
0x0000030f:
...
In particular, because the CU for foo.c is there at 0x120 (the rest of the CUs
is due to openSUSE having debug info for various linked in objects).

Fix the assert by not assuming to know the length of CUs in
create_cus_from_debug_names_list (if the .debug_names is not produced by GDB),
and setting it to 0, and setting it later to the actual length.

Note that this does not fix the .debug_aranges warning, that's PR25969.

Build and tested on x86_64-linux, with native and debug-names.

gdb/ChangeLog:

2020-05-11  Tom de Vries  <tdevries@suse.de>

	PR symtab/25941
	* dwarf2/read.c (create_cus_from_debug_names_list): Initialize CUs
	with length 0, if not gdb-produced.
	(cutu_reader::cutu_reader): Set CU length to actual length if 0.

gdb/testsuite/ChangeLog:

2020-05-11  Tom de Vries  <tdevries@suse.de>

	PR symtab/25941
	* gdb.dwarf2/clang-debug-names.exp.in: New include exp file, factored
	out of ...
	* gdb.dwarf2/clang-debug-names.exp: ... here.
	* gdb.dwarf2/clang-debug-names-2.exp: New file.  Include
	clang-debug-names.exp.in.
	* gdb.dwarf2/clang-debug-names-2-foo.c: New test.
	* gdb.dwarf2/clang-debug-names-2.c: New test.
2020-05-11 15:03:54 +02:00
Tom de Vries 4343499695 [gdb] Fix catch throw regexp matching
When running test-case gdb.mi/mi-catch-cpp-exceptions.exp, we have:
...
FAIL: gdb.mi/mi-catch-cpp-exceptions.exp: all with invalid regexp: run until \
  breakpoint in main (unknown output after running)
...

This is a regression since commit 596dc4adff "Speed up psymbol reading by
removing a copy".

Before that commit, we have:
...
$ gdb \
    -batch \
    ./outputs/gdb.mi/mi-catch-cpp-exceptions/mi-catch-cpp-exceptions \
    -ex "break 67" \
    -ex "catch throw -r blahblah" \
    -ex r
Breakpoint 1 at 0x4008e5: file mi-catch-cpp-exceptions.cc, line 67.
Catchpoint 2 (throw)

Breakpoint 1, main () at mi-catch-cpp-exceptions.cc:67
67                  return 1;   /* Stop here.  */
...
In other words:
- we set a breakpoint somewhere in main,
- we set a catchpoint with a regexp that is intended to not match any
  exception, and
- run to the breakpoint, without the catchpoint triggering.

After the commit, we have:
...
$ gdb \
    -batch \
    ./outputs/gdb.mi/mi-catch-cpp-exceptions/mi-catch-cpp-exceptions \
    -ex "break 67" \
    -ex "catch throw -r blahblah" \
    -ex r
Breakpoint 1 at 0x4008e5: file mi-catch-cpp-exceptions.cc, line 67.
Catchpoint 2 (throw)

Catchpoint 2 (exception thrown), 0x00007ffff7ab037e in __cxa_throw () from \
  /usr/lib64/libstdc++.so.6
...
In other words, the catchpoint triggers.

This is caused by this bit of the commit:
...
       type_name = cplus_typename_from_type_info (typeinfo_arg);

       canon = cp_canonicalize_string (type_name.c_str ());
-      if (!canon.empty ())
-       std::swap (type_name, canon);
+      name = (canon == nullptr
+	      ? canon.get ()
+	      : type_name.c_str ());
     }
   catch (const gdb_exception_error &e)
     {
       exception_print (gdb_stderr, e);
     }

-  if (!type_name.empty ())
+  if (name != nullptr)
     {
-      if (self->pattern->exec (type_name.c_str (), 0, NULL, 0) != 0)
+      if (self->pattern->exec (name, 0, NULL, 0) != 0)
...

Before the commit, we have:
- type_name == "my_exception"
- canon = ""
and the !type_name.empty () test succeeds, and gdb executes the
self->pattern->exec call.

After the commit, we have:
- type_name == "my_exception"
- canon == NULL
- name == NULL
and the name != nullptr test fails, and gdb doesn't execute the
self->pattern->exec call.

Fix this by inverting the condition for the calculation of name:
...
-      name = (canon == nullptr
+      name = (canon != nullptr
...

Build and tested on x86_64-linux.

gdb/ChangeLog:

2020-05-09  Tom de Vries  <tdevries@suse.de>

	PR gdb/25955
	* break-catch-throw.c (check_status_exception_catchpoint): Fix name
	calculation.
2020-05-09 20:17:10 +02:00
Tom Tromey 2f78cffc16 Change server_command to bool
I noticed that "server_command" is an int, but really it should be a
bool.

gdb/ChangeLog
2020-05-09  Tom Tromey  <tom@tromey.com>

	* top.c (server_command): Now bool.
	* top.h (server_command): Now bool.
2020-05-09 12:04:58 -06:00
Tom Tromey 4f7bc5edbd Don't re-process a DIE in read_lexical_block_scope
A customer reported a crash in the DWARF reader.

Investigation showed that the crash occurred in an unusual scenario: a
function was lexically scoped within some other function -- but the
inner function inlined the outer function and referred to its DIE via
DW_AT_abstract_origin.  With the executable in question,
inherit_abstract_dies could eventually call read_lexical_block_scope,
which in turn could recurse into process_die, to process a DIE that
was already being read, triggering an assert.

This came up once before; see:

https://www.sourceware.org/ml/gdb-patches/2014-02/msg00652.html

However, in this case, I don't have an easy way to reproduce.  So,
there is no test case.

I did experiment with the failing executable.  This patch fixes the
bug and doesn't seem to cause other issues.  For example, I can still
set breakpoints on the relevant functions.

gdb/ChangeLog
2020-05-08  Tom Tromey  <tromey@adacore.com>

	* dwarf2/read.c (read_lexical_block_scope): Don't process a DIE
	already being processed.
2020-05-08 14:26:11 -06:00
Tom Tromey 8be4b118a9 More C++-ification for struct display
This changes displays to have a constructor, use bool and std::string,
and to be stored using std::vector.  The ALL_DISPLAYS and
ALL_DISPLAYS_SAFE macros are removed.  While internal iteration is
still done via map_display_numbers, this is updated to use a
function_view.  These changes simplify the code somewhat; for example,
free_display can now be removed in favor of ordinary destruction.

gdb/ChangeLog
2020-05-08  Tom Tromey  <tom@tromey.com>

	* printcmd.c (struct display) <next>: Remove.
	<display>: New constructor.
	<exp_string>: Now a std::string.
	<enabled_p>: Now a bool.
	(display_number): Move definition earlier.
	(displays): Rename from display_chain.  Now a std::vector.
	(ALL_DISPLAYS, ALL_DISPLAYS_SAFE): Remove.
	(display_command): Update.
	(do_one_display, disable_display)
	(enable_disable_display_command, do_enable_disable_display):
	Update.
	(free_display): Remove.
	(clear_displays): Rewrite.
	(delete_display): Update.
	(map_display_numbers): Use function_view.  Remove "data"
	parameter.  Update.
	(do_delete_display): Remove.
	(undisplay_command): Update.
	(do_one_display, do_displays, disable_display)
	(info_display_command): Update.
	(do_enable_disable_display): Remove.
	(enable_disable_display_command)
	(clear_dangling_display_expressions): Update.
2020-05-08 14:21:23 -06:00
Tom Tromey 94c93c35b5 Remove ALL_PSPACES
This removes the ALL_PSPACES macro.  In this case it seemed cleanest
to change how program spaces are stored -- instead of using a linked
list, they are now stored in a std::vector.

gdb/ChangeLog
2020-05-08  Tom Tromey  <tom@tromey.com>

	* symtab.c (set_symbol_cache_size)
	(maintenance_print_symbol_cache, maintenance_flush_symbol_cache)
	(maintenance_print_symbol_cache_statistics): Update.
	* symmisc.c (print_symbol_bcache_statistics)
	(print_objfile_statistics, maintenance_print_objfiles)
	(maintenance_info_symtabs, maintenance_check_symtabs)
	(maintenance_expand_symtabs, maintenance_info_line_tables):
	Update.
	* symfile-debug.c (set_debug_symfile): Update.
	* source.c (forget_cached_source_info): Update.
	* python/python.c (gdbpy_progspaces): Update.
	* psymtab.c (maintenance_info_psymtabs): Update.
	* probe.c (parse_probes): Update.
	* linespec.c (iterate_over_all_matching_symtabs)
	(collect_symtabs_from_filename, search_minsyms_for_name): Update.
	* guile/scm-progspace.c (gdbscm_progspaces): Update.
	* exec.c (exec_target::close): Update.
	* ada-tasks.c (ada_tasks_new_objfile_observer): Update.
	* breakpoint.c (print_one_breakpoint_location)
	(create_longjmp_master_breakpoint)
	(create_std_terminate_master_breakpoint): Update.
	* progspace.c (program_spaces): Now a std::vector.
	(maybe_new_address_space): Update.
	(add_program_space): Remove.
	(program_space::program_space): Update.
	(remove_program_space): Update.
	(number_of_program_spaces): Remove.
	(print_program_space, update_address_spaces): Update.
	* progspace.h (program_spaces): Change type.
	(ALL_PSPACES): Remove.
	(number_of_program_spaces): Don't declare.
	(struct program_space) <next>: Remove.
2020-05-08 14:21:22 -06:00
Tom Tromey a1fd1ac9de Remove ALL_SO_LIBS and so_list_head
This patch started as an attempt to replace ALL_SO_LIBS with an
ordinary C++ iterator.  However, then I tripped over the so_list_head
define again, and decided to remove it as well.

gdb/ChangeLog
2020-05-08  Tom Tromey  <tom@tromey.com>

	* mi/mi-cmd-file.c (mi_cmd_file_list_shared_libraries): Update.
	* solib-svr4.c (svr4_fetch_objfile_link_map): Update.
	(enable_break): Update.
	* solib-frv.c (frv_fdpic_find_global_pointer): Update.
	(frv_fdpic_find_canonical_descriptor): Update.
	(frv_fetch_objfile_link_map): Update.
	* progspace.c (program_space::free_all_objfiles): Update.
	(program_space::solibs): New method.
	* progspace.h (struct program_space) <solibs>: New method.
	* solist.h (master_so_list): Don't declare.
	(ALL_SO_LIBS): Remove.
	* solib.h (so_list_head): Remove.
	(update_solib_list): Update comment.
	* solib.c (master_so_list): Remove.
	(solib_used, update_solib_list, solib_add)
	(info_sharedlibrary_command, clear_solib)
	(reload_shared_libraries_1, remove_user_added_objfile): Update.
2020-05-08 14:21:22 -06:00
Tom Tromey 38eae08459 Remove ALL_EXTENSION_LANGUAGES and ALL_ENABLED_EXTENSION_LANGUAGES
This removes the ALL_EXTENSION_LANGUAGES and
ALL_ENABLED_EXTENSION_LANGUAGES macros, in favor of ordinary
iterators.  For ALL_ENABLED_EXTENSION_LANGUAGES, I chose to simply
inline the check, as that seemed simpler than trying to make
filtered_iterator work for std::array.  (As an aside, this sort of
thing will be easier once we can use the ranges library...)

gdb/ChangeLog
2020-05-08  Tom Tromey  <tom@tromey.com>

	* extension.c (extension_languages): Now a std::array.
	(ALL_EXTENSION_LANGUAGES): Remove.
	(get_ext_lang_defn, get_ext_lang_of_file)
	(eval_ext_lang_from_control_command): Update.
	(finish_ext_lang_initialization)
	(auto_load_ext_lang_scripts_for_objfile)
	(ext_lang_type_printers::ext_lang_type_printers)
	(apply_ext_lang_type_printers)
	(ext_lang_type_printers::~ext_lang_type_printers)
	(apply_ext_lang_val_pretty_printer, apply_ext_lang_frame_filter)
	(preserve_ext_lang_values, get_breakpoint_cond_ext_lang)
	(breakpoint_ext_lang_cond_says_stop, check_quit_flag)
	(get_matching_xmethod_workers, ext_lang_colorize)
	(ext_lang_before_prompt): Update.
	(ALL_ENABLED_EXTENSION_LANGUAGES): Remove.
2020-05-08 14:21:22 -06:00
Tom Tromey 596dc4adff Speed up psymbol reading by removing a copy
I noticed that cp_canonicalize_string and friends copy a
unique_xmalloc_ptr to a std::string.  However, this copy isn't
genuinely needed anywhere, and it serves to slow down DWARF psymbol
reading.

This patch removes the copy and updates the callers to adapt.

This speeds up the reader from 1.906 seconds (mean of 10 runs, of gdb
on a copy of itself) to 1.888 seconds (mean of 10 runs, on the same
copy as the first trial).

gdb/ChangeLog
2020-05-08  Tom Tromey  <tom@tromey.com>

	* symtab.h (class demangle_result_storage) <set_malloc_ptr>: New
	overload.
	<swap_string, m_string>: Remove.
	* symtab.c (demangle_for_lookup, completion_list_add_symbol):
	Update.
	* stabsread.c (define_symbol, read_type): Update.
	* linespec.c (find_linespec_symbols): Update.
	* gnu-v3-abi.c (gnuv3_get_typeid): Update.
	* dwarf2/read.c (dwarf2_canonicalize_name): Update.
	* dbxread.c (read_dbx_symtab): Update.
	* cp-support.h (cp_canonicalize_string_full)
	(cp_canonicalize_string, cp_canonicalize_string_no_typedefs):
	Return unique_xmalloc_ptr.
	* cp-support.c (inspect_type): Update.
	(cp_canonicalize_string_full): Return unique_xmalloc_ptr.
	(cp_canonicalize_string_no_typedefs, cp_canonicalize_string):
	Likewise.
	* c-typeprint.c (print_name_maybe_canonical): Update.
	* break-catch-throw.c (check_status_exception_catchpoint):
	Update.
2020-05-08 14:14:06 -06:00
Tom de Vries bf4cb9bee2 [gdb] Fix stepping over fork with follow-fork-mode child and gcc-8
When running test-case gdb.threads/fork-child-threads.exp with gcc-8 instead
of gcc-7, we have:
...
 (gdb) next^M
 [Attaching after Thread 0x7ffff7fae740 (LWP 27574) fork to child process \
   27578]^M
 [New inferior 2 (process 27578)]^M
 [Detaching after fork from parent process 27574]^M
 [Inferior 1 (process 27574) detached]^M
 [Thread debugging using libthread_db enabled]^M
 Using host libthread_db library "/lib64/libthread_db.so.1".^M
 [Switching to Thread 0x7ffff7fae740 (LWP 27578)]^M
-main () at src/gdb/testsuite/gdb.threads/fork-child-threads.c:41^M
+main () at src/gdb/testsuite/gdb.threads/fork-child-threads.c:34^M
-41            i = pthread_create (&thread, NULL, start, NULL);^M
+34        switch (fork ())^M
-(gdb) PASS: gdb.threads/fork-child-threads.exp: next over fork
+(gdb) FAIL: gdb.threads/fork-child-threads.exp: next over fork
...

This is due to the fact that gcc-8 generates more precise line info, making
the instruction after the call to fork a "recommended breakpoint location".
However, it is a bug because next is supposed to move to the next source
line.

The problem is that in process_event_stop_test we hit this code:
...
  if ((ecs->event_thread->suspend.stop_pc == stop_pc_sal.pc)
      && (ecs->event_thread->current_line != stop_pc_sal.line
	  || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
    {
      if (stop_pc_sal.is_stmt)
	{
	  /* We are at the start of a different line.  So stop.  Note that
	     we don't stop if we step into the middle of a different line.
	     That is said to make things like for (;;) statements work
	     better.  */
	  if (debug_infrun)
	    fprintf_unfiltered (gdb_stdlog,
				"infrun: stepped to a different line\n");
	  end_stepping_range (ecs);
	  return;
	}
...
because current_line and current_symtab have initial values:
...
(gdb) p ecs->event_thread->current_line
$8 = 0
(gdb) p ecs->event_thread->current_symtab
$9 = (symtab *) 0x0
...

Fix this in follow_fork by copying current_line and current_symtab from
parent thread to child thread.

Tested on x86_64-linux, with gcc 7.5.0 and gcc 10.0.1.

gdb/ChangeLog:

2020-05-08  Tom de Vries  <tdevries@suse.de>

	* infrun.c (follow_fork): Copy current_line and current_symtab to
	child thread.
2020-05-08 17:26:32 +02:00
Simon Marchi a1b68f2834 gdb: small cleanup of async-event.c structs
This is a small cleanup to normalize the structures in async-event.c
with the rest of the code base:

- Remove the unnecessary typedefs
- Fix indentation of struct bodies
- Put comments above fields

No functional changes expected.

gdb/ChangeLog:

	* async-event.c (struct async_signal_handler, struct
	async_event_handler): Reformat, remove typedef.
2020-05-07 11:41:58 -04:00
Simon Marchi 98d48915d9 gdb: remove TYPE_DYN_PROP_LIST macro
Remove this macro, which abstracts how to obtain the dyn_prop_list of a
given type.  We could replace it with a method on `struct type`, but I
don't think it's needed, as the only code that accesses the dynamic prop
list directly is internal gdbtypes.c code (that can be seen as code
internal to `struct type`).  So it can just refer to the field directly.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_DYN_PROP_LIST): Remove.  Update all users
	access thistype->main_type->dyn_prop_list directly.
2020-05-07 11:32:38 -04:00
Simon Marchi 7aa9131366 gdb: make remove_dyn_prop a method of struct type
Move remove_dyn_prop, currently a free function, to be a method of
struct type.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <remove_dyn_prop>: New method.
	(remove_dyn_prop): Remove.  Update all users to use
	type::remove_dyn_prop.
	* gdbtypes.c (remove_dyn_prop): Rename to...
	(type::remove_dyn_prop): ... this.
2020-05-07 11:32:33 -04:00
Simon Marchi 5c54719c22 gdb: make add_dyn_prop a method of struct type
Move add_dyn_prop, currently a free function, to be a method of struct
type.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <add_dyn_prop>: New method.
	(add_dyn_prop): Remove.  Update all users to use
	type::add_dyn_prop.
	* gdbtypes.c (add_dyn_prop): Rename to...
	(type::add_dyn_prop): ... this.
2020-05-07 11:32:29 -04:00
Simon Marchi 24e99c6c3c gdb: make get_dyn_prop a method of struct type
Move get_dyn_prop, currently a free function, to be a method on struct
type.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <get_dyn_prop>: New method.
	(get_dyn_prop): Remove.  Update all users to use
	type::dyn_prop.
	* gdbtypes.c (get_dyn_prop): Rename to...
	(type::dyn_prop): ... this.
2020-05-07 11:32:25 -04:00
Simon Marchi 0d4bf01694 gdb: remove main_type::flag_static
It is not used.

gdb/ChangeLog:

	* gdbtypes.h (struct main_type) <flag_static>: Remove.
2020-05-06 12:26:05 -04:00
Simon Marchi ac4a4f1cd7 gdb: handle endbr64 instruction in amd64_analyze_prologue
v2:
  - test: build full executable instead of object
  - test: add and use supports_fcf_protection
  - test: use gdb_test_multiple's -wrap option
  - test: don't execute gdb_assert if failed to get breakpoint address

Some GCCs now enable -fcf-protection by default.  This is the case, for
example, with GCC 9.3.0 on Ubuntu 20.04.  Enabling it causes the
`endbr64` instruction to be inserted at the beginning of all functions
and that breaks GDB's prologue analysis.

I noticed this because it gives many failures in gdb.base/break.exp.
But let's take this dummy program and put a breakpoint on main:

    int main(void)
    {
        return 0;
    }

Without -fcf-protection, the breakpoint is correctly put after the prologue:

    $ gcc test.c -g3 -O0 -fcf-protection=none
    $ ./gdb -q -nx --data-directory=data-directory a.out
    Reading symbols from a.out...
    (gdb) disassemble main
    Dump of assembler code for function main:
       0x0000000000001129 <+0>:     push   %rbp
       0x000000000000112a <+1>:     mov    %rsp,%rbp
       0x000000000000112d <+4>:     mov    $0x0,%eax
       0x0000000000001132 <+9>:     pop    %rbp
       0x0000000000001133 <+10>:    retq
    End of assembler dump.
    (gdb) b main
    Breakpoint 1 at 0x112d: file test.c, line 3.

With -fcf-protection, the breakpoint is incorrectly put on the first
byte of the function:

    $ gcc test.c -g3 -O0 -fcf-protection=full
    $ ./gdb -q -nx --data-directory=data-directory a.out
    Reading symbols from a.out...
    (gdb) disassemble main
    Dump of assembler code for function main:
       0x0000000000001129 <+0>:     endbr64
       0x000000000000112d <+4>:     push   %rbp
       0x000000000000112e <+5>:     mov    %rsp,%rbp
       0x0000000000001131 <+8>:     mov    $0x0,%eax
       0x0000000000001136 <+13>:    pop    %rbp
       0x0000000000001137 <+14>:    retq
    End of assembler dump.
    (gdb) b main
    Breakpoint 1 at 0x1129: file test.c, line 2.

Stepping in amd64_skip_prologue, we can see that the prologue analysis,
for GCC-compiled programs, is done in amd64_analyze_prologue by decoding
the instructions and looking for typical patterns.  This patch changes
the analysis to check for a prologue starting with the `endbr64`
instruction, and skip it if it's there.

gdb/ChangeLog:

	* amd64-tdep.c (amd64_analyze_prologue): Check for `endbr64`
	instruction, skip it if it's there.

gdb/testsuite/ChangeLog:

	* gdb.arch/amd64-prologue-skip-cf-protection.exp: New file.
	* gdb.arch/amd64-prologue-skip-cf-protection.c: New file.
2020-05-06 12:01:37 -04:00
Simon Marchi a3bbacc120 gdb: remove main_type::flag_incomplete
It is unused.  The corresponding macro was removed in c3236f84c1 ("gdb:
remove TYPE_INCOMPLETE").

gdb/ChangeLog:

	* gdbtypes.h (struct main_type) <flag_incomplete>: Remove.
2020-05-05 16:59:32 -04:00
Simon Marchi c3236f84c1 gdb: remove TYPE_INCOMPLETE
The "HP platforms" comment prompted me to check if this was still used
somewhere.  Apparently it's not, so remove it.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_INCOMPLETE): Remove.
	* gdbtypes.c (recursive_dump_type): Remove use of
	TYPE_INCOMPLETE.
2020-05-04 22:39:39 -04:00
Tom Tromey 3b6acaee89 Update more calls to add_prefix_cmd
I looked at all the calls to add_prefix_cmd, and replaced them with
calls to add_basic_prefix_cmd or add_show_prefix_cmd when appropriate.
This makes gdb's command language a bit more regular.  I don't think
there's a significant downside.

Note that this patch removes a couple of tests.  The removed ones are
completely redundant.

gdb/ChangeLog
2020-05-03  Tom Tromey  <tom@tromey.com>

	* breakpoint.c (catch_command, tcatch_command): Remove.
	(_initialize_breakpoint): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	(set_breakpoint_cmd, show_breakpoint_cmd): Remove
	* utils.c (set_internal_problem_cmd, show_internal_problem_cmd):
	Remove.
	(add_internal_problem_command): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* mips-tdep.c (set_mipsfpu_command): Remove.
	(_initialize_mips_tdep): Use add_basic_prefix_cmd.
	* dwarf2/index-cache.c (set_index_cache_command): Remove.
	(_initialize_index_cache): Use add_basic_prefix_cmd.
	* memattr.c (dummy_cmd): Remove.
	(_initialize_mem): Use add_basic_prefix_cmd, add_show_prefix_cmd.
	* tui/tui-win.c (set_tui_cmd, show_tui_cmd): Remove.
	(_initialize_tui_win): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* cli/cli-logging.c (set_logging_command): Remove.
	(_initialize_cli_logging): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	(show_logging_command): Remove.
	* target.c (target_command): Remove.
	(add_target): Use add_basic_prefix_cmd.

gdb/testsuite/ChangeLog
2020-05-03  Tom Tromey  <tom@tromey.com>

	* gdb.base/sepdebug.exp: Remove "catch" test.
	* gdb.base/break.exp: Remove "catch" test.
	* gdb.base/default.exp: Update expected output.
2020-05-03 11:31:20 -06:00
Hannes Domani a51119cde4 Fix typo in comment of DYN_PROP_ASSOCIATED
gdb/ChangeLog:

2020-05-02  Hannes Domani  <ssbssa@yahoo.de>

	* gdbtypes.h (enum dynamic_prop_node_kind): Fix typo.
2020-05-02 12:55:51 +02:00
Andrew Burgess 6a6ea76aee gdb: Fix formatting error in ChangeLog 2020-05-02 10:28:56 +01:00
Philippe Waroquiers 652fc23a30 Remove gdb-gdb.gdb breakpoint on disappeared function info_command.
The function info_command has disappeared, so this breakpoint does not
work anymore.
"info_command" was a function for the prefix command "info",
giving the list of "info" subcommands.
It is not very clear what the removed breakpoint and its associated
command list was supposed to do.

Removed and pushed as obvious, after discussion with Tom.
2020-05-01 16:47:05 +02:00
Kamil Rytarowski 117539e6d5 Add support for NetBSD thread events (create, exit)
Report LWP CREATE and LWP EXIT events and setup this on post_attach()
and post_startup_inferior().

Stop reinitializing the list of recognized threads in update_thread_list().

Handle LWP CREATE and EXIT events in nbsd_nat_target::wait().

gdb/ChangeLog:

        * nbsd-nat.c (nbsd_enable_proc_events)
        (nbsd_nat_target::post_startup_inferior): Add.
        (nbsd_nat_target::post_attach): Call `nbsd_enable_proc_events'.
        (nbsd_nat_target::update_thread_list): Rewrite.
        (nbsd_nat_target::wait): Handle "PTRACE_LWP_EXIT" and
        "PTRACE_LWP_CREATE".
        * nbsd-nat.h (nbsd_nat_target::post_startup_inferior): Add.
2020-04-30 21:53:12 +02:00
Tom de Vries b2a0dd767a Revert "2020-04-29 Sterling Augustine <saugustine@google.com>"
This reverts commit 84ed7a4725.

The problem that the commit attempts to address has already been fixed in
commit 770479f223 "gdb: Fix toplevel types with -fdebug-types-section".

The commit itself is superfluous because it sets list_in_scope at a point that
it's already set (by start_symtab).
2020-04-30 18:51:49 +02:00
Philippe Waroquiers 102e38eba7 Remove duplicated creation of "frame" command and "f" alias.
"frame" and "f" are created twice by stack.c _initialize_stack.
Remove the second creation.
Regression tested on amd64/Debian.

2020-04-30  Philippe Waroquiers  <philippe.waroquiers@skynet.be>
	* stack.c (_initialize_stack): Remove duplicated creation
	of "frame" command and "f" alias.
2020-04-30 18:40:57 +02:00
Hannes Domani ee9d1e5f76 Calculate size of array of stubbed type
Sizes of stubbed types are calculated on demand in check_typedef, so the
same must also be done for arrays of stubbed types.

A stubbed type is usually a structure that has only been forward declared,
but can also happen if the structure has a virtual function that's not
inline in the class definition.

For these stubbed types, the size must be recalculated once the full
definition is available.

gdb/ChangeLog:

2020-04-30  Hannes Domani  <ssbssa@yahoo.de>

	PR gdb/18706
	* gdbtypes.c (check_typedef): Calculate size of array of
	stubbed type.

gdb/testsuite/ChangeLog:

2020-04-30  Hannes Domani  <ssbssa@yahoo.de>

	PR gdb/18706
	* gdb.cp/stub-array-size.cc: New test.
	* gdb.cp/stub-array-size.exp: New file.
	* gdb.cp/stub-array-size.h: New test.
	* gdb.cp/stub-array-size2.cc: New test.
2020-04-30 18:20:16 +02:00
Hannes Domani 627c7fb8ea Use thiscall calling convention for class members
Non-static member functions for Windows 32bit programs need the thiscall
calling convention, so the 'this' pointer needs to be passed in ECX.

gdb/ChangeLog:

2020-04-30  Hannes Domani  <ssbssa@yahoo.de>

	PR gdb/15559
	* i386-tdep.c (i386_push_dummy_call): Call
	i386_thiscall_push_dummy_call.
	(i386_thiscall_push_dummy_call): New function.
	* i386-tdep.h (i386_thiscall_push_dummy_call): Declare.
	* i386-windows-tdep.c (i386_windows_push_dummy_call): New function.
	(i386_windows_init_abi): Call set_gdbarch_push_dummy_call.
2020-04-30 14:36:55 +02:00
Simon Marchi ffc2844e96 gdb: silence shellcheck warning SC2162 (use read -r) in gdbarch.sh
shellcheck reports:

    In gdbarch.sh line 53:
        while IFS='' read line
                     ^--^ SC2162: read without -r will mangle backslashes.

See the rationale at [1].  In our case, we actually want the backslashes
to be interpreted and removed.  Silence the warning using a directive.

[1] https://github.com/koalaman/shellcheck/wiki/SC2162

gdb/ChangeLog:

	* gdbarch.sh (do_read): Add shellcheck disable directive for
	warning SC2162.
2020-04-29 20:35:36 -04:00
Simon Marchi 1207375d76 gdb: fix shellcheck warnings SC2154 (referenced but not assigned) in gdbarch.sh
Fix all instances of this kind of warning:

    In gdbarch.sh line 96:
                    m ) staticdefault="${predefault}" ;;
                                       ^-----------^ SC2154: predefault is referenced but not assigned.

These warnings appear because we are doing something a bit funky when reading
the gdbarch fields.  These variables are not assigned explicitly, but
using some `eval` commands.

I don't think there is so much we can fix about those warnings.  To
silence them, I've changed `${foo}` to `${foo:-}`.  This tells the shell
to substitute with an empty string if `foo` is not defined.  This
retains the current behavior, but the warnings go away.

gdb/ChangeLog:

	* gdbarch.sh: Use ${foo:-} where shellcheck would report a
	"referenced but not assigned" warning.
2020-04-29 20:35:35 -04:00
Simon Marchi 9fdb2916fe gdb: fix shellcheck warnings SC2034 (unused variable) in gdbarch.sh
shellcheck reports:

    In gdbarch.sh line 139:
                    fallbackdefault="0"
                    ^-------------^ SC2034: fallbackdefault appears unused. Verify use (or export if used externally).

Indeed, the `fallbackdefault` variable appears to be unused, remove the
code that sets it.

gdb/ChangeLog:

	* gdbarch.sh: Remove code that sets fallbackdefault.
2020-04-29 20:35:35 -04:00
Simon Marchi 759cea5e3f gdb: fix shellcheck warnings SC2166 (&& and !! instead of -a and -o) in gdbarch.sh
Fix all warnings of this type:

    In gdbarch.sh line 1238:
        if [ "x${invalid_p}" = "x0" -a -n "${postdefault}" ]
                                    ^-- SC2166: Prefer [ p ] && [ q ] as [ p -a q ] is not well defined.

See the rationale here [1].

[1] https://github.com/koalaman/shellcheck/wiki/SC2166

gdb/ChangeLog:

	* gdbarch.sh: Use shell operators && and || instead of
	-a and -o.
2020-04-29 20:35:34 -04:00
Simon Marchi cb02ab2416 gdb: fix shellcheck warnings SC2006 (use $() instead of ``) in gdbarch.sh
Fix all instances of:

    In gdbarch.sh line 2195:
            printf "            `echo "$function" | sed -e 's/./ /g'`  %s %s)\n" "$returntype" "$function"
                                ^-- SC2006: Use $(...) notation instead of legacy backticked `...`.

    Did you mean:
            printf "            $(echo "$function" | sed -e 's/./ /g')  %s %s)\n" "$returntype" "$function"

See here [1] for the rationale.

[1] https://github.com/koalaman/shellcheck/wiki/SC2006

gdb/ChangeLog:

	* gdbarch.sh: Use $(...) instead of `...`.
2020-04-29 20:35:34 -04:00
Simon Marchi a6fc5ffc50 gdb: fix shellcheck warnings SC2086 (missing double quotes) in gdbarch.sh
Fix all instances of:

    In gdbarch.sh line 31:
        if test ! -r ${file}
                     ^-----^ SC2086: Double quote to prevent globbing and word splitting.

    Did you mean:
        if test ! -r "${file}"

Note that some instances of these are in text that is eval'ed.  I'm
pretty sure that things could go wrong during the eval too, but that's
not something shellcheck can check.

gdb/ChangeLog:

	* gdbarch.sh: Use double quotes around variables.
2020-04-29 20:35:34 -04:00
Simon Marchi 8d113d130e gdb: fix shellcheck warnings SC2059 (variables in printf format string) in gdbarch.sh
Fix all instances of this:

    In gdbarch.sh line 2182:
                printf "  gdb_assert (!(${invalid_p}));\n"
                       ^-- SC2059: Don't use variables in the printf format string. Use printf "..%s.." "$foo".

... by doing exactly as the message suggests.

The rationale explained here [1] makes sense, if there happens to be a
format specifier in text substituted for the variable, the printf won't
do what we expect.

[1] https://github.com/koalaman/shellcheck/wiki/SC2059

gdb/ChangeLog:

	* gdbarch.sh: Use %s with printf, instead of variables in the
	format string.
2020-04-29 20:35:33 -04:00
Sterling Augustine 84ed7a4725 2020-04-29 Sterling Augustine <saugustine@google.com>
* dwarf2/read.c (setup_type_unit_groups): Set list_in_scope.
2020-04-29 17:28:19 -07:00
Tom Tromey ed6aceddf5 Fix Ada crash with .debug_types
PR ada/25875 concerns a gdb crash when gdb.ada/arr_enum_idx_w_gap.exp
is run using the .debug_types board.

The problem turns out to be caused by weird compiler output.  In this
test, the compiler emits a top-level type that refers to an
enumeration type which is nested in a function.  However, this
function is just a declaration.

This results in gdb calling read_enumeration_type for the enum type,
but process_enumeration_scope is never called, yielding an enum with
no fields.  This causes the crash.

This patch fixes the problem by arranging to create the enum fields in
read_enumeration_type.

Tested on x86-64 Fedora 30.

gdb/ChangeLog
2020-04-29  Tom Tromey  <tromey@adacore.com>

	PR ada/25875:
	* dwarf2/read.c (update_enumeration_type_from_children): Compute
	type fields here.
	(read_enumeration_type): Call
	update_enumeration_type_from_children later.  Update comments.
	(process_enumeration_scope): Don't create type fields.
2020-04-29 11:16:57 -06:00
Kamil Rytarowski b68b1b58d6 Set NetBSD xml syscall file name to syscalls/netbsd.xml
The syscall literal names are not stable on NetBSD and can change
once a syscall is versioned. Thus these names are internal to the
system and in GDB mostly descriptive, not intended to be a stable
interface with fixed names across GDB and NetBSD versions to track
certain syscalls.

gdb/ChangeLog:

	* nbsd-tdep.c: Include "xml-syscall.h".
	(nbsd_init_abi): Call `set_xml_syscall_file_name'.
2020-04-29 20:03:44 +02:00
Kamil Rytarowski f94b2e0387 Add basic event handling in the NetBSD target
Implement the following events:
 - single step (TRAP_TRACE)
 - software breakpoint (TRAP_DBREG)
 - exec() (TRAP_EXEC)
 - syscall entry/exit (TRAP_SCE / TRAP_SCX)

Add support for NetBSD specific ::wait () and ::resume ().

Instruct the generic code that exec and syscall events are supported.

Define an empty nbsd_get_syscall_number as it is prerequisite for
catching syscall entry and exit events, even if it is unused.
This function is used to detect whether the gdbarch supports the
'catch syscall' feature.

gdb/ChangeLog:

       * nbsd-nat.c: Include "sys/wait.h".
       (nbsd_resume, nbsd_nat_target::resume, nbsd_wait)
       (nbsd_nat_target::wait, nbsd_nat_target::insert_exec_catchpoint)
       (nbsd_nat_target::remove_exec_catchpoint)
       (nbsd_nat_target::set_syscall_catchpoint): Add.
       * nbsd-nat.h (nbsd_nat_target::resume, nbsd_nat_target::wait)
       (nbsd_nat_target::insert_exec_catchpoint)
       (nbsd_nat_target::remove_exec_catchpoint)
       (nbsd_nat_target::set_syscall_catchpoint): Add.
       * nbsd-tdep.c (nbsd_get_syscall_number): Add.
       (nbsd_init_abi): Call `set_gdbarch_get_syscall_number' and pass
       `nbsd_get_syscall_number'.
2020-04-29 20:02:35 +02:00
Tom Tromey fc49bc7237 Remove some dead code
print_block_frame_labels has been commented out since 2010.
I don't think we need it; this patch removes it.

2020-04-29  Tom Tromey  <tom@tromey.com>

	* stack.c (print_block_frame_labels): Remove.
2020-04-29 08:11:45 -06:00
Hannes Domani d642b6920b Fix array pretty formatter
Currently, printing with array pretty formatting makes the output actually
less readable than without:

(gdb) p -array on -- {{1,2,3},{4,5,6}}
$1 =   {    {1,
    2,
    3},
      {4,
    5,
    6}}
(gdb) p -array on -array-indexes on -- {{1,2,3},{4,5,6}}
$2 =   {[0] =     {[0] = 1,
    [1] = 2,
    [2] = 3},
  [1] =     {[0] = 4,
    [1] = 5,
    [2] = 6}}

These changes now also put the first element and the array end bracket on a new
line, similar to the structure pretty formatter:

(gdb) p -array on -- {{1,2,3},{4,5,6}}
$1 = {
  {
    1,
    2,
    3
  },
  {
    4,
    5,
    6
  }
}
(gdb) p -array on -array-indexes on -- {{1,2,3},{4,5,6}}
$2 = {
  [0] = {
    [0] = 1,
    [1] = 2,
    [2] = 3
  },
  [1] = {
    [0] = 4,
    [1] = 5,
    [2] = 6
  }
}

gdb/ChangeLog:

2020-04-29  Hannes Domani  <ssbssa@yahoo.de>

	PR gdb/17320
	* ada-valprint.c (val_print_packed_array_elements): Move array
	end bracket to new line.
	(ada_val_print_string): Remove extra spaces before first array
	element.
	* c-valprint.c (c_value_print_array): Likewise.
	* m2-valprint.c (m2_print_array_contents): Likewise.
	(m2_value_print_inner): Likewise.
	* p-valprint.c (pascal_value_print_inner): Likewise.
	* valprint.c (generic_val_print_array): Likewise.
	(value_print_array_elements): Move first array element and array
	end bracket to new line.

gdb/testsuite/ChangeLog:

2020-04-29  Hannes Domani  <ssbssa@yahoo.de>

	PR gdb/17320
	* gdb.base/pretty-array.c: New test.
	* gdb.base/pretty-array.exp: New file.
2020-04-29 12:57:25 +02:00
Tom de Vries ea90f2278c [gdb] Fix range loop index in find_method
With target board debug-types, we have:
...
FAIL: gdb.cp/cpexprs.exp: list policy1::function
...

This is a regression triggered by commit 770479f223 "gdb: Fix toplevel types
with -fdebug-types-section".

However, the FAIL is caused by commit 4dedf84da9 "Change
decode_compound_collector to use std::vector" which changes a VEC_iterate loop
into a range loop:
...
-  for (ix = 0; VEC_iterate (symbolp, sym_classes, ix, sym); ++ix)
+  unsigned int ix = 0;
+  for (const auto &sym : *sym_classes)
...
but fails to ensure that the increment of ix happens every iteration.

Fix this by calculating the index variable at the start of the loop body:
...
  for (const auto &elt : *sym_classes)
    {
      unsigned int ix = &elt - &*sym_classes->begin ();
...

Tested on x86_64-linux, with native and target board debug-types.

gdb/ChangeLog:

2020-04-29  Tom de Vries  <tdevries@suse.de>

	PR symtab/25889
	* linespec.c (find_method): Fix ix calculation.

gdb/testsuite/ChangeLog:

2020-04-29  Tom de Vries  <tdevries@suse.de>

	PR symtab/25889
	* gdb.cp/cpexprs.exp: Adapt for inclusion.
	* gdb.cp/cpexprs-debug-types.exp: New file.  Set -fdebug-types-section
	and include cpexprs.exp.
2020-04-29 11:39:36 +02:00
Kamil Rytarowski 4498ef4f8b Add definitions of system calls to catch in native NetBSD targets
All platforms on NetBSD use a shared system call table, so use a
single XML file to describe the system calls available on each NetBSD
platform.

gdb/ChangeLog:

       * syscalls/update-netbsd.sh: New file.
       * syscalls/netbsd.xml: Regenerate.
       * data-directory/Makefile.in: Register `netbsd.xml' in
       `SYSCALLS_FILES'
2020-04-29 01:48:58 +02:00
Simon Marchi a55e30b51b gdb: fix shellcheck warning in update-freebsd.sh
shellcheck reports:

    In update-freebsd.sh line 72:
    }' $1 >> freebsd.xml.tmp
       ^-- SC2086: Double quote to prevent globbing and word splitting.

    Did you mean:
    }' "$1" >> freebsd.xml.tmp

    For more information:
      https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...

Add double quotes to fix it.

gdb/ChangeLog:

	* syscalls/update-freebsd.sh: Add double quotes.
2020-04-28 14:29:39 -04:00
Tom Tromey 2b2fbab8ef Allow Python commands to be in class_tui
Now that Python code can create TUI windows, it seemed appropriate to
allow Python commands to appear in the "TUI" help class.  This patch
adds this capability.

gdb/ChangeLog
2020-04-28  Tom Tromey  <tom@tromey.com>

	* NEWS: Update.
	* python/py-cmd.c (gdbpy_initialize_commands): Add COMMAND_TUI.
	(cmdpy_init): Allow class_tui.

gdb/doc/ChangeLog
2020-04-28  Tom Tromey  <tom@tromey.com>

	* python.texi (Commands In Python): Document gdb.COMMAND_TUI.
2020-04-28 08:54:17 -06:00
Tom de Vries a65189c980 Add missing ChangeLog entries 2020-04-28 16:34:38 +02:00
Simon Marchi 1b95cdb76c gdb: use gdb:hash_enum as hash function in offset_map_type
When building with g++ 4.8, we get this error (just an excerpt, because
g++ outputs a very long error message):

      CXX    dwarf2/read.o
    ...
    /home/smarchi/src/binutils-gdb/gdb/dwarf2/read.c:14616:31:   required from here
    /usr/include/c++/4.8/bits/hashtable_policy.h:1070:12: error: invalid use of incomplete type ‘struct std::hash<sect_offset>’
         struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2,

This is the same problem and fix as in commit f23f598e28 ("[gdb] Fix
build breaker with gcc 4.8").  Pass an explicit hash function rather
than relying on the default std::hash<sect_offset>.

gdb/ChangeLog:

	PR gdb/25881
	* dwarf2/read.c (offset_map_type): Use
	gdb:hash_enum<sect_offset> as hash function.
2020-04-28 09:50:12 -04:00
Tom de Vries 15cd93d05e [gdb/symtab] Handle struct decl with DW_AT_signature
Consider a test-case with sources 36.c:
...
struct s { int i; };
extern void f (void);
int main (void) {
  struct s a;
  f ();
  return 0;
}
...
and 36b.c:
...
struct s { int j; };
void f (void) {
  struct s b;
}
...
compiled like this:
...
$ gcc 36.c 36b.c -g
...

It contains DWARF like this:
...
 <0><d2>: Abbrev Number: 1 (DW_TAG_compile_unit)
    <d8>   DW_AT_name        : 36.c
 <1><f4>: Abbrev Number: 2 (DW_TAG_structure_type)
    <f5>   DW_AT_name        : s
 <2><fe>: Abbrev Number: 3 (DW_TAG_member)
    <ff>   DW_AT_name        : i
 <1><110>: Abbrev Number: 5 (DW_TAG_subprogram)
    <111>   DW_AT_name        : main
 <2><12d>: Abbrev Number: 6 (DW_TAG_variable)
    <12e>   DW_AT_name        : a
    <132>   DW_AT_type        : <0xf4>
 <0><146>: Abbrev Number: 1 (DW_TAG_compile_unit)
    <14c>   DW_AT_name        : 36b.c
 <1><168>: Abbrev Number: 2 (DW_TAG_structure_type)
    <169>   DW_AT_name        : s
 <2><172>: Abbrev Number: 3 (DW_TAG_member)
    <173>   DW_AT_name        : j
 <1><184>: Abbrev Number: 5 (DW_TAG_subprogram)
    <185>   DW_AT_name        : f
 <2><19b>: Abbrev Number: 6 (DW_TAG_variable)
    <19c>   DW_AT_name        : b
    <1a0>   DW_AT_type        : <0x168>
...

And when printing "struct s", we get first a random one (with int j), and then
context-specific ones (with int i in main, and int j in f):
...
$ gdb -batch a.out \
  -ex "ptype struct s" \
  -ex start \
  -ex "ptype struct s" \
  -ex "break f" -ex continue \
  -ex "ptype struct s" \
  | grep "int [ij];"
    int j;
    int i;
    int j;
...
Same for -readnow.

However, if we use -fdebug-types-section:
...
$ gcc 36.c 36b.c -g -fdebug-types-section
...
we get:
...
$ gdb ... | grep "int [ij];"
    int j;
    int i;
    int i;
$ gdb -readnow ... | grep "int [ij];"
    int j;
    int j;
    int j;
...

This is due to the fact that both "struct s" DIEs have been moved to the
.debug_types section:
...
  Compilation Unit @ offset 0x0:
   Signature:     0xfd1462823bb6f7b7
 <0><17>: Abbrev Number: 1 (DW_TAG_type_unit)
 <1><1d>: Abbrev Number: 2 (DW_TAG_structure_type)
    <1e>   DW_AT_name        : s
 <2><27>: Abbrev Number: 3 (DW_TAG_member)
    <28>   DW_AT_name        : i
  Compilation Unit @ offset 0x3a:
   Signature:     0x534310fbefba324d
 <0><51>: Abbrev Number: 1 (DW_TAG_type_unit)
 <1><57>: Abbrev Number: 2 (DW_TAG_structure_type)
    <58>   DW_AT_name        : s
 <2><61>: Abbrev Number: 3 (DW_TAG_member)
    <62>   DW_AT_name        : j
...
and there's no longer a "struct s" DIE in the 36.c and
and 36b.c CUs to specify which "struct s" belongs in the CU.  This is gcc
PR90232.

However, using a tentative patch for gcc that adds these DIEs (according to
DWARF standard: If the complete declaration of a type has been placed in a
separate type unit, an incomplete declaration of that type in the compilation
unit may provide the unique 64-bit signature of the type using a
DW_AT_signature attribute):
...
  <0><d2>: Abbrev Number: 5 (DW_TAG_compile_unit)
     <d8>   DW_AT_name        : 36.c
+ <1><f4>: Abbrev Number: 6 (DW_TAG_structure_type)
+    <f5>   DW_AT_name        : s
+    <f7>   DW_AT_signature   : signature: 0xfd1462823bb6f7b7
+    <ff>   DW_AT_declaration : 1
  <0><13c>: Abbrev Number: 5 (DW_TAG_compile_unit)
     <142>   DW_AT_name        : 36b.c
+ <1><15e>: Abbrev Number: 6 (DW_TAG_structure_type)
+    <15f>   DW_AT_name        : s
+    <161>   DW_AT_signature   : signature: 0x534310fbefba324d
+    <169>   DW_AT_declaration : 1
...
still does not help, because they're declarations, so new_symbol is not called
for them in process_structure_scope.

Fix this by calling new_symbol for these decls.

Build and tested on x86_64-linux.

Also tested with target board enabling by default -fdebug-types-section
-gdwarf-4, and with gcc with aforementioned tentative patch.  In this
configuration, the patch reduces number of FAILs from 2888 to 238.

gdb/ChangeLog:

2020-04-28  Tom de Vries  <tdevries@suse.de>

	* dwarf2/read.c (process_structure_scope): Add symbol for struct decl
	with DW_AT_signature.

gdb/testsuite/ChangeLog:

2020-04-28  Tom de Vries  <tdevries@suse.de>

	* gdb.dwarf2/main-foo.c: New test.
	* gdb.dwarf2/struct-with-sig.exp: New file.
2020-04-28 06:12:35 +02:00
Simon Marchi 1eb3991427 gdb, gdbserver: remove configure check for fs_base/gs_base in user_regs_struct
I recently stumbled on this code mentioning Linux kernel 2.6.25, and
thought it could be time for some spring cleaning (newer GDBs probably
don't need to supports 12-year old kernels).  I then found that the
"legacy" case is probably broken anyway, which gives an even better
motivation for its removal.

In short, this patch removes the configure checks that check if
user_regs_struct contains the fs_base/gs_base fields and adjusts all
uses of the HAVE_STRUCT_USER_REGS_STRUCT_{FS,GS}_BASE macros.  The
longer explanation/rationale follows.

Apparently, Linux kernels since 2.6.25 (that's from 2008) have been
reliably providing fs_base and gs_base as part of user_regs_struct.
Commit df5d438e33d7 in the Linux kernel [1] seems related.  This means
that we can get these values by reading registers with PTRACE_GETREGS.
Previously, these values were obtained using a separate
PTRACE_ARCH_PRCTL ptrace call.

First, I'm not even sure the configure check was really right in the
first place.

The user_regs_struct used by GDB comes from
/usr/include/x86_64-linux-gnu/sys/user.h (or equivalent on other
distros) and is provided by glibc.  glibc has had the fs_base/gs_base
fields in there for a very long time, at least since this commit from
2001 [2].  The Linux kernel also has its version of user_regs_struct,
which I think was exported to user-space at some point.  It included the
fs_base/gs_base fields since at least this 2002 commit [3].  In any
case, my conclusion is that the fields were there long before the
aforementioned Linux kernel commit.  The kernel commit didn't add these
fields, it only made sure that they have reliable values when obtained
with PTRACE_GETREGS.

So, checking for the presence of the fs_base/gs_base fields in struct
user_regs_struct doesn't sound like a good way of knowing if we can
reliably get the fs_base/gs_base values from PTRACE_GETREGS.  My guess
is that if we were using that strategy on a < 2.6.25 kernel, things
would not work correctly:

- configure would find that the user_regs_struct has the fs_base/gs_base
  fields (which are probided by glibc anyway)
- we would be reading the fs_base/gs_base values using PTRACE_GETREGS,
  for which the kernel would provide unreliable values

Second, I have tried to see how things worked by forcing GDB to not use
fs_base/gs_base from PTRACE_GETREGS (forcing it to use the "legacy"
code, by configuring with

  ac_cv_member_struct_user_regs_struct_gs_base=no ac_cv_member_struct_user_regs_struct_fs_base=no

Doing so breaks writing registers back to the inferior.  For example,
calling an inferior functions gives an internal error:

    (gdb) p malloc(10)
    /home/smarchi/src/binutils-gdb/gdb/i387-tdep.c:1408: internal-error: invalid i387 regnum 152

The relevant last frames where this error happens are:

    #8  0x0000563123d262fc in internal_error (file=0x563123e93fd8 "/home/smarchi/src/binutils-gdb/gdb/i387-tdep.c", line=1408, fmt=0x563123e94482 "invalid i387 regnum %d") at /home/smarchi/src/binutils-gdb/gdbsupport/errors.cc:55
    #9  0x0000563123047d0d in i387_collect_xsave (regcache=0x5631269453f0, regnum=152, xsave=0x7ffd38402a20, gcore=0) at /home/smarchi/src/binutils-gdb/gdb/i387-tdep.c:1408
    #10 0x0000563122c69e8a in amd64_collect_xsave (regcache=0x5631269453f0, regnum=152, xsave=0x7ffd38402a20, gcore=0) at /home/smarchi/src/binutils-gdb/gdb/amd64-tdep.c:3448
    #11 0x0000563122c5e94c in amd64_linux_nat_target::store_registers (this=0x56312515fd10 <the_amd64_linux_nat_target>, regcache=0x5631269453f0, regnum=152) at /home/smarchi/src/binutils-gdb/gdb/amd64-linux-nat.c:335
    #12 0x00005631234c8c80 in target_store_registers (regcache=0x5631269453f0, regno=152) at /home/smarchi/src/binutils-gdb/gdb/target.c:3485
    #13 0x00005631232e8df7 in regcache::raw_write (this=0x5631269453f0, regnum=152, buf=0x56312759e468 "@\225\372\367\377\177") at /home/smarchi/src/binutils-gdb/gdb/regcache.c:765
    #14 0x00005631232e8f0c in regcache::cooked_write (this=0x5631269453f0, regnum=152, buf=0x56312759e468 "@\225\372\367\377\177") at /home/smarchi/src/binutils-gdb/gdb/regcache.c:778
    #15 0x00005631232e75ec in regcache::restore (this=0x5631269453f0, src=0x5631275eb130) at /home/smarchi/src/binutils-gdb/gdb/regcache.c:283
    #16 0x0000563123083fc4 in infcall_suspend_state::restore (this=0x5631273ed930, gdbarch=0x56312718cf20, tp=0x5631270bca90, regcache=0x5631269453f0) at /home/smarchi/src/binutils-gdb/gdb/infrun.c:9103
    #17 0x0000563123081eed in restore_infcall_suspend_state (inf_state=0x5631273ed930) at /home/smarchi/src/binutils-gdb/gdb/infrun.c:9151

The problem seems to be that amd64_linux_nat_target::store_registers
calls amd64_native_gregset_supplies_p to know whether gregset provides
fs_base.  When !HAVE_STRUCT_USER_REGS_STRUCT_FS_BASE,
amd64_native_gregset_supplies_p returns false.  store_registers
therefore assumes that it must be an "xstate" register.  This is of
course wrong, and that leads to the failed assertion when
i387_collect_xsave doesn't recognize the register.

amd64_linux_nat_target::store_registers could probably be fixed to
handle this case, but I don't think it's worth it, given that it would
only be to support very old kernels.

[1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=df5d438e33d7fc914ba9b6e0d6b019a8966c5fcc
[2] https://sourceware.org/git/?p=glibc.git;a=commit;h=c9cf6ddeebb7bb
[3] https://git.kernel.org/pub/scm/linux/kernel/git/tglx/history.git/commit/?id=88e4bc32686ebd0b1111a94f93eba2d334241f68

gdb/ChangeLog:

	* configure.ac: Remove check for fs_base/gs_base in
	user_regs_struct.
	* configure: Re-generate.
	* config.in: Re-generate.
	* amd64-nat.c (amd64_native_gregset_reg_offset): Adjust.
	* amd64-linux-nat.c (amd64_linux_nat_target::fetch_registers,
	amd64_linux_nat_target::store_registers, ps_get_thread_area, ): Adjust.

gdbserver/ChangeLog:

	* configure.ac: Remove check for fs_base/gs_base in
	user_regs_struct.
	* configure: Re-generate.
	* config.in: Re-generate.
	* linux-x86-low.cc (x86_64_regmap, x86_fill_gregset,
	x86_store_gregset): Adjust.
2020-04-27 10:47:50 -04:00
Luis Machado 991a3e2e99 Fix remaining inline/tailcall unwinding breakage for x86_64
Commit 5939967b35 fixed inline
frame unwinding breakage for some targets (aarch64, riscv, s390...)
but regressed a few amd64 testcases related to tailcalls.

Given the following example situation...

Frame #-1 - sentinel frame
Frame # 0 - inline frame
Frame # 1 - normal frame

... suppose we're at level #1 and call into dwarf2_tailcall_sniffer_first.

We'll attempt to fetch PC, which used to be done via the gdbarch_unwind_pc call
(before 5939967b35), but now it is being handled
by the get_frame_register function.

gdbarch_unwind_pc will attempt to use frame #1's cache to retrieve information
about the PC. Here's where different architectures behave differently.

x86_64 will find a dwarf rule to retrieve PC from memory, at a CFA + offset
location. So the PC value is readily available and there is no need to
create a lazy value.

For aarch64 (and others), GCC doesn't emit an explicit location for PC, so we
eventually will find that PC is DWARF2_FRAME_REG_UNSPECIFIED. This is known
and is handled by GDB by assuming GCC really meant DWARF2_FRAME_REG_SAME_VALUE.

This means we'll attempt to fetch the register value from frame #0, via a call
to frame_unwind_got_register, which will trigger the creation of a lazy value
that requires a valid frame id for frame #0.

We don't have a valid id for frame #0 yet, so we assert.

Given the above, the following patch attempts to handle the situation without
being too hacky. We verify if the next frame is an inline frame and if its
frame id has been computed already. If it hasn't been computed yet, then we
use the safer get_frame_register function, otherwise we use the regular
gdbarch_unwind_pc hook.

gdb/ChangeLog:

2020-04-27  Luis Machado  <luis.machado@linaro.org>

	* dwarf2/frame-tailcall.c (dwarf2_tailcall_sniffer_first): Handle
	problematic inline frame unwinding situation.
	* frame.c (frame_id_computed_p): New function.
	* frame.h (frame_id_computed_p): New prototype.
2020-04-27 09:04:55 -03:00
Tom Tromey 361ba0e891 Remove class_pseudo
The class_pseudo constant is unused, so this removes it.
Tested by rebuilding.

gdb/ChangeLog
2020-04-26  Tom Tromey  <tom@tromey.com>

	* command.h (enum command_class) <class_pseudo>: Remove.
2020-04-26 13:48:11 -06:00
Philippe Waroquiers bc3609fd38 Fix comments and whitespace in lookup_cmd_composition
2020-04-26  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-decode.c (lookup_cmd_composition): Fix comments
	and whitespace.
2020-04-26 16:05:41 +02:00
Kamil Rytarowski b9771db784 Remove unused code block in inf_ptrace_target::wait
Remove unused PT_GET_PROCESS_STATE block. It used to be used
by OpenBSD, but it is now reimplemented independently in
obsd-nat.c.

gdb/ChangeLog:

       * inf-ptrace.c (inf_ptrace_target::wait): Remove
       `PT_GET_PROCESS_STATE' block.

Change-Id: I9b872df8517b658c0dfe889fc1e4a7009bc5c076
2020-04-25 17:24:51 -05:00
Tom Tromey 7151c1af38 Remove symbol_get_demangled_name
Now that symbol_get_demangled_name is only used by general_symbol_info
methods, and because these methods already check the symbol's language
to decide what to return, symbol_get_demangled_name is no longer
needed.  This patch removes it.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* symtab.h (symbol_get_demangled_name): Don't declare.
	* symtab.c (symbol_get_demangled_name): Remove.
	(general_symbol_info::natural_name)
	(general_symbol_info::demangled_name): Update.
2020-04-24 15:35:04 -06:00
Tom Tromey 906bb4c58f Fix Rust test cases
PR rust/25025 notes that some Rust test cases fail.

Debugging gdb revealed that the Rust compiler emits different linkage
names that demangle to the same result.  Enabling complaints when
reading the test case is enough to show it:

    During symbol reading: Computed physname <generics::identity<f64>> does not match demangled <generics::identity> (from linkage <_ZN8generics8identity17h8540b320af6656d6E>) - DIE at 0x424 [in module /home/tromey/gdb/build/gdb/testsuite/outputs/gdb.rust/generics/generics]
    During symbol reading: Computed physname <generics::identity<u32>> does not match demangled <generics::identity> (from linkage <_ZN8generics8identity17hae302fad0c33bd7dE>) - DIE at 0x459 [in module /home/tromey/gdb/build/gdb/testsuite/outputs/gdb.rust/generics/generics]
    ...

This patch changes the DWARF reader to prefer the computed physname,
rather than the output of the demangler, for Rust.  This fixes the
bug.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	PR rust/25025:
	* dwarf2/read.c (dwarf2_physname): Do not demangle for Rust.
2020-04-24 15:35:03 -06:00
Tom Tromey bcfe6157ca Use the linkage name if it exists
The DWARF reader has had some odd code since the "physname" patches landed.

In particular, these patches caused PR symtab/12707; namely, they made
it so "set print demangle off" no longer works.

This patch attempts to fix the problem.  It arranges to store the
linkage name on the symbol if it exists, and it changes the DWARF
reader so that the demangled name is no longer (usually) stored in the
symbol's "linkage name" field.

c-linkage-name.exp needed a tweak, because it started working
correctly.  This conforms to what I think ought to happen, so this
seems like an improvement here.

compile-object-load.c needed a small change to use
symbol_matches_search_name rather than directly examining the linkage
name.  Looking directly at the name does the wrong thing for C++.

There is still some name-related confusion in the DWARF reader:

* "physname" often refers to the logical name and not what I would
  consider to be the "physical" name;

* dwarf2_full_name, dwarf2_name, and dwarf2_physname all exist and
  return different strings -- but this seems like at least one name
  too many.  For example, Fortran requires dwarf2_full_name, but other
  languages do not.

* To my surprise, dwarf2_physname prefers the form emitted by the
  demangler over the one that it computes.  This seems backward to me,
  given that the partial symbol reader prefers the opposite, and it
  seems to me that this choice may perform better as well.

I didn't attempt to clean up these things.  It would be good to do,
but whenever I contemplate it I get caught up in dreams of truly
rewriting the DWARF reader instead.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	PR symtab/12707:
	* dwarf2/read.c (add_partial_symbol): Use the linkage name if it
	exists.
	(new_symbol): Likewise.
	* compile/compile-object-load.c (get_out_value_type): Use
	symbol_matches_search_name.

gdb/testsuite/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	PR symtab/12707:
	* gdb.python/py-symbol.exp: Update expected results for
	linkage_name test.
	* gdb.cp/print-demangle.exp: New file.
	* gdb.base/c-linkage-name.exp: Fix test.
	* gdb.guile/scm-symbol.exp: Update expected results for
	linkage_name test.
2020-04-24 15:35:03 -06:00
Tom Tromey f049a313fc Don't call compute_and_set_names for partial symbols
As mentioned in another thread, there's currently no need to call
compute_and_set_names for partial symbols.  Because the DWARF partial
symbol reader constructs demangled names, this call can only demangle
a name by mistake.

So, this patch changes the DWARF reader to simply set the linkage name
on the new symbol.  This is equivalent to what was done before.  There
should be no user-visible change from this patch, aside from gdb
speeding up a bit.

... there *should* be, but this regressed
dw2-namespaceless-anonymous.exp.  However, upon examination, I think
that test is incorrect.  It puts a mangled name into DW_AT_name, and
it puts the variable at the top level, not in a namespace.  This isn't
what C++ compilers ought to do.  So, this patch also updates the test
case.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* dwarf2/read.c (add_partial_symbol): Do not call
	compute_and_set_names.

gdb/testsuite/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* gdb.dwarf2/dw2-namespaceless-anonymous.S: Remove.
	* gdb.dwarf2/dw2-namespaceless-anonymous.c: New file.
	* gdb.dwarf2/dw2-namespaceless-anonymous.exp: Use DWARF
	assembler.
2020-04-24 15:35:03 -06:00
Tom Tromey 76e288d1d2 Use the new add_psymbol_to_list overload
This changes the DWARF reader to use the new add_psymbol_to_list
overload.  There should be no visible changes due to this patch.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* dwarf2/read.c (add_partial_symbol): Use new add_psymbol_to_list
	overload.
2020-04-24 15:35:03 -06:00
Tom Tromey 2467f4f6a5 Introduce new add_psymbol_to_list overload
This adds a new overload of add_psymbol_to_list.  This one takes an
already constructed psymbol and adds it to the bcache and the
appropriate list.

This seemed cleaner than continuing to add parameters to the existing
add_psymbol_to_list, and is more in line with how full symbols are
constructed.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* psymtab.c (add_psymbol_to_bcache): Simplify calling convention.
	(add_psymbol_to_list): New overload.  Make old overload call new
	one.
	* psympriv.h (add_psymbol_to_list): New overload.
2020-04-24 15:35:02 -06:00
Tom Tromey e61108c92d Add attribute::value_as_string method
The full DIE reader checks that an attribute has a "string" form in
some spots, but the partial DIE reader does not.  This patch brings
the two readers in sync for one specific case, namely when examining
the linkage name.  This avoids regressions in an existing DWARF test
case.

A full fix for this problem would be preferable.  An accessor like
DW_STRING should always check the form.  However, I haven't attempted
that in this series.

Also the fact that the partial and full readers can disagree like this
is a design flaw.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* dwarf2/read.c (partial_die_info::read) <case
	DW_AT_linkage_name>: Use value_as_string.
	(dwarf2_string_attr): Use value_as_string.
	* dwarf2/attribute.h (struct attribute) <value_as_string>: Declare
	method.
	* dwarf2/attribute.c (attribute::value_as_string): New method.
2020-04-24 15:35:02 -06:00
Tom Tromey 8c87a4527f Fix two latent Rust bugs
Two methods on general_symbol_info did not handle the language_rust
case.  I don't think these problems can be noticed with the current
code (which is why the bugs went unnoticed), but a future patch will
change this.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* symtab.c (general_symbol_info::natural_name)
	(general_symbol_info::demangled_name): Check for language_rust.
2020-04-24 15:35:02 -06:00
Tom Tromey 787de330ee Move the rust "{" hack
The DWARF reader has a special case to work around a bug in some
versions of the Rust compiler -- it ignores mangled names that contain
a "{" character.

I noticed that this check should probably be in dw2_linkage_name
rather than only in dwarf2_physname.  The former is called in some
cases that the latter is not.

Also, I noticed that this work is not done for the partial DIE reader,
so this patch adds the check there as well.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* dwarf2/read.c (dw2_linkage_name): Move Rust "{" hack here...
	(dwarf2_physname): ... from here.
	(partial_die_info::read): Add Rust "{" hack.
2020-04-24 15:35:02 -06:00
Tom Tromey ff98567107 Convert symbol_set_demangled_name to a method
This changes symbol_set_demangled_name to be a method on
general_symbol_info, and updates the users.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tom@tromey.com>

	* symtab.h (struct general_symbol_info) <set_demangled_name>: New
	method.
	(symbol_set_demangled_name): Don't declare.
	* symtab.c (general_symbol_info::set_demangled_name): Rename from
	symbol_set_demangled_name.
	(general_symbol_info::set_language)
	(general_symbol_info::compute_and_set_names): Update.
	* minsyms.c (minimal_symbol_reader::install): Update.
	* dwarf2/read.c (new_symbol): Update.
2020-04-24 15:35:02 -06:00
Tom Tromey 1acda8039b Add Python support for dynamic types
This changes the gdb Python API to add support for dynamic types.  In
particular, this adds an attribute to gdb.Type, and updates some
attributes to reflect dynamic sizes and field offsets.

There's still no way to get the dynamic type from one of its concrete
instances.  This could perhaps be added if needed.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	PR python/23662:
	* python/py-type.c (convert_field): Handle
	FIELD_LOC_KIND_DWARF_BLOCK.
	(typy_get_sizeof): Handle TYPE_HAS_DYNAMIC_LENGTH.
	(typy_get_dynamic): Nw function.
	(type_object_getset): Add "dynamic".
	* NEWS: Add entry.

gdb/doc/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	PR python/23662:
	* python.texi (Types In Python): Document new features.

gdb/testsuite/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	PR python/23662:
	* gdb.ada/variant.exp: Add Python checks.
	* gdb.rust/simple.exp: Add dynamic type checks.
2020-04-24 13:40:33 -06:00
Tom Tromey d656f129eb Update Ada ptype support for dynamic types
The DWARF reader was updated to handle variant parts and some other
selected features for Ada; but the Ada "ptype" code was not touched.
This patch changes the Ada ptype code to handle the new types
properly.

Test cases for this and for some of the other code in this series are
in a separate patch.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* ada-typeprint.c (print_choices, print_variant_part)
	(print_record_field_types_dynamic): New functions.
	(print_record_field_types): Use print_record_field_types_dynamic.
2020-04-24 13:40:32 -06:00
Tom Tromey 7d79de9a4b Add support for variable field offsets
In Ada, a field can have a variable offset.  This patch adds support
for this case to gdb, using the existing dynamic type resolution code.

Doing just this, though, would break C++ virtual base handling.

It turns out that virtual base handling only worked by the ugliest of
hacks.  In particular, the DWARF reader would call decode_locdesc for
a virtual base location.  Here's an example of such an expression from
gdb's m-static test case:

    <241>   DW_AT_data_member_location: 6 byte block: 12 6 48 1c 6 22 	(DW_OP_dup; DW_OP_deref; DW_OP_lit24; DW_OP_minus; DW_OP_deref; DW_OP_plus)

When examining this, decode_locdesc would treat DW_OP_deref as a no-op
and compute some answer (here, -24).  This would be stored as the
offset.

Later, in gnu-v3-abi.c, the real offset would be computed by digging
around in the vtable.

This patch cleans up this area.  In particular, it now evaluates the
location expression on demand.

Note there is a new FIXME in gnu-v3-abi.c.  I think some of the
callers are incorrect here, and have only worked because this member
is unused.  I will file a bug for this.  I didn't fix this problem in
this series because I felt it was already too complex.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* dwarf2/read.c (handle_data_member_location): New overload.
	(dwarf2_add_field): Use it.
	(decode_locdesc): Add "computed" parameter.  Update comment.
	* gdbtypes.c (is_dynamic_type_internal): Also look for
	FIELD_LOC_KIND_DWARF_BLOCK.
	(resolve_dynamic_struct): Handle FIELD_LOC_KIND_DWARF_BLOCK.
	* gdbtypes.c (is_dynamic_type_internal): Add special case for C++
	virtual base classes.
	* gnu-v3-abi.c (gnuv3_baseclass_offset): Handle
	FIELD_LOC_KIND_DWARF_BLOCK.

gdb/testsuite/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* gdb.ada/variant.exp: Add dynamic field offset tests.
	* gdb.ada/variant/pck.ads (Nested_And_Variable): New type.
	* gdb.ada/variant/pkg.adb: Add new variables.
2020-04-24 13:40:32 -06:00
Tom Tromey f8e89861cf Add support for dynamic type lengths
In Ada, a type with variant parts can have a variable length.  This
patch adds support for this to gdb, by integrating the length
computation into the dynamic type resolution code.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* dwarf2/read.c (read_structure_type): Handle dynamic length.
	* gdbtypes.c (is_dynamic_type_internal): Check
	TYPE_HAS_DYNAMIC_LENGTH.
	(resolve_dynamic_type_internal): Use TYPE_DYNAMIC_LENGTH.
	* gdbtypes.h (TYPE_HAS_DYNAMIC_LENGTH, TYPE_DYNAMIC_LENGTH):
	New macros.
	(enum dynamic_prop_node_kind) <DYN_PROP_BYTE_SIZE>: New
	constant.

gdb/testsuite/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* gdb.ada/variant.exp: New file
	* gdb.ada/variant/pkg.adb: New file
	* gdb.ada/variant/pck.adb: New file
2020-04-24 13:40:32 -06:00
Tom Tromey 9c6a1327ad Rewrite the existing variant part code
This rewrites the existing variant part code to follow the new model
implemented in the previous patch.  The old variant part code is
removed.

This only affects Rust for the moment.  I tested this using various
version of the Rust compiler, including one that emits old-style enum
debuginfo, exercising the quirks code.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* dwarf2/read.c (struct variant_field): Rewrite.
	(struct variant_part_builder): New.
	(struct nextfield): Remove "variant" field.  Add "offset".
	(struct field_info): Add "current_variant_part" and
	"variant_parts".
	(alloc_discriminant_info): Remove.
	(alloc_rust_variant): New function.
	(quirk_rust_enum): Update.
	(dwarf2_add_field): Set "offset" member.  Don't handle
	DW_TAG_variant_part.
	(offset_map_type): New typedef.
	(convert_variant_range, create_one_variant)
	(create_one_variant_part, create_variant_parts)
	(add_variant_property): New functions.
	(dwarf2_attach_fields_to_type): Call add_variant_property.
	(read_structure_type): Don't handle DW_TAG_variant_part.
	(handle_variant_part, handle_variant): New functions.
	(handle_struct_member_die): Use them.
	(process_structure_scope): Don't handle variant parts.
	* gdbtypes.h (TYPE_FLAG_DISCRIMINATED_UNION): Remove.
	(struct discriminant_info): Remove.
	(enum dynamic_prop_node_kind) <DYN_PROP_DISCRIMINATED>: Remove.
	(struct main_type) <flag_discriminated_union>: Remove.
	* rust-lang.c (rust_enum_p, rust_empty_enum_p): Rewrite.
	(rust_enum_variant): Return int.  Remove "contents".  Rewrite.
	(rust_print_enum, rust_print_struct_def, rust_evaluate_subexp):
	Update.
	* valops.c (value_union_variant): Remove.
	* value.h (value_union_variant): Don't declare.
2020-04-24 13:40:32 -06:00
Tom Tromey b249d2c2c0 Prefer existing data when evaluating DWARF expression
When evaluating a DWARF expression, the dynamic type resolution code
will pass in a buffer of bytes via the property_addr_info.  However,
the DWARF expression evaluator will then proceed to read memory from
the inferior, even when the request could be filled from this buffer.

This, in turn, is a problem in some cases; and specifically when
trying to handle the Ada scenario of extracting a variable-length
value from a packed array.  Here, the ordinary DWARF expression cannot
be directly evaluated, because the data may appear at some arbitrary
bit offset.  So, it is unpacked into a staging area and then the
expression is evaluated -- using an address of 0.

This patch fixes the problem by arranging for the DWARF evaluator, in
this case, to prefer passed-in memory when possible.  The type of the
buffer in the property_addr_info is changed to an array_view so that
bounds checking can be done.

gdb/ChangeLog
2020-04-24  Tom Tromey  <tromey@adacore.com>

	* ada-lang.c (ada_discrete_type_high_bound, ada_discrete_type_low)
	(ada_value_primitive_packed_val): Update.
	* ada-valprint.c (ada_value_print_1): Update.
	* dwarf2/loc.c (evaluate_for_locexpr_baton): New struct.
	(dwarf2_locexpr_baton_eval): Take a property_addr_info rather than
	just an address.  Use evaluate_for_locexpr_baton.
	(dwarf2_evaluate_property): Update.
	* dwarf2/loc.h (struct property_addr_info) <valaddr>: Now an
	array_view.
	* findvar.c (default_read_var_value): Update.
	* gdbtypes.c (compute_variant_fields_inner)
	(resolve_dynamic_type_internal): Update.
	(resolve_dynamic_type): Change type of valaddr parameter.
	* gdbtypes.h (resolve_dynamic_type): Update.
	* valarith.c (value_subscripted_rvalue): Update.
	* value.c (value_from_contents_and_address): Update.
2020-04-24 13:40:31 -06:00