Commit Graph

29894 Commits

Author SHA1 Message Date
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
Tom Tromey 61122aa9ed Allow DWARF expression to push the initial address
Some DWARF expressions must be evaluated by first pushing the object
address onto the evaluation stack.  This patch adds this ability.
This functionality is not used yet, but it will be used in a later
patch.  This is split out for easier review and also because it
improved the patch series ordering.

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

	* dwarf2/loc.c (dwarf2_locexpr_baton_eval): Add
	"push_initial_value" parameter.
	(dwarf2_evaluate_property): Likewise.
	* dwarf2/loc.h (dwarf2_evaluate_property): Update.
2020-04-24 13:40:31 -06:00
Tom Tromey ef83a141a2 Add new variant part code
This patch adds the infrastructure for the new variant part code.  At
this point, nothing uses this code.  This is done in a separate patch
to make it simpler to review.

I examined a few possible approaches to handling variant parts.  In
particular, I considered having a DWARF variant part be a union
(similar to how the Rust code works now); and I considered having type
fields have a flag indicating that they are variants.

Having separate types seemed bad conceptually, because these variants
aren't truly separate -- they rely on the "parent" type.  And,
changing how fields worked seemed excessively invasive.

So, in the end I thought the approach taken in this patch was both
simple to implement and understand, without losing generality.  The
idea in this patch is that all the fields of a type with variant parts
will be stored in a single field array, just as if they'd all been
listed directly.  Then, the variants are attached as a dynamic
property.  These control which fields end up in the type that's
constructed during dynamic type resolution.

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

	* gdbtypes.c (is_dynamic_type_internal): Check for variant parts.
	(variant::matches, compute_variant_fields_recurse)
	(compute_variant_fields_inner, compute_variant_fields): New
	functions.
	(resolve_dynamic_struct): Check for DYN_PROP_VARIANT_PARTS.
	Use resolved_type after type is made.
	(operator==): Add new cases.
	* gdbtypes.h (TYPE_HAS_VARIANT_PARTS): New macro.
	(struct discriminant_range, struct variant, struct variant_part):
	New.
	(union dynamic_prop_data) <variant_parts, original_type>: New
	members.
	(enum dynamic_prop_node_kind) <DYN_PROP_VARIANT_PARTS>: New constant.
	(enum dynamic_prop_kind) <PROP_TYPE, PROP_VARIANT_PARTS>: New
	constants.
	* value.c (unpack_bits_as_long): Now public.
	* value.h (unpack_bits_as_long): Declare.
2020-04-24 13:40:31 -06:00
Tom Tromey 675127ec64 Rename "variant" to "ppc_variant"
I wanted to use the name "variant" to represent a DWARF variant, but
it turned out there was an existing structure of that name.  This
renames the existing variant to "ppc_variant".

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

	* rs6000-tdep.c (struct ppc_variant): Rename from "variant".
	(variants, find_variant_by_arch, rs6000_gdbarch_init): Update.
2020-04-24 13:40:31 -06:00
Hannes Domani 9852ceef7f Add WOW64 exception numbers to $_siginfo.ExceptionCode enum
gdb/ChangeLog:

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

	* windows-tdep.c (exception_values): Add WOW64 exception numbers.
2020-04-24 18:55:28 +02:00
Kamil Rytarowski 7632c6ce2b Move OpenBSD-only functions from inf-ptrace to obsd-nat
All major BSDs implement PT_GET_PROCESS_STATE, but they differ in
details and want to implement follow-fork functionality differently.

gdb/ChangeLog:

	* inf-ptrace.h (follow_fork, insert_fork_catchpoint)
	(remove_fork_catchpoint, post_startup_inferior)
	(post_attach): Move...
	* obsd-nat.h (follow_fork, insert_fork_catchpoint)
	(remove_fork_catchpoint, post_startup_inferior)
	(post_attach): ...here.
	* inf-ptrace.c (follow_fork, insert_fork_catchpoint)
	(remove_fork_catchpoint, post_startup_inferior)
	(post_attach): Move...
	* obsd-nat.c (follow_fork, insert_fork_catchpoint)
	(remove_fork_catchpoint, post_startup_inferior)
	(post_attach): ...here.
2020-04-24 17:46:36 +02:00
Tom Tromey 7be2bb4f47 Fix Windows debugging regression
The updated pending stop series introduced a regression in Windows
debugging.  When stopped at a software breakpoint, we would adjust the
PC each time it was requested -- however, more than a single
adjustment is incorrect.  This patch introduces a new flag that is
used to ensure the adjustment only happens a single time.

No similar change is needed in gdbserver, because it adjusts the PC in
a different way.

I still can't run the gdb test suite on Windows, but I can run the
internal AdaCore test suite there; and this fixes the regressions
there.

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

	* nat/windows-nat.h (struct windows_thread_info)
	<pc_adjusted>: New member.
	* windows-nat.c (windows_fetch_one_register): Check
	pc_adjusted.
	(windows_nat_target::get_windows_debug_event)
	(windows_nat_target::wait): Set pc_adjusted.
2020-04-24 06:48:01 -06:00
Tom de Vries f80cb3b46a [gdb/contrib] Use temp dir for gdb-add-index in cc-with-tweaks.sh
When running test-case gdb.dwarf2/gdb-index.exp cleanly by issuing this
command:
...
$ rm -Rf build/gdb/testsuite/outputs/gdb.dwarf2/gdb-index
...
before running, it passes both with native and target board
cc-with-gdb-index.

But when we run the test-case first with native and then with
cc-with-gdb-index without intermediate cleanup, we get instead:
...
 Running src/gdb/testsuite/gdb.dwarf2/gdb-index.exp ...
 gdb compile failed, cc-with-tweaks.sh: Index file \
   build/gdb/testsuite/outputs/gdb.dwarf2/gdb-index/gdb-index.gdb-index \
   exists, won't clobber.

                 === gdb Summary ===

 # of untested testcases         1
...

What happens is that the native run produces a file
build/gdb/testsuite/outputs/gdb.dwarf2/gdb-index/gdb-index.gdb-index, which
causes gdb/contrib/cc-with-tweaks.sh to hit this code:
...
index_file="${output_file}.gdb-index"
if [ "$want_index" = true ] && [ -f "$index_file" ]
then
    echo "$myname: Index file $index_file exists, won't clobber." >&2
    exit 1
fi
...

The gdb-add-index script has a problem that it uses temp files alongside the
executable, filed as PR25843.

The code in cc-with-tweaks.sh attempts to detect the case that creating such a
temp file would overwrite an pre-existing file.  It however does this only for
a single file, while gdb-add-index uses more temporary files:
- <exec>.gdb-index
- <exec>.debug_names
- <exec>.debug_str
- <exec>.debug_str.merge
- <exec>.debug_str.err

Fix this by working around PR25843 in a more generic way:
- move the executable into a temp directory
- execute gdb-add-index, allowing it to create any temp file alongside the
  executable in the temp directory
- move the executable back to the original location

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

gdb/ChangeLog:

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

	* contrib/cc-with-tweaks.sh: Remove <exec>.gdb-index file handling.
	Run gdb-add-index inside temp dir.
2020-04-24 11:31:06 +02:00
Tom Tromey 29514b8728 Fix infinite loop in is_linked_with_cygwin_dll
There were some Windows timeouts after the last merge.  Debugging
showed that these were caused by an infinite loop in
is_linked_with_cygwin_dll when reading C:\Windows\SysWOW64\win32u.dll.

This patch fixes the problem by ensuring that the loop always makes
progress.

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

	* windows-tdep.c (is_linked_with_cygwin_dll): Always update "iter"
	in loop.
2020-04-23 12:53:15 -06:00
Luis Machado 5939967b35 Fix inline frame unwinding breakage
There has been some breakage for aarch64-linux, arm-linux and s390-linux in
terms of inline frame unwinding. There may be other targets, but these are
the ones i'm aware of.

The following testcases started to show numerous failures and trigger internal
errors in GDB after commit 1009d92fc6,
"Find tailcall frames before inline frames".

gdb.opt/inline-break.exp
gdb.opt/inline-cmds.exp
gdb.python/py-frame-inline.exp
gdb.reverse/insn-reverse.exp

The internal errors were of this kind:

binutils-gdb/gdb/frame.c:579: internal-error: frame_id get_frame_id(frame_info*): Assertion `fi->level == 0' failed.

After a lengthy investigation to try and find the cause of these assertions,
it seems we're dealing with some fragile/poorly documented code to handle inline
frames and we are attempting to unwind from this fragile section of code.

Before commit 1009d92fc6, the tailcall sniffer
was invoked from dwarf2_frame_prev_register. By the time we invoke the
dwarf2_frame_prev_register function, we've probably already calculated the
frame id (via compute_frame_id).

After said commit, the call to dwarf2_tailcall_sniffer_first was moved to
dwarf2_frame_cache. This is very early in a frame creation process, and
we're still calculating the frame ID (so compute_frame_id is in the call
stack).

This would be fine for regular frames, but the above testcases all deal
with some inline frames.

The particularity of inline frames is that their frame ID's depend on
the previous frame's ID, and the previous frame's ID relies in the inline
frame's registers. So it is a bit of a messy situation.

We have comments in various parts of the code warning about some of these
particularities.

In the case of dwarf2_tailcall_sniffer_first, we attempt to unwind the PC,
which goes through various functions until we eventually invoke
frame_unwind_got_register. This function will eventually attempt to create
a lazy value for a particular register, and this lazy value will require
a valid frame ID.  Since the inline frame doesn't have a valid frame ID
yet (remember we're still calculating the previous frame's ID so we can tell
what the inline frame ID is) we will call compute_frame_id for the inline
frame (level 0).

We'll eventually hit the assertion above, inside get_frame_id:

--
      /* If we haven't computed the frame id yet, then it must be that
         this is the current frame.  Compute it now, and stash the
         result.  The IDs of other frames are computed as soon as
         they're created, in order to detect cycles.  See
         get_prev_frame_if_no_cycle.  */
      gdb_assert (fi->level == 0);
--

It seems to me we shouldn't have reached this assertion without having the
inline frame ID already calculated. In fact, it seems we even start recursing
a bit when we invoke get_prev_frame_always within inline_frame_this_id. But
a check makes us quit the recursion and proceed to compute the id.

Here's the call stack for context:

 #0  get_prev_frame_always_1 (this_frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:2109
 RECURSION - #1  0x0000aaaaaae1d098 in get_prev_frame_always (this_frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:2124
 #2  0x0000aaaaaae95768 in inline_frame_this_id (this_frame=0xaaaaab85a670, this_cache=0xaaaaab85a688, this_id=0xaaaaab85a6d0)
     at ../../../repos/binutils-gdb/gdb/inline-frame.c:165
 #3  0x0000aaaaaae1916c in compute_frame_id (fi=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:550
 #4  0x0000aaaaaae19318 in get_frame_id (fi=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:582
 #5  0x0000aaaaaae13480 in value_of_register_lazy (frame=0xaaaaab85a730, regnum=30) at ../../../repos/binutils-gdb/gdb/findvar.c:296
 #6  0x0000aaaaaae16c00 in frame_unwind_got_register (frame=0xaaaaab85a730, regnum=30, new_regnum=30) at ../../../repos/binutils-gdb/gdb/frame-unwind.c:268
 #7  0x0000aaaaaad52604 in dwarf2_frame_prev_register (this_frame=0xaaaaab85a730, this_cache=0xaaaaab85a748, regnum=30)
     at ../../../repos/binutils-gdb/gdb/dwarf2/frame.c:1296
 #8  0x0000aaaaaae1ae68 in frame_unwind_register_value (next_frame=0xaaaaab85a730, regnum=30) at ../../../repos/binutils-gdb/gdb/frame.c:1229
 #9  0x0000aaaaaae1b304 in frame_unwind_register_unsigned (next_frame=0xaaaaab85a730, regnum=30) at ../../../repos/binutils-gdb/gdb/frame.c:1320
 #10 0x0000aaaaaab76574 in aarch64_dwarf2_prev_register (this_frame=0xaaaaab85a730, this_cache=0xaaaaab85a748, regnum=32)
     at ../../../repos/binutils-gdb/gdb/aarch64-tdep.c:1114
 #11 0x0000aaaaaad52724 in dwarf2_frame_prev_register (this_frame=0xaaaaab85a730, this_cache=0xaaaaab85a748, regnum=32)
     at ../../../repos/binutils-gdb/gdb/dwarf2/frame.c:1316
 #12 0x0000aaaaaae1ae68 in frame_unwind_register_value (next_frame=0xaaaaab85a730, regnum=32) at ../../../repos/binutils-gdb/gdb/frame.c:1229
 #13 0x0000aaaaaae1b304 in frame_unwind_register_unsigned (next_frame=0xaaaaab85a730, regnum=32) at ../../../repos/binutils-gdb/gdb/frame.c:1320
 #14 0x0000aaaaaae16a84 in default_unwind_pc (gdbarch=0xaaaaab81edc0, next_frame=0xaaaaab85a730) at ../../../repos/binutils-gdb/gdb/frame-unwind.c:223
 #15 0x0000aaaaaae32124 in gdbarch_unwind_pc (gdbarch=0xaaaaab81edc0, next_frame=0xaaaaab85a730) at ../../../repos/binutils-gdb/gdb/gdbarch.c:3074
 #16 0x0000aaaaaad4f15c in dwarf2_tailcall_sniffer_first (this_frame=0xaaaaab85a730, tailcall_cachep=0xaaaaab85a830, entry_cfa_sp_offsetp=0x0)
     at ../../../repos/binutils-gdb/gdb/dwarf2/frame-tailcall.c:388
 #17 0x0000aaaaaad520c0 in dwarf2_frame_cache (this_frame=0xaaaaab85a730, this_cache=0xaaaaab85a748) at ../../../repos/binutils-gdb/gdb/dwarf2/frame.c:1190
 #18 0x0000aaaaaad52204 in dwarf2_frame_this_id (this_frame=0xaaaaab85a730, this_cache=0xaaaaab85a748, this_id=0xaaaaab85a790)
     at ../../../repos/binutils-gdb/gdb/dwarf2/frame.c:1218
 #19 0x0000aaaaaae1916c in compute_frame_id (fi=0xaaaaab85a730) at ../../../repos/binutils-gdb/gdb/frame.c:550
 #20 0x0000aaaaaae1c958 in get_prev_frame_if_no_cycle (this_frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:1927
 #21 0x0000aaaaaae1cc44 in get_prev_frame_always_1 (this_frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:2006
 FIRST CALL - #22 0x0000aaaaaae1d098 in get_prev_frame_always (this_frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:2124
 #23 0x0000aaaaaae18f68 in skip_artificial_frames (frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:495
 #24 0x0000aaaaaae193e8 in get_stack_frame_id (next_frame=0xaaaaab85a670) at ../../../repos/binutils-gdb/gdb/frame.c:596
 #25 0x0000aaaaaae87a54 in process_event_stop_test (ecs=0xffffffffefc8) at ../../../repos/binutils-gdb/gdb/infrun.c:6857
 #26 0x0000aaaaaae86bdc in handle_signal_stop (ecs=0xffffffffefc8) at ../../../repos/binutils-gdb/gdb/infrun.c:6381
 #27 0x0000aaaaaae84fd0 in handle_inferior_event (ecs=0xffffffffefc8) at ../../../repos/binutils-gdb/gdb/infrun.c:5578
 #28 0x0000aaaaaae81588 in fetch_inferior_event (client_data=0x0) at ../../../repos/binutils-gdb/gdb/infrun.c:4020
 #29 0x0000aaaaaae5f7fc in inferior_event_handler (event_type=INF_REG_EVENT, client_data=0x0) at ../../../repos/binutils-gdb/gdb/inf-loop.c:43
 #30 0x0000aaaaaae8d768 in infrun_async_inferior_event_handler (data=0x0) at ../../../repos/binutils-gdb/gdb/infrun.c:9377
 #31 0x0000aaaaaabff970 in check_async_event_handlers () at ../../../repos/binutils-gdb/gdb/async-event.c:291
 #32 0x0000aaaaab27cbec in gdb_do_one_event () at ../../../repos/binutils-gdb/gdbsupport/event-loop.cc:194
 #33 0x0000aaaaaaef1894 in start_event_loop () at ../../../repos/binutils-gdb/gdb/main.c:356
 #34 0x0000aaaaaaef1a04 in captured_command_loop () at ../../../repos/binutils-gdb/gdb/main.c:416
 #35 0x0000aaaaaaef3338 in captured_main (data=0xfffffffff1f0) at ../../../repos/binutils-gdb/gdb/main.c:1254
 #36 0x0000aaaaaaef33a0 in gdb_main (args=0xfffffffff1f0) at ../../../repos/binutils-gdb/gdb/main.c:1269
 #37 0x0000aaaaaab6e0dc in main (argc=6, argv=0xfffffffff348) at ../../../repos/binutils-gdb/gdb/gdb.c:32

The following patch addresses this by using a function that unwinds the PC
from the next (inline) frame directly as opposed to creating a lazy value
that is bound to the next frame's ID (still not computed).

gdb/ChangeLog:

2020-04-23  Luis Machado  <luis.machado@linaro.org>

	* dwarf2/frame-tailcall.c (dwarf2_tailcall_sniffer_first): Use
	get_frame_register instead of gdbarch_unwind_pc.
2020-04-23 14:50:22 -03:00
Tom de Vries 70bc38f513 [gdb/symtab] Prefer def over decl (inter-CU case, with context)
This is a follow-up patch on "[PATCH][gdb/symtab] Prefer def over decl
(inter-CU case)" (
https://sourceware.org/pipermail/gdb-patches/2020-April/167489.html ).

Consider the test-case from that patch.  It contains a decl and def of var a
in different CUs, and tests whether var a can be printed using the def, even
if the decl is found first.

However, the test-case does this in a contextless environment, so if we add to
the test-case like this to set the context to the CU containing main:
...
 gdb_test "p a" { = \{1, 2\}}
+
+if ![runto_main] then {
+    fail "can't run to main"
+    return 0
+}
+
+gdb_test "p a" { = \{1, 2\}}
...
then the second test fails, because the decl is found in the context.

Fix this by preferring defs over decls in lookup_global_symbol.

Build and reg-tested on x86_64-linux.

gdb/ChangeLog:

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

	* symtab.c (lookup_global_symbol): Prefer def over decl.

gdb/testsuite/ChangeLog:

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

	* gdb.base/decl-before-def.exp: Run to main and print a again.
2020-04-23 15:42:47 +02:00
Tom de Vries de82891ce5 [gdb/symtab] Prefer def over decl (inter-CU case)
When running test-case gdb.threads/tls.exp with target board -readnow, we
have:
...
(gdb) print a_thread_local^M
Cannot find thread-local storage for process 0, executable file tls/tls:^M
Cannot find thread-local variables on this target^M
(gdb) FAIL: gdb.threads/tls.exp: print a_thread_local
...
while with native we have:
...
(gdb) print a_thread_local^M
Cannot read `a_thread_local' without registers^M
(gdb) PASS: gdb.threads/tls.exp: print a_thread_local
...

The difference in behaviour can be explained as follows.  Without -readnow, we
have two a_thread_locals, the def and the decl, each in a different CU:
...
$ gdb -batch outputs/gdb.threads/tls/tls \
    -ex "maint expand-symtabs" \
    -ex "print a_thread_local" \
    -ex "maint print symbols" \
    | grep "a_thread_local;"
Cannot read `a_thread_local' without registers
 int a_thread_local; computed at runtime
 int a_thread_local; unresolved
...
and with -readnow, we have the opposite order:
...
$ gdb -readnow -batch outputs/gdb.threads/tls/tls  \
    -ex "maint expand-symtabs" \
    -ex "print a_thread_local" \
    -ex "maint print symbols" \
    | grep "a_thread_local;"
Cannot find thread-local storage for process 0, executable file tls/tls:
Cannot find thread-local variables on this target
 int a_thread_local; unresolved
 int a_thread_local; computed at runtime
...

Fix the FAIL by preferring the def over the decl (something we already do
intra-CU since the fix for PR24971, commit 93e55f0a03 "[gdb/symtab] Prefer var
def over decl").

Build and reg-tested on x86_64-linux.

gdb/ChangeLog:

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

	PR symtab/25807
	* block.c (best_symbol, better_symbol): Promote to external.
	* block.h (best_symbol, better_symbol): Declare.
	* symtab.c (lookup_symbol_in_objfile_symtabs): Prefer def over
	decl.

gdb/testsuite/ChangeLog:

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

	* gdb.base/decl-before-def-decl.c: New test.
	* gdb.base/decl-before-def-def.c: New test.
	* gdb.base/decl-before-def.exp: New file.
2020-04-23 15:42:47 +02:00
Tom Tromey ecc6c6066b Fix Ada crash with .debug_names
PR ada/25837 points out a crash in the gdb testsuite when .debug_names
is used.  You can reproduce like:

    runtest --target_board=cc-with-debug-names \
        gdb.ada/big_packed_array.exp

The bug was introduced by commit e0802d599 ("Avoid copying in
lookup_name_info").  The problem is that the return type of
language_lookup_name changed, but in a way that didn't cause existing
callers to trigger a compilation error.  Previously, it returned a
"const string &", but after it returned a "const char *".  This caused
a string to be created in dw2_expand_symtabs_matching_symbol, but one
that had too short of a lifetime; so eventually the matcher cache
would wind up with invalid data.

This patch fixes the problem by updating the callers to use the new
type.

Tested on x86-64 Fedora 30.

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

	PR ada/25837:
	* dwarf2/read.c (dw2_expand_symtabs_matching_symbol): Store a
	"const char *", not a "const std::string &".
	<name_and_matcher::operator==>: Update.
	* unittests/lookup_name_info-selftests.c: Change type of
	"result".
2020-04-23 07:19:43 -06:00
Tom Tromey 740480b88a Remove iterate_over_inferiors
The last caller of iterate_over_inferiors is darwin-nat.c.  This patch
removes the calls from this file, and then remove
iterate_over_inferiors.

In general I think "external iteration" is to be preferred in gdb, the
main benefit being that the code is easier to read.

I rebuilt this on Darwin.  I seem to only have access to Darwin
systems where gdb does not yet work :-(, so I can't run the test
suite.

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

	* inferior.h (iterate_over_inferiors): Don't declare.
	* inferior.c (iterate_over_inferiors): Remove.
	* darwin-nat.c (find_inferior_task_it, find_inferior_pid_it):
	Remove.
	(darwin_find_inferior_by_task, darwin_find_inferior_by_pid): Don't
	use iterate_over_inferiors.
	(darwin_resume_inferior_it)
	(struct resume_inferior_threads_param)
	(darwin_resume_inferior_threads_it): Remove.
	(darwin_nat_target::resume): Don't use iterate_over_inferiors.

Change-Id: Ib2fdf2c98e40f13156ff869ed3173d5f1fdae7ea
2020-04-23 06:26:31 -06:00
Tom de Vries ae3ab1f067 [gdb/symtab] Fix disassembly of non-contiguous functions
When running test-case gdb.dwarf2/dw2-ranges-func.exp with target board
readnow, we have:
...
FAIL: gdb.dwarf2/dw2-ranges-func.exp: disassemble foo (pattern 2)
...

The function foo consists of two ranges:
...
 <1><12f>: Abbrev Number: 7 (DW_TAG_subprogram)
    <130>   DW_AT_external    : 1
    <131>   DW_AT_name        : foo
    <135>   DW_AT_ranges      : 0x40
...
which are listed here:
...
    00000040 00000000004004c1 00000000004004dc
    00000040 00000000004004ae 00000000004004ba
...

Normally the disassemble instruction lists both ranges, but with -readnow it
only lists the first.

This is due to function find_pc_partial_function, which only interacts with
partial symtabs, but not with expanded ones.

Fix this by using find_pc_sect_compunit_symtab in find_pc_partial_function.

Tested on x86_64, with native and target board readnow.

This fixes 19 FAILs for target board readnow, in test-cases
gdb.arch/amd64-entry-value.exp, gdb.base/multi-forks.exp,
gdb.dwarf2/dw2-ranges-func.exp and gdb.linespec/skip-two.exp.

gdb/ChangeLog:

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

	* blockframe.c (find_pc_partial_function): Use
	find_pc_sect_compunit_symtab rather than
	objfile->sf->qf->find_pc_sect_compunit_symtab.
2020-04-23 09:07:50 +02:00
Tom de Vries 317d2668d0 [gdb/symtab] Store external var decls in psymtab
Consider a test-case consisting of source file test.c:
...
extern int aaa;
int
main (void)
{
  return 0;
}
...
and test-2.c:
...
int aaa = 33;
...
compiled with debug info only for test.c:
...
$ gcc -c test.c -g; gcc -c test2.c; gcc test.o test2.o -g
...

When trying to print aaa, we get:
...
$ gdb -batch a.out -ex "print aaa"
'aaa' has unknown type; cast it to its declared type
...
but with -readnow we have:
...
$ gdb -readnow -batch a.out -ex "print aaa"
$1 = 33
...

In the -readnow case, the symbol for aaa in the full symtab has
LOC_UNRESOLVED, and the symbol type is combined with the minimal symbol
address, to read the value and print it without cast.

Without the -readnow, we create partial symbols, but the aaa decl is missing
from the partial symtabs, so we find it only in the minimal symbols, resulting
in the cast request.  If the aaa decl would have been in the partial symtabs,
it would have been found, and the full symtab would have been expanded, after
which things would be as with -readnow.

The function add_partial_symbol has a comment on the LOC_UNRESOLVED +
minimal symbol addres construct at DW_TAG_variable handling:
...
      else if (pdi->is_external)
	{
	  /* Global Variable.
	     Don't enter into the minimal symbol tables as there is
	     a minimal symbol table entry from the ELF symbols already.
	     Enter into partial symbol table if it has a location
	     descriptor or a type.
	     If the location descriptor is missing, new_symbol will create
	     a LOC_UNRESOLVED symbol, the address of the variable will then
	     be determined from the minimal symbol table whenever the variable
	     is referenced.
...
but it's not triggered due to this test in scan_partial_symbols:
...
            case DW_TAG_variable:
	    ...
              if (!pdi->is_declaration)
                {
                  add_partial_symbol (pdi, cu);
                }
...

Fix this in scan_partial_symbols by allowing external variable decls to be
added to the partial symtabs.

Build and reg-tested on x86_64-linux.

The patch caused this regression:
...
(gdb) print a_thread_local^M
Cannot find thread-local storage for process 0, executable file tls/tls:^M
Cannot find thread-local variables on this target^M
(gdb) FAIL: gdb.threads/tls.exp: print a_thread_local
...
while without the patch we have:
...
(gdb) print a_thread_local^M
Cannot read `a_thread_local' without registers^M
(gdb) PASS: gdb.threads/tls.exp: print a_thread_local
...

However, without the patch but with -readnow we have the same FAIL as with the
patch (filed as PR25807).  In other words, the patch has the effect that we
get the same result with and without -readnow.

This can be explained as follows.  Without the patch, and without -readnow, we
have two a_thread_locals, the def and the decl:
...
$ gdb -batch outputs/gdb.threads/tls/tls \
    -ex "maint expand-symtabs" \
    -ex "print a_thread_local" \
    -ex "maint print symbols" \
    | grep "a_thread_local;"
Cannot read `a_thread_local' without registers
 int a_thread_local; computed at runtime
 int a_thread_local; unresolved
...
while without the patch and with -readnow, we have the opposite order:
...
$ gdb -readnow -batch outputs/gdb.threads/tls/tls  \
    -ex "maint expand-symtabs" \
    -ex "print a_thread_local" \
    -ex "maint print symbols" \
    | grep "a_thread_local;"
Cannot find thread-local storage for process 0, executable file tls/tls:
Cannot find thread-local variables on this target
 int a_thread_local; unresolved
 int a_thread_local; computed at runtime
...

With the patch we have the same order with and without -readnow, but just a
different one than before without -readnow.

Mark the "Cannot find thread-local variables on this target" variant a PR25807
kfail.

gdb/ChangeLog:

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

	PR symtab/25764
	* dwarf2/read.c (scan_partial_symbols): Allow external variable decls
	in psymtabs.

gdb/testsuite/ChangeLog:

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

	PR symtab/25764
	* gdb.base/psym-external-decl-2.c: New test.
	* gdb.base/psym-external-decl.c: New test.
	* gdb.base/psym-external-decl.exp: New file.
	* gdb.threads/tls.exp: Add PR25807 kfail.
2020-04-22 08:38:44 +02:00
Tom de Vries eea9e35758 [gdb/symtab] Find filename in shared psymtab
When running test-case gdb.ada/dgopt.exp with target board
unix/-flto/-O0/-flto-partition=none/-ffat-lto-objects and gcc-8, gcc-9 or
gcc-10, and the fix for PR25700, we run into this regression:
...
(gdb) list x.adb:16, 16^M
No source file named x.adb.^M
(gdb) FAIL: gdb.ada/dgopt.exp: list x.adb:16, 16
...

The reason for the failure is that without the fix for PR25700, we
have an unshared psymtab:
...
  { psymtab gdb.ada/dgopt/x.adb ((struct partial_symtab *) $hex)^M
    readin no^M
    fullname (null)^M
    text addresses 0x0 -- 0x0^M
    psymtabs_addrmap_supported yes^M
    globals (none)^M
    statics (none)^M
    dependencies (none)^M
  }^M
...
and a shared psymtab (with user field set):
...
  { psymtab gdb.ada/dgopt/x.adb ((struct partial_symtab *) $hex)^M
    readin no^M
    fullname (null)^M
    text addresses 0x0 -- 0x0^M
    psymtabs_addrmap_supported yes^M
    globals (none)^M
    statics (none)^M
    user <artificial>@0x159a ((struct partial_symtab *) 0x37b57c0)^M
    dependencies (none)^M
  }^M
...

The fix for PR25700 removes the unshared psymtab.

Then when trying to find a psymtab matching x.adb in
psym_map_symtabs_matching_filename, we run into this continue for the shared
psymtab:
...
  for (partial_symtab *pst : require_partial_symbols (objfile, true))
    {
      /* We can skip shared psymtabs here, because any file name will be
        attached to the unshared psymtab.  */
      if (pst->user != NULL)
       continue;
...
and consequently cannot find the file.

Fix this by not skipping the shared symtab in
psym_map_symtabs_matching_filename.

Build and reg-tested on x86_64-linux.

gdb/ChangeLog:

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

	PR symtab/25801
	* psymtab.c (psym_map_symtabs_matching_filename): Don't skip shared
	symtabs.

gdb/testsuite/ChangeLog:

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

	PR symtab/25801
	* gdb.dwarf2/imported-unit.exp: Test that we can get imported_unit.c
	in "info source" output.
2020-04-22 08:24:11 +02:00
Tom de Vries 3d5afab339 [gdb/symtab] Don't create duplicate psymtab for forward-imported CU
Consider the executable generated for test-case gdb.dwarf2/imported-unit.exp.

When loading the executable using various tracing:
...
$ gdb \
  outputs/gdb.dwarf2/imported-unit/imported-unit \
  -batch \
  -iex "set verbose on" \
  -iex "set debug symtab-create 1"
  ...
Created psymtab 0x213f380 for module <artificial>@0xc7.
Created psymtab 0x20e7b00 for module imported_unit.c.
Created psymtab 0x215da20 for module imported_unit.c.
Created psymtab 0x2133630 for module elf-init.c.
Created psymtab 0x215b910 for module ../sysdeps/x86_64/crtn.S.
...
we notice that there are two psymtabs generated for imported_unit.c.

This is due to the following: in dwarf2_build_psymtabs_hard we loop over CUs
and generate partial symtabs for those, and if we encounter an import of
another CU, we also generate a partial symtab for that one, unless already
created.

This works well with backward import references:
- the imported CU is read
- then the importing CU is read
- the import is encountered, but the imported CU is already read, so
  we're done.

But with forward import references, we have instead:
- the importing CU is read
- the import is encountered, and the imported CU is read
- the imported CU is read once more

Fix this by skipping already created psymtabs in the loop in
dwarf2_build_psymtabs_hard.

Tested on x86_64-linux, with native and target board
unix/-flto/-O0/-flto-partition=none/-ffat-lto-objects.

This causes this regression with the target board:
...
FAIL: gdb.ada/dgopt.exp: list x.adb:16, 16
...
which I consider a seperate PR, filed as PR25801 - "Filename of shared psymtab
is ignored".

gdb/ChangeLog:

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

	PR symtab/25700
	* dwarf2/read.c (dwarf2_build_psymtabs_hard): Don't create psymtab for
	CU if already created.

gdb/testsuite/ChangeLog:

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

	PR symtab/25700
	* gdb.dwarf2/imported-unit.exp: Verify that there's only one partial
	symtab for imported_unit.c.
2020-04-22 08:09:45 +02:00
Tankut Baris Aktemur d43b7a2d57 gdb/infrun: switch the context before 'displaced_step_restore'
In infrun.c's 'displaced_step_fixup', as part of the 'finish_step_over'
flow, switch to the eventing thread *before* calling
'displaced_step_restore', because down in the flow ptid-dependent
memory accesses are used via current_inferior() and current_top_target().

Without this patch, the problem is exposed with the scenario below:

   $ gdb -q
   (gdb) maint set target-non-stop on
   (gdb) file a.out
   Reading symbols from a.out...
   (gdb) set remote exec-file a.out
   (gdb) target extended-remote | gdbserver --once --multi -
   ...
   (gdb) add-inferior
   [New inferior 2]
   Added inferior 2 on connection 1 (extended-remote ...)
   (gdb) inferior 2
   [Switching to inferior 2 [<null>] (<noexec>)]
   (gdb) file a.out
   Reading symbols from a.out...
   (gdb) set remote exec-file a.out
   (gdb) run
   ...
   Cannot access memory at address 0x555555555042
   (gdb)

The problem is, down inside 'displaced_step_restore', GDB wants to
access the memory for inferior 2 because of an internal breakpoint.
However, the current inferior and inferior_ptid are out of sync.
While inferior_ptid correctly points to the process of inf 2 that was
just started, current_inferior points to inf 1.  Then, the attempt to
access the memory fails, because target_has_execution results in false
since inf 1 was not started.  I was not able to simplify the failing
scenario, but it shows the problem.

After this patch, we get

  ... same steps above...
  (gdb) run
  ...
  [Inferior 2 (process 28652) exited normally]
  (gdb)

Regression-tested on X86_64 Linux with `make check`s default board file
and also `--target_board=native-extended-gdbserver`.  In fact, the bug
fixed by this patch was exposed when using the native-extended-gdbserver
board file.

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

	* infrun.c (displaced_step_fixup): Switch to the event_thread
	before calling displaced_step_restore, not after.

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

	* gdb.multi/run-only-second-inf.c: New file.
	* gdb.multi/run-only-second-inf.exp: New file.
2020-04-21 17:24:03 +02:00
Markus Metzger d89edf9b81 gdb, btrace: make record-btrace per-inferior
When there is more than one inferior, the "record btrace" command should
only apply to the current inferior.

gdb/ChangeLog:

2020-03-19  Markus Metzger  <markus.t.metzger@intel.com>

	* record-btrace.c (record_btrace_enable_warn): Ignore thread if
	its inferior is not recorded by us.
	(record_btrace_target_open): Replace call to all_non_exited_threads ()
	with call to current_inferior ()->non_exited_threads ().
	(record_btrace_target::stop_recording): Likewise.
	(record_btrace_target::close): Likewise.
	(record_btrace_target::wait): Likewise.
	(record_btrace_target::record_stop_replaying): Likewise.

gdb/testsuite/ChangeLog:

2020-03-19  Markus Metzger  <markus.t.metzger@intel.com>

	* gdb.btrace/multi-inferior.c: New test.
	* gdb.btrace/multi-inferior.exp: New file.
2020-04-21 15:56:23 +02:00
Markus Metzger 5897fd4994 gdb, btrace: diagnose double and failed enable
GDB silently ignores attempts to enable branch tracing on a thread that is
already recorded.  This shouldn't happen as recording is enabled exactly
once:

  - when the btrace record target is opened for existing threads
  - when a new thread is added while the btrace record target is pushed

GDB also silently ignores if recording is disabled on threads that were not
recorded.  This shouldn't happen, either, since when stopping recording,
we only disable recording on threads that were recorded.

GDB further silently ignores if recording was not enabled by the
corresponding target method.  Also this shouldn't happen since the target
is supposed to already throw an error if recording cannot be enabled.
This new error in btrace_enable catches cases where the target silently
failed to enable recording.

Throw an error in those cases.

This allows us to detect an actual issue more easily.  It will be
addressed in the next patch.

gdb/ChangeLog:

2020-03-19  Markus Metzger  <markus.t.metzger@intel.com>

	* btrace.c (btrace_enable): Throw an error on double enables and
	when enabling recording fails.
	(btrace_disable): Throw an error if the thread is not recorded.
2020-04-21 15:54:32 +02:00
Markus Metzger 1a476b6d68 gdb, btrace: forward fetch_registers for unknown threads
In the record-btrace target, while replaying, we can only provide the PC
register.  The btrace state is stored in the thread_info.  So, when trying
to determine whether we are currently replaying, GDB calls
find_thread_ptid() to obtain the thread_info.  It also asserts that we do
have a thread_info.

For new threads, libthread-db may fetch registers before the thread is
known to GDB.  In this case, find_thread_ptid() returns nullptr and the
assertion fails.

Forward the fetch_registers request to the target beneath in that case.

gdb/ChangeLog:

2020-03-19  Markus Metzger  <markus.t.metzger@intel.com>

	* record-btrace.c (record_btrace_target::fetch_registers): Forward
	request if we do not have a thread_info.

gdb/testsuite/ChangeLog:

2020-03-19  Markus Metzger  <markus.t.metzger@intel.com>

	* gdb.btrace/enable-new-thread.c: New test.
	* gdb.btrace/enable-new-thread.exp: New file.
2020-04-21 15:51:06 +02:00
Tom de Vries 4778a5f87d [gdb] Fix hang after ext sigkill
Consider the test-case from this patch, compiled with pthread support:
...
$ gcc gdb/testsuite/gdb.threads/killed-outside.c -lpthread -g
...

After running to all_started, we can print pid:
...
$ gdb a.out -ex "b all_started" -ex run -ex "delete 1" -ex "p pid"
...
Reading symbols from a.out...
Breakpoint 1 at 0x40072b: file killed-outside.c, line 29.
Starting program: /data/gdb_versions/devel/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
[New Thread 0x7ffff77fc700 (LWP 3155)]

Thread 1 "a.out" hit Breakpoint 1, all_started () at killed-outside.c:29
29      }
$1 = 3151
(gdb)
...

If we then kill the inferior using an external SIGKILL:
...
(gdb) shell kill -9 3151
...
and subsequently continue:
...
(gdb) c
Continuing.
Couldn't get registers: No such process.
Couldn't get registers: No such process.
(gdb) Couldn't get registers: No such process.
(gdb) Couldn't get registers: No such process.
(gdb) Couldn't get registers: No such process.
<repeat>
...
gdb hangs repeating the same warning.  Typing control-C no longer helps,
and we have to kill gdb.

This is a regression since commit 873657b9e8 "Preserve selected thread in
all-stop w/ background execution".  The commit adds a
scoped_restore_current_thread typed variable restore_thread to
fetch_inferior_event, and the hang is caused by the constructor throwing an
exception.

Fix this by catching the exception in the constructor.

Build and reg-tested on x86_64-linux.

gdb/ChangeLog:

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

	PR gdb/25471
	* thread.c
	(scoped_restore_current_thread::scoped_restore_current_thread): Catch
	exception in get_frame_id.

gdb/testsuite/ChangeLog:

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

	PR gdb/25471
	* gdb.threads/killed-outside.c: New test.
	* gdb.threads/killed-outside.exp: New file.
2020-04-21 15:45:57 +02:00
Tom Tromey 0fa7617d84 Mark move constructors as "noexcept"
I recently learned that move constructors generally should be marked
"noexcept".  This ensures that standard containers will move objects
when possible, rather than copy them.

This patch fixes the cases I could find.  Note that implicitly-defined
or defaulted move constructors will automatically do what you'd
expect; that is, they are noexcept if all the members have noexcept
move constructors.

While doing this, I noticed a couple of odd cases where the move
constructor seemed to assume that the object being constructed could
have state requiring destruction.  I've fixed these as well.  See
completion_result and scoped_mmap.

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

	* python/python.c (struct gdbpy_event): Mark move constructor as
	noexcept.
	* python/py-tui.c (class gdbpy_tui_window_maker): Mark move
	constructor as noexcept.
	* completer.h (struct completion_result): Mark move constructor as
	noexcept.
	* completer.c (completion_result::completion_result): Use
	initialization style.  Don't call reset_match_list.

gdbsupport/ChangeLog
2020-04-20  Tom Tromey  <tromey@adacore.com>

	* scoped_mmap.h (scoped_mmap): Mark move constructor as noexcept.
	Use initialization style.  Don't call destroy.
	* scoped_fd.h (class scoped_fd): Mark move constructor as
	noexcept.
	* gdb_ref_ptr.h (class ref_ptr): Mark move constructor as
	noexcept.
2020-04-20 11:45:06 -06:00
Mihails Strasuns ad23bda0db Add myself to gdb/MAINTAINERS
2020-04-20  Mihails Strasuns  <mihails.strasuns@intel.com>

	* MAINTAINERS (Write After Approval): Add myself.

Change-Id: I3f412e328b42dea875a6d7cb74fc55415865f134
2020-04-20 16:44:44 +02:00
Simon Marchi aac66a4c0b gdb: fix tabs vs spaces in ChangeLog 2020-04-20 10:18:56 -04:00
Tom Tromey 45e1f031e8 Restore some windows-tdep.c code
When I removed init_w32_command_list, I weirdly neglected to see if it
was called anywhere else.  This patch restores the function, which is
called from windows-nat.c.  Sorry about the breakage.

Is it possible to have a windows-native gdb that isn't also using
windows-tdep?

Anyway, I'm checking this in.

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

	* windows-tdep.c (init_w32_command_list)
	(w32_prefix_command_valid): Restore.
	(_initialize_windows_tdep): Call init_w32_command_list.
2020-04-18 19:40:52 -06:00
Tom Tromey 08feed99cb Change get_objfile_arch to a method on objfile
This changes get_objfile_arch to be a new inline method,
objfile::arch.

To my surprise, this function came up while profiling DWARF psymbol
reading.  Making this change improved performance from 1.986 seconds
to 1.869 seconds.  Both measurements were done by taking the mean of
10 runs on a fixed copy of the gdb executable.

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

	* xcoffread.c (enter_line_range, scan_xcoff_symtab): Update.
	* value.c (value_fn_field): Update.
	* valops.c (find_function_in_inferior)
	(value_allocate_space_in_inferior): Update.
	* tui/tui-winsource.c (tui_update_source_windows_with_line):
	Update.
	* tui/tui-source.c (tui_source_window::set_contents): Update.
	* symtab.c (lookup_global_or_static_symbol)
	(find_function_start_sal_1, skip_prologue_sal)
	(print_msymbol_info, find_gnu_ifunc, symbol_arch): Update.
	* symmisc.c (dump_msymbols, dump_symtab_1)
	(maintenance_print_one_line_table): Update.
	* symfile.c (init_entry_point_info, section_is_mapped)
	(list_overlays_command, simple_read_overlay_table)
	(simple_overlay_update_1): Update.
	* stap-probe.c (handle_stap_probe): Update.
	* stabsread.c (dbx_init_float_type, define_symbol)
	(read_one_struct_field, read_enum_type, read_range_type): Update.
	* source.c (info_line_command): Update.
	* python/python.c (gdbpy_source_objfile_script)
	(gdbpy_execute_objfile_script): Update.
	* python/py-type.c (save_objfile_types): Update.
	* python/py-objfile.c (py_free_objfile): Update.
	* python/py-inferior.c (python_new_objfile): Update.
	* psymtab.c (psym_find_pc_sect_compunit_symtab, dump_psymtab)
	(dump_psymtab_addrmap_1, maintenance_info_psymtabs)
	(maintenance_check_psymtabs): Update.
	* printcmd.c (info_address_command): Update.
	* objfiles.h (struct objfile) <arch>: New method, from
	get_objfile_arch.
	(get_objfile_arch): Don't declare.
	* objfiles.c (get_objfile_arch): Remove.
	(filter_overlapping_sections): Update.
	* minsyms.c (msymbol_is_function): Update.
	* mi/mi-symbol-cmds.c (mi_cmd_symbol_list_lines)
	(output_nondebug_symbol): Update.
	* mdebugread.c (parse_symbol, basic_type, parse_partial_symbols)
	(mdebug_expand_psymtab): Update.
	* machoread.c (macho_add_oso_symfile): Update.
	* linux-tdep.c (linux_infcall_mmap, linux_infcall_munmap):
	Update.
	* linux-fork.c (checkpoint_command): Update.
	* linespec.c (convert_linespec_to_sals): Update.
	* jit.c (finalize_symtab): Update.
	* infrun.c (insert_exception_resume_from_probe): Update.
	* ia64-tdep.c (ia64_find_unwind_table): Update.
	* hppa-tdep.c (internalize_unwinds): Update.
	* gdbtypes.c (get_type_arch, init_float_type, objfile_type):
	Update.
	* gcore.c (call_target_sbrk): Update.
	* elfread.c (record_minimal_symbol, elf_symtab_read)
	(elf_rel_plt_read, elf_gnu_ifunc_record_cache)
	(elf_gnu_ifunc_resolve_by_got): Update.
	* dwarf2/read.c (create_addrmap_from_index)
	(create_addrmap_from_aranges, dw2_find_pc_sect_compunit_symtab)
	(read_debug_names_from_section)
	(process_psymtab_comp_unit_reader, add_partial_symbol)
	(add_partial_subprogram, process_full_comp_unit)
	(read_file_scope, read_func_scope, read_lexical_block_scope)
	(read_call_site_scope, dwarf2_ranges_read)
	(dwarf2_record_block_ranges, dwarf2_add_field)
	(mark_common_block_symbol_computed, read_tag_pointer_type)
	(read_tag_string_type, dwarf2_init_float_type)
	(dwarf2_init_complex_target_type, read_base_type)
	(partial_die_info::read, partial_die_info::read)
	(read_attribute_value, dwarf_decode_lines_1, new_symbol)
	(dwarf2_fetch_die_loc_sect_off): Update.
	* dwarf2/loc.c (dwarf2_find_location_expression)
	(class dwarf_evaluate_loc_desc, rw_pieced_value)
	(dwarf2_evaluate_loc_desc_full, dwarf2_locexpr_baton_eval)
	(dwarf2_loc_desc_get_symbol_read_needs)
	(locexpr_describe_location_piece, locexpr_describe_location_1)
	(loclist_describe_location): Update.
	* dwarf2/index-write.c (write_debug_names): Update.
	* dwarf2/frame.c (dwarf2_build_frame_info): Update.
	* dtrace-probe.c (dtrace_process_dof): Update.
	* dbxread.c (read_dbx_symtab, dbx_end_psymtab)
	(process_one_symbol): Update.
	* ctfread.c (ctf_init_float_type, read_base_type): Update.
	* coffread.c (coff_symtab_read, enter_linenos, decode_base_type)
	(coff_read_enum_type): Update.
	* cli/cli-cmds.c (edit_command, list_command): Update.
	* buildsym.c (buildsym_compunit::finish_block_internal): Update.
	* breakpoint.c (create_overlay_event_breakpoint)
	(create_longjmp_master_breakpoint)
	(create_std_terminate_master_breakpoint)
	(create_exception_master_breakpoint, get_sal_arch): Update.
	* block.c (block_gdbarch): Update.
	* annotate.c (annotate_source_line): Update.
2020-04-18 08:35:04 -06:00
Tom Tromey 0743fc83c0 Replace most calls to help_list and cmd_show_list
Currently there are many prefix commands that do nothing but call
either help_list or cmd_show_list.  I happened to notice that one such
call, for "set print type", used the wrong command list parameter,
causing incorrect output.

Rather than fix this bug in isolation, I decided to eliminate this
possibility by adding two new ways to add prefix commands, which
simply route the call to help_list or cmd_show_list, as appropriate.
This makes it impossible for a mismatch to occur.

In some cases, a bit of output was removed; however, I don't think
this output in general was very useful.  It seemed redundant with
what's already printed by help_list.  A representative example is this
hunk, removed from ada-lang.c:

-  printf_unfiltered (_(\
-"\"set ada\" must be followed by the name of a setting.\n"));

This simplified the CLI style set/show commands quite a bit, and
allowed the deletion of a macro.

This also cleans up some unusual code in windows-tdep.c.

Tested on x86-64 Fedora 30.  Note that I have no way to build the
go32-nat.c change.

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

	* auto-load.c (show_auto_load_cmd): Remove.
	(auto_load_show_cmdlist_get): Use add_show_prefix_cmd.
	* arc-tdep.c (_initialize_arc_tdep): Use add_show_prefix_cmd.
	(maintenance_print_arc_command): Remove.
	* tui/tui-win.c (tui_command): Remove.
	(tui_get_cmd_list): Use add_basic_prefix_cmd.
	* tui/tui-layout.c (tui_layout_command): Remove.
	(_initialize_tui_layout): Use add_basic_prefix_cmd.
	* python/python.c (user_set_python, user_show_python): Remove.
	(_initialize_python): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* guile/guile.c (set_guile_command, show_guile_command): Remove.
	(install_gdb_commands): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	(info_guile_command): Remove.
	* dwarf2/read.c (set_dwarf_cmd, show_dwarf_cmd): Remove.
	(_initialize_dwarf2_read): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* cli/cli-style.h (class cli_style_option) <add_setshow_commands>:
	Remove do_set and do_show parameters.
	* cli/cli-style.c (set_style, show_style): Remove.
	(_initialize_cli_style): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	(cli_style_option::add_setshow_commands): Remove do_set and
	do_show parameters.
	(cli_style_option::add_setshow_commands): Use
	add_basic_prefix_cmd, add_show_prefix_cmd.
	(STYLE_ADD_SETSHOW_COMMANDS): Remove macro.
	(set_style_name): Remove.
	* cli/cli-dump.c (dump_command, append_command): Remove.
	(srec_dump_command, ihex_dump_command, verilog_dump_command)
	(tekhex_dump_command, binary_dump_command)
	(binary_append_command): Remove.
	(_initialize_cli_dump): Use add_basic_prefix_cmd.
	* windows-tdep.c (w32_prefix_command_valid): Remove global.
	(init_w32_command_list): Remove; move into ...
	(_initialize_windows_tdep): ... here.  Use add_basic_prefix_cmd.
	* valprint.c (set_print, show_print, set_print_raw)
	(show_print_raw): Remove.
	(_initialize_valprint): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* typeprint.c (set_print_type, show_print_type): Remove.
	(_initialize_typeprint): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* record.c (set_record_command, show_record_command): Remove.
	(_initialize_record): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* cli/cli-cmds.c (_initialize_cli_cmds): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	(info_command, show_command, set_debug, show_debug): Remove.
	* top.h (set_history, show_history): Don't declare.
	* top.c (set_history, show_history): Remove.
	* target-descriptions.c (set_tdesc_cmd, show_tdesc_cmd)
	(unset_tdesc_cmd): Remove.
	(_initialize_target_descriptions): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* symtab.c (info_module_command): Remove.
	(_initialize_symtab): Use add_basic_prefix_cmd.
	* symfile.c (overlay_command): Remove.
	(_initialize_symfile): Use add_basic_prefix_cmd.
	* sparc64-tdep.c (info_adi_command): Remove.
	(_initialize_sparc64_adi_tdep): Use add_basic_prefix_cmd.
	* sh-tdep.c (show_sh_command, set_sh_command): Remove.
	(_initialize_sh_tdep): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* serial.c (serial_set_cmd, serial_show_cmd): Remove.
	(_initialize_serial): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* ser-tcp.c (set_tcp_cmd, show_tcp_cmd): Remove.
	(_initialize_ser_tcp): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* rs6000-tdep.c (set_powerpc_command, show_powerpc_command)
	(_initialize_rs6000_tdep): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* riscv-tdep.c (show_riscv_command, set_riscv_command)
	(show_debug_riscv_command, set_debug_riscv_command): Remove.
	(_initialize_riscv_tdep): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* remote.c (remote_command, set_remote_cmd): Remove.
	(_initialize_remote): Use add_basic_prefix_cmd.
	* record-full.c (set_record_full_command)
	(show_record_full_command): Remove.
	(_initialize_record_full): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* record-btrace.c (cmd_set_record_btrace)
	(cmd_show_record_btrace, cmd_set_record_btrace_bts)
	(cmd_show_record_btrace_bts, cmd_set_record_btrace_pt)
	(cmd_show_record_btrace_pt): Remove.
	(_initialize_record_btrace): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* ravenscar-thread.c (set_ravenscar_command)
	(show_ravenscar_command): Remove.
	(_initialize_ravenscar): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* mips-tdep.c (show_mips_command, set_mips_command)
	(_initialize_mips_tdep): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* maint.c (maintenance_command, maintenance_info_command)
	(maintenance_check_command, maintenance_print_command)
	(maintenance_set_cmd, maintenance_show_cmd): Remove.
	(_initialize_maint_cmds): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	(show_per_command_cmd): Remove.
	* maint-test-settings.c (maintenance_set_test_settings_cmd):
	Remove.
	(maintenance_show_test_settings_cmd): Remove.
	(_initialize_maint_test_settings): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* maint-test-options.c (maintenance_test_options_command):
	Remove.
	(_initialize_maint_test_options): Use add_basic_prefix_cmd.
	* macrocmd.c (macro_command): Remove
	(_initialize_macrocmd): Use add_basic_prefix_cmd.
	* language.c (set_check, show_check): Remove.
	(_initialize_language): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* infcmd.c (unset_command): Remove.
	(_initialize_infcmd): Use add_basic_prefix_cmd.
	* i386-tdep.c (set_mpx_cmd, show_mpx_cmd): Remove.
	(_initialize_i386_tdep): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* go32-nat.c (go32_info_dos_command): Remove.
	(_initialize_go32_nat): Use add_basic_prefix_cmd.
	* cli/cli-decode.c (do_prefix_cmd, add_basic_prefix_cmd)
	(do_show_prefix_cmd, add_show_prefix_cmd): New functions.
	* frame.c (set_backtrace_cmd, show_backtrace_cmd): Remove.
	(_initialize_frame): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* dcache.c (set_dcache_command, show_dcache_command): Remove.
	(_initialize_dcache): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* cp-support.c (maint_cplus_command): Remove.
	(_initialize_cp_support): Use add_basic_prefix_cmd.
	* btrace.c (maint_btrace_cmd, maint_btrace_set_cmd)
	(maint_btrace_show_cmd, maint_btrace_pt_set_cmd)
	(maint_btrace_pt_show_cmd, _initialize_btrace): Use
	add_basic_prefix_cmd, add_show_prefix_cmd.
	* breakpoint.c (save_command): Remove.
	(_initialize_breakpoint): Use add_basic_prefix_cmd.
	* arm-tdep.c (set_arm_command, show_arm_command): Remove.
	(_initialize_arm_tdep): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* ada-lang.c (maint_set_ada_cmd, maint_show_ada_cmd)
	(set_ada_command, show_ada_command): Remove.
	(_initialize_ada_language): Use add_basic_prefix_cmd,
	add_show_prefix_cmd.
	* command.h (add_basic_prefix_cmd, add_show_prefix_cmd): Declare.

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

	* gdb.cp/maint.exp (test_help): Simplify multiple_help_body.
	Update tests.
	* gdb.btrace/cpu.exp: Update tests.
	* gdb.base/maint.exp: Update tests.
	* gdb.base/default.exp: Update tests.
	* gdb.base/completion.exp: Update tests.
2020-04-17 15:13:41 -06:00
Kamil Rytarowski 3557f442a1 Remove obsolete and unused inf_ptrace_target::auxv_parse
The only two potential users (NetBSD, OpenBSD) use svr4_auxv_parse.

gdb/ChangeLog:

        * nbsd-nat.c (inf_ptrace_target::auxv_parse): Remove.
        * nbsd-nat.h (inf_ptrace_target::auxv_parse): Likewise.
2020-04-17 05:52:43 +02:00
Simon Marchi 1619720823 gdb: is_linked_with_cygwin_dll: mention filename in warning messages
When a warning is displayed, it isn't clear to the user which file is
the cause of the warning.  Add the filename in there.  Remove the
"Failed to parse .idata section" part, since the .idata section is
always mentioned one way or another anyway, so it just contributes to
make the message longer than it needs to be.

gdb/ChangeLog:

	* windows-tdep.c (is_linked_with_cygwin_dll): Add filename to
	warning messages.
2020-04-16 15:46:44 -04:00
Simon Marchi 00ac85d375 gdb: is_linked_with_cygwin_dll: handle import table not at beginning of .idata section
When loading the file C:\Windows\SysWOW64\msvcrt.dll, taken from a
Windows 10 system, into GDB, we get the following warning:

    warning: Failed to parse .idata section: name's virtual address (0x0) is outside .idata section's range [0xb82b8, 0xb97f0[.

This uncovers an issue with how we parse the import table, part of the
.idata section.  Right now, we assume that the import table is located
at the beginning of the section.  That was the case in everything I had
tried so far, but this file is an example where that's not true.

We need to compute the offset of the import table within the .idata
section, and start there, instead of at the beginning of the .idata
section.  Using the file mentioned above, this is the values we have to
work with:

  A) bfd_section_vma (idata_section)    101b8000
  B) Import table's virtual address        b82b8
  C) Image base                         10100000

The virtual address that BFD returns us for the section has the image
base applied, so we need to subtract it first.  The offset of the table
in the section is therefore:

    B - (A - C)

This patch implements that.

gdb/ChangeLog:

	* windows-tdep.c (is_linked_with_cygwin_dll): Consider case where
	import table is not at beginning of .idata section.
2020-04-16 15:46:36 -04:00
Pedro Alves 381ce63f2f Refactor delete_program_space as a destructor
Currently, while the program_space's ctor adds the new pspace to the
pspaces list, the destructor doesn't remove the pspace from the pspace
list.  Instead, you're supposed to use delete_program_space, to both
remove the pspace from the list, and deleting the pspace.

This patch eliminates delete_program_space, and makes the pspace dtor
remove the deleted pspace from the pspace list itself, i.e., makes the
dtor do the mirror opposite of the ctor.

I found this helps with a following patch that will allocate a mock
program_space on the stack.  It's easier to just let the regular dtor
remove the mock pspace from the pspace list than arrange to call
delete_program_space instead of the pspace dtor in that situation.

While at it, move the ctor/dtor intro comments to the header file, and
make the ctor explicit.

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

	* inferior.c (delete_inferior): Use delete operator directly
	instead of delete_program_space.
	* progspace.c (add_program_space): New, factored out from
	program_space::program_space.
	(remove_program_space): New, factored out from
	delete_program_space.
	(program_space::program_space): Remove intro comment.  Rewrite.
	(program_space::~program_space): Remove intro comment.  Call
	remove_program_space.
	(delete_program_space): Delete.
	* progspace.h (program_space::program_space): Make explicit.  Move
	intro comment here, adjusted.
	(program_space::~program_space): Move intro comment here,
	adjusted.
	(delete_program_space): Remove.
2020-04-16 14:50:07 +01:00
Tom Tromey a010605fef Fix Cygwin gdb build
Simon pointed out that the windows-nat sharing series broke the Cygwin
build.  This patch fixes the problem, by moving the Cygwin-specific
code to a new handler function.  This approach is taken because this
code calls find_pc_partial_function, which isn't available in
gdbserver.

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

	* windows-nat.c (windows_nat::handle_access_violation): New
	function.
	* nat/windows-nat.h (handle_access_violation): Declare.
	* nat/windows-nat.c (handle_exception): Move Cygwin code to
	windows-nat.c.  Call handle_access_violation.

gdbserver/ChangeLog
2020-04-16  Tom Tromey  <tromey@adacore.com>

	* win32-low.cc (windows_nat::handle_access_violation): New
	function.
2020-04-16 07:24:57 -06:00
Tom de Vries efba5c2319 [gdb/symtab] Handle PU without import in "save gdb-index"
Consider the test-case added in this patch, with resulting dwarf:
...
  Compilation Unit @ offset 0xc7:
   Length:        0x2c (32-bit)
   Version:       4
   Abbrev Offset: 0x64
   Pointer Size:  8
 <0><d2>: Abbrev Number: 2 (DW_TAG_partial_unit)
    <d3>   DW_AT_language    : 2        (non-ANSI C)
    <d4>   DW_AT_name        : imported_unit.c
 <1><e4>: Abbrev Number: 3 (DW_TAG_base_type)
    <e5>   DW_AT_byte_size   : 4
    <e6>   DW_AT_encoding    : 5        (signed)
    <e7>   DW_AT_name        : int
 <1><eb>: Abbrev Number: 4 (DW_TAG_subprogram)
    <ec>   DW_AT_name        : main
    <f1>   DW_AT_type        : <0xe4>
    <f5>   DW_AT_external    : 1
 <1><f6>: Abbrev Number: 0
  Compilation Unit @ offset 0xf7:
   Length:        0x2c (32-bit)
   Version:       4
   Abbrev Offset: 0x85
   Pointer Size:  8
 <0><102>: Abbrev Number: 2 (DW_TAG_compile_unit)
    <103>   DW_AT_language    : 2       (non-ANSI C)
    <104>   DW_AT_name        : <artificial>
 <1><111>: Abbrev Number: 3 (DW_TAG_subprogram)
    <112>   DW_AT_abstract_origin: <0xeb>
    <116>   DW_AT_low_pc      : 0x4004a7
    <11e>   DW_AT_high_pc     : 0x4004b2
 <1><126>: Abbrev Number: 0
...

When run with target board cc-with-gdb-index, we run into:
...
(gdb) break main
warning: (Internal error: pc 0x4004a7 in read in CU, but not in symtab.)
<repeat>
warning: (Internal error: pc 0x4004ab in read in CU, but not in symtab.)
<repeat>
Breakpoint 1 at 0x4004ab
(gdb) PASS: gdb.dwarf2/imported-unit-runto-main.exp: setting breakpoint at main
run
Starting program: /data/gdb_versions/devel/build/gdb/testsuite/outputs/gdb.dwarf2/imported-unit-runto-main/imported-unit-runto-main
warning: (Internal error: pc 0x4004a7 in read in CU, but not in symtab.)
<repeat>
warning: (Internal error: pc 0x4004ab in read in CU, but not in symtab.)
<repeat>

Breakpoint 1, warning: (Internal error: pc 0x4004ab in read in CU, but not in symtab.)
warning: (Internal error: pc 0x4004ab in read in CU, but not in symtab.)
<repeat>
0x00000000004004ab in main ()
warning: (Internal error: pc 0x4004ab in read in CU, but not in symtab.)
<repeat>
(gdb) FAIL: gdb.dwarf2/imported-unit-runto-main.exp: running to main in runto
...

Looking at the .gdb_index section contents using objdump --dwarf=gdb_index, we
have:
...
CU table:
[  0] 0x0 - 0x2d
[  1] 0x2e - 0xa4
[  2] 0xa5 - 0xc6
[  3] 0xf7 - 0x126
[  4] 0x127 - 0x2de
[  5] 0x2df - 0x300

Address table:
00000000004004a7 00000000004004b2 4

Symbol table:
[489] main: 4 [global, function]
...
We see that both the main symbol, and main address range map to CU 4, which has
offset range 0x127 - 0x2de, while main actually is contained in CU 3 at offset
range 0xf7 - 0x126.

This is caused by this continue in write_gdbindex, which triggers for the PU:
...
      /* CU of a shared file from 'dwz -m' may be unused by this main file.
        It may be referenced from a local scope but in such case it does not
        need to be present in .gdb_index.  */
      if (psymtab == NULL)
       continue;
...
The continue causes the PU to be skipped in the CU table (we can see that the
PU offset range 0xc7-0xf6 is missing) but the references are not taking that
into account.

I've tried fixing this in the optimal way, by updating the references, but ran
into trouble when follow_die_offset tries to find the CU for the inter-CU
ref.  Because the PU is missing from the CU table,
dwarf2_find_containing_comp_unit bisects to the wrong CU.

Fix this by not skipping the PU in the CU table.

Build and reg-tested on x86_64-linux, with native and target boards
cc-with-gdb-index, cc-with-dwz and cc-with-dwz-m.

gdb/ChangeLog:

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

	PR symtab/25791
	* dwarf2/index-write.c (write_gdbindex): Generate CU table entries for
	CUs without psymtab.

gdb/testsuite/ChangeLog:

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

	PR symtab/25791
	* gdb.dwarf2/gdb-add-index.exp (add_gdb_index): Move ...
	(ensure_gdb_index): and factor out and move ...
	* lib/gdb.exp (add_gdb_index, ensure_gdb_index): ... here.
	* gdb.dwarf2/imported-unit-runto-main.exp: New file.
2020-04-16 14:56:32 +02:00
Kevin Buettner 97ed802d15 Fix compilation of python/python.c for Python 3.9
This commit fixes a compilation warning/error when building GDB
with Python 3.9:

g++ -x c++  -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection  -DDNF_DEBUGINFO_INSTALL   -I. -I../../gdb -I../../gdb/config -DLOCALEDIR="\"/usr/share/locale\"" -DHAVE_CONFIG_H -I../../gdb/../include/opcode   -I../bfd -I../../gdb/../bfd -I../../gdb/../include -I../libdecnumber -I../../gdb/../libdecnumber  -I../../gdb/../gnulib/import -I../gnulib/import  -DTUI=1    -I/usr/include/guile/2.0 -pthread  -I/usr/include/python3.9 -I/usr/include/python3.9  -I../../gdb/.. -pthread -Wall -Wpointer-arith -Wno-unused -Wunused-value -Wunused-variable -Wunused-function -Wno-switch -Wno-char-subscripts -Wempty-body -Wunused-but-set-parameter -Wunused-but-set-variable -Wno-sign-compare -Wno-error=maybe-uninitialized -Wno-mismatched-tags -Wsuggest-override -Wimplicit-fallthrough=3 -Wduplicated-cond -Wshadow=local -Wdeprecated-copy -Wdeprecated-copy-dtor -Wredundant-move -Wformat -Wformat-nonliteral -Wno-unused -Werror -c -o ser-tcp.o -MT ser-tcp.o -MMD -MP -MF ./.deps/ser-tcp.Tpo ../../gdb/ser-tcp.c
../../gdb/python/python.c: In function 'bool do_start_initialization()':
../../gdb/python/python.c:1621:23: error: 'void PyEval_InitThreads()' is deprecated [-Werror=deprecated-declarations]
 1621 |   PyEval_InitThreads ();
      |                       ^
In file included from /usr/include/python3.9/Python.h:141,
                 from ../../gdb/python/python-internal.h:86,
                 from ../../gdb/python/python.c:92:
/usr/include/python3.9/ceval.h:132:37: note: declared here
  132 | Py_DEPRECATED(3.9) PyAPI_FUNC(void) PyEval_InitThreads(void);
      |                                     ^~~~~~~~~~~~~~~~~~

Information about the deprecated function can be found here:

https://docs.python.org/3.9/whatsnew/3.9.html#deprecated

Specifically, with regard to PyEval_InitThreads(), it says:

    The PyEval_InitThreads() and PyEval_ThreadsInitialized() functions
    are now deprecated and will be removed in Python 3.11.  Calling
    PyEval_InitThreads() now does nothing.  The GIL is initialized by
    Py_Initialize() since Python 3.7.  (Contributed by Victor Stinner
    in bpo-39877.)

I chose to disable the call with a #if test using PY_VERSION_HEX.
There is precedent for use of PY_VERSION_HEX; it's used in two places
in python-internal.h.  I noticed that under certain circumstances
python-internal.h defines PyEval_InitThreads to be nothing, which
accomplishes the same thing.  I considered doing something similar for
this case, but decided against it because, at some point in the future,
the presence of PyEval_InitThreads() without some explanation will be
confusing to a reader who won't be able to find PyEval_InitThreads in
the current (future for us) Python API.  IMO, use of the #if along
with an accompanying comment seemed more straightforward.

gdb/ChangeLog:

	* python/python.c (do_start_initialization): Don't call
	PyEval_InitThreads for Python 3.9 and beyond.

Change-Id: I0679fc10b6b76761a99538568f13188c6d8014e0
2020-04-16 05:13:47 -07:00
Kamil Rytarowski c7d6480903 Fix OpenBSD build error.
This was likely introduced by 5b6d1e4fa4

gdb/ChangeLog:

2020-04-15  Kamil Rytarowski  <n54@gmx.com>

	* obsd-nat.c (obsd_nat_target::update_thread_list): Pass "this" to
	thread functions.
	(obsd_nat_target::wait): Likewise.

Change-Id: Ib8d11238c55e0ebdbcf127d1f28c9693c785527a
2020-04-15 14:59:44 -05:00
Tom Tromey ce127a96c9 Use debug_printf in windows-nat.c
While debugging a bug on Windows, I noticed that windows-nat.c is not
sending its debugging output to gdb_stdlog.  This is unfortunate
because it means that "set logging debugredirect" doesn't work
properly.

This patch fixes the problem by changing windows-nat.c to use
debug_printf.

Note that get_windows_debug_event also writes one debugging message
unconditionally.  It isn't clear to me if this really ought to use
DEBUG_EVENTS or not, since it seems like perhaps it is intended to
note an unexpected event occurring.  So, I didn't change this.

I'm checking this in.

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

	* windows-nat.c (DEBUG_EXEC, DEBUG_EVENTS, DEBUG_MEM)
	(DEBUG_EXCEPT): Use debug_printf.
2020-04-15 12:49:05 -06:00
Andrew Burgess 99f1bc6aaa gdb: Don't corrupt completions hash when expanding the hash table
Commit:

  commit 724fd9ba43
  Date:   Mon Jan 27 17:37:20 2020 +0000

      gdb: Restructure the completion_tracker class

caused the completion hash table to become corrupted if the table ever
needed to grow beyond its original size of 200 elements.

The hash table stores completion_tracker::completion_hash_entry
objects, but hashes them based on their name, which is only one field
of the object.

When possibly inserting a new element we compute the hash with
htab_hash_string of the new elements name, and then lookup matching
elements using htab_find_slot_with_hash.  If there's not matching
element we create a completion_hash_entry object within the hash
table.

However, when we allocate the hash we pass htab_hash_string to
htab_create_alloc as the hash function, and this is not OK.  This
means that when the hash table needs to grow, existing elements within
the hash are re-hashed by passing the completion_hash_entry pointer to
htab_hash_string, which obviously does not do what we expect.

The solution is to create a new hash function that takes a pointer to
a completion_hash_entry, and then calls htab_hash_string on the name
of the entry only.

This regression was spotted when running the gdb.base/completion.exp
test on the aarch64 target.

gdb/ChangeLog:

	* completer.c (class completion_tracker::completion_hash_entry)
	<hash_name>: New member function.
	(completion_tracker::discard_completions): New callback to hash a
	completion_hash_entry, pass this to htab_create_alloc.

gdb/testsuite/ChangeLog:

	* gdb.base/many-completions.exp: New file.
2020-04-15 16:36:28 +01:00
Jon Turney a0e9b53238
Better handling of realpath() failure in windows_make_so() on Cygwin
It seems Cygwin's realpath() can fail on certain DLLs (apparently some
AV software prevent it working on it's DLLs; See [1], [2]).  Warn rather
than stopping with an error if that occurs.

Based on an original patch from Tim Chick.

[1] https://cygwin.com/ml/cygwin/2014-08/msg00401.html
[2] https://cygwin.com/ml/cygwin/2015-11/msg00353.html

gdb/ChangeLog:

2016-01-20  Jon Turney  <jon.turney@dronecode.org.uk>

	* windows-nat.c (windows_make_so): Warn rather than stopping with
	an error if realpath() fails.
2020-04-15 15:07:02 +01:00
Kamil Rytarowski 06ca5dd49a Implement IP_STAT+IP_STATUS (aliases of the same format) on NetBSD
Output based on FreeBSD with the following changes:
 - "utime+stime, children" merged from "utime, children" and
   "stime, children".
 - "Minor faults, children", "Major faults, children",
   "Virtual memory size" removed as not available in a direct
   equivalent.

No new values missing or skipped in FreeBSD are printed, although
there is a long list of potential candiates.

gdb/ChangeLog:

        * nbsd-nat.c (nbsd_pid_to_kinfo_proc2): New.
        (nbsd_nat_target::info_proc): Add do_status.
2020-04-14 17:35:56 +02:00
Tom de Vries 194d088fb1 [gdb] Fix missing symtab includes
[ The test-case requires commit c1a66c0629 "[gdb] Expand symbolless symtabs
using maint expand-symtabs". ]

Consider the debug info for the test-case included in this patch.  It consists
of a PU:
...
 <0><d2>: Abbrev Number: 2 (DW_TAG_partial_unit)
 <1><d3>: Abbrev Number: 0
...
imported by a CU:
...
 <0><df>: Abbrev Number: 2 (DW_TAG_compile_unit)
    <e0>   DW_AT_language    : 2        (non-ANSI C)
    <e1>   DW_AT_stmt_list   : 0xe9
 <1><e5>: Abbrev Number: 3 (DW_TAG_imported_unit)
    <e6>   DW_AT_import      : <0xd2>   [Abbrev Number: 2]
 <1><ea>: Abbrev Number: 0
...
and the CU has a dw2-symtab-includes.h file in the .debug_line file name
table:
...
 The Directory Table (offset 0x101):
  1     /data/gdb_versions/devel/src/gdb/testsuite/gdb.dwarf2

 The File Name Table (offset 0x138):
  Entry Dir     Time    Size    Name
  1     1       0       0       dw2-symtab-includes.h
...

After expanding all symtabs, we can see the CU listed in the user field of the
PU, and vice-versa the PU listed in the includes of the CU:
...
$ gdb.sh -batch \
  -iex "set language c" \
  outputs/gdb.dwarf2/dw2-symtab-includes/dw2-symtab-includes \
  -ex "maint expand-symtabs" \
  -ex "maint info symtabs"
  ...
  { ((struct compunit_symtab *) 0x394dd60)
    debugformat DWARF 2
    producer (null)
    dirname (null)
    blockvector ((struct blockvector *) 0x394dea0)
    user ((struct compunit_symtab *) 0x394dba0)
  }
  { ((struct compunit_symtab *) 0x394dba0)
    debugformat DWARF 2
    producer (null)
    dirname (null)
    blockvector ((struct blockvector *) 0x394dd10)
    user ((struct compunit_symtab *) (null))
    ( includes
      ((struct compunit_symtab *) 0x394dd60)
    )
  }
...

But if we instead only expand the symtab for the dw2-symtab-includes.h file,
the includes and user links are gone:
...
$ gdb -batch \
  -iex "set language c" \
  outputs/gdb.dwarf2/dw2-symtab-includes/dw2-symtab-includes \
  -ex "maint expand-symtabs dw2-symtab-includes.h" \
  -ex "maint info symtabs"
  ...
  { ((struct compunit_symtab *) 0x2728210)
    debugformat DWARF 2
    producer (null)
    dirname (null)
    blockvector ((struct blockvector *) 0x2728350)
    user ((struct compunit_symtab *) (null))
  }
  { ((struct compunit_symtab *) 0x2728050)
    debugformat DWARF 2
    producer (null)
    dirname (null)
    blockvector ((struct blockvector *) 0x27281c0)
    user ((struct compunit_symtab *) (null))
  }
...

The includes are calculated by process_cu_includes in gdb/dwarf2/read.c.

In the case of expanding all symtabs:
- the CU partial symtab is expanded using psymtab_to_symtab
- psymtab_to_symtab calls dwarf2_psymtab::read_symtab
- dwarf2_psymtab::read_symtab calls dwarf2_psymtab::expand_psymtab
- dwarf2_psymtab::read_symtab calls process_cu_includes, and we have the
  includes

In the case of expanding the symtab for dw2-symtab-includes.h:
- the dw2-symtab-includes.h partial symtab is expanded using psymtab_to_symtab
- psymtab_to_symtab calls dwarf2_include_psymtab::read_symtab
- dwarf2_include_psymtab::read_symtab calls
  dwarf2_include_psymtab::expand_psymtab
- dwarf2_include_psymtab::expand_psymtab calls
  partial_symtab::expand_dependencies
- partial_symtab::expand_dependencies calls dwarf2_psymtab::expand_psymtab
  for the CU partial symtab
- the CU partial symtab is expanded using dwarf2_psymtab::expand_psymtab
- process_cu_includes is never called

Fix this by making sure in dwarf2_include_psymtab::read_symtab that
read_symtab is called for the CU partial symtab.

Tested on x86_64-linux, with native, and target board cc-with-dwz and
cc-with-dwz-m.

In addition, tested test-case with target boards cc-with-gdb-index.exp,
cc-with-debug-names.exp and readnow.exp.

gdb/ChangeLog:

2020-04-14  Simon Marchi  <simon.marchi@polymtl.ca>
	    Tom de Vries  <tdevries@suse.de>

	PR symtab/25718
	* psympriv.h (struct partial_symtab::read_symtab)
	(struct partial_symtab::expand_psymtab)
	(struct partial_symtab::read_dependencies): Update comments.
	* dwarf2/read.c (struct dwarf2_include_psymtab::read_symtab): Call
	read_symtab for includer.
	(struct dwarf2_include_psymtab::expand_psymtab): Assert false.
	(struct dwarf2_include_psymtab::readin_p): Call readin_p () for includer.
	(struct dwarf2_include_psymtab::m_readin): Remove.
	(struct dwarf2_include_psymtab::includer): New member function.
	(dwarf2_psymtab::expand_psymtab): Assert !readin.

gdb/testsuite/ChangeLog:

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

	PR symtab/25718
	* gdb.dwarf2/dw2-symtab-includes.exp: New file.
2020-04-14 15:30:50 +02:00
Tom de Vries c1a66c0629 [gdb] Expand symbolless symtabs using maint expand-symtabs
Consider this test-case, consisting of header file hello.h:
...
inline static const char*
foo (void)
{
  return "foo";
}
...
and source file hello.c:
...
int
main (void)
{
  printf ("hello: %s\n", foo ());
  return 0;
}
...
compiled with -g:
...
$ gcc hello.c -g
...

When trying to expand the partial symtab for hello.h:
...
$ gdb -batch \
  -iex "set language c" \
  a.out \
  -ex "maint expand-symtabs hello.h" \
  -ex "maint info psymtabs"
...
we in fact find that the partial symtab for hello.h (and corresponding
includer partial symtab hello.c) have not been expanded:
...
  { psymtab hello.h ((struct partial_symtab *) 0x27cf070)
    readin no
  ...
  { psymtab hello.c ((struct partial_symtab *) 0x2cf09e0)
    readin no
...

This is due to the recursively_search_psymtabs call in
psym_expand_symtabs_matching:
...
      if (recursively_search_psymtabs (ps, objfile, domain,
                                      lookup_name, symbol_matcher))
...
which always returns false for symbolless partial symtabs.

The same problem occurs with CUs where the dwarf is generated by gas
--gdwarf-2 for a foo.S: if we read such a test-case with -readnow, we'll have
a symbolless symtab for foo.S.  But if we read the test-case with partial
symtabs, and expand those using "maint expand-symtabs", the foo.S psymtab
remains unexpanded.

Fix this by passing a NULL symbol_matcher and lookup_name to
expand_symtabs_matching in maintenance_expand_symtabs, and skipping the call
to recursively_search_psymtabs if symbol_matcher == NULL and
lookup_name == NULL.

Build and tested on x86_64-linux, with native.

In addition, tested test-case with target boards cc-with-gdb-index.exp,
cc-with-debug-names.exp and readnow.exp.

gdb/ChangeLog:

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

	PR symtab/25720
	* symmisc.c (maintenance_expand_symtabs): Call expand_symtabs_matching
	with NULL symbol_matcher and lookup_name.
	* psymtab.c (psym_expand_symtabs_matching): Handle NULL symbol_matcher
	and lookup_name.
	* dwarf2/read.c (dw2_expand_symtabs_matching)
	(dw2_debug_names_expand_symtabs_matching): Same.
	* symfile.h (struct quick_symbol_functions::expand_symtabs_matching):
	Make lookup_name a pointer.  Update comment.
	* symtab.c (global_symbol_searcher::expand_symtabs): Handle
	lookup_name being a pointer.
	* symfile.c (expand_symtabs_matching): Same.
	* symfile-debug.c (debug_qf_expand_symtabs_matching): Same.
	* linespec.c (iterate_over_all_matching_symtabs): Same.

gdb/testsuite/ChangeLog:

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

	PR symtab/25720
	* gdb.base/maint-expand-symbols-header-file.c: New test.
	* gdb.base/maint-expand-symbols-header-file.exp: New file.
	* gdb.base/maint-expand-symbols-header-file.h: New test.
2020-04-14 15:08:42 +02:00
Tom Tromey 400b5eca00 Move event-loop.[ch] to gdbsupport/
This moves event-loop.[ch] to gdbsupport/ and updates the uses in gdb.

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

	* run-on-main-thread.c: Update include.
	* unittests/main-thread-selftests.c: Update include.
	* tui/tui-win.c: Update include.
	* tui/tui-io.c: Update include.
	* tui/tui-interp.c: Update include.
	* tui/tui-hooks.c: Update include.
	* top.h: Update include.
	* top.c: Update include.
	* ser-base.c: Update include.
	* remote.c: Update include.
	* remote-notif.c: Update include.
	* remote-fileio.c: Update include.
	* record-full.c: Update include.
	* record-btrace.c: Update include.
	* python/python.c: Update include.
	* posix-hdep.c: Update include.
	* mingw-hdep.c: Update include.
	* mi/mi-main.c: Update include.
	* mi/mi-interp.c: Update include.
	* main.c: Update include.
	* linux-nat.c: Update include.
	* interps.c: Update include.
	* infrun.c: Update include.
	* inf-loop.c: Update include.
	* event-top.c: Update include.
	* event-loop.c: Move to ../gdbsupport/.
	* event-loop.h: Move to ../gdbsupport/.
	* async-event.h: Update include.
	* Makefile.in (COMMON_SFILES, HFILES_NO_SRCDIR): Update.

gdbsupport/ChangeLog
2020-04-13  Tom Tromey  <tom@tromey.com>

	* event-loop.h: Move from ../gdb/.
	* event-loop.cc: Move from ../gdb/.
2020-04-13 14:10:04 -06:00
Tom Tromey 93b54c8ed3 Introduce async-event.[ch]
This patch splits out some gdb-specific code from event-loop, into new
files async-event.[ch].  Strictly speaking this code could perhaps be
put into gdbsupport/, but because gdbserver does not currently use it,
it seemed better, for size reasons, to split it out.

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

	* tui/tui-win.c: Include async-event.h.
	* remote.c: Include async-event.h.
	* remote-notif.c: Include async-event.h.
	* record-full.c: Include async-event.h.
	* record-btrace.c: Include async-event.h.
	* infrun.c: Include async-event.h.
	* event-top.c: Include async-event.h.
	* event-loop.h: Move some declarations to async-event.h.
	* event-loop.c: Don't include ser-event.h or top.h.  Move some
	code to async-event.c.
	* async-event.h: New file.
	* async-event.c: New file.
	* Makefile.in (COMMON_SFILES): Add async-event.c.
	(HFILES_NO_SRCDIR): Add async-event.h.
2020-04-13 14:10:04 -06:00
Tom Tromey c1cd3163d9 Introduce and use flush_streams
Code in gdbsupport can't call gdb_flush, so this introduces a new
"flush_streams" function that must be supplied by the client.

Note that the similar gdb_flush_out_err exists, but it isn't defined
in quite the same way, so it wasn't clear to me whether the two could
be merged.

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

	* utils.c (flush_streams): New function.
	* event-loop.c (gdb_wait_for_event): Call flush_streams.

gdbsupport/ChangeLog
2020-04-13  Tom Tromey  <tom@tromey.com>

	* errors.h (flush_streams): Declare.
2020-04-13 14:10:04 -06:00
Tom Tromey 29f2bf4f22 Use warning in event-loop
Change event-loop.c to avoid printf_unfiltered in favor of warning.
warning is aleady available to code in gdbsupport/.

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

	* event-loop.c (handle_file_event): Use warning, not
	printf_unfiltered.
2020-04-13 14:10:04 -06:00
Tom Tromey 98029d02d7 Include <chrono> in event-loop.c
Include <chrono> in event-loop.c, because it is used there.  Currently
it is included indirectly, but after the subsequent patches this will
no longer be the case.

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

	* event-loop.c: Include <chrono>.
2020-04-13 14:10:03 -06:00
Tom Tromey 06cc9596e8 Move gdb_select.h to gdbsupport/
This moves gdb_select.h to gdbsupport/, so it can be used by other
code there.

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

	* gdb_select.h: Move to ../gdbsupport/.
	* event-loop.c: Update include path.
	* top.c: Update include path.
	* ser-base.c: Update include path.
	* ui-file.c: Update include path.
	* ser-tcp.c: Update include path.
	* guile/scm-ports.c: Update include path.
	* posix-hdep.c: Update include path.
	* ser-unix.c: Update include path.
	* gdb_usleep.c: Update include path.
	* mingw-hdep.c: Update include path.
	* inflow.c: Update include path.
	* infrun.c: Update include path.
	* event-top.c: Update include path.

gdbsupport/ChangeLog
2020-04-13  Tom Tromey  <tom@tromey.com>

	* gdb_select.h: Move from ../gdb/.
2020-04-13 14:10:03 -06:00
Tom Tromey 8ae8e19796 Move event-loop configury to common.m4
gdb_select.h and the event loop require some configure checks, so this
moves the needed checks to common.m4 and updates the configure
scripts.

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

	* configure: Rebuild.
	* configure.ac: Remove checks that are now in GDB_AC_COMMON.

gdbserver/ChangeLog
2020-04-13  Tom Tromey  <tom@tromey.com>

	* configure: Rebuild.
	* config.in: Rebuild.

gdbsupport/ChangeLog
2020-04-13  Tom Tromey  <tom@tromey.com>

	* config.in, configure: Rebuild.
	* common.m4 (GDB_AC_COMMON): Check for poll.h, sys/poll.h,
	sys/select.h, and poll.
2020-04-13 14:10:03 -06:00
Tom Tromey 58cf28e860 Move start_event_loop out of event-loop.c
A subsequent patch is going to move event-loop.c to gdbsupport.  In a
review of an earlier version of this series, Pedro pointed out that
the resulting code would be cleaner if start_event_loop were not
shared -- because gdb and gdbserver have some different needs here --
and so this moves start_event_loop to main.c.  Because the only caller
is there, it is also now static.

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

	* event-loop.h (start_event_loop): Don't declare.
	* event-loop.c (start_event_loop): Move...
	* main.c (start_event_loop): ...here.  Now static.
2020-04-13 14:10:03 -06:00
Sergio Durigan Junior b7f999aee3 Update my email address on MAINTAINERS
Commit pushed under the obvious/trivial rule.

gdb/ChangeLog:
2020-04-13  Sergio Durigan Junior  <sergiodj@sergiodj.net>

	* MAINTAINERS: Update my email address.
2020-04-13 15:53:28 -04:00
Kamil Rytarowski 1085dfd4e1 Implement IP_MINIMAL and IP_ALL on NetBSD
gdb/ChangeLog:

       * nbsd-nat.c (nbsd_nat_target::info_proc): Add IP_MINIMAL and
       IP_ALL.
2020-04-13 11:49:36 +02:00
Kamil Rytarowski 49d1d1f53d Implement "info proc cmdline" for NetBSD
Add nbsd_pid_to_cmdline() to query the program command line.

gdb/ChangeLog:

        * nbsd-nat.c (nbsd_pid_to_cmdline): Add.
        (nbsd_nat_target::info_proc): Add do_cmdline.
2020-04-12 21:33:06 +02:00
Kamil Rytarowski b4848d2a7b Implement "info proc cwd" for NetBSD
Add nbsd_pid_to_cwd() to query the program current directory.

gdb/ChangeLog:

	* nbsd-nat.c (nbsd_pid_to_cwd): Add.
	(nbsd_nat_target::info_proc): Add do_cwd.
2020-04-12 20:15:00 +02:00
Kamil Rytarowski 51c133d547 Implement "info proc exe" for NetBSD
Use pid_to_exec_file() to query the program.

gdb/ChangeLog:

	* nbsd-nat.c (nbsd_nat_target::info_proc): Add do_exe.
2020-04-12 19:25:35 +02:00
Kamil Rytarowski 54b8cbd0e4 Implement "info proc mappings" for NetBSD
Define nbsd_nat_target::find_memory_regions and
nbsd_nat_target::info_proc. info_proc handles as of now only
the "mappings" command.

Define a local static function kinfo_get_vmmap() that reads
the process memory layout of a specified process.
kinfo_get_vmmap() wraps the sysctl(3) call.

nbsd-tdep.c defines now utility functions for printing the
process memory layout:
 * nbsd_info_proc_mappings_header()
 * nbsd_vm_map_entry_flags()
 * nbsd_info_proc_mappings_entry()

gdb/ChangeLog:

	* nbsd-nat.c; Include "nbsd-tdep.h" and "gdbarch.h".
	* nbsd-nat.c (nbsd_nat_target::find_memory_regions)
	(nbsd_nat_target::info_proc): New functions.
	* nbsd-nat.c (kinfo_get_vmmap): New function.
	* nbsd-nat.c (nbsd_nat_target::info_proc) Use
	nbsd_info_proc_mappings_header and nbsd_info_proc_mappings_entry.
	* nbsd-tdep.c (nbsd_info_proc_mappings_header)
	(nbsd_info_proc_mappings_entry, nbsd_vm_map_entry_flags): New
	functions.
	* nbsd-tdep.c (KINFO_VME_PROT_READ, KINFO_VME_PROT_WRITE)
	(KINFO_VME_PROT_EXEC, KINFO_VME_FLAG_COW)
	(KINFO_VME_FLAG_NEEDS_COPY, KINFO_VME_FLAG_NOCOREDUMP)
	(KINFO_VME_FLAG_PAGEABLE, KINFO_VME_FLAG_GROWS_UP)
	(KINFO_VME_FLAG_GROWS_DOWN): New.
2020-04-12 13:06:08 +02:00
Artur Shepilko cf83625da2 gdb: fix undefined behavior reported in copy_bitwise
gdb version 9.1, built with clang 8.0.0 on Ubuntu 18.04 (x86_64);
--enable-ubsan (for clang's undefined behavior sanitizer)

Executing command; `maint selftest copy_bitwise` bombs in runtime error:
../../gdb/utils.c:3432:28: runtime error: left shift of negative value -1

Closer look reveals the offending shift: `(~0 << nbits)`, apparently 0
is treated as signed int, resulting in negative complement. Explicitly
stating it unsigned 0U  fixes it and the `copy_bitwise` test passes
ok.
2020-04-10 21:04:03 -04:00
Tom Tromey 0c4311ab90 Avoid infinite recursion in get_msymbol_address
Sometimes, get_msymbol_address can cause infinite recursion, leading
to a crash.  This was reported previously here:

https://sourceware.org/pipermail/gdb-patches/2019-November/162154.html

A user on irc reported this as well, and with his help and the help of
a friend of his, we found that the problem occurred because, when
reloading a separate debug objfile, the objfile would lose the
OBJF_MAINLINE flag.  This would cause some symbols from this separate
debug objfile to be marked "maybe_copied" -- but then
get_msymbol_address could find the same symbol and fail as reported.

This patch fixes the bug by preserving OBJF_MAINLINE.

No test case, unfortunately, because I could not successfully make
one.

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

	* symfile.c (symbol_file_add_separate): Preserve OBJF_MAINLINE.
2020-04-10 07:21:16 -06:00
Tom Tromey 3e65b3e9af Skip separate debug files when handling copy relocations
get_symbol_address and get_msymbol_address call
lookup_minimal_symbol_linkage, which iterates over the separate debug
files of the objfile that is passed in.

This means that if these functions pass in a separate debug objfile,
then they are doing unnecessary work.

This patch avoids the extra work by skipping separate debug objfiles
in the loops.

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

	* symtab.c (get_symbol_address, get_msymbol_address): Skip
	separate debug files.
2020-04-10 07:21:16 -06:00
Hannes Domani 13302e956f Fix debugging of WOW64 processes
The new code regarding pending stops only checks for EXCEPTION_BREAKPOINT,
but for WOW64 processes STATUS_WX86_BREAKPOINT is necessary as well.

Also, ignore_first_breakpoint is used now in nat/windows-nat.c as well,
but was not available there.

gdb/ChangeLog:

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

	* nat/windows-nat.c (STATUS_WX86_BREAKPOINT, STATUS_WX86_SINGLE_STEP):
	Move to...
	* nat/windows-nat.h (STATUS_WX86_BREAKPOINT, STATUS_WX86_SINGLE_STEP):
	... here.
	* windows-nat.c (windows_nat_target::get_windows_debug_event):
	Check for STATUS_WX86_BREAKPOINT.
	(windows_nat_target::wait): Same.
2020-04-10 13:01:31 +02:00
Tom de Vries bdfc1e8a0b [gdb/cli] Don't let python colorize strip leading newlines
Consider the test-case gdb.base/async.exp.  Using the executable, I run to
main, and land on a line advertised as line 26:
...
$ gdb outputs/gdb.base/async/async -ex start
Reading symbols from outputs/gdb.base/async/async...
Temporary breakpoint 1 at 0x4004e4: file gdb.base/async.c, line 26.
Starting program: outputs/gdb.base/async/async

Temporary breakpoint 1, main () at gdb.base/async.c:26
26       y = foo ();
...

But actually, the line turns out to be line 28:
...
$ cat -n gdb.base/async.c
    ...
    26   y = 2;
    27   z = 9;
    28   y = foo ();
...

This is caused by the following: the python colorizer initializes the lexer
with default options (no second argument to get_lexer_for_filename):
...
    def colorize(filename, contents):
        # Don't want any errors.
        try:
            lexer = lexers.get_lexer_for_filename(filename)
            formatter = formatters.TerminalFormatter()
            return highlight(contents, lexer, formatter)
...
which include option stripnl=True, which strips leading and trailing newlines.

This causes the python colorizer to strip the two leading newlines of async.c.

Fix this by initializing the lexer with stripnl=False.

Build and reg-tested on x86_64-linux.

gdb/ChangeLog:

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

	PR cli/25808
	* python/lib/gdb/__init__.py: Initialize lexer with stripnl=False.

gdb/testsuite/ChangeLog:

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

	PR cli/25808
	* gdb.base/style.c: Add leading newlines.
	* gdb.base/style.exp: Use gdb_get_line_number to get specific lines.
	Check listing of main's one-line body.
2020-04-10 09:29:52 +02:00
Simon Marchi f4460aec69 gdb: move Tom de Vries to Global Maintainers
gdb/ChangeLog:

	* MAINTAINERS (Global Maintainers): Add Tom de Vries.
	(Write After Approval): Remove Tom de Vries.
2020-04-09 19:06:16 -04:00
Bernd Edlinger a25198bba2 Partially revert my UB fix in record_line
This reverts the following commit partially:

commit 64dc2d4bd2
Author: Bernd Edlinger <bernd.edlinger@hotmail.de>
Date:   Thu Mar 12 11:52:34 2020 +0100

    Fix an undefined behavior in record_line

    Additionally do not completely remove symbols
    at the same PC than the end marker, instead
    make them non-is-stmt breakpoints.

We keep the undefined behavoir fix,
but have to restore the original behavior
regarding deletion of the line entries.

2020-04-09  Bernd Edlinger  <bernd.edlinger@hotmail.de>

	revert partially:
	2020-04-01  Bernd Edlinger  <bernd.edlinger@hotmail.de>

        * buildsym.c (record_line): Fix undefined behavior and preserve
        lines at eof.
2020-04-09 17:06:58 +02:00
Kamil Rytarowski 206c98a650 Add SVR4 psABI specific parser for AUXV entries
NetBSD and OpenBSD always use an int to store the type as
defined in the SVR4 psABI specifications rather than long
as assumed by the default parser.

Define svr4_auxv_parse() that shares code with default_auxv_parse().

Remove obsd_auxv_parse() and switch OpenBSD to svr4_auxv_parse().
Remove not fully accurate comment from obsd-tdep.c.

Use svr4_auxv_parse() on NetBSD.

gdb/ChangeLog:

	* auxv.h (svr4_auxv_parse): New.
	* auxv.c (default_auxv_parse): Split into default_auxv_parse
	and generic_auxv_parse.
	(svr4_auxv_parse): Add.
	* obsd-tdep.c: Include "auxv.h".
	(obsd_auxv_parse): Remove.
	(obsd_init_abi): Remove comment.
	(obsd_init_abi): Change set_gdbarch_auxv_parse passed argument
	from `obsd_auxv_parse' to `svr4_auxv_parse'.
	* nbsd-tdep.c: Include "auxv.h".
	(nbsd_init_abi): Call set_gdbarch_auxv_parse.
2020-04-09 13:17:29 +02:00
Tom Tromey 71fbdbafe0 Make last_wait_event static
Now that last_wait_event is entirely handled in nat/windows-nat.c, it
can be made static.

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

	* nat/windows-nat.h (last_wait_event): Don't declare.
	(wait_for_debug_event): Update comment.
	* nat/windows-nat.c (last_wait_event): Now static.
2020-04-08 14:47:59 -06:00
Tom Tromey 2c1d95e869 Move wait_for_debug_event to nat/windows-nat.c
This moves the wait_for_debug_event helper function to
nat/windows-nat.c, and changes gdbserver to use it.
wait_for_debug_event is a wrapper for WaitForDebugEvent that also sets
last_wait_event when appropriate.  This is needed to properly handle
queued stops.

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

	* windows-nat.c (wait_for_debug_event): Move to
	nat/windows-nat.c.
	* nat/windows-nat.h (wait_for_debug_event): Declare.
	* nat/windows-nat.c (wait_for_debug_event): Move from
	windows-nat.c.  No longer static.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (win32_kill, get_child_debug_event): Use
	wait_for_debug_event.
2020-04-08 14:47:59 -06:00
Tom Tromey d2977bc425 Introduce fetch_pending_stop
This introduces a new "fetch_pending_stop" function and changes gdb to
use it.  This function removes the first matching pending stop from
the list of such stops.

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

	* windows-nat.c (get_windows_debug_event): Use
	fetch_pending_stop.
	* nat/windows-nat.h (fetch_pending_stop): Declare.
	* nat/windows-nat.c (fetch_pending_stop): New function.
2020-04-08 14:47:59 -06:00
Tom Tromey e758e19c59 Share some inferior-related Windows code
This adds a couple of functions to nat/windows-nat.c and changes gdb
and gdbserver to use them.  One function checks the list of pending
stops for a match (not yet used by gdbserver, but will be in a
subsequent patch); and the other is a wrapper for ContinueDebugEvent
that always uses the last "real" stop event.

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

	* windows-nat.c (windows_continue): Use matching_pending_stop and
	continue_last_debug_event.
	* nat/windows-nat.h (matching_pending_stop)
	(continue_last_debug_event): Declare.
	* nat/windows-nat.c (DEBUG_EVENTS): New define.
	(matching_pending_stop, continue_last_debug_event): New
	functions.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (child_continue): Call continue_last_debug_event.
2020-04-08 14:47:59 -06:00
Tom Tromey 8d30e39577 Share handle_exception
Both gdb and gdbserver have a "handle_exception" function, the bulk of
which is shared between the two implementations.  This patch arranges
for the entire thing to be moved into nat/windows-nat.c, with the
differences handled by callbacks.  This patch introduces one more
callback to make this possible.

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

	* windows-nat.c (MS_VC_EXCEPTION): Move to nat/windows-nat.c.
	(handle_exception_result): Move to nat/windows-nat.h.
	(DEBUG_EXCEPTION_SIMPLE): Remove.
	(windows_nat::handle_ms_vc_exception): New function.
	(handle_exception): Move to nat/windows-nat.c.
	(get_windows_debug_event): Update.
	(STATUS_WX86_BREAKPOINT, STATUS_WX86_SINGLE_STEP): Move to
	nat/windows-nat.c.
	* nat/windows-nat.h (handle_ms_vc_exception): Declare.
	(handle_exception_result): Move from windows-nat.c.
	(handle_exception): Declare.
	* nat/windows-nat.c (MS_VC_EXCEPTION, handle_exception)
	(STATUS_WX86_SINGLE_STEP, STATUS_WX86_BREAKPOINT): Move from
	windows-nat.c.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (handle_exception): Remove.
	(windows_nat::handle_ms_vc_exception): New function.
	(get_child_debug_event): Add "continue_status" parameter.
	Update.
	(win32_wait): Update.
2020-04-08 14:47:59 -06:00
Tom Tromey 29de418dee Remove some globals from windows-nat.c
windows-nat.c has a few "count" globals that don't seem to be used.
Possibly they were used for debugging at some point, but they no
longer seem useful to me.  Because they get in the way of some code
sharing, this patch removes them.

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

	* windows-nat.c (exception_count, event_count): Remove.
	(handle_exception, get_windows_debug_event)
	(do_initial_windows_stuff): Update.
2020-04-08 14:47:59 -06:00
Tom Tromey a816ba1897 Share handle_load_dll and handle_unload_dll declarations
This changes nat/windows-nat.h to declare handle_load_dll and
handle_unload_dll.  The embedding application is required to implement
these -- while the actual code was difficult to share due to some
other differences between the two programs, sharing the declaration
lets a subsequent patch share more code that uses these as callbacks.

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

	* windows-nat.c (windows_nat::handle_load_dll)
	(windows_nat::handle_unload_dll): Rename.  No longer static.
	* nat/windows-nat.h (handle_load_dll, handle_unload_dll):
	Declare.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (windows_nat::handle_load_dll): Rename from
	handle_load_dll.  No longer static.
	(windows_nat::handle_unload_dll): Rename from handle_unload_dll.
	No longer static.
2020-04-08 14:47:58 -06:00
Tom Tromey a00caa1279 Fix up complaints.h for namespace use
If 'complaint' is used in a namespace context, it will fail because
'stop_whining' is only declared at the top level.  This patch fixes
this problem in a simple way, by moving the declaration of
'stop_whining' out of the macro and to the top-level.

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

	* complaints.h (stop_whining): Declare at top-level.
	(complaint): Don't declare stop_whining.
2020-04-08 14:47:58 -06:00
Tom Tromey d41b524f45 Normalize handle_output_debug_string API
This changes gdbserver's implementation of handle_output_debug_string
to have the same calling convention as that of gdb.  This allows for
sharing some more code in a subsequent patch.

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

	* windows-nat.c (windows_nat::handle_output_debug_string):
	Rename.  No longer static.
	* nat/windows-nat.h (handle_output_debug_string): Declare.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (handle_output_debug_string): Add parameter.  Change
	return type.
	(win32_kill, get_child_debug_event): Update.
2020-04-08 14:47:58 -06:00
Tom Tromey 3c76026df8 Share some Windows-related globals
This moves some Windows-related globals into nat/windows-nat.c,
sharing them between gdb and gdbserver.

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

	* windows-nat.c (current_process_handle, current_process_id)
	(main_thread_id, last_sig, current_event, last_wait_event)
	(current_windows_thread, desired_stop_thread_id, pending_stops)
	(struct pending_stop, siginfo_er): Move to nat/windows-nat.c.
	(display_selectors, fake_create_process)
	(get_windows_debug_event): Update.
	* nat/windows-nat.h (current_process_handle, current_process_id)
	(main_thread_id, last_sig, current_event, last_wait_event)
	(current_windows_thread, desired_stop_thread_id, pending_stops)
	(struct pending_stop, siginfo_er): Move from windows-nat.c.
	* nat/windows-nat.c (current_process_handle, current_process_id)
	(main_thread_id, last_sig, current_event, last_wait_event)
	(current_windows_thread, desired_stop_thread_id, pending_stops)
	(siginfo_er): New globals.  Move from windows-nat.c.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (current_process_handle, current_process_id)
	(main_thread_id, last_sig, current_event, siginfo_er): Move to
	nat/windows-nat.c.
2020-04-08 14:47:58 -06:00
Tom Tromey 9d8679cc71 Share get_image_name between gdb and gdbserver
This moves get_image_name to nat/windows-nat.c so that it can be
shared between gdb and gdbserver.

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

	* windows-nat.c (get_image_name): Move to nat/windows-nat.c.
	(handle_load_dll): Update.
	* nat/windows-nat.c (get_image_name): Move from windows-nat.c.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (get_image_name): Remove.
	(handle_load_dll): Update.
2020-04-08 14:47:58 -06:00
Tom Tromey 28688adf8f Share thread_rec between gdb and gdbserver
This changes gdb and gdbserver to use the same calling convention for
the "thread_rec" helper function.  Fully merging these is difficult
due to differences in how threads are managed by the enclosing
applications; but sharing a declaration makes it possible for future
shared code to call this method.

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

	* windows-nat.c (enum thread_disposition_type): Move to
	nat/windows-nat.h.
	(windows_nat::thread_rec): Rename from thread_rec.  No longer
	static.
	(windows_add_thread, windows_nat_target::fetch_registers)
	(windows_nat_target::store_registers, handle_exception)
	(windows_nat_target::resume, get_windows_debug_event)
	(windows_nat_target::get_tib_address)
	(windows_nat_target::thread_name)
	(windows_nat_target::thread_alive): Update.
	* nat/windows-nat.h (enum thread_disposition_type): Move from
	windows-nat.c.
	(thread_rec): Declare.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (windows_nat::thread_rec): Rename from thread_rec.
	No longer static.  Change parameters.
	(child_add_thread, child_fetch_inferior_registers)
	(child_store_inferior_registers, win32_resume)
	(win32_get_tib_address): Update.
2020-04-08 14:47:58 -06:00
Tom Tromey 4834dad062 Wrap shared windows-nat code in windows_nat namespace
This wraps the shared windows-nat code in a windows_nat namespace.
This helps avoid name clashes.

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

	* windows-nat.c: Add "using namespace".
	* nat/windows-nat.h: Wrap contents in windows_nat namespace.
	* nat/windows-nat.c: Wrap contents in windows_nat namespace.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.h (struct win32_target_ops): Use qualified names where
	needed.
	* win32-i386-low.c: Add "using namespace".
	* win32-low.c: Add "using namespace".
	* win32-arm-low.c: Add "using namespace".
2020-04-08 14:47:58 -06:00
Tom Tromey 65bafd5b15 Call CloseHandle from ~windows_thread_info
Add a destructor to windows_thread_info that calls CloseHandle.

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

	* nat/windows-nat.h (struct windows_thread_info): Declare
	destructor.
	* nat/windows-nat.c (~windows_thread_info): New.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (delete_thread_info): Don't call CloseHandle.
2020-04-08 14:47:58 -06:00
Tom Tromey 0a4afda3c6 Handle pending stops from the Windows kernel
PR gdb/22992 concerns an assertion failure in gdb when debugging a
certain inferior:

    int finish_step_over(execution_control_state*): Assertion `ecs->event_thread->control.trap_expected' failed.

Initially the investigation centered on the discovery that gdb was not
suspending other threads when attempting to single-step.  This
oversight is corrected in this patch: now, when stepping a thread, gdb
will call SuspendThread on all other threads.

However, the bug persisted even after this change.  In particular,
WaitForDebugEvent could see a stop for a thread that was ostensibly
suspended.  Our theory of what is happening here is that there are
actually simultaneous breakpoint hits, and the Windows kernel queues
the events, causing the second stop to be reported on a suspended
thread.

In Windows 10 or later gdb could use the DBG_REPLY_LATER flag to
ContinueDebugEvent to request that such events be re-reported later.
However, relying on that did not seem advisable, so this patch instead
arranges to queue such "pending" stops, and then to report them later,
once the step has completed.

In the PR, Pedro pointed out that it's best in this scenario to
implement the stopped_by_sw_breakpoint method, so this patch does this
as well.

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

	PR gdb/22992
	* windows-nat.c (current_event): Update comment.
	(last_wait_event, desired_stop_thread_id): New globals.
	(struct pending_stop): New.
	(pending_stops): New global.
	(windows_nat_target) <stopped_by_sw_breakpoint>
	<supports_stopped_by_sw_breakpoint>: New methods.
	(windows_fetch_one_register): Add assertions.  Adjust PC.
	(windows_continue): Handle pending stops.  Suspend other threads
	when stepping.  Use last_wait_event
	(wait_for_debug_event): New function.
	(get_windows_debug_event): Use wait_for_debug_event.  Handle
	pending stops.  Queue spurious stops.
	(windows_nat_target::wait): Set stopped_at_software_breakpoint.
	(windows_nat_target::kill): Use wait_for_debug_event.
	* nat/windows-nat.h (struct windows_thread_info)
	<stopped_at_software_breakpoint>: New field.
	* nat/windows-nat.c (windows_thread_info::resume): Clear
	stopped_at_software_breakpoint.
2020-04-08 14:47:58 -06:00
Tom Tromey 8e61ebec34 Change type of argument to windows-nat.c:thread_rec
windows-nat.c:thread_rec accepts an integer parameter whose
interpretation depends on whether it is less than, equal to, or
greater than zero.  I found this confusing at times, so this patch
replaces it with an enum instead.

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

	* windows-nat.c (enum thread_disposition_type): New.
	(thread_rec): Replace "get_context" parameter with "disposition";
	change type.
	(windows_add_thread, windows_nat_target::fetch_registers)
	(windows_nat_target::store_registers, handle_exception)
	(windows_nat_target::resume, get_windows_debug_event)
	(windows_nat_target::get_tib_address)
	(windows_nat_target::thread_name)
	(windows_nat_target::thread_alive): Update.
2020-04-08 14:47:58 -06:00
Tom Tromey 98a0328732 Share Windows thread-suspend and -resume code
This adds "suspend" and "resume" methods to windows_thread_info, and
changes gdb and gdbserver to share this code.

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

	* windows-nat.c (thread_rec): Use windows_thread_info::suspend.
	(windows_continue): Use windows_continue::resume.
	* nat/windows-nat.h (struct windows_thread_info) <suspend,
	resume>: Declare new methods.
	* nat/windows-nat.c: New file.
	* configure.nat (NATDEPFILES): Add nat/windows-nat.o when needed.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (win32_require_context, suspend_one_thread): Use
	windows_thread_info::suspend.
	(continue_one_thread): Use windows_thread_info::resume.
	* configure.srv (srv_tgtobj): Add windows-nat.o when needed.
2020-04-08 14:47:58 -06:00
Tom Tromey 7c7411bcab Use lwp, not tid, for Windows thread id
This changes windows-nat.c to put the Windows thread id into the "lwp"
field of ptid_t, not the "tid" field.  This is done for two reasons.

First, ptid.h has this to say:

   process_stratum targets that handle threading themselves should
   prefer using the ptid.lwp field, leaving the ptid.tid field for any
   thread_stratum target that might want to sit on top.

Second, this change brings gdb and gdbserver into sync here, which
makes sharing code simpler.

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

	* windows-nat.c (windows_add_thread, windows_delete_thread)
	(windows_nat_target::fetch_registers)
	(windows_nat_target::store_registers, fake_create_process)
	(windows_nat_target::resume, windows_nat_target::resume)
	(get_windows_debug_event, windows_nat_target::wait)
	(windows_nat_target::pid_to_str)
	(windows_nat_target::get_tib_address)
	(windows_nat_target::get_ada_task_ptid)
	(windows_nat_target::thread_name)
	(windows_nat_target::thread_alive): Use lwp, not tid.
2020-04-08 14:47:58 -06:00
Tom Tromey 2950fdf742 Make windows_thread_info::name a unique_xmalloc_ptr
This changes windows_thread_info::name to be a unique_xmalloc_ptr,
removing some manual memory management.

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

	* windows-nat.c (handle_exception)
	(windows_nat_target::thread_name): Update.
	* nat/windows-nat.h (windows_thread_info): Remove destructor.
	<name>: Now unique_xmalloc_ptr.
2020-04-08 14:47:58 -06:00
Tom Tromey 62fe396b1c Change two windows_thread_info members to "bool"
This changes a couple of fields of windows_thread_info to have type
"bool".  It also updates the comment of another field, to clarify the
possible values it can hold.

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

	* windows-nat.c (thread_rec)
	(windows_nat_target::fetch_registers): Update.
	* nat/windows-nat.h (struct windows_thread_info) <suspended>:
	Update comment.
	<debug_registers_changed, reload_context>: Now bool.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-i386-low.c (update_debug_registers)
	(i386_prepare_to_resume, i386_thread_added): Update.
2020-04-08 14:47:57 -06:00
Tom Tromey e9534bd257 Use new and delete for windows_thread_info
This adds a constructor, destructor, and member initializers to
windows_thread_info, and changes gdb and gdbserver to use new and
delete.

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

	* windows-nat.c (windows_add_thread): Use new.
	(windows_init_thread_list, windows_delete_thread): Use delete.
	(get_windows_debug_event): Update.
	* nat/windows-nat.h (struct windows_thread_info): Add constructor,
	destructor, and initializers.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.c (child_add_thread): Use new.
	(delete_thread_info): Use delete.
2020-04-08 14:47:57 -06:00
Tom Tromey ae1f888075 Share windows_thread_info between gdb and gdbserver
This introduces a new file, nat/windows-nat.h, which holds the
definition of windows_thread_info.  This is now shared between gdb and
gdbserver.

Note that the two implementations different slightly.  gdb had a
couple of fields ("name" and "reload_context") that gdbserver did not;
while gdbserver had one field ("base_context") that gdb did not, plus
better comments.  The new file preserves all the fields, and the
comments.

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

	* windows-nat.c (struct windows_thread_info): Remove.
	* nat/windows-nat.h: New file.

gdbserver/ChangeLog
2020-04-08  Tom Tromey  <tromey@adacore.com>

	* win32-low.h (struct windows_thread_info): Remove.
2020-04-08 14:47:57 -06:00
Tom Tromey 55a1e039f9 Rename windows_thread_info::id to "tid"
This changes the name of a field in windows_thread_info, bringing gdb
and gdbserver closer into sync.

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

	* windows-nat.c (struct windows_thread_info) <tid>: Rename from "id".
	(thread_rec, windows_add_thread, windows_delete_thread)
	(windows_continue): Update.
2020-04-08 14:47:57 -06:00
Tom Tromey 93366324f5 Remove the "next" field from windows_thread_info
This changes windows_thread_info to remove the "next" field, replacing
the linked list of threads with a vector.  This is a prerequisite to
sharing this structure with gdbserver, which manages threads
differently.

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

	* windows-nat.c (struct windows_thread_info): Remove typedef.
	(thread_head): Remove.
	(thread_list): New global.
	(thread_rec, windows_add_thread, windows_init_thread_list)
	(windows_delete_thread, windows_continue): Update.
2020-04-08 14:47:57 -06:00
Simon Marchi 0f2265e246 gdb: stop using host-dependent signal numbers in windows-tdep.c
The signal enumeration in windows-tdep.c is defined differently whether
it is compiled on Cygwin or not.  This is problematic, since the code in
tdep files is not supposed to be influenced by the host platform (the
platform GDB itself runs on).

This makes a difference in windows_gdb_signal_to_target.  An obvious
example of clash is SIGABRT.  Let's pretend we are cross-debugging a
Cygwin process from a MinGW (non-Cygwin Windows) GDB.  If GDB needs to
translate the gdb signal number GDB_SIGNAL_ABRT into a target
equivalent, it would obtain the MinGW number (22), despite the target
being a Cygwin process.  Conversely, if debugging a MinGW process from a
Cygwin-hosted GDB, GDB_SIGNAL_ABRT would be converted to a Cygwin signal
number (6) despite the target being a MinGW process.  This is wrong,
since we want the result to depend on the target's platform, not GDB's
platform.

This known flaw was accepted because at the time we had a single OS ABI
(called Cygwin) for all Windows binaries (Cygwin ones and non-Cygwin
ones).  This limitation is now lifted, as we now have separate Windows
and Cygwin OS ABIs.  This means we are able to detect at runtime whether
the binary we are debugging is a Cygwin one or non-Cygwin one.

This patch splits the signal enum in two, one for the MinGW flavors and
one for Cygwin, removing all the ifdefs that made it depend on the host
platform.  It then makes two separate gdb_signal_to_target gdbarch
methods, that are used according to the OS ABI selected at runtime.

There is a bit of re-shuffling needed in how the gdbarch'es are
initialized, but nothing major.

gdb/ChangeLog:

	* windows-tdep.h (windows_init_abi): Add comment.
	(cygwin_init_abi): New declaration.
	* windows-tdep.c: Split signal enumeration in two, one for
	Windows and one for Cygwin.
	(windows_gdb_signal_to_target): Only deal with signal of the
	Windows OS ABI.
	(cygwin_gdb_signal_to_target): New function.
	(windows_init_abi): Rename to windows_init_abi_common, don't set
	gdb_signal_to_target gdbarch method.  Add new new function with
	this name.
	(cygwin_init_abi): New function.
	* amd64-windows-tdep.c (amd64_windows_init_abi_common): Add
	comment.  Don't call windows_init_abi.
	(amd64_windows_init_abi): Add comment, call windows_init_abi.
	(amd64_cygwin_init_abi): Add comment, call cygwin_init_abi.
	* i386-windows-tdep.c (i386_windows_init_abi): Rename to
	i386_windows_init_abi_common, don't call windows_init_abi.  Add
	a new function of this name.
	(i386_cygwin_init_abi): New function.
	(_initialize_i386_windows_tdep): Bind i386_cygwin_init_abi to
	OS ABI Cygwin.
2020-04-08 14:05:54 -04:00
Simon Marchi 3810f182ee Remove objfile parameter from read_gdb_index_from_buffer
I noticed this was unused, so remove it.

gdb/ChangeLog:

	* dwarf2/read.c (read_gdb_index_from_buffer): Remove objfile
	parameter.c.
	(dwarf2_read_gdb_index): Update.
2020-04-08 08:07:33 -04:00
Kamil Rytarowski 063f8e80b0 Define NetBSD specific skip_solib_resolver
gdb/ChangeLog:

	* nbsd-tdep.c: Include "objfiles.h".
	(nbsd_skip_solib_resolver): New.
	(nbsd_init_abi): Call set_gdbarch_skip_solib_resolver().
2020-04-07 19:12:03 +02:00
nitachra 85a9510ccb DWARFv5: Info address command error in gdb with DWARFfv5.
GDB throws the error 'Unrecognized DWARF opcode 0x02 at 2' when running
Info address command with the executable file compiled with -gdwarf-5 flag.
This patch fixes this error.

Tested by running the testsuite before and after the patch and there is
no increase in the number of test cases that fails. Tested with both
-gdwarf-4 and -gdwarf-5 flags. Also tested -gslit-dwarf along with
-gdwarf-4 as well as -gdwarf-5 flags. Used clang version 10.0.0.
This is the test case used-

void bar(int arr[], int l, int m, int r) {
    int i, j, k, n1= m - l + 1, n2= r - m, L[n1], R[n2];
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];
}

int main()
{
    int arr[] = {12, 11};
    bar(arr,0,1,2);
    return 0;
}

clang -gdwarf-5 test.c -o test.out

gdb test.out
gdb> start
gdb> step
gdb> step
gdb> step
gdb> step
gdb> info address L
Symbol "L" is multi-location:
  Range 0x7c04007902bc5084-0x67fb876440700: a complex DWARF expression:
     0: DW_OP_breg16 1 [$rip]
Unrecognized DWARF opcode 0x02 at 2

gdb/ChangeLog:
2020-04-07  Nitika Achra  <Nitika.Achra@amd.com>

	* dwarf2/loc.c (loclist_describe_location): Call the function decode_debug_loclists_
	addresses if DWARF version is 5 or more because DW_LLE_start* or DW_LLE_offset_pair
	with DW_LLE_base_addressx are being emitted in DWARFv5.
	Add the newly added kind DW_LOC_OFFSET_PAIR also.
	The length of location description is an unsigned ULEB integer in DWARFv5 instead of
	unsigned integer.
2020-04-07 09:55:35 -06:00
nitachra 9fc3eaae69 DWARFv5: Handle location list for split dwarf.
GDB throws the error '<error reading variable: dwarf2_find_location_
expression: Corrupted DWARF expression.>' while printing the variable
value with executable file compiled with -gdwarf-5 and -gdwarf-split
flags. This is because DW_LLE_start* or DW_LLE_offset_pair with
DW_LLE_base_addressx are being emitted in DWARFv5 location list instead of
DW_LLE_GNU*. This patch fixes this error.

Tested by running the testsuite before and after the patch and there is no
increase in the number of test cases that fails. Tested with both -gdwarf-4
and -gdwarf-5 flags. Also tested -gslit-dwarf along with -gdwarf-4 as well as
-gdwarf-5 flags. Used clang version 10.0.0. This is the test case used-

void bar(int arr[], int l, int m, int r) {
    int i, j, k, n1= m - l + 1, n2= r - m, L[n1], R[n2];
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];
}

int main()
{
    int arr[] = {12, 11};
    bar(arr,0,1,2);
    return 0;
}

clang -gdwarf-5 -gsplit-dwarf test.c -o test.out

gdb test.out
gdb> start
gdb> step
gdb> step
gdb> step
gdb> step
gdb> p L[0]
dwarf2_find_location_expression: Corrupted DWARF expression.

gdb/ChangeLog:
2020-04-07  Nitika Achra  <Nitika.Achra@amd.com>

	* dwarf2/loc.c (enum debug_loc_kind): Add a new kind DEBUG_LOC_OFFSET_PAIR.
	(dwarf2_find_location_expression): Call the function decode_debug_loclists_
	addresses if DWARF version is 5 or more. DW_LLE_start* or DW_LLE_offset_pair
	with DW_LLE_base_addressx are being emitted in DWARFv5 instead of DW_LLE_GNU*.
	Add applicable base address if the entry is DW_LLE_offset_pair from DWO.
	(decode_debug_loclists_addresses): Return DEBUG_LOC_OFFSET_PAIR instead of
	DEBUG_LOC_START_END in case of DW_LLE_offset_pair.
2020-04-07 09:55:35 -06:00
nitachra 4114425321 Support for DW_AT_loclists_base and DW_FORM_loclistx.
Hi Tom,

This is the updated series with ChangeLogs edits.

Regards,
Nitika
2020-04-07 09:55:35 -06:00
Simon Marchi 9f4e76a4b3 gdb: small cleanups in dwarf2_psymtab constructors
I noticed that only one of the two dwarf2_psymtab constructors are
actually used.  The one that is used accepts an `addr` parameter (the
base text offset), but its sole caller passes a constant, 0.  We want to
keep calling the three-arguments standard_psymtab constructor form,
however, since it differs from the two-arguments form in subtle ways.

Also, I believe the dwarf2_per_cu_data associated to the created
dwarf2_psymtab should be passed as a constructor argument.  That will
help me in a future patchset, to convince myself that the `per_cu_data`
field can't be NULL.

So this patch:

- Removes the two-parameters constructor of dwarf2_psymtab, as it is
  unused.
- Removes the `addr` parameter of the remaining constructor, passing 0
  directly to the base class' constructor.
- Adds a `per_cu` parameter, to assign the `per_cu_data` field at
  construction.

gdb/ChangeLog:

	* dwarf2/read.h (struct dwarf2_psymtab): Remove two-parameters
	constructor.  Remove `addr` parameter from other constructor and
	add `per_cu` parameter.
	* dwarf2/read.c (create_partial_symtab): Update.
2020-04-07 11:48:46 -04:00
Tom de Vries 25c11acac3 [gdb/symtab] Add symbol with inherited DW_AT_const_value to psymtabs
Consider the test-case added in this patch, with resulting dwarf (related to
variable aaa):
...
 <0><d2>: Abbrev Number: 2 (DW_TAG_partial_unit)
 <1><eb>: Abbrev Number: 4 (DW_TAG_variable)
    <ec>   DW_AT_name        : aaa
    <f0>   DW_AT_type        : <0xe4>
    <f4>   DW_AT_const_value : 1
 <0><10c>: Abbrev Number: 2 (DW_TAG_compile_unit)
    <10e>   DW_AT_name        : <artificial>
 <1><11b>: Abbrev Number: 3 (DW_TAG_variable)
    <11c>   DW_AT_abstract_origin: <0xeb>
...

When running the test-case, we see:
...
(gdb) p aaa^M
No symbol "aaa" in current context.^M
(gdb) FAIL: gdb.dwarf2/imported-unit-abstract-const-value.exp: p aaa
...
while with target board readnow.exp, we have:
...
(gdb) p aaa^M
$1 = 1^M
...

This is due to the fact that there's no aaa symbol in the partial symtabs:
...
Partial symtab for source file <artificial>@0x101 (object 0x351cf40)^M
   ...
Global partial symbols:^M
    `main', function, 0x4004a7^M
^M
...
which is due to the fact that when attempting to add the symbol corresponding
to DIE 0x11b in add_partial_symbol:
...
(gdb) p /x pdi->sect_off
$4 = 0x11b
(gdb) p pdi.has_const_value
$5 = 0
...
it seems the DW_AT_const_value was not inherited from DIE 0xeb, and
consequently we leave without adding a partial symbol.

Fix this by making sure that partial_die_info::has_const_value is inherited
in partial_die_info::fixup.

Build and reg-tested on x86_64-linux.

Tested test-case with target boards readnow, cc-with-gdb-index and
cc-with-debug-names.  The "print aaa" test fails for cc-with-gdb-index, that's
PR25791, the test passes when applying the corresponding proposed patch.

gdb/ChangeLog:

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

	PR symtab/25796
	* dwarf2/read.c (can_have_DW_AT_const_value_p): New function.
	(partial_die_info::fixup): Inherit has_const_value.

gdb/testsuite/ChangeLog:

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

	PR symtab/25796
	* gdb.dwarf2/imported-unit-abstract-const-value.exp: New file.
2020-04-07 17:33:05 +02:00
Tom de Vries 5707e24baa [gdb/symtab] Fix check-psymtab failure for inline function
Consider test-case inline.c, containing an inline function foo:
...
static inline int foo (void) { return 0; }
int main (void) { return foo (); }
...

And the test-case compiled with -O2 and debug info:
...
$ gcc -g inline.c -O2
...

This results in a DWARF entry for foo without pc info:
...
<1><114>: Abbrev Number: 4 (DW_TAG_subprogram)
   <115>   DW_AT_name        : foo
   <119>   DW_AT_decl_file   : 1
   <11a>   DW_AT_decl_line   : 2
   <11b>   DW_AT_prototyped  : 1
   <11b>   DW_AT_type        : <0x10d>
   <11f>   DW_AT_inline      : 3       (declared as inline and inlined)
...

When loading the executable in gdb, we create a partial symbol for foo, but
after expansion into a full symbol table no actual symbol is created,
resulting in a maint check-psymtab failure:
...
(gdb) maint check-psymtab
Static symbol `foo' only found in inline.c psymtab
...

Fix this by skipping this type of partial symbol during the check.

Note that we're not fixing this by not creating the partial symbol, because
this breaks setting a breakpoint on an inlined inline function in a CU for
which the partial symtab has not been expanded (test-case
gdb.dwarf2/break-inline-psymtab.exp).

Tested on x86_64-linux.

gdb/ChangeLog:

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

	* psymtab.c (maintenance_check_psymtabs): Skip static LOC_BLOCK
	symbols without address.

gdb/testsuite/ChangeLog:

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

	* gdb.base/check-psymtab.c: New test.
	* gdb.base/check-psymtab.exp: New file.
2020-04-07 10:57:20 +02:00
Kamil Rytarowski 05f00e223d Implement basic threading support in the NetBSD target
Use sysctl(3) as the portable interface to prompt NetBSD threads on
all supported NetBSD versions. In future newer versions could switch
to PT_LWPSTATUS ptrace(2) API that will be supported on NetBSD 10.0
and newer.

Implement as part of nbsd_nat_target:
 - thread_name()         - read descriptive thread name
 - thread_alive()        - check whether a thread is alive
 - post_attach()         - updates the list of threads after attach
 - update_thread_list()  - updates the list of threads
 - pid_to_str()          - translates ptid to a descriptive string

There are two local static functions:
 - nbsd_thread_lister()  - generic LWP lister for a specified pid
 - nbsd_add_threads()    - utility to update the list of threads

Now, GDB on NetBSD can attach to a multithreaded process, spawn
a multithreaded process, list threads, print their LWP+PID numbers
and descriptive thread names.

gdb/ChangeLog:

       * nbsd-nat.h (struct thread_info): Add forward declaration.
       (nbsd_nat_target::thread_alive): Add.
       (nbsd_nat_target::thread_name): Likewise.
       (nbsd_nat_target::update_thread_list): Likewise.
       (update_thread_list::post_attach): Likewise.
       (post_attach::pid_to_str): Likewise.
       * nbsd-nat.c: Include "gdbthread.h" and "inferior.h".
       (nbsd_thread_lister): Add.
       (nbsd_nat_target::thread_alive): Likewise.
       (nbsd_nat_target::thread_name): Likewise.
       (nbsd_add_threads): Likewise.
       (update_thread_list::post_attach): Likewise.
       (nbsd_nat_target::update_thread_list): Likewise.
       (post_attach::pid_to_str): Likewise.
2020-04-06 23:04:36 +02:00
Tom Tromey 6ee448cc2d Select variant field when printing variant
When I updated the Ada variant-printing code to be value-based, I
neglected a couple of issues.  First, print_variant_part must first
extract the variant field before finding the active component; second,
print_field_values should pass in the field value as the outer value
when recursing.

This patch fixes both of these issues.

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

	* ada-valprint.c (print_variant_part): Extract the variant field.
	(print_field_values): Use the field as the outer value when
	recursing.

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

	* gdb.ada/variant-record/proc.adb: New file.
	* gdb.ada/variant-record/value.adb: New file.
	* gdb.ada/variant-record/value.s: New file.
	* gdb.ada/variant-record.exp: New file.
2020-04-06 12:59:57 -06:00
Tom Tromey dea34e8cc3 Fix build breakage in NetBSD tdep files
A recent patch caused some build failures in NetBSD tdep files.  I saw
this failure in my --enable-target=all build.

This patch fixes the problems.  Tested by rebuilding.
I am going to check this in.

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

	* sh-nbsd-tdep.c: Include nbsd-tdep.h.
	* ppc-nbsd-tdep.c: Include nbsd-tdep.h.
	* mips-nbsd-tdep.c (mipsnbsd_init_abi): Add missing ";".
	* arm-nbsd-tdep.c: Include nbsd-tdep.h.
	* hppa-nbsd-tdep.c: Include nbsd-tdep.h.
2020-04-06 12:42:40 -06:00