Commit Graph

45413 Commits

Author SHA1 Message Date
Tom de Vries
6dcfb80a28 [gdb/testsuite] Require gnatmake-8 for gdb.ada/mi_prot.exp
With gcc-7, I run into:
...
gcc -c -I./ -gnata -Isrc/gdb/testsuite/gdb.ada/mi_prot -g -lm -I- \
  src/gdb/testsuite/gdb.ada/mi_prot/prot.adb^M
prot.adb:21:04: info: "Obj_Type" is frozen here, aspects evaluated at this \
  point^M
prot.adb:23:09: visibility of aspect for "Obj_Type" changes after freeze \
  point^M
gnatmake: "src/gdb/testsuite/gdb.ada/mi_prot/prot.adb" compilation error^M
compiler exited with status 1
  ...
FAIL: gdb.ada/mi_prot.exp: compilation prot.adb
...

Fix this by requiring gnatmake-8 for this test-case.

Tested on x86_64-linux, with gnatmake-7, gnatmake-8 and gnatmake-11.

gdb/testsuite/ChangeLog:

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

	PR testsuite/26293
	* gdb.ada/mi_prot.exp: Require gnatmake-8.
2020-07-24 14:10:50 +02:00
Kevin Buettner
513487e1a8 Fix BZ 26294 - Add period to help text for maint print core-file-backed-mappings
gdb/ChangeLog:

	PR corefiles/26294
	* corelow.c (_initialize_corelow): Add period to help text
	for "maintenance print core-file-backed-mappings".
2020-07-23 13:41:36 -07:00
Pedro Alves
e7bc9db8f4 Don't touch frame_info objects if frame cache was reinitialized
This fixes yet another bug exposed by ASAN + multi-target.exp

Running an Asan-enabled GDB against gdb.multi/multi-target.exp exposed
yet another latent GDB bug.  See here for the full log:

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

As Simon described, the problem is:

 - We create a new frame_info object in restore_selected_frame (by
   calling find_relative_frame)

 - The frame is allocated on the frame_cache_obstack

 - In frame_unwind_try_unwinder, we try to find an unwinder for that
   frame

 - While trying unwinders, memory read fails because the remote target
   closes, because of "monitor exit"

 - That calls reinit_frame_cache (as shown above), which resets
   frame_cache_obstack

 - When handling the exception in frame_unwind_try_unwinder, we try to
   set some things on the frame_info object (like *this_cache, which
   in fact tries to write into frame_info::prologue_cache), but the
   frame_info object is no more, it went away with the obstack.

Fix this by maintaining a frame cache generation counter.  Then in
exception handling code paths, don't touch frame objects if the
generation is not the same as it was on entry.

This commit generalizes the gdb.server/server-kill.exp testcase and
reuses it to test the scenario in question.  The new tests fail
without the GDB fix.

gdb/ChangeLog:

	* frame-unwind.c (frame_unwind_try_unwinder): On exception, don't
	touch THIS_CACHE/THIS_FRAME if the frame cache was cleared
	meanwhile.
	* frame.c (frame_cache_generation, get_frame_cache_generation):
	New.
	(reinit_frame_cache): Increment FRAME_CACHE_GENERATION.
	(get_prev_frame_if_no_cycle): On exception, don't touch
	PREV_FRAME/THIS_FRAME if the frame cache was cleared meanwhile.
	* frame.h (get_frame_cache_generation): Declare.

gdb/testsuite/ChangeLog:

	* gdb.server/server-kill.exp (prepare): New, factored out from the
	top level.
	(kill_server): New.
	(test_tstatus, test_unwind_nosyms, test_unwind_syms): New.
	(top level) : Call test_tstatus, test_unwind_nosyms, test_unwind_syms.
2020-07-23 16:29:28 +01:00
Tom de Vries
90fcc46681 [gdb/tui] Fix Wmaybe-uninitialized warning in tui-winsource.c
When compiling with CFLAGS/CXXFLAGS="-O0 -g -Wall" and using g++ 11.0.0, we
run into:
...
src/gdb/tui/tui-winsource.c: In function \
  'void tui_update_all_breakpoint_info(breakpoint*)':
src/gdb/tui/tui-winsource.c:427:58: warning: '<unknown>' may be used \
  uninitialized [-Wmaybe-uninitialized]
  427 |   for (tui_source_window_base *win : tui_source_windows ())
      |                                                          ^
In file included from src/gdb/tui/tui-winsource.c:38:
src/gdb/tui/tui-winsource.h:236:30: note: by argument 1 of type \
  'const tui_source_windows*' to 'tui_source_window_iterator \
  tui_source_windows::begin() const' declared here
  236 |   tui_source_window_iterator begin () const
      |                              ^~~~~
src/gdb/tui/tui-winsource.c:427:58: note: '<anonymous>' declared here
  427 |   for (tui_source_window_base *win : tui_source_windows ())
      |                                                          ^
...

The warning doesn't make sense for an empty struct, PR gcc/96295 has been
filed about that.

For now, work around the warning by defining a default constructor.

Build on x86_64-linux.

gdb/ChangeLog:

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

	PR tui/26282
	* tui/tui-winsource.h (struct tui_source_windows::tui_source_windows):
	New default constructor.
2020-07-23 13:45:46 +02:00
Andrew Burgess
78344df7b5 gdb/disassembly: Update to handle non-statement addresses
After the introduction of support for non-statement addresses in the
line table, the output for 'disassemble /m' can be broken in some
cases.

With the /m format disassembly GDB associates a set of addresses with
each line, these addresses are then sorted and printed for each line.

When the non-statement support was added GDB was incorrectly told to
ignore non-statement instructions, and not add these to the result
table.  This means that these instructions are completely missing from
the output.

This commit removes the code that caused non-statement lines to be
ignored.

A result of this change is that GDB will now potentially include new
line numbers in the 'disassemble /m' output, lines that previously
were only in the line table as non-statement lines will now appear in
the disassembly output.  This feels like an improvement though.

gdb/ChangeLog:

	* disasm.c (do_mixed_source_and_assembly_deprecated): Don't
	exclude non-statement entries.

gdb/testsuite/ChangeLog:

	* gdb.dwarf2/dw2-disasm-over-non-stmt.exp: New file.
2020-07-23 11:16:50 +01:00
Sandra Loosemore
25dfed247b Fix more bugs in gdb testglue wrapper handling
In commit 24ac169ac5, this patch:

	2020-02-21  Shahab Vahedi  <shahab@synopsys.com>

	* lib/gdb.exp (gdb_wrapper_init): Reset
	"gdb_wrapper_initialized" to 0 if "wrapper_file" does
	not exist.

attempted to fix problems finding the gdb test wrapper gdb_tg.o in
some tests that cd to some non-default directory by rebuilding also
the test wrapper in that directory.  This had the side-effect of
leaving these .o files in various places in the GDB source directory
tree.

Furthermore, while the tests that cd to some non-default directory
cannot run on remote host, the code that was added to probe for the
presence of the wrapper file was also specific to host == build.

This patch reverts the problematic parts of that commit and replaces
it with forcing use of an absolute (rather than relative) pathname to
the .o file for linking when host == build.

While debugging this patch, I also observed that use of the construct
"[info exists gdb_wrapper_file]" was not reliable for detecting when
that variable had been initialized by gdb_wrapper_init.  I rewrote
that so that the variable is always initialized and has a value of an
empty string when no wrapper file is needed.

2020-07-22  Sandra Loosemore  <sandra@codesourcery.com>

	gdb/testsuite/
	* lib/gdb.exp (gdb_wrapper_file, gdb_wrapper_flags):
	Initialize to empty string at top level.
	(gdb_wrapper_init): Revert check for file existence on build.
	Build the wrapper in its default place, not a build-specific
	location.  When host == build, make the pathname absolute.
	(gdb_compile): Delete leftover declaration of
	gdb_wrapper_initialized.  Check gdb_wrapper_file being an empty
	string instead of uninitialized.
2020-07-22 20:42:20 -07:00
Kevin Buettner
7da515fd76 New core file tests with mappings over existing program memory
This test case was inspired by Pedro's demonstration of a problem
with my v2 patches.  It can be found here:

    https://sourceware.org/pipermail/gdb-patches/2020-May/168826.html

In a nutshell, my earlier patches could not handle the case in
which a read-only mapping created with mmap() was created at
an address used by other file-backed read-only memory in use by
the process.

This problem has been fixed (for Linux, anyway) by the commit "Use
NT_FILE note section for reading core target memory".

When I run this test without any of my recent corefile patches,
I see these failures:

FAIL: gdb.base/corefile2.exp: kernel core: print/x mbuf_ro[0]@4
FAIL: gdb.base/corefile2.exp: kernel core: print/x mbuf_ro[pagesize-4]@4
FAIL: gdb.base/corefile2.exp: kernel core: print/x mbuf_ro[-3]@6
FAIL: gdb.base/corefile2.exp: kernel core: print/x mbuf_rw[pagesize-3]@6
FAIL: gdb.base/corefile2.exp: kernel core: print/x mbuf_ro[pagesize-3]@6
FAIL: gdb.base/corefile2.exp: maint print core-file-backed-mappings
FAIL: gdb.base/corefile2.exp: gcore core: print/x mbuf_ro[-3]@6

The ones involving mbuf_ro will almost certainly fail when run on
non-Linux systems; I've used setup_xfail on those tests to prevent
them from outright FAILing when not run on Linux.  For a time, I
had considered skipping these tests altogether when not run on
Linux, but I changed my mind due to this failure...

FAIL: gdb.base/corefile2.exp: print/x mbuf_rw[pagesize-3]@6

I think it *should* pass without my recent corefile patches.  The fact
that it doesn't is likely due to a bug in GDB.  The following
interaction with GDB demonstrates the problem:

(gdb) print/x mbuf_rw[pagesize-3]@6
$1 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0}
(gdb) print/x mbuf_rw[pagesize]@3
$2 = {0x6b, 0x6b, 0x6b}

The last three values in display of $1 should be the same as those
shown by $2.  Like this...

(gdb) print/x mbuf_rw[pagesize-3]@6
$1 = {0x0, 0x0, 0x0, 0x6b, 0x6b, 0x6b}
(gdb) print/x mbuf_rw[pagesize]@3
$2 = {0x6b, 0x6b, 0x6b}

That latter output was obtained with the use of all of my current
corefile patches.  I see no failures on Linux when running this test
with my current set of corefile patches.  I tested 3 architectures:
x86_64, s390x, and aarch64.

I also tested on FreeBSD 12.1-RELEASE.  I see the following results
both with and without the current set of core file patches:

    # of expected passes		26
    # of expected failures		8

Of particular interest is that I did *not* see the problematic mbuf_rw
failure noted earlier (both with and without the core file patches).
I still don't have an explanation for why this failure occurred on
Linux.  Prior to running the tests, I had hypothesized that I'd see
this failure on FreeBSD too, but testing shows that this is not the
case.

Also of importance is that we see no FAILs with this test on FreeBSD
which indicates that I XFAILed the correct tests.

This version runs the interesting tests twice, once with a kernel
created core file and another time with a gcore created core file.

It also does a very minimal test of the new command "maint print
core-file-backed-mappings".

gdb/testsuite/ChangeLog:

	* gdb.base/corefile2.exp: New file.
	* gdb.base/coremaker2.exp: New file.
2020-07-22 12:53:37 -07:00
Kevin Buettner
b089853a22 Add documentation for "maint print core-file-backed-mappings"
gdb/ChangeLog:

	* NEWS (New commands): Mention new command
	"maintenance print core-file-backed-mappings".

gdb/doc/ChangeLog:

	* gdb.texinfo (Maintenance Commands): Add documentation for
	new command "maintenance print core-file-backed-mappings".
2020-07-22 12:52:31 -07:00
Kevin Buettner
09c2f5d45c Add new command "maint print core-file-backed-mappings"
I wrote a read_core_file_mappings method for FreeBSD and then registered
this gdbarch method.  I saw some strange behavior while testing it and
wanted a way to make sure that mappings were being correctly loaded
into corelow.c, so I wrote the new command which is the topic of this
commit.  I think it might be occasionally useful for debugging strange
corefile behavior.

With regard to FreeBSD, my work isn't ready yet.  Unlike Linux,
FreeBSD puts all mappings into its core file note.  And, unlike Linux,
it doesn't dump load segments which occupy no space in the file.  So
my (perhaps naive) implementation of a FreeBSD read_core_file_mappings
didn't work all that well:  I saw more failures in the corefile2.exp
tests than without it.  I think it should be possible to make FreeBSD
work as well as Linux, but it will require doing something with all of
the mappings, not just the file based mappings that I was considering.

In the v4 series, Pedro asked the following:

    I don't understand what this command provides that "info proc
    mappings" doesn't?  Can you give an example of when you'd use this
    command over "info proc mappings" ?

On Linux, "info proc mappings" and "maint print core-file-backed-mappings"
will produce similar, possibly identical, output.  This need not be
the case for other OSes.  E.g. on FreeBSD, had I finished the
implementation, the output from these commands would have been very
different.  The FreeBSD "info proc mappings" command would show
additional (non-file-backed) mappings in addition to at least one
additional field (memory permissions) for each mapping.

As noted earlier, I was seeing some unexpected behavior while working
on the FreeBSD implementation and wanted to be certain that the
mappings were being correctly loaded by corelow.c.  "info proc
mappings" prints the core file mappings, but doesn't tell us anything
about whether they've been loaded by corelow.c This new maintenance
command directly interrogates the data structures and prints the
values found there.

gdb/ChangeLog:

	* corelow.c (gdbcmd.h): Include.
	(core_target::info_proc_mappings): New method.
	(get_current_core_target): New function.
	(maintenance_print_core_file_backed_mappings): New function.
	(_initialize_corelow): Add core-file-backed-mappings to
	"maint print" commands.
2020-07-22 12:50:30 -07:00
Kevin Buettner
9c5ec5c2da Adjust coredump-filter.exp to account for NT_FILE note handling
This commit makes adjustments to coredump-filter.exp to account
for the fact that NT_FILE file-backed mappings are now available
when a core file is loaded.  Thus, a test which was expected
to PASS when a memory region was determined to be unavailable
(due to no file-backed mappings being available) will now FAIL
due to those mappings being available from having loaded the
NT_FILE note.

I had originally marked the test as XFAIL, but Mihails Strasuns
suggested a much better approach:

    1) First test that it still works if file is accessible in the
       filesystem.
    2) Temporarily move / rename the file and test that disassembly
       doesn't work anymore.

That's what this commit implements.

gdb/testsuite/ChangeLog:

	* gdb.base/coredump-filter.exp: Add second
	non-Private-Shared-Anon-File test.
	(test_disasm): Rename binfile for test which is expected
	to fail.
2020-07-22 12:49:18 -07:00
Kevin Buettner
4ba11f89a2 gcore command: Place all file-backed mappings in NT_FILE note
When making a core file with the GDB's gcore command on Linux,
the same criteria used for determining which mappings should be
dumped were also being used for determining which entries should
be placed in the NT_FILE note.  This is wrong; we want to place
all file-backed mappings in this note.

The predicate function, dump_mapping_p, was used to determine whether
or not to dump a mapping from within linux_find_memory_regions_full.
This commit leaves this predicate in place, but adds a new parameter,
should_dump_mapping_p, to linux_find_memory_regions_full.  It then
calls should_dump_mapping_p instead of dump_mapping_p.  dump_mapping_p
is passed to linux_find_memory_regions_full at one call site; at the
other call site, dump_note_entry_p is passed instead.

gdb/ChangeLog:

	* linux-tdep.c (dump_note_entry_p): New function.
	(linux_dump_mapping_p_ftype): New typedef.
	(linux_find_memory_regions_full): Add new parameter,
	should_dump_mapping_p.
	(linux_find_memory_regions): Adjust call to
	linux_find_memory_regions_full.
	(linux_make_mappings_core_file_notes): Use dump_note_entry_p in
	call to linux_find_memory_regions_full.
2020-07-22 12:47:50 -07:00
Kevin Buettner
f9e233c9c4 Add test for accessing read-only mmapped data in a core file
This test passes when run using a GDB with my corefile patches.  When
run against a GDB without my patches, I see the following failures,
the first of which is due to the test added by this commit:

FAIL: gdb.base/corefile.exp: accessing read-only mmapped data in core file (mapping address not found in core file)
FAIL: gdb.base/corefile.exp: accessing anonymous, unwritten-to mmap data

gdb/testsuite/ChangeLog:

	* gdb.base/corefile.exp: Add test "accessing read-only mmapped
	data in core file".
	* gdb.base/coremaker.c (buf2ro): New global.
	(mmapdata): Add a read-only mmap mapping.
2020-07-22 12:47:30 -07:00
Kevin Buettner
db082f5979 Use NT_FILE note section for reading core target memory
In his reviews of my v1 and v2 corefile related patches, Pedro
identified two cases which weren't handled by those patches.

In https://sourceware.org/pipermail/gdb-patches/2020-May/168826.html,
Pedro showed that debugging a core file in which mmap() is used to
create a new mapping over an existing file-backed mapping will
produce incorrect results.  I.e, for his example, GDB would
show:

(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004004e6 <+0>:	push   %rbp
   0x00000000004004e7 <+1>:	mov    %rsp,%rbp
=> 0x00000000004004ea <+4>:	callq  0x4003f0 <abort@plt>
End of assembler dump.

This sort of looks like it might be correct, but is not due to the
fact that mmap(...MAP_FIXED...) was used to create a mapping (of all
zeros) on top of the .text section.  So, the correct result should be:

(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004004e6 <+0>:	add    %al,(%rax)
   0x00000000004004e8 <+2>:	add    %al,(%rax)
=> 0x00000000004004ea <+4>:	add    %al,(%rax)
   0x00000000004004ec <+6>:	add    %al,(%rax)
   0x00000000004004ee <+8>:	add    %al,(%rax)
End of assembler dump.

The other case that Pedro found involved an attempted examination of a
particular section in the test case from gdb.base/corefile.exp.  On
Fedora 27 or 28, the following behavior may be observed:

(gdb) info proc mappings
Mapped address spaces:

          Start Addr           End Addr       Size     Offset objfile
...
      0x7ffff7839000     0x7ffff7a38000   0x1ff000   0x1b5000 /usr/lib64/libc-2.27.so
...
(gdb) x/4x 0x7ffff7839000
0x7ffff7839000:	Cannot access memory at address 0x7ffff7839000

FYI, this section appears to be unrelocated vtable data.  See
https://sourceware.org/pipermail/gdb-patches/2020-May/168331.html for
a detailed analysis.

The important thing here is that GDB should be able to access this
address since it should be backed by the shared library.  I.e. it
should do this:

(gdb) x/4x 0x7ffff7839000
0x7ffff7839000:	0x0007ddf0	0x00000000	0x0007dba0	0x00000000

Both of these cases are fixed with this commit.

In a nutshell, this commit opens a "binary" target BFD for each of the
files that are mentioned in an NT_FILE / .note.linuxcore.file note
section.  It then uses these mappings instead of the file stratum
mappings that GDB has used in the past.

If this note section doesn't exist or is mangled for some reason, then
GDB will use the file stratum as before.  Should this happen, then
we can expect both of the above problems to again be present.

See the code comments in the commit for other details.

gdb/ChangeLog:

	* corelow.c (solist.h, unordered_map): Include.
	(class core_target): Add field m_core_file_mappings and
	method build_file_mappings.
	(core_target::core_target): Call build_file_mappings.
	(core_target::~core_target): Free memory associated with
	m_core_file_mappings.
	(core_target::build_file_mappings): New method.
	(core_target::xfer_partial): Use m_core_file_mappings
	for memory transfers.
	* linux-tdep.c (linux_read_core_file_mappings): New
	function.
	(linux_core_info_proc_mappings): Rewrite to use
	linux_read_core_file_mappings.
	(linux_init_abi): Register linux_read_core_file_mappings.
2020-07-22 12:45:29 -07:00
Kevin Buettner
7e183d2736 Add new gdbarch method, read_core_file_mappings
The new gdbarch method, read_core_file_mappings, will be used for
reading file-backed mappings from a core file.  It'll be used
for two purposes: 1) to construct a table of file-backed mappings
in corelow.c, and 2) for display of core file mappings.

For Linux, I tried a different approach in which knowledge of the note
format was placed directly in corelow.c.  This seemed okay at first;
it was only one note format and the note format was fairly simple.
After looking at FreeBSD's note/mapping reading code, I concluded
that it's best to leave architecture specific details for decoding
the note in (architecture specific) tdep files.

With regard to display of core file mappings, I experimented with
placing the mappings display code in corelow.c.  It has access to the
file-backed mappings which were read in when the core file was loaded.
And, better, still common code could be used for all architectures.
But, again, the FreeBSD mapping code convinced me that this was not
the best approach since it has even more mapping info than Linux.
Display code which would work well for Linux will leave out mappings
as well as protection info for mappings.

So, for these reasons, I'm introducing a new gdbarch method for
reading core file mappings.

gdb/ChangeLog:

	* arch-utils.c (default_read_core_file_mappings): New function.
	* arch-utils.c (default_read_core_file_mappings): Declare.
	* gdbarch.sh (read_core_file_mappings): New gdbarch method.
	* gdbarch.h, gdbarch.c: Regenerate.
2020-07-22 12:44:13 -07:00
Kevin Buettner
94c265d790 Test ability to access unwritten-to mmap data in core file
gdb/testsuite/ChangeLog:

	PR corefiles/25631
	* gdb.base/corefile.exp (accessing anonymous, unwritten-to mmap data):
	New test.
	* gdb.base/coremaker.c (buf3): New global.
	(mmapdata): Add mmap call which uses MAP_ANONYMOUS and MAP_PRIVATE
	flags.
2020-07-22 12:40:42 -07:00
Kevin Buettner
2735d4218e Provide access to non SEC_HAS_CONTENTS core file sections
Consider the following program:

- - - mkmmapcore.c - - -

static char *buf;

int
main (int argc, char **argv)
{
  buf = mmap (NULL, 8192, PROT_READ | PROT_WRITE,
              MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  abort ();
}
- - - end mkmmapcore.c - - -

Compile it like this:

gcc -g -o mkmmapcore mkmmapcore.c

Now let's run it from GDB.  I've already placed a breakpoint on the
line with the abort() call and have run to that breakpoint.

Breakpoint 1, main (argc=1, argv=0x7fffffffd678) at mkmmapcore.c:11
11	  abort ();
(gdb) x/x buf
0x7ffff7fcb000:	0x00000000

Note that we can examine the memory allocated via the call to mmap().

Now let's try debugging a core file created by running this program.
Depending on your system, in order to make a core file, you may have to
run the following as root (or using sudo):

    echo core > /proc/sys/kernel/core_pattern

It may also be necessary to do:

    ulimit -c unlimited

I'm using Fedora 31. YMMV if you're using one of the BSDs or some other
(non-Linux) system.

This is what things look like when we debug the core file:

    [kev@f31-1 tmp]$ gdb -q ./mkmmapcore core.304767
    Reading symbols from ./mkmmapcore...
    [New LWP 304767]
    Core was generated by `/tmp/mkmmapcore'.
    Program terminated with signal SIGABRT, Aborted.
    #0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
    50	  return ret;
    (gdb) x/x buf
    0x7ffff7fcb000:	Cannot access memory at address 0x7ffff7fcb000

Note that we can no longer access the memory region allocated by mmap().

Back in 2007, a hack for GDB was added to _bfd_elf_make_section_from_phdr()
in bfd/elf.c:

	  /* Hack for gdb.  Segments that have not been modified do
	     not have their contents written to a core file, on the
	     assumption that a debugger can find the contents in the
	     executable.  We flag this case by setting the fake
	     section size to zero.  Note that "real" bss sections will
	     always have their contents dumped to the core file.  */
	  if (bfd_get_format (abfd) == bfd_core)
	    newsect->size = 0;

You can find the entire patch plus links to other discussion starting
here:

    https://sourceware.org/ml/binutils/2007-08/msg00047.html

This hack sets the size of certain BFD sections to 0, which
effectively causes GDB to ignore them.  I think it's likely that the
bug described above existed even before this hack was added, but I
have no easy way to test this now.

The output from objdump -h shows the result of this hack:

 25 load13        00000000  00007ffff7fcb000  0000000000000000  00013000  2**12
                  ALLOC

(The first field, after load13, shows the size of 0.)

Once the hack is removed, the output from objdump -h shows the correct
size:

 25 load13        00002000  00007ffff7fcb000  0000000000000000  00013000  2**12
                  ALLOC

(This is a digression, but I think it's good that objdump will now show
the correct size.)

If we remove the hack from bfd/elf.c, but do nothing to GDB, we'll
see the following regression:

FAIL: gdb.base/corefile.exp: print coremaker_ro

The reason for this is that all sections which have the BFD flag
SEC_ALLOC set, but for which SEC_HAS_CONTENTS is not set no longer
have zero size.  Some of these sections have data that can (and should)
be read from the executable.  (Sections for which SEC_HAS_CONTENTS
is set should be read from the core file; sections which do not have
this flag set need to either be read from the executable or, failing
that, from the core file using whatever BFD decides is the best value
to present to the user - it uses zeros.)

At present, due to the way that the target strata are traversed when
attempting to access memory, the non-SEC_HAS_CONTENTS sections will be
read as zeroes from the process_stratum (which in this case is the
core file stratum) without first checking the file stratum, which is
where the data might actually be found.

What we should be doing is this:

- Attempt to access core file data for SEC_HAS_CONTENTS sections.
- Attempt to access executable file data if the above fails.
- Attempt to access core file data for non SEC_HAS_CONTENTS sections, if
  both of the above fail.

This corresponds to the analysis of Daniel Jacobowitz back in 2007
when the hack was added to BFD:

    https://sourceware.org/legacy-ml/binutils/2007-08/msg00045.html

The difference, observed by Pedro in his review of my v1 patches, is
that I'm using "the section flags as proxy for the p_filesz/p_memsz
checks."

gdb/ChangeLog:

	PR corefiles/25631
	* corelow.c (core_target:xfer_partial):  Revise
	TARGET_OBJECT_MEMORY case to consider non-SEC_HAS_CONTENTS
	case after first checking the stratum beneath the core
	target.
	(has_all_memory): Return true.
	* target.c (raw_memory_xfer_partial): Revise comment
	regarding use of has_all_memory.
2020-07-22 12:38:33 -07:00
Kevin Buettner
e56cb451c9 section_table_xfer_memory: Replace section name with callback predicate
This patch is motivated by the need to be able to select sections
that section_table_xfer_memory_partial should consider for memory
transfers.  I'll use this facility in the next patch in this series.

section_table_xfer_memory_partial() can currently be passed a section
name which may be used to make name-based selections.  This is similar
to what I want to do, except that I want to be able to consider
section flags instead of the name.

I'm replacing the section name parameter with a predicate that,
when passed a pointer to a target_section struct, will return
true if that section should be further considered, or false which
indicates that it shouldn't.

I've converted the one existing use where a non-NULL section
name is passed to section_table_xfer_memory_partial().   Instead
of passing the section name, it now looks like this:

	  auto match_cb = [=] (const struct target_section *s)
	    {
	      return (strcmp (section_name, s->the_bfd_section->name) == 0);
	    };

	  return section_table_xfer_memory_partial (readbuf, writebuf,
						    memaddr, len, xfered_len,
						    table->sections,
						    table->sections_end,
						    match_cb);

The other callers all passed NULL; they've been simplified somewhat
in that they no longer need to pass NULL.

gdb/ChangeLog:

	* exec.h (section_table_xfer_memory): Revise declaration,
	replacing section name parameter with an optional callback
	predicate.
	* exec.c (section_table_xfer_memory): Likewise.
	* bfd-target.c, exec.c, target.c, corelow.c: Adjust all callers
	of section_table_xfer_memory.
2020-07-22 12:36:42 -07:00
Kevin Buettner
678c7a56ce Adjust corefile.exp test to show regression after bfd hack removal
In his review of my BZ 25631 patch series, Pedro was unable to
reproduce the regression which should occur after patch #1, "Remove
hack for GDB which sets the section size to 0", is applied.

Pedro was using an ld version older than 2.30.  Version 2.30
introduced the linker option -z separate-code.  Here's what the man
page has to say about it:

    Create separate code "PT_LOAD" segment header in the object.  This
    specifies a memory segment that should contain only instructions
    and must be in wholly disjoint pages from any other data.

In ld version 2.31, use of separate-code became the default for
Linux/x86.  So, really, 2.31 or later is required in order to see the
regression that occurs in recent Linux distributions when only the
bfd hack removal patch is applied.

For the test case in question, use of the separate-code linker option
means that the global variable "coremaker_ro" ends up in a separate
load segment (though potentially with other read-only data).  The
upshot of this is that when only patch #1 is applied, GDB won't be
able to correctly access coremaker_ro.  The reason for this is due
to the fact that this section will now have a non-zero size, but
will not have contents from the core file to find this data.
So GDB will ask BFD for the contents and BFD will respond with
zeroes for anything from those sections.  GDB should instead be
looking in the executable for this data.  Failing that, it can
then ask BFD for a reasonable value.  This is what a later patch
in this series does.

When using ld versions earlier than 2.31 (or 2.30 w/ the
-z separate-code option explicitly provided to the linker), there is
the possibility that coremaker_ro ends up being placed near other data
which is recorded in the core file.  That means that the correct value
will end up in the core file, simply because it resides on a page that
the kernel chooses to put in the core file.  This is why Pedro wasn't
able to reproduce the regression that should occur after fixing the
BFD hack.

This patch places a big chunk of memory, two pages worth on x86, in
front of "coremaker_ro" to attempt to force it onto another page
without requiring use of that new-fangled linker switch.

Speaking of which, I considered changing the test to use
-z separate-code, but this won't work because it didn't
exist prior to version 2.30.  The linker would probably complain
of an unrecognized switch.  Also, it likely won't be available in
other linkers not based on current binutils.  I.e. it probably won't
work in FreeBSD, NetBSD, etc.

To make this more concrete, this is what *should* happen when
attempting to access coremaker_ro when only patch #1 is applied:

    Core was generated by `/mesquite2/sourceware-git/f28-coresegs/bld/gdb/testsuite/outputs/gdb.base/coref'.
    Program terminated with signal SIGABRT, Aborted.
    #0  0x00007f68205deefb in raise () from /lib64/libc.so.6
    (gdb) p coremaker_ro
    $1 = 0

Note that this result is wrong; 201 should have been printed instead.
But that's the point of the rest of the patch series.

However, without this commit, or when using an old Linux distro with
a pre-2.31 ld, this is what you might see instead:

    Core was generated by `/mesquite2/sourceware-git/f28-coresegs/bld/gdb/testsuite/outputs/gdb.base/coref'.
    Program terminated with signal SIGABRT, Aborted.
    #0  0x00007f63dd658efb in raise () from /lib64/libc.so.6
    (gdb) p coremaker_ro
    $1 = 201

I.e. it prints the right answer, which sort of makes it seem like the
rest of the series isn't required.

Now, back to the patch itself... what should be the size of the memory
chunk placed before coremaker_ro?

It needs to be at least as big as the page size (PAGE_SIZE) from
the kernel.  For x86 and several other architectures this value is
4096.  I used MAPSIZE which is defined to be 8192 in coremaker.c.
So it's twice as big as what's currently needed for most Linux
architectures.  The constant PAGE_SIZE is available from <sys/user.h>,
but this isn't portable either.  In the end, it seemed simpler to
just pick a value and hope that it's big enough.  (Running a separate
program which finds the page size via sysconf(_SC_PAGESIZE) and then
passes it to the compilation via a -D switch seemed like overkill
for a case which is rendered moot by recent linker versions.)

Further information can be found here:

   https://sourceware.org/pipermail/gdb-patches/2020-May/168168.html
   https://sourceware.org/pipermail/gdb-patches/2020-May/168170.html

Thanks to H.J. Lu for telling me about the '-z separate-code' linker
switch.

gdb/testsuite/ChangeLog:

	* gdb.base/coremaker.c (filler_ro): New global constant.
2020-07-22 12:34:37 -07:00
Tom Tromey
32fa152e3b Fix crash in -stack-list-arguments
-stack-list-arguments will crash when stopped in an Ada procedure that
has an argument with a certain name ("_objectO" -- which can only be
generated by the compiler).  The bug occurs because lookup_symbol will
fail in this case.

This patch changes -stack-list-arguments to mirror what is done with
arguments elsewhere.  (As an aside, I don't understand why this lookup
is even needed, but I assume it is some stabs thing?)

In the longer term I think it would be good to share this code between
MI and the CLI.  However, due to the upcoming release, I preferred a
more local fix.

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

	* mi/mi-cmd-stack.c (list_args_or_locals): Use
	lookup_symbol_search_name.

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

	* gdb.ada/mi_prot.exp: New file.
	* gdb.ada/mi_prot/pkg.adb: New file.
	* gdb.ada/mi_prot/pkg.ads: New file.
	* gdb.ada/mi_prot/prot.adb: New file.
2020-07-22 12:28:33 -06:00
Reuben Thomas
c9fe1b583c Correct an error in the remote protocol specification
The list of commands that a stub must implement was wrong.

gdb/ChangeLog:
2020-07-22  Reuben Thomas  <rrt@sc3d.org>

	* gdb.texinfo (Remote Protocol, Overview): Correct the description
	of which remote protocol commands are mandatory for a stub to
	implement.
2020-07-22 16:15:29 +01:00
Andrew Burgess
a67a1c41fe gdb/python: Use reference not pointer in py-registers.c
Pedro's review comments arrived after I'd already committed this
change:

  commit f7306dac19
  Date:   Tue Jul 7 15:00:30 2020 +0100

      gdb/python: Reuse gdb.RegisterDescriptor objects where possible

See:

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

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* python/py-registers.c (gdbpy_register_object_data_init): Remove
	redundant local variable.
	(gdbpy_get_register_descriptor): Extract descriptor vector as a
	reference, not pointer, update code accordingly.
2020-07-22 16:09:16 +01:00
Simon Marchi
a7b4ff4f0a gdb/jit: skip jit symbol lookup if already detected the symbols don't exist
To detect whether an objfile is a JITer, we lookup JIT interface
symbols in the objfile.  If an objfile does not have these symbols, we
conclude that it is not a JITer.  An objfile that does not have the
symbols will never have them.  Therefore, once we do a lookup and find
out that the objfile does not have JIT symbols, just set a flag so
that we can skip symbol lookup for that objfile the next time we reset
JIT breakpoints.

gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>
	    Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* objfiles.h (struct objfile) <skip_jit_symbol_lookup>: New field.
	* jit.c (jit_breakpoint_re_set_internal): Use the
	`skip_jit_symbol_lookup` field.
2020-07-22 15:56:08 +02:00
Simon Marchi
2340e834df gdb/jit: apply minor cleanup and modernization
gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>
	    Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* jit.c (jit_read_descriptor): Define the descriptor address once,
	use twice.
	(jit_breakpoint_deleted): Move the declaration of the loop variable
	`iter` into the loop header.
	(jit_breakpoint_re_set_internal): Move the declaration of the local
	variable `objf_data` to the first point of definition.
	(jit_event_handler): Move the declaration of local variables
	`code_entry`, `entry_addr`, and `objf` to their first point of use.
	Rename `objf` to `jited`.
2020-07-22 15:56:08 +02:00
Simon Marchi
c1072906f1 gdb/jit: remove jiter_objfile_data -> objfile back-link
This is no longer needed, remove it.

gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>

	* jit.h (struct jiter_objfile_data) <jiter_objfile_data, objfile>:
	Remove.
	* jit.c (get_jiter_objfile_data): Update.
2020-07-22 15:56:08 +02:00
Tankut Baris Aktemur
c8474dc353 gdb/jit: enable tracking multiple JITer objfiles
GDB's JIT handler stores an objfile (and data associated with it) per
program space to keep track of JIT breakpoint information.  This assumes
that there is at most one JITer objfile in the program space.  However,
there may be multiple.  If so, only the first JITer's hook breakpoints
would be realized and the JIT events from the other JITers would be
missed.

This patch removes that assumption, allowing an arbitrary number of
objfiles within a program space to be JITers.

- The "unique" program_space -> JITer objfile pointer in
  jit_program_space_data is removed.  In fact, jit_program_space_data
  becomes empty, so it is removed entirely.

- jit_breakpoint_deleted is modified, it now has to assume that any
  objfile in a program space is a potential JITer.  It now iterates on
  all objfiles, checking if they are indeed JITers, and if they are,
  whether the deleted breakpoint belongs to them.

- jit_breakpoint_re_set_internal also has to assume that any objfile in
  a program space is a potential JITer.  It creates (or updates) one
  jiter_objfile_data structure for each JITer it finds.

- Same for jit_inferior_init.  It now iterates all objfiles to read the
  initial JIT object list.

gdb/ChangeLog:
2020-07-22  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>
	    Simon Marchi  <simon.marchi@polymtl.ca>

	* jit.c (struct jit_program_space_data): Remove.
	(jit_program_space_key): Remove.
	(jiter_objfile_data::~jiter_objfile_data): Remove program space
	stuff.
	(get_jit_program_space_data): Remove.
	(jit_breakpoint_deleted): Iterate on all of the program space's
	objfiles.
	(jit_inferior_init): Likewise.
	(jit_breakpoint_re_set_internal): Likewise.  Also change return
	type to void.
	(jit_breakpoint_re_set): Pass current_program_space to
	jit_breakpoint_re_set_internal.

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

	* gdb.base/jit-reader-simple.exp: Add a scenario for a binary that
	loads two JITers.
2020-07-22 15:56:07 +02:00
Simon Marchi
77208eb7e2 gdb/jit: move cached_code_address and jit_breakpoint to jiter_objfile_data
This is in preparation for allowing more than one JITer objfile per
program space.  Once we do that, each JITer objfile will have its own
JIT breakpoint (on the __jit_debug_register_code function it provides).
The cached_code_address field is just the runtime / relocated address of
that symbol.

Since they are going to become JITer-objfile-specific and not
program-space-specific, move these fields from jit_program_space_data to
jiter_objfile_data.

gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>

	* jit.h (struct jiter_objfile_data) <cached_code_address,
	jit_breakpoint>: Move to here from ...
	* jit.c (jit_program_space_data): ... here.
	(jiter_objfile_data::~jiter_objfile_data): Update.
	(jit_breakpoint_deleted): Update.
	(jit_breakpoint_re_set_internal): Update.
2020-07-22 15:56:07 +02:00
Simon Marchi
8c1c720faa gdb/jit: apply some simplifications and assertions
Following patch "gdb/jit: split jit_objfile_data in two", there are some
simplifications we can make.  The invariants described there mean that
we can assume / assert some things instead of checking them using
conditionals.

If an instance of jiter_objfile_data exists for a given objfile, it's
because the required JIT interface symbols were found.  Therefore, in
~jiter_objfile_data, the `register_code` field can't be NULL.  It was
previously used to differentiate a jit_objfile_data object used for a
JITer vs a JITed.  We can remove that check.

If an instance of jiter_objfile_data exists for a given objfile, it's
because it's the sole JITer objfile in the scope of its program space
(jit_program_space_data::objfile points to it).  At the moment,
jit_breakpoint_re_set_internal won't create a second instance of
jiter_objfile_data for a given program space.  Therefore, it's not
necessary to check for `ps_data != NULL` in ~jiter_objfile_data: we know
a jit_program_space_data for that program space exists.  We also don't
need to check for `ps_data->objfile == this->objfile`, because we know
the objfile is the sole JITer in this program space.  Replace these two
conditions with assertions.

A pre-condition for calling the jit_read_descriptor function (which is
respected in the two call sites) is that the objfile `jiter` _is_ a
JITer - it already has a jiter_objfile_data attached to it.  When a
jiter_objfile_data exists, its `descriptor` field is necessarily set:
had the descriptor symbol not been found, jit_breakpoint_re_set_internal
would not have created the jiter_objfile_data.  Remove the check and
early return in jit_read_descriptor.  Access objfile's `jiter_data` field
directly instead of calling `get_jiter_objfile_data` (which creates the
jiter_objfile_data if it doesn't exist yet) and assert that the result
is not nullptr.

Finally, `jit_event_handler` is always passed a JITer objfile.  So, add
an assertion to ensure that.

gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>

	* jit.c (jiter_objfile_data::~jiter_objfile_data): Remove some
	checks.
	(jit_read_descriptor): Remove NULL check.
	(jit_event_handler): Add an assertion.
2020-07-22 15:56:07 +02:00
Simon Marchi
0e74a041c0 gdb/jit: split jit_objfile_data in two
The jit_objfile_data is currently used to hold information about both
objfiles that are the result of JIT compilation (JITed) and objfiles
that can produce JITed objfiles (JITers).  I think that this double use
of the type is confusing, and that things would be more obvious if we
had one type for each role.

This patch splits it into:

- jited_objfile_data: for data about an objfile that is the result of a
  JIT compilation
- jiter_objfile_data: for data about an objfile which produces JITed
  objfiles

There are now two JIT-related fields in an objfile, one for each kind.
With this change, the following invariants hold:

- an objfile has a non-null `jiter_data` field iff it defines the required
  symbols of the JIT interface
- an objfile has a non-null `jited_data` field iff it is the product of
  JIT compilation (has been produced by some JITer)

gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>

	* jit.h (struct jit_objfile_data):  Split into...
	(struct jiter_objfile_data): ... this ...
	(struct jited_objfile_data): ... and this.
	* objfiles.h (struct objfile) <jit_data>: Remove.
	<jiter_data, jited_data>: New fields.
	* jit.c (jit_objfile_data::~jit_objfile_data): Rename to ...
	(jiter_objfile_data::~jiter_objfile_data): ... this.
	(get_jit_objfile_data): Rename to ...
	(get_jiter_objfile_data): ... this.
	(add_objfile_entry): Update.
	(jit_read_descriptor): Use get_jiter_objfile_data.
	(jit_find_objf_with_entry_addr): Use objfile's jited_data field.
	(jit_breakpoint_re_set_internal): Use get_jiter_objfile_data.
	(jit_inferior_exit_hook): Use objfile's jited_data field.
2020-07-22 15:56:07 +02:00
Simon Marchi
238b5c9f08 gdb/jit: link to jit_objfile_data directly from the objfile struct
Remove the use of objfile_data to associate a jit_objfile_data with an
objfile.  Instead, directly link to a jit_objfile_data from an objfile
struct.  The goal is to eliminate unnecessary abstraction.

The free_objfile_data function naturally becomes the destructor of
jit_objfile_data.  However, free_objfile_data accesses the objfile to
which the data is attached, which the destructor of jit_objfile_data
doesn't have access to.  To work around this, add a backlink to the
owning objfile in jit_objfile_data.  This is however temporary, it goes
away in a subsequent patch.

gdb/ChangeLog:
2020-07-22  Simon Marchi  <simon.marchi@polymtl.ca>

	* jit.h: Forward-declare `struct minimal_symbol`.
	(struct jit_objfile_data): Migrate to here from jit.c; also add a
	constructor, destructor, and an objfile* field.
	* jit.c (jit_objfile_data): Remove.
	(struct jit_objfile_data): Migrate from here to jit.h.
	(jit_objfile_data::~jit_objfile_data): New destructor
	implementation with code moved from free_objfile_data.
	(free_objfile_data): Delete.
	(get_jit_objfile_data): Update to use the jit_data field of objfile.
	(jit_find_objf_with_entry_addr): Ditto.
	(jit_inferior_exit_hook): Ditto.
	(_initialize_jit): Remove the call to
	register_objfile_data_with_cleanup.
	* objfiles.h (struct objfile) <jit_data>: New field.
2020-07-22 15:56:06 +02:00
Tankut Baris Aktemur
fe053b9e85 gdb/jit: pass the jiter objfile as an argument to jit_event_handler
This is a refactoring that adds a new parameter to the `jit_event_handler`
function: the JITer objfile.  The goal is to distinguish which JITer
triggered the JIT event, in case there are multiple JITers -- a capability
that is added in a subsequent patch.

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

	* jit.h: Forward-declare `struct objfile`.
	(jit_event_handler): Add a second parameter, the JITer objfile.
	* jit.c (jit_read_descriptor): Change the signature to take the
	JITer objfile as an argument instead of the jit_program_space_data.
	(jit_inferior_init): Update the call to jit_read_descriptor.
	(jit_event_handler): Use the new JITer objfile argument when calling
	jit_read_descriptor.
	* breakpoint.c (handle_jit_event): Update the call to
	jit_event_handler to pass the JITer objfile.
2020-07-22 15:56:06 +02:00
John Baldwin
4cec0c6689 Retire the now-unused gdbarch handle_segmentation_fault hook.
* gdbarch.c: Regenerate.
	* gdbarch.h: Regenerate.
	* gdbarch.sh (handle_segmentation_fault): Remove method.
	* infrun.c (handle_segmentation_fault): Remove.
	(print_signal_received_reason): Remove call to
	handle_segmentation_fault.
2020-07-21 17:28:16 -07:00
John Baldwin
0e42f66a30 Migrate the sparc64 ADI handle_segmentation_fault hook to report_signal_info.
gdb/ChangeLog:

	* sparc64-linux-tdep.c (sparc64_linux_handle_segmentation_fault):
	Rename to sparc64_linux_report_signal_info and add siggnal
	argument.
	(sparc64_linux_init_abi): Use sparc64_linux_report_signal_info
	instead of sparc64_linux_handle_segmentation_fault.
2020-07-21 17:28:16 -07:00
John Baldwin
77bdfeb2e6 Migrate the x86 MPX handle_segmentation_fault hook to report_signal_info.
gdb/ChangeLog:

	* amd64-linux-tdep.c (amd64_linux_init_abi_common): Use
	i386_linux_report_signal_info instead of
	i386_linux_handle_segmentation_fault.
	* i386-linux-tdep.c (i386_linux_handle_segmentation_fault): Rename
	to i386_linux_report_signal_info and add siggnal argument.
	(i386_linux_init_abi): Use i386_linux_report_signal_info instead
	of i386_linux_handle_segmentation_fault.
	* i386-linux-tdep.h (i386_linux_handle_segmentation_fault): Rename
	to i386_linux_report_signal_info and add siggnal argument.
2020-07-21 17:28:16 -07:00
John Baldwin
ad97bfc533 Report architecture-specific signal information for core files.
When opening a core file, if the process terminated due to a signal,
invoke the gdbarch report_signal_info hook to report
architecture-specific information about the signal.

gdb/ChangeLog:

	* corelow.c (core_target_open): Invoke gdbarch report_signal_info
	hook if present.
2020-07-21 17:28:16 -07:00
John Baldwin
272bb05cc5 Add a new gdbarch hook to report additional signal information.
This is a more general version of the existing handle_segmentation_fault
hook that is able to report information for an arbitrary signal, not
just SIGSEGV.

gdb/ChangeLog:

	* gdbarch.c: Regenerate.
	* gdbarch.h: Regenerate.
	* gdbarch.sh (report_signal_info): New method.
	* infrun.c (print_signal_received_reason): Invoke gdbarch
	report_signal_info hook if present.
2020-07-21 17:28:16 -07:00
Andrew Burgess
baf8791efb gdb/python: Reuse gdb.RegisterGroup objects where possible
Only create one gdb.RegisterGroup Python object for each of GDB's
reggroup objects.

I could have added a field into the reggroup object to hold the Python
object pointer for each reggroup, however, as reggroups are never
deleted within GDB, and are global (not per-architecture) a simpler
solution seemed to be just to hold a single global map from reggroup
pointer to a Python object representing the reggroup.  Then we can
reuse the objects out of this map.

After this commit it is possible for a user to tell that two
gdb.RegisterGroup objects are now identical when previously they were
unique, however, as both these objects are read-only I don't think
this should be a problem.

There should be no other user visible changes after this commit.

gdb/ChangeLog:

	* python/py-registers.c : Add 'unordered_map' include.
	(gdbpy_new_reggroup): Renamed to...
	(gdbpy_get_reggroup): ...this.  Update to only create register
	group descriptors when needed.
	(gdbpy_reggroup_iter_next): Update.

gdb/testsuite/ChangeLog:

	* gdb.python/py-arch-reg-groups.exp: Additional tests.
2020-07-21 21:57:08 +01:00
Andrew Burgess
f7306dac19 gdb/python: Reuse gdb.RegisterDescriptor objects where possible
Instead of having the gdb.RegisterDescriptorIterator creating new
gdb.RegisterDescriptor objects for each regnum, instead cache
gdb.RegisterDescriptor objects on the gdbarch object and reuse these.

This means that for every gdbarch/regnum pair there is a single unique
gdb.RegisterDescriptor, this feels like a neater implementation than
the existing one.

It is possible for a user to see (in Python code) that the descriptors
are now identical, but as the descriptors are read-only this should
make no real difference.

There should be no other user visible changes.

gdb/ChangeLog:

	* python/py-registers.c (gdbpy_register_object_data): New static
	global.
	(gdbpy_register_object_data_init): New function.
	(gdbpy_new_register_descriptor): Renamed to...
	(gdbpy_get_register_descriptor): ...this, and update to reuse
	existing register descriptors where possible.
	(gdbpy_register_descriptor_iter_next): Update.
	(gdbpy_initialize_registers): Register new gdbarch data.

gdb/testsuite/ChangeLog:

	* gdb.python/py-arch-reg-names.exp: Additional tests.
2020-07-21 21:57:08 +01:00
Simon Marchi
05c309a8ae gdb, gdbserver: make stopped_pids global variables static
I noticed that my IDE was confusing the two stopped_pids variables.
There is one in GDB and one in GDBserver.  They should be static, make
them so.

gdb/ChangeLog:

	* linux-nat.c (stopped_pids): Make static.

gdbserver/ChangeLog:

	* linux-low.cc (stopped_pids): Make static.

Change-Id: If4a2bdcd45d32eb3a732d266a0f686a4e4c23672
2020-07-21 16:49:36 -04:00
Simon Marchi
d1fd641e0b gdb: handle undefined properties in ada_discrete_type_{low,high}_bound
This patch fixes a failure in test `gdb.ada/access_to_packed_array.exp`.
The failure was introduced by 8c2e4e0689 ("gdb: add accessors to
struct dynamic_prop"), but I think it in fact exposed a latent buglet.

Note that to reproduce it, I had to use AdaCore's Ada "distribution"
[1].  The one that comes with my distro doesn't have debug info for the
standard library stuff, so the bug wouldn't trigger.

The bug is that while executing the `maint print symbols` command, we
are accessing the value of a range type's high bound dynamic prop as a
"const" value (PROP_CONST), when it is actually undefined
(PROP_UNDEFINED).  It results in this failed assertion:

    /home/simark/src/binutils-gdb/gdb/gdbtypes.h:526: internal-error: LONGEST dynamic_prop::const_val() const: Assertion `m_kind == PROP_CONST' failed.

`ada_discrete_type_high_bound` calls `resolve_dynamic_type`, which
eventually calls `resolve_dynamic_range`.  This one is responsible for
evaluating a range type's dynamic bounds in the current context and
returning static values.  It returns a new range type with these static
bounds.

The resulting bounds are typically properties of the PROP_CONST kind.
But when it's not possible to evaluate the properties, the properties
are PROP_UNDEFINED.  In the case we are looking at, it's not possible to
evaluate the dynamic high bound, which is of type PROP_LOCLIST.  It
would require a target with registers and a frame, but we run `maint
print symbols` without a live process.

`ada_discrete_type_high_bound` then accesses the high bound
unconditionally as a const value, which triggers the assert.

Note that the previous code in resolve_dynamic_range (before commit
8c2e4e0689) did this:

    prop = &TYPE_RANGE_DATA (dyn_range_type)->high;
    if (dwarf2_evaluate_property (prop, NULL, addr_stack, &value))
      {
        high_bound.kind = PROP_CONST;
        high_bound.data.const_val = value;

        if (TYPE_RANGE_DATA (dyn_range_type)->flag_upper_bound_is_count)
  	high_bound.data.const_val
  	  = low_bound.data.const_val + high_bound.data.const_val - 1;
      }
    else
      {
        high_bound.kind = PROP_UNDEFINED;
        high_bound.data.const_val = 0;
      }

That did not really made sense, setting the kind to `PROP_UNDEFINED` but
also setting the `const_val` field.  The `const_val` field is only
meaningful if the kind if `PROP_CONST`.  The new code
(post-8c2e4e0689ea24) simply calls `set_undefined ()`.

Fix this by making the caller, `ada_discrete_type_high_bound`, consider
that a range high bound could be of kind `PROP_UNDEFINED`, and return
0 in this case.  I made the same change in ada_discrete_type_low_bound.
I didn't encounter a problem with this function, but the same could in
theory happen there.

Returning 0 here is kind of a lie, but the goal here is just to restore
the behavior of pre-8c2e4e0689ea24.

The output of `maint print symbols` is:

     typedef <ada__exceptions__exception_data__append_info_basic_exception_information__TTnameSP1: range 1 .. 0;
     record
         ada__exceptions__exception_data__append_info_basic_exception_information__TTnameSP1: range 1 .. 0;
     end record;

Instead of `1 .. 0`, which does not make sense, we could say something
like `1 .. <dynamic>`.  But that would require more changes than I'm
willing to do at the moment.

[1] https://www.adacore.com/download

gdb/ChangeLog:

	PR ada/26235
	* gdbtypes.c (ada_discrete_type_low_bound,
	ada_discrete_type_high_bound): Handle undefined bounds.

Change-Id: Ia12167e61ef030941c0790f83294f3418e6a7c12
2020-07-21 15:13:21 -04:00
Tom de Vries
6d3d6e4ba7 [gdb/testsuite] Fix gdb.reverse/solib-{precsave,reverse}.exp with gcc-8
With gcc-8, we have the following FAILs, which are not there for gcc-7:
...
FAIL: gdb.reverse/solib-precsave.exp: reverse-step into solib function one
FAIL: gdb.reverse/solib-precsave.exp: reverse-step within solib function one
FAIL: gdb.reverse/solib-precsave.exp: reverse-step back to main one
FAIL: gdb.reverse/solib-precsave.exp: reverse-step into solib function two
FAIL: gdb.reverse/solib-precsave.exp: reverse-step within solib function two
FAIL: gdb.reverse/solib-precsave.exp: reverse-step back to main two
FAIL: gdb.reverse/solib-precsave.exp: run until end part two
FAIL: gdb.reverse/solib-precsave.exp: reverse-next over solib function one
FAIL: gdb.reverse/solib-reverse.exp: reverse-step into solib function one
FAIL: gdb.reverse/solib-reverse.exp: reverse-step within solib function one
FAIL: gdb.reverse/solib-reverse.exp: reverse-step back to main one
FAIL: gdb.reverse/solib-reverse.exp: reverse-step into solib function two
FAIL: gdb.reverse/solib-reverse.exp: reverse-step within solib function two
FAIL: gdb.reverse/solib-reverse.exp: reverse-step back to main two
FAIL: gdb.reverse/solib-reverse.exp: run until end part two
FAIL: gdb.reverse/solib-reverse.exp: reverse-next over solib function one
...

Looking at the first FAIL for gdb.reverse/solib-precsave.exp, we have:
...
 (gdb) PASS: reverse-next first shr1
 reverse-next^M
 40        b[0] = 6;   b[1] = 9;     /* generic statement, end part two */^M
 (gdb) PASS: reverse-next generic
 reverse-step^M
-shr2 (x=17) at gdb.reverse/shr2.c:23^M
-23      }^M
-(gdb) PASS: reverse-step into solib function one
+38        b[1] = shr2(17);              /* middle part two */^M
+(gdb) FAIL: reverse-step into solib function one
...

There's a difference in line number info for line 38, where for gcc-7 we have:
...
Line number    Starting address    View    Stmt
         38            0x4005c6               x
...
and for gcc-8:
...
         38            0x4005c1               x
         38            0x4005cb               x
...
which explains why we don't step directly into "solib function one".

Fix this by recognizing the extra "recommended breakpoint location" and
issuing an additional reverse-next/step.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.reverse/solib-precsave.exp: Handle additional "recommended
	breakpoint locations".
	* gdb.reverse/solib-reverse.exp: Same.
2020-07-21 16:22:34 +02:00
Tom de Vries
803d0592ab [gdb/testsuite] Fix step-reverse.c with gcc-10
The file gdb.reverse/step-reverse.c is used in test-cases:
- gdb.reverse/step-reverse.exp
- gdb.reverse/next-reverse-bkpt-over-sr.exp
- gdb.reverse/step-precsave.exp

With gcc-7, there are only PASSes (apart from one KFAIL), but with gcc-10, we
have the following FAILs:
...
FAIL: gdb.reverse/step-reverse.exp: reverse stepi from a function call \
  (start statement)
FAIL: gdb.reverse/step-reverse.exp: simple reverse stepi
FAIL: gdb.reverse/step-reverse.exp: reverse step out of called fn
FAIL: gdb.reverse/step-reverse.exp: reverse next over call
FAIL: gdb.reverse/step-reverse.exp: reverse step test 1
FAIL: gdb.reverse/step-reverse.exp: reverse next test 1
FAIL: gdb.reverse/step-reverse.exp: reverse step test 2
FAIL: gdb.reverse/step-reverse.exp: reverse next test 2
FAIL: gdb.reverse/step-precsave.exp: reverse stepi from a function call \
  (start statement)
FAIL: gdb.reverse/step-precsave.exp: simple reverse stepi
FAIL: gdb.reverse/step-precsave.exp: reverse step out of called fn
FAIL: gdb.reverse/step-precsave.exp: reverse next over call
FAIL: gdb.reverse/step-precsave.exp: reverse step test 1
FAIL: gdb.reverse/step-precsave.exp: reverse next test 1
FAIL: gdb.reverse/step-precsave.exp: reverse step test 2
FAIL: gdb.reverse/step-precsave.exp: reverse next test 2
...

Looking at the first step-precsave.exp FAIL, we have:
...
(gdb) stepi^M
26        myglob++; return 0;   /* ARRIVED IN CALLEE */^M
(gdb) PASS: gdb.reverse/step-precsave.exp: reverse stepi thru function return
stepi^M
0x000000000040055f      26        myglob++; return 0;   /* ARRIVED IN CALLEE */^M
(gdb) FAIL: gdb.reverse/step-precsave.exp: reverse stepi from a function call \
  (start statement)
...

There's a difference in line info for callee:
...
    25  int callee() {          /* ENTER CALLEE */
    26    myglob++; return 0;   /* ARRIVED IN CALLEE */
    27  }                       /* RETURN FROM CALLEE */
...
between gcc-7:
...
Line number    Starting address    View    Stmt
         25            0x400557               x
         26            0x40055b               x
         27            0x40056f               x
...
and gcc-10:
...
         25            0x400552               x
         26            0x400556               x
         26            0x400565               x
         27            0x40056a               x
...

The two "recommend breakpoint location" entries at line 26 are for the two
statements ("myglob++" and "return 0"), but the test-case expects to hit line
26 only once.

Fix this by rewriting the two statements into a single statement:
...
-  myglob++; return 0;  /* ARRIVED IN CALLEE */
+  return myglob++;     /* ARRIVED IN CALLEE */
...

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.reverse/step-reverse.c (callee): Merge statements.
2020-07-21 15:27:18 +02:00
Kamil Rytarowski
1de14d77bb Enable multi-process mode in the NetBSD native target.
This enables proper support for multiple inferiors and ptrace(2)
assisted management of the inferior processes and their threads.

(gdb) info inferior
  Num  Description       Connection           Executable
* 1    process 14952     1 (native)           /usr/bin/dig
  2    <null>            1 (native)
  3    process 25684     1 (native)           /bin/ls
  4    <null>            1 (native)           /bin/ls

Without this patch, additional inferiors can be added, but not
properly controlled.

gdb/ChangeLog:

        * nbsd-nat.h (nbsd_nat_target::supports_multi_process): New
        declaration.
        * nbsd-nat.c (nbsd_nat_target::supports_multi_process): New
        function.
2020-07-21 14:43:36 +02:00
Tom de Vries
e9bdc5108c [gdb/testsuite] Fix gdb.fortran/info-modules.exp with gcc-8
When using test-case gdb.fortran/info-modules.exp with gcc 8.4.0, I run into:
...
FAIL: gdb.fortran/info-modules.exp: info module variables: check for entry \
  'info-types.f90', '35', 'Type m1t1 mod1::__def_init_mod1_M1t1;'
FAIL: gdb.fortran/info-modules.exp: info module variables: check for entry \
  'info-types.f90', '35', 'Type __vtype_mod1_M1t1 mod1::__vtab_mod1_M1t1;'
...

This is caused by this change in gdb output:
...
 (gdb) info module variables
    ...
 File gdb.fortran/info-types.f90:
-35:     Type m1t1 mod1::__def_init_mod1_M1t1;
+        Type m1t1 mod1::__def_init_mod1_M1t1;
-35:     Type __vtype_mod1_M1t1 mod1::__vtab_mod1_M1t1;
+        Type __vtype_mod1_M1t1 mod1::__vtab_mod1_M1t1;
 21:     real(kind=4) mod1::mod1_var_1;
 22:     integer(kind=4) mod1::mod1_var_2;
...
caused by a change in debug info.

Fix this by allowing those entries without line number.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.fortran/info-modules.exp (info module variables): Allow missing
	line numbers for some variables.
2020-07-21 11:37:17 +02:00
Tom de Vries
f0f9e75a82 [gdb/testsuite] Make inline-locals.c deterministic
When running testcase gdb.opt/inline-locals.exp on openSUSE Tumbleweed, I get:
...
(gdb) info locals^M
array = {0 <repeats 48 times>, 15775231, 0, 194, 0, -11497, 32767, 4199061, \
  0, 0, 0, 0, 0, 4198992, 0, 4198432, 0}^M
(gdb) FAIL: gdb.opt/inline-locals.exp: info locals above bar 2
...

Fix this by:
- completely initializing array before printing any value
- updating the pattern to match "array = {0 <repeats 64 times>}"

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.opt/inline-locals.c (init_array): New func.
	(func1): Use init_array.
	* gdb.opt/inline-locals.exp: Update pattern.
2020-07-21 10:25:42 +02:00
Tom de Vries
bd460ecb31 [gdb/testsuite] Don't leak env vars in gdb.debuginfod/fetch_src_and_symbols.exp
Test-case gdb.debuginfod/fetch_src_and_symbols.exp leaks env vars
DEBUGINFOD_URLS, DEBUGINFOD_TIMEOUT and DEBUGINFOD_CACHE_PATH, causing
timeouts in subsequent tests.

Fix this by using save_vars.  Also, fix PATH and DUPLICATE errors.  Finally,
cleanup whitespace.

gdb/testsuite/ChangeLog:

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

	* gdb.debuginfod/fetch_src_and_symbols.exp: Use save_vars for env
	vars.  Fix PATH and DUPLICATE errors.  Cleanup whitespace.
2020-07-21 09:40:21 +02:00
John Baldwin
ed810cc7d3 Implement the skip_solib_resolver gdbarch hook for FreeBSD architectures.
The ELF runtime linker on all FreeBSD architectures uses the
"_rtld_bind" entry point for unresolved PTL entries.  FreeBSD/mips has
an additional entry point called "_mips_rtld_bind".

gdb/ChangeLog:

	* fbsd-tdep.c (fbsd_skip_solib_resolver): New function.
	(fbsd_init_abi): Install gdbarch "skip_solib_resolver" method.
	* fbsd-tdep.h (fbsd_skip_solib_resolver): New prototype.
	* mips-fbsd-tdep.c (mips_fbsd_skip_solib_resolver): New function.
	(mips_fbsd_init_abi): Install gdbarch "skip_solib_resolver"
	method.
2020-07-20 09:10:18 -07:00
Ludovic Courtès
ae5369e773 guile: Add support for Guile 3.0.
gdb/ChangeLog
2020-06-28  Ludovic Courtès  <ludo@gnu.org>

	* guile/scm-math.c (vlscm_integer_fits_p): Use 'uintmax_t'
	and 'intmax_t' instead of 'scm_t_uintmax' and 'scm_t_intmax',
	which are deprecated in Guile 3.0.
	* configure.ac (try_guile_versions): Add "guile-3.0".
	* configure (try_guile_versions): Regenerate.
	* NEWS: Update entry.

gdb/testsuite/ChangeLog
2020-06-28  Ludovic Courtès  <ludo@gnu.org>

	* gdb.guile/source2.scm: Add #f first argument to 'format'.
	* gdb.guile/types-module.exp: Remove "ERROR:" from
	regexps since Guile 3.0 no longer prints that.

gdb/doc/ChangeLog
2020-06-28  Ludovic Courtès  <ludo@gnu.org>

	* doc/guile.texi (Guile Introduction): Mention Guile 3.0.

Change-Id: Iff116c2e40f334e4e0ca4e759a097bfd23634679
2020-07-20 11:00:55 -04:00
Ludovic Courtès
68cf161c24 guile: Add support for Guile 2.2.
This primarily updates code that uses the I/O port API of Guile.

gdb/ChangeLog
2020-06-28  Ludovic Courtès  <ludo@gnu.org>
            Doug Evans  <dje@google.com>

	PR gdb/21104
	* guile/scm-ports.c (USING_GUILE_BEFORE_2_2): New macro.
	(ioscm_memory_port)[read_buf_size, write_buf_size]: Wrap in #if
	USING_GUILE_BEFORE_2_2.
	(stdio_port_desc, memory_port_desc) [!USING_GUILE_BEFORE_2_2]:
	Change type to 'scm_t_port_type *'.
	(natural_buffer_size) [!USING_GUILE_BEFORE_2_2]: New variable.
	(ioscm_open_port) [USING_GUILE_BEFORE_2_2]: Add 'stream'
	parameter and honor it.  Update callers.
	(ioscm_open_port) [!USING_GUILE_BEFORE_2_2]: New function.
	(ioscm_read_from_port, ioscm_write) [!USING_GUILE_BEFORE_2_2]: New
	functions.
	(ioscm_fill_input, ioscm_input_waiting, ioscm_flush): Wrap in #if
	USING_GUILE_BEFORE_2_2.
	(ioscm_init_gdb_stdio_port) [!USING_GUILE_BEFORE_2_2]: Use
	'ioscm_read_from_port'.  Call 'scm_set_port_read_wait_fd'.
	(ioscm_init_stdio_buffers) [!USING_GUILE_BEFORE_2_2]: New function.
	(gdbscm_stdio_port_p) [!USING_GUILE_BEFORE_2_2]: Use 'SCM_PORTP'
	and 'SCM_PORT_TYPE'.
	(gdbscm_memory_port_end_input, gdbscm_memory_port_seek)
	(ioscm_reinit_memory_port): Wrap in #if USING_GUILE_BEFORE_2_2.
	(gdbscm_memory_port_read, gdbscm_memory_port_write)
	(gdbscm_memory_port_seek, gdbscm_memory_port_close)
	[!USING_GUILE_BEFORE_2_2]: New functions.
	(gdbscm_memory_port_print): Remove use of 'SCM_PTOB_NAME'.
	(ioscm_init_memory_port_type) [!USING_GUILE_BEFORE_2_2]: Use
	'gdbscm_memory_port_read'.
	Wrap 'scm_set_port_end_input', 'scm_set_port_flush', and
	'scm_set_port_free' calls in #if USING_GUILE_BEFORE_2_2.
	(gdbscm_get_natural_buffer_sizes) [!USING_GUILE_BEFORE_2_2]: New
	function.
	(ioscm_init_memory_port): Remove.
	(ioscm_init_memory_port_stream): New function
	(ioscm_init_memory_port_buffers) [USING_GUILE_BEFORE_2_2]: New
	function.
	(gdbscm_memory_port_read_buffer_size) [!USING_GUILE_BEFORE_2_2]:
	Return scm_from_uint (0).
	(gdbscm_set_memory_port_read_buffer_size_x)
	[!USING_GUILE_BEFORE_2_2]: Call 'scm_setvbuf'.
	(gdbscm_memory_port_write_buffer_size) [!USING_GUILE_BEFORE_2_2]:
	Return scm_from_uint (0).
	(gdbscm_set_memory_port_write_buffer_size_x)
	[!USING_GUILE_BEFORE_2_2]: Call 'scm_setvbuf'.
	* configure.ac (try_guile_versions): Add "guile-2.2".
	* configure: Regenerate.
	* NEWS: Add entry.

gdb/testsuite/ChangeLog
2020-06-28  Ludovic Courtès  <ludo@gnu.org>

	* gdb.guile/scm-error.exp ("source $remote_guile_file_1"): Relax
	error regexp to match on Guile 2.2.

gdb/doc/ChangeLog
2020-06-28  Ludovic Courtès  <ludo@gnu.org>

	* guile.texi (Memory Ports in Guile): Mark
	'memory-port-read-buffer-size',
	'set-memory-port-read-buffer-size!',
	'memory-port-write-buffer-size',
	'set-memory-port-read-buffer-size!' as deprecated.
	* doc/guile.texi (Guile Introduction): Clarify which Guile
	versions are supported.

Change-Id: Ib119b10a2787446e0ae482a5e1b36d809c44bb31
2020-07-20 10:59:47 -04:00
Gary Benson
c14b491355 Skip tests requiring "alignof (void)" when compiling using clang
As an extension, GCC allows void pointer arithmetic, with sizeof(void)
and alignof(void) both 1.  GDB supports this extension, but clang does
not, and fails to compile the generated output of gdb.cp/align.exp
with the following error:

 gdb compile failed, /gdbtest/build/gdb/testsuite/outputs/gdb.cp/align/align.cc:28:23:
       error: invalid application of 'alignof' to an incomplete type 'void'
    unsigned a_void = alignof (void);
                      ^       ~~~~~~
 1 error generated.

This commit adds preprocessor conditionals to the generated output, to
omit the unsupported code when using clang, and supplies the expected
value so the test can complete.

gdb/testsuite/ChangeLog:

	* gdb.cp/align.exp: Fix "alignof (void)" tests when compiling
	with clang.
2020-07-20 15:01:04 +01:00
Tom de Vries
b243ba58e8 [gdb/testsuite] Stabilize execution order in omp-par-scope.c
In openmp test-case gdb.threads/omp-par-scope.exp we xfail and kfail dependent
on omp_get_thread_num ().  Since execution order of the threads can vary from
execution to execution, this can cause changes in test results.

F.i., we can see this difference between two test runs:
...
-KFAIL: single_scope: first thread: print i3 (PRMS: gdb/22214)
+PASS: single_scope: first thread: print i3
-PASS: single_scope: second thread: print i3
+KFAIL: single_scope: second thread: print i3 (PRMS: gdb/22214)
...
In both cases, the KFAIL is for omp_get_thread_num () == 1, but in one case
that corresponds to the first thread executing that bit of code, and in the
other case to the second thread.

Get rid of this difference by stabilizing execution order.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.threads/omp-par-scope.c (lock, lock2): New variable.
	(omp_set_lock_in_order): New function.
	(single_scope, multi_scope, nested_func, nested_parallel): Use
	omp_set_lock_in_order and omp_unset_lock.
	(main): Init and destroy lock and lock2.
2020-07-20 14:40:52 +02:00
Tom de Vries
c06ad8b573 [gdb/testsuite] Fix valgrind-infcall-2.exp without libc debug info
When running test-case gdb.base/valgrind-infcall-2.exp on a system without
libc debug info installed, I run into:
...
(gdb) p printf ("bla")^M
'printf' has unknown return type; cast the call to its declared return type^M
(gdb) FAIL: gdb.base/valgrind-infcall-2.exp: do printf
...

Fix this by casting the result of the printf call to int.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.base/valgrind-infcall-2.exp: Handle printf unknown return type.
2020-07-20 11:19:51 +02:00
Tom de Vries
6e22f11784 [gdb/testsuite] Bail out after gdb_start error in gdb.threads/attach-slow-waitpid.exp
When building gdb using CFLAGS/CXXFLAGS+=-fsanitizer=address and
LDFLAGS+=-lasan, and running test-case gdb.threads/attach-slow-waitpid.exp,
we get:
...
spawn gdb -nw -nx -data-directory data-directory^M
==16079==ASan runtime does not come first in initial library list; \
  you should either link runtime to your application or manually preload \
  it with LD_PRELOAD.^M
ERROR: (eof) GDB never initialized.
ERROR: : spawn id exp10 not open
    while executing
"expect {
-i exp10 -timeout 120
        -re "Kill the program being debugged. .y or n. $" {
            send_gdb "y\n" answer
            verbose "\t\tKilling previous pro..."
    ("uplevel" body line 1)
    invoked from within
"uplevel $body" NONE : spawn id exp10 not open
WARNING: remote_expect statement without a default case
ERROR: : spawn id exp10 not open
    while executing
"expect {
-i exp10 -timeout 120
        -re "Reading symbols from.*LZMA support was disabled.*$gdb_prompt $" {
            verbose "\t\tLoaded $arg into $GDB; .gnu_..."
    ("uplevel" body line 1)
    invoked from within
"uplevel $body" NONE : spawn id exp10 not open
ERROR: Couldn't load attach-slow-waitpid into GDB (eof).
ERROR: Couldn't send attach 16070 to GDB.
UNRESOLVED: gdb.threads/attach-slow-waitpid.exp: attach to target
...

Bail out at the first ERROR, such that we have instead:
...
ERROR: (eof) GDB never initialized.
UNTESTED: gdb.threads/attach-slow-waitpid.exp: \
  Couldn't start GDB with preloaded lib
...

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.threads/attach-slow-waitpid.exp: Bail out if gdb_start fails.
2020-07-20 10:54:31 +02:00
Tom Tromey
aee91db3eb Remove "linux_multi_process" global
The "linux_multi_process" is initialized but never modified.  I
discussed this with Pedro on irc, and he said that, while it was
useful when developing this feature, it is now no longer needed.  So,
this removes it.

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

	* linux-nat.c (linux_multi_process): Remove.
	(linux_nat_target::supports_multi_process): Return true.
2020-07-18 10:43:16 -06:00
Andrew Burgess
0e26741636 gdb/riscv: delete target descriptions when gdb exits
It was pointed out on IRC that the RISC-V target allocates target
descriptions and stores them in a global map, and doesn't delete these
target descriptions when GDB shuts down.

This isn't a particular problem, the total number of target
descriptions we can create is very limited so creating these on demand
and holding them for the entire run on GDB seems reasonable.

However, not deleting these objects on GDB exit means extra warnings
are printed from tools like valgrind, and the address sanitiser,
making it harder to spot real issues.  As it's reasonably easy to have
GDB correctly delete these objects on exit, lets just do that.

I started by noticing that we already have a target_desc_up type, a
wrapper around unique_ptr that calls a function that will correctly
delete target descriptions, so I want to use that, but....

...that type is declared in gdb/target-descriptions.h.  If I try to
include that file in gdb/arch/riscv.c I run into a problem, that file
is compiled into both GDB and GDBServer.

OK, I could guard the include with #ifdef, but surely we can do
better.

So then I decided to move the target_desc_up type into
gdbsupport/tdesc.h, this is the interface file for generic code shared
between GDB and GDBserver (relating to target descriptions).  The
actual implementation for the delete function still lives in
gdb/target-description.c, but now gdb/arch/riscv.c can see the
declaration.  Problem solved....

... but, though RISC-V doesn't use it I've now exposed the
target_desc_up type to gdbserver, so in future someone _might_ start
using it, which is fine, except right now there's no definition of the
delete function - remember the delete I used is only defined in GDB
code.

No problem, I add an implementation of the delete operator into
gdbserver/tdesc.cc, and all is good..... except....

I start getting this error from GCC:

  tdesc.cc:109:10: error: deleting object of polymorphic class type ‘target_desc’ which has non-virtual destructor might cause undefined behavior [-Werror=delete-non-virtual-dtor]

Which is caused because gdbserver's target_desc type inherits from
tdesc_element which has a virtual method, and so GCC worries that
target_desc might be used as a base class.

The solution is to declare gdbserver's target_desc class as final.
This is fine so long as we never intent to inherit from
target_desc (in gdbserver).  But if we did then we'd want to make
target_desc's destructor virtual anyway, so the error above would be
resolved, and there wouldn't be an issue.

gdb/ChangeLog:

	* arch/riscv.c (riscv_tdesc_cache): Change map type.
	(riscv_lookup_target_description): Return pointer out of
	unique_ptr.
	* target-descriptions.c (allocate_target_description): Add
	comment.
	(target_desc_deleter::operator()): Likewise.
	* target-descriptions.h (struct target_desc_deleter): Moved to
	gdbsupport/tdesc.h.
	(target_desc_up): Likewise.

gdbserver/ChangeLog:

	* tdesc.cc (allocate_target_description): Add header comment.
	(target_desc_deleter::operator()): New function.
	* tdesc.h (struct target_desc): Declare as final.

gdbsupport/ChangeLog:

	* tdesc.h (struct target_desc_deleter): Moved here
	from gdb/target-descriptions.h, extend comment.
	(target_desc_up): Likewise.
2020-07-17 21:15:32 +01:00
Tom de Vries
33176ea7d7 [gdb/testsuite] Add gdb.base/valgrind-infcall-2.exp
In commit ee3c5f8968 "Fix GDB crash when registers cannot be modified", we
fix a GDB crash:
...
$ valgrind /usr/bin/sleep 10000
==31595== Memcheck, a memory error detector
==31595== Command: /usr/bin/sleep 10000
==31595==
$ gdb /usr/bin/sleep
(gdb) target remote | vgdb --pid=31595
Remote debugging using | vgdb --pid=31595
  ...
$hex in __GI___nanosleep () at nanosleep.c:27
27	  return SYSCALL_CANCEL (nanosleep, requested_time, remaining);
(gdb) p printf ("bla")
terminate called after throwing an instance of 'gdb_exception_error'
Aborted (core dumped)
...

This patch adds a test-case for it.

Unfortunately, I was not able to trigger the error condition using a regular
vgdb_start, so I've added a parameter active_at_startup, and when set to 0
this causes valgrind to be started without --vgdb-error=0.

Tested on x86_64-linux.

Tested with the commit mentioned above reverted, resulting in:
...
(gdb) p printf ("bla")^M
terminate called after throwing an instance of 'gdb_exception_error'^M
ERROR: GDB process no longer exists
GDB process exited with wait status 6152 exp10 0 0 CHILDKILLED SIGABRT SIGABRT
UNRESOLVED: gdb.base/valgrind-infcall-2.exp: do printf
...

gdb/testsuite/ChangeLog:

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

	* gdb.base/valgrind-infcall-2.c: New test.
	* gdb.base/valgrind-infcall-2.exp: New file.
	* lib/valgrind.exp (vgdb_start): Add and handle active_at_startup.
2020-07-17 17:33:18 +02:00
Tom Tromey
f80c8ec423 Use boolean literals in linux-nat.c
I noticed a couple of spots in linux-nat.c that use 0/1 where boolean
literals would be more idiomatic.  This patch makes this change.

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

	* linux-nat.c (linux_nat_target::supports_non_stop)
	(linux_nat_target::always_non_stop_p): Use "true".
	(linux_nat_target::supports_disable_randomization): Use "true" and
	"false".
2020-07-17 09:21:12 -06:00
Tom de Vries
90c3ec2d21 [gdb/testsuite] Use MACRO_AT_{func,range}
Use dwarf assembly procs MACRO_AT_func and MACRO_AT_range in test-cases where
that's appropriate.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.dlang/circular.c (found): Use found_label as label name.
	* gdb.dwarf2/arr-subrange.c (main): Use main_label as label name.
	* gdb.dwarf2/comp-unit-lang.c (func): Use func_label as label name.
	* gdb.dlang/circular.exp: Use MACRO_AT_func and MACRO_AT_range.
	* gdb.dwarf2/ada-linkage-name.exp: Same.
	* gdb.dwarf2/arr-subrange.exp: Same.
	* gdb.dwarf2/atomic-type.exp: Same.
	* gdb.dwarf2/comp-unit-lang.exp: Same.
	* gdb.dwarf2/cpp-linkage-name.exp: Same.
	* gdb.dwarf2/dw2-bad-mips-linkage-name.exp: Same.
	* gdb.dwarf2/dw2-lexical-block-bare.exp: Same.
	* gdb.dwarf2/dw2-regno-invalid.exp: Same.
	* gdb.dwarf2/implptr-64bit.exp: Same.
	* gdb.dwarf2/imported-unit-abstract-const-value.exp: Same.
	* gdb.dwarf2/imported-unit-runto-main.exp: Same.
	* gdb.dwarf2/imported-unit.exp: Same.
	* gdb.dwarf2/main-subprogram.exp: Same.
	* gdb.dwarf2/missing-type-name.exp: Same.
	* gdb.dwarf2/nonvar-access.exp: Same.
	* gdb.dwarf2/struct-with-sig.exp: Same.
	* gdb.dwarf2/typedef-void-finish.exp: Same.
	* gdb.dwarf2/void-type.exp: Same.
2020-07-17 16:42:37 +02:00
Tom de Vries
10da644dc4 [gdb/testsuite] Drop src arg of MACRO_AT_{func,range}
The dwarf assembly procs MACRO_AT_func and MACRO_AT_range have a src
parameter, which is set to $srcdir/$subdir/$srcfile in every single call.

Drop the src parameter and hardcode usage of $srcdir/$subdir/$srcfile in the
procs.

Build and reg-tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* lib/dwarf.exp (Dwarf::MACRO_AT_func, Dwarf::MACRO_AT_range): Drop
	src parameter.
	* gdb.dlang/watch-loc.exp: Update MACRO_AT_{func,range} calls.
	* gdb.dwarf2/bitfield-parent-optimized-out.exp: Same.
	* gdb.dwarf2/dw2-ifort-parameter.exp: Same.
	* gdb.dwarf2/dw2-opt-structptr.exp: Same.
	* gdb.dwarf2/dwz.exp: Same.
	* gdb.dwarf2/implptr-optimized-out.exp: Same.
	* gdb.dwarf2/implref-array.exp: Same.
	* gdb.dwarf2/implref-const.exp: Same.
	* gdb.dwarf2/implref-global.exp: Same.
	* gdb.dwarf2/implref-struct.exp: Same.
	* gdb.dwarf2/info-locals-optimized-out.exp: Same.
	* gdb.dwarf2/opaque-type-lookup.exp: Same.
	* gdb.dwarf2/var-access.exp: Same.
	* gdb.dwarf2/varval.exp: Same.
	* gdb.trace/entry-values.exp: Same.
2020-07-17 14:35:44 +02:00
Tom de Vries
315e6afc82 [gdb/testsuite] Remove Dwarf::extern
The file lib/dwarf.exp contains:
...
    # Declare a global label.  This is typically used to refer to
    # labels defined in other files, for example a function defined in
    # a .c file.
    proc extern {args} {
	foreach name $args {
	    _op .global $name
	}
    }
...

The assembler directive to refer to labels defined in other files is
not .global, but .extern, and that one is ignored by gas.

Since we require gas for all dwarf assembly test-cases, remove the proc and
all it's uses.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* lib/dwarf.exp (Dwarf::extern): Remove.
	* gdb.compile/compile-ops.exp: Remove use of Dwarf::extern.
	* gdb.dlang/circular.exp: Same.
	* gdb.dwarf2/comp-unit-lang.exp: Same.
	* gdb.dwarf2/dw2-ifort-parameter.exp: Same.
	* gdb.dwarf2/dw2-symtab-includes.exp: Same.
	* gdb.dwarf2/dwz.exp: Same.
	* gdb.dwarf2/imported-unit-abstract-const-value.exp: Same.
	* gdb.dwarf2/imported-unit-runto-main.exp: Same.
	* gdb.dwarf2/imported-unit.exp: Same.
	* gdb.dwarf2/opaque-type-lookup.exp: Same.
2020-07-17 13:06:42 +02:00
Sandra Loosemore
5597c9402d Fix POSIX-isms in gdb.base/shell.exp
Some recent tests added to gdb.base/shell.exp have been failing on
Windows host due to assumptions that the shell is a POSIX variant.  On
Windows, GDB uses CMD.EXE via the system() call to run shell commands
instead.

There seems to be no obvious CMD.EXE equivalent for "kill -2 $$" to
signal the shell process, so this patch skips those tests on Windows
host.  The second problem addressed here is that CMD.EXE only
recognizes double quotes, not single quotes; that change can be made
unconditionally since POSIX shells recognize double quotes as well.

2020-07-16  Sandra Loosemore  <sandra@codesourcery.com>

	gdb/testsuite/
	* gdb.base/shell.exp: Skip pipe tests dependent on sh on Windows host.
	Use double quotes instead of single quotes.
2020-07-16 14:03:09 -07:00
Caroline Tice
d0ce17d853 gdb: fix issues with handling DWARF v5 rnglists & .dwo files.
While experimenting with GDB on DWARF 5 with split debug (dwo files),
I discovered that GDB was not reading the rnglist index
properly (it needed to be reprocessed in the same way the loclist
index does), and that there was no code for reading rnglists out of
dwo files at all.  Also, the rnglist address reading function
(dwarf2_rnglists_process) was adding the base address to all rnglist
entries, when it's only supposed to add it to the DW_RLE_offset_pair
entries (http://dwarfstd.org/doc/DWARF5.pdf, p. 53), and was not
handling several entry types.

- Added 'reprocessing' for reading rnglist index (as is done for loclist
  index).
- Added code for reading rnglists out of .dwo files.
- Added several missing rnglist forms to dwarf2_rnglists_process.
- Fixed bug that was alwayas adding base address for rnglists (only
  one form needs that).
- Updated dwarf2_rnglists_process to read rnglist out of dwo file when
  appropriate.
- Added new functions cu_debug_rnglist_section & read_rnglist_index.
- Added new testcase, dw5-rnglist-test.{cc,exp}

Special note about the new testcase:

In order for the test case to test anything meaningful, it must be
compiled with clang, not GCC.  The way to do this is as follows:

$ make check RUNTESTFLAGS="CC_FOR_TARGET=/path/to/clang CXX_FOR_TARGET=/path/to/clang++ dw5-rnglist-test.exp"

This following version of clang was used for this testing:

clang version 9.0.1-11
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

Change-Id: I3053c5ddc345720b8ed81e23a88fe537ab38748d
2020-07-16 11:37:15 -04:00
Tom de Vries
853772cc18 [gdb/testsuite] Add pseudo line number program instruction: line
There's an idiom in dwarf assembly test-cases:
...
set line1 [gdb_get_line_number "line 1"]
set line2 [gdb_get_line_number "line 2"]
set line3 [gdb_get_line_number "line 3"]
  ...
            {DW_LNS_advance_line [expr $line1 - 1]}
  ...
            {DW_LNS_advance_line [expr $line2 - $line1]}
  ...
            {DW_LNS_advance_line [expr $line3 - $line2]}
...

Add a pseudo line number program instruction "line", such that we can simply
write:
...
            {line $line1}
  ...
            {line $line2}
  ...
            {line $line3}
...

Build and reg-tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* lib/dwarf.exp (program): Initialize _line.
	(DW_LNE_end_sequence): Reinitialize _line.
	(DW_LNS_advance_line): Update _line.
	(line): New proc.
	* gdb.dwarf2/dw2-inline-many-frames.exp: Use line.
	* gdb.dwarf2/dw2-inline-small-func.exp: Same.
	* gdb.dwarf2/dw2-inline-stepping.exp: Same.
	* gdb.dwarf2/dw2-is-stmt-2.exp: Same.
	* gdb.dwarf2/dw2-is-stmt.exp: Same.
	* gdb.dwarf2/dw2-ranges-func.exp: Same.
2020-07-16 15:34:00 +02:00
Andrew Burgess
fe07b5721a gdb/testsuite: Update test pattern in ptype-on-functions.exp
It was pointed out that the recently added test
gdb.fortran/ptype-on-functions.exp fails on older versions of
gfortran.  This is because the ABI for passing string lengths changed
from a 4-byte to 8-byte value (on some targets).

This change is documented here:
  https://gcc.gnu.org/gcc-8/changes.html.

  Character variables longer than HUGE(0) elements are now possible on
  64-bit targets. Note that this changes the procedure call ABI for
  all procedures with character arguments on 64-bit targets, as the
  type of the hidden character length argument has changed. The hidden
  character length argument is now of type INTEGER(C_SIZE_T).

This commit just relaxes the pattern to accept any size of integer for
the string length argument.

gdb/testsuite/ChangeLog:

	* gdb.fortran/ptype-on-functions.exp: Make the result pattern more
	generic.
2020-07-15 16:12:17 +01:00
Tom de Vries
52781cce79 [gdb/testsuite] Handle callq -> call disassembly change
We're currently running into:
...
FAIL: gdb.trace/entry-values.exp: disassemble bar
...

Since commit 36938cabf0 "x86: avoid attaching suffixes to unambiguous insns",
"callq" is disassembled as "call", and the test-case expects "callq".

Fix this by expecting "call" instead.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.trace/entry-values.exp: Expect "call" instead of "callq" if
	is_amd64_regs_target.
2020-07-15 11:17:41 +02:00
Andrew Burgess
3dcc261cf8 gdb/fortran: Handle dynamic string types when printing types
After commit:

  commit 8c2e4e0689
  Date:   Sun Jul 12 22:58:51 2020 -0400

      gdb: add accessors to struct dynamic_prop

An existing bug was exposed in the Fortran type printing code.  When
GDB is asked to print the type of a function that takes a dynamic
string argument GDB will try to read the upper bound of the string.

The read of the upper bound is written as:

    if (type->bounds ()->high.kind () == PROP_UNDEFINED)
      // Treat the upper bound as unknown.
    else
      // Treat the upper bound as known and constant.

However, this is not good enough.  When printing a function type the
dynamic argument types will not have been resolved.  As a result the
dynamic property is not PROP_UNDEFINED, but nor is it constant.

By rewriting this code to specifically check for the PROP_CONST case,
and treating all other cases as the upper bound being unknown we avoid
incorrectly treating the dynamic property as being constant.

gdb/ChangeLog:

	* f-typeprint.c (f_type_print_base): Allow for dynamic types not
	being resolved.

gdb/testsuite/ChangeLog:

	* gdb.fortran/ptype-on-functions.exp: Add more tests.
	* gdb.fortran/ptype-on-functions.f90: Likewise.
2020-07-15 08:56:25 +01:00
Simon Marchi
054a095926 gdb/testsuite/lib/dwarf.exp: fix addr_size parameter comments
The comments modified in this patch claim that the addr_size parameters
can take the value 32 or 64 (suggesting the value is in bits).  In fact,
the expected value is in bytes, either 4 or 8.

The actual value in the DWARF info is in bytes.  And we can see that the
default values used (if addr_size == "default") are:

	if {$_cu_addr_size == "default"} {
	    if {[is_64_target]} {
		set _cu_addr_size 8
	    } else {
		set _cu_addr_size 4
	    }
	}

gdb/testsuite/ChangeLog:

	* lib/dwarf.exp (Dwarf::cu, Dwarf::tu, Dwarf::lines): Change valid
	values in documentation for addr_size to 4 and 8.

Change-Id: I4a02dca2bb7992198864e545ef099f020f54ff2f
2020-07-14 23:18:30 -04:00
Andrew Burgess
f63dcaf808 gdb: Improve formatting of 'show endian' messages
This commit changes the output of 'show endian'.  Here is a
session before this commit:

    (gdb) show endian
    The target endianness is set automatically (currently little endian)
    (gdb) set endian big
    The target is assumed to be big endian
    (gdb) show endian
    The target is assumed to be big endian
    (gdb)

After this commit the session now looks like this:

    (gdb) show endian
    The target endianness is set automatically (currently little endian).
    (gdb) set endian big
    The target is set to big endian.
    (gdb) show endian
    The target is set to big endian.
    (gdb)

The changes are:

  1. Each line ends with '.', and
  2. After setting the endianness GDB is now a little more assertive;
  'target is set to' not 'target is assumed to be', the user did just
  tell us after all!
2020-07-14 13:21:42 +01:00
Andrew Burgess
ccb9eba6a2 gdb: Improve formatting of 'show architecture' messages
This commit changes the output of 'show architecture'.  Here is a
session before this commit:

  (gdb) show architecture
  The target architecture is set automatically (currently i386)
  (gdb) set architecture mips
  The target architecture is assumed to be mips
  (gdb) show architecture
  The target architecture is assumed to be mips
  (gdb)

After this commit the session now looks like this:

  (gdb) show architecture
  The target architecture is set to "auto" (currently "i386").
  (gdb) set architecture mips
  The target architecture is set to "mips".
  (gdb) show architecture
  The target architecture is set to "mips".
  (gdb)

The changes are:

  1. The value is now enclosed in quotes,
  2. Each line ends with '.', and
  3. After setting the architecture GDB is now a little more
  assertive; 'architecture is set to' not 'is assumed to be', the user
  did just tell us after all!

gdb/ChangeLog:

	* arch-utils.c (show_architecture): Update formatting of messages.

gdb/testsuite/ChangeLog:

	* gdb.arch/amd64-osabi.exp: Update.
	* gdb.arch/arm-disassembler-options.exp: Update.
	* gdb.arch/powerpc-disassembler-options.exp: Update.
	* gdb.arch/ppc64-symtab-cordic.exp: Update.
	* gdb.arch/s390-disassembler-options.exp: Update.
	* gdb.base/all-architectures.exp.tcl: Update.
	* gdb.base/attach-pie-noexec.exp: Update.
	* gdb.base/catch-syscall.exp: Update.
	* gdb.xml/tdesc-arch.exp: Update.
2020-07-14 13:21:42 +01:00
Tom de Vries
025a39a7c2 [gdb/testsuite] Fix clone-new-thread-event.c with glibc 2.30
Starting glibc 2.30, unistd.h declares gettid (for _GNU_SOURCE).

This clashes with a static gettid in test source
clone-new-thread-event.c:
...
gdb compile failed, gdb.threads/clone-new-thread-event.c:46:1: error: \
  static declaration of 'gettid' follows non-static declaration
   46 | gettid (void)
      | ^~~~~~
In file included from /usr/include/unistd.h:1170,
                 from gdb.threads/clone-new-thread-event.c:27:
/usr/include/bits/unistd_ext.h:34:16: note: previous declaration of 'gettid' \
  was here
   34 | extern __pid_t gettid (void) __THROW;
      |                ^~~~~~
...

Fix this by renaming the static gettid to local_gettid.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* gdb.threads/clone-new-thread-event.c (gettid): Rename to ...
	(local_gettid): ... this.
	(fn): Update.
2020-07-14 10:36:17 +02:00
Paul Carroll
ed788fee02 Fix frame-apply.html collision in GDB manual.
The addition of an anchor for the "frame apply" command was causing
the HTML documentation to include files named both "frame-apply.html"
and "Frame-Apply.html", which collide on case-insensitive file
systems.  This patch removes the redundant anchor and adjusts the two
xrefs to it.

2020-07-13 Paul Carroll <pcarroll@codesourcery.com>

	PR gdb/25716

	gdb/doc/
	* gdb.texinfo (Frame Apply): Remove anchor for 'frame
	apply' and adjust xrefs to it.
2020-07-13 12:31:05 -07:00
Sandra Loosemore
74e4b667ec Skip directory tests in gdb.base/info_sources.exp on remote host
When testing on a remote host, source files from build are copied to
an arbitrary location on host.  Tests that try to pattern-match host
pathnames against directory prefixes on build don't generally work.

2020-07-13  Sandra Loosemore  <sandra@codesourcery.com>

	gdb/testsuite/
	* gdb.base/info_sources.exp: Skip directory match tests on
	remote hosts.
2020-07-13 11:34:04 -07:00
Gary Benson
f413dd7439 Fix gdb.base/savedregs.exp with clang
gdb.base/savedregs.exp fails to run with clang, because of:

 gdb compile failed, /gdbtest/src/gdb/testsuite/gdb.base/savedregs.c:36:37:
       warning: operator '<<' has lower precedence than '+'; '+' will be
       evaluated first [-Wshift-op-parentheses]
   return callee (a1 << a2 * a3 / a4 + a6 & a6 % a7 - a8) + done;
                     ~~ ~~~~~~~~~~~~~^~~~
 /gdbtest/build/gdb/testsuite/gdb.base/savedregs.c:36:37: note: place
       parentheses around the '+' expression to silence this warning
   return callee (a1 << a2 * a3 / a4 + a6 & a6 % a7 - a8) + done;
                                     ^
                        (                )
 1 warning generated.

This commit fixes it by adding the suggested parentheses.

gdb/testsuite/ChangeLog:

	* gdb.base/savedregs.exp (caller): Use parentheses to
	make expected expression evaluation ordering explicit.
2020-07-13 16:01:00 +01:00
Gary Benson
915771bb8a Fix gdb.arch/i386-sse.exp with clang
gdb.arch/i386-sse.exp fails to run with clang, because of:

 gdb compile failed, /gdbtest/src/gdb/testsuite/gdb.arch/i386-sse.c:56:40: warning:
       passing 'int *' to parameter of type 'unsigned int *' converts between
       pointers to integer types with different sign [-Wpointer-sign]
   if (!x86_cpuid (1, NULL, NULL, NULL, &edx))
                                        ^~~~
 /gdbtest/src/gdb/testsuite/../nat/x86-cpuid.h:35:41: note: passing
       argument to parameter '__edx' here
             unsigned int *__ecx, unsigned int *__edx)
                                               ^
 1 warning generated.

Fix it by declaring edx unsigned.

gdb/testsuite/ChangeLog:

	* gdb.arch/i386-sse.c (have_sse) <edx>: Make unsigned.
2020-07-13 15:14:07 +01:00
Gary Benson
2a122642b4 Use volatile pointers when attempting to trigger SIGSEGVs
Clang fails to compile a number of files with the following warning:
indirection of non-volatile null pointer will be deleted, not trap
[-Wnull-dereference].  This commit qualifies the relevant pointers
with 'volatile'.

gdb/testsuite/ChangeLog:

	* gdb.base/bigcore.c (main): Use a volatile pointer when
	attempting to trigger a SIGSEGV.
	* gdb.base/gcore-relro-pie.c (break_here): Likewise.
	* gdb.base/gcore-tls-pie.c (break_here): Likewise.
	* gdb.base/savedregs.c (thrower): Likewise.
	* gdb.mi/mi-syn-frame.c (bar): Likewise.
2020-07-13 14:47:44 +01:00
Gary Benson
3f00c730ac Skip VLA structure field tests when compiling with clang
Clang fails to compile gdb.base/vla-datatypes.c with the following
error: fields must have a constant size: 'variable length array in
structure' extension will never be supported.  This commit factors
the affected tests out into a new testcase, vla-struct-fields.{exp,c},
which is skipped when the testcase is compiled using clang,

gdb/testsuite/ChangeLog:

	* gdb.base/vla-datatypes.c (vla_factory): Factor out sections
	defining and using VLA structure fields into...
	* gdb.base/vla-struct-fields.c: New file.
	* gdb.base/vla-datatypes.exp: Factor out VLA structure field
	tests into...
	* gdb.base/vla-struct-fields.exp: New file.
2020-07-13 14:47:44 +01:00
Tom de Vries
963eeee42a [gdb/testsuite] Handle missing gold linker in gdb.base/morestack.exp
When running test-case gdb.base/morestack.exp without the gold linker
installed, we run into:
...
Running src/gdb/testsuite/gdb.base/morestack.exp ...
gdb compile failed, collect2: fatal error: cannot find 'ld'
compilation terminated.
FAIL: gdb.base/morestack.exp: continue

                === gdb Summary ===

nr of expected passes            1
nr of unexpected failures        1
nr of untested testcases         1
...

The test-case needs the gold linker to run correctly (as explained in commit
b8d38ee425 "testsuite: Fix false FAIL for gdb.base/morestack.exp"), but
only prefers it, and doesn't require it.

Fix this by requiring the gold linker in the test-case.  Furthermore, silence
the compilation error by introducing a caching proc have_fuse_ld_gold and
using it in this and other test-cases that use -fuse-ld=gold.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* lib/gdb.exp (have_fuse_ld_gold): New caching proc.
	* gdb.base/gcore-tls-pie.exp: Use have_fuse_ld_gold.
	* gdb.base/gold-gdb-index.exp: Same.
	* gdb.base/morestack.exp: Same.
2020-07-13 14:14:47 +02:00
Simon Marchi
cf88be6855 gdb: make type::bounds work for array and string types
Getting the bounds of an array (or string) type is a common operation,
and is currently done through its index type:

    my_array_type->index_type ()->bounds ()

I think it would make sense to let the `type::bounds` methods work for
arrays and strings, as a shorthand for this.  It's natural that when
asking for the bounds of an array, we get the bounds of the range type
used as its index type.  In a way, it's equivalent as the now-removed
TYPE_ARRAY_{LOWER,UPPER}_BOUND_IS_UNDEFINED and
TYPE_ARRAY_{LOWER,UPPER}_BOUND_VALUE, except it returns the
`range_bounds` object.  The caller is then responsible for getting the
property it needs in it.

I updated all the spots I could find that could take advantage of this.

Note that this also makes `type::bit_stride` work on array types, since
`type::bit_stride` uses `type::bounds`.  `my_array_type->bit_stride ()`
now returns the bit stride of the array's index type.  So some spots
are also changed to take advantage of this.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <bounds>: Handle array and string
	types.
	* ada-lang.c (assign_aggregate): Use type::bounds on
	array/string type.
	* c-typeprint.c (c_type_print_varspec_suffix): Likewise.
	* c-varobj.c (c_number_of_children): Likewise.
	(c_describe_child): Likewise.
	* eval.c (evaluate_subexp_for_sizeof): Likewise.
	* f-typeprint.c (f_type_print_varspec_suffix): Likewise.
	(f_type_print_base): Likewise.
	* f-valprint.c (f77_array_offset_tbl): Likewise.
	(f77_get_upperbound): Likewise.
	(f77_print_array_1): Likewise.
	* guile/scm-type.c (gdbscm_type_range): Likewise.
	* m2-typeprint.c (m2_array): Likewise.
	(m2_is_long_set_of_type): Likewise.
	* m2-valprint.c (get_long_set_bounds): Likewise.
	* p-typeprint.c (pascal_type_print_varspec_prefix): Likewise.
	* python/py-type.c (typy_range): Likewise.
	* rust-lang.c (rust_internal_print_type): Likewise.
	* type-stack.c (type_stack::follow_types): Likewise.
	* valarith.c (value_subscripted_rvalue): Likewise.
	* valops.c (value_cast): Likewise.

Change-Id: I5c0c08930bffe42fd69cb4bfcece28944dd88d1f
2020-07-12 23:06:12 -04:00
Simon Marchi
509971ae76 gdb: remove TYPE_ARRAY_BIT_STRIDE
Remove it and update all callers to use the equivalent accessor methods.
A subsequent patch will make type::bit_stride work for array types
(effectively replacing this macro), but I wanted to keep this patch a
simple mechanical change.

gdb/ChangeLog:

	* gdbtypes.c (TYPE_ARRAY_BIT_STRIDE): Remove.  Update all
	callers to use the equivalent accessor methods.

Change-Id: I09e14bd45075f98567adce8a0b93edea7722f812
2020-07-12 22:58:53 -04:00
Simon Marchi
107406b738 gdb: remove TYPE_BIT_STRIDE
Remove the macro and add a `bit_stride` method to `struct range_bounds`,
which does the byte -> bit conversion if needed.

Add a convenience `bit_stride` method to `struct type` as well.  I don't
really understand why the bit/byte stride is stored in the data
structure for bounds.  Maybe it was just put there because
`range_bounds` was already a data structure specific to TYPE_CODE_RANGE
types?  If the stride is indeed not related to the bounds, then I find
it more logical to do `my_range_type->bit_stride ()` than
`my_range_type->bounds ()->bit_stride ()`, hence the convenience
function on `struct type`.

gdb/ChangeLog:

	* gdbtypes.h (struct range_bounds) <bit_stride>: New method.
	(struct type) <bit_stride>: New method.
	(TYPE_BIT_STRIDE): Remove.
	* gdbtypes.c (update_static_array_size): Use type::bit_stride.

Change-Id: I6ecc1cfefdc20711fa8f188a94a05c1e116c9922
2020-07-12 22:58:53 -04:00
Simon Marchi
bb789949e9 gdb: remove TYPE_ARRAY_{LOWER,UPPER}_BOUND_VALUE
Remove the macros, use the various equivalent getters instead.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_ARRAY_LOWER_BOUND_VALUE,
	TYPE_ARRAY_UPPER_BOUND_VALUE): Remove.  Update all
	callers to use the equivalent accessor methods instead.

Change-Id: I7f96d988f872170e7a2f58095832710e62b85cfd
2020-07-12 22:58:53 -04:00
Simon Marchi
39498edbc8 gdb: remove TYPE_ARRAY_{UPPER,LOWER}_BOUND_IS_UNDEFINED
Remove the macros, use the various equivalent getters instead.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_ARRAY_UPPER_BOUND_IS_UNDEFINED,
	TYPE_ARRAY_LOWER_BOUND_IS_UNDEFINED): Remove.  Update all
	callers to use the equivalent accessor methods instead.

Change-Id: Ifb4c36f440b82533bde5d15a5cbb2fc91f467292
2020-07-12 22:58:52 -04:00
Simon Marchi
3b606f384d gdb: remove TYPE_LOW_BOUND_KIND and TYPE_HIGH_BOUND_KIND
Remove the macros, use the getters of `struct dynamic_prop` instead.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_LOW_BOUND_KIND,
	TYPE_HIGH_BOUND_KIND): Remove.  Update all callers
	to use dynamic_prop::kind.

Change-Id: Icb1fc761f675bfac934209f8102392504d905c44
2020-07-12 22:58:52 -04:00
Simon Marchi
064d9cb9e7 gdb: remove TYPE_LOW_BOUND_UNDEFINED and TYPE_HIGH_BOUND_UNDEFINED
Remove the macros, use the getters of `struct dynamic_prop` instead.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_LOW_BOUND_UNDEFINED,
	TYPE_HIGH_BOUND_UNDEFINED): Remove.  Update all callers
	to get the bound property's kind and check against
	PROP_UNDEFINED.

Change-Id: I6a7641ac1aa3fa7fca0c21f00556f185f2e2d68c
2020-07-12 22:58:52 -04:00
Simon Marchi
5537ddd024 gdb: remove TYPE_HIGH_BOUND and TYPE_LOW_BOUND
Remove the macros, use the getters of `struct dynamic_prop` instead.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_LOW_BOUND, TYPE_HIGH_BOUND): Remove.  Update
	all callers to use type::range_bounds followed by
	dynamic_prop::{low,high}.

Change-Id: I31beeed65d94d81ac4f999244a8b859e2ee961d1
2020-07-12 22:58:52 -04:00
Simon Marchi
8c2e4e0689 gdb: add accessors to struct dynamic_prop
Add setters, to ensure that the kind and value of the property are
always kept in sync (a caller can't forget one or the other).  Add
getters, such that we can assert that when a caller accesses a data bit
of the property, the property is indeed of the corresponding kind.

Note that because of the way `struct dynamic_prop` is allocated
currently, we can't make the `m_kind` and `m_data` fields private.  That
would make the type non-default-constructible, and we would have to call
the constructor when allocating them.  However, I still prefixed them
with `m_` to indicate that they should not be accessed from outside the
class (and also to be able to use the name `kind` for the method).

gdb/ChangeLog:

	* gdbtypes.h (struct dynamic_prop) <kind, set_undefined,
	const_val, set_const_val, baton, set_locexpr, set_loclist,
	set_addr_offset, variant_parts, set_variant_parts,
	original_type, set_original_type>: New methods.
	<kind>: Rename to...
	<m_kind>: ... this.  Update all users to use the new methods
	instead.
	<data>: Rename to...
	<m_data>: ... this.  Update all users to use the new methods
	instead.

Change-Id: Ib72a8eb440dfeb1a5421d0933334230d7f2478f9
2020-07-12 22:58:51 -04:00
Simon Marchi
7c6f271296 gdb: make get_discrete_bounds check for non-constant range bounds
The next patch adds getters to the `dynamic_prop` structure.  These
getters validate that the accessed data matches the property kind (for
example, to access the `const_val` field, the property must be of kind
`PROP_CONST`).  It found one instance where we are accessing the
`const_val` data of a property that has the undefined kind.

This happens in function `get_discrete_bounds`, and is exposed by test
gdb.base/ptype.exp, amongst others.  Without this patch, we would get:

    $ ./gdb -q -nx --data-directory=data-directory testsuite/outputs/gdb.base/ptype/ptype -ex "ptype t_char_array"
    Reading symbols from testsuite/outputs/gdb.base/ptype/ptype...
    type = char [
    /home/smarchi/src/binutils-gdb/gdb/gdbtypes.h:526: internal-error: LONGEST dynamic_prop::const_val() const: Assertion `m_kind == PROP_CONST' failed.
    A problem internal to GDB has been detected,
    further debugging may prove unreliable.
    Quit this debugging session? (y or n)

The `get_discrete_bounds` function returns the bounds of a type (not
only range types).  For range types, it naturally uses the bound
properties that are intrinsic to the range type.  It accesses these
properties using TYPE_LOW_BOUND and TYPE_HIGH_BOUND, which assume the
properties are defined and have constant values.  This is sometimes not
the case, and the passed range type (as in the example above) has an
undefined high/upper bound.

Given its current interface (returning two LONGEST values for low and
high), `get_discrete_bounds` can't really work if the range type's
bounds are not both defined and both constant values.

This patch changes the function to return -1 (failure to get the bounds)
if any of the range type's bounds is not a constant value.  It is
sufficient to fix the issue and it seems to keep the callers happy, at
least according to the testsuite.

A bit in `get_array_bounds` could be removed, since
`get_discrete_bounds` no longer returns 1 if a bound is undefined.

gdb/ChangeLog:

	* gdbtypes.c (get_discrete_bounds): Return failure if
	the range type's bounds are not both defined and constant
	values.
	(get_array_bounds): Update comment.  Remove undefined bound check.

Change-Id: I047a3beee2c1e275f888cfc4778228339922bde9
2020-07-12 22:58:51 -04:00
Simon Marchi
599088e3ff gdb: remove TYPE_RANGE_DATA macro
Remove it in favor of using type::bounds directly.

gdb/ChangeLog:

	* gdbtypes.h (TYPE_RANGE_DATA): Remove.  Update callers to use
	the type::bounds method directly.

Change-Id: Id4fab22af0a94cbf505f78b01b3ee5b3d682fba2
2020-07-12 22:58:51 -04:00
Simon Marchi
c4dfcb3638 gdb: add type::bounds / type::set_bounds
Add the `bounds` and `set_bounds` methods on `struct type`, in order to
remove the `TYPE_RANGE_DATA` macro.  In this patch, the
`TYPE_RANGE_DATA` macro is changed to use `type::bounds`, so all the
call sites that are used to set a range type's bounds are changed to use
`type::set_bounds`.  The next patch will remove `TYPE_RANGE_DATA`
completely.

gdb/ChangeLog:

	* gdbtypes.h (struct type) <bounds, set_bounds>: New methods.
	(TYPE_RANGE_DATA): Use type::bounds.  Change all uses that
	are used to set the range type's bounds to use set_bounds.

Change-Id: I62e15506239b98404e62bbea8120db184ed87847
2020-07-12 22:58:50 -04:00
Daniel Xu
0ed35c9ae0 rust: Fix rust modules test
I noticed that the modules test was failing. Some choice use of `nm`
revealed `TWENTY_THREE` was not in the final binary. Fix by taking a
pointer to the global, forcing the linker to keep the symbol in.

gdb/testsuite/ChangeLog
2020-07-11  Daniel Xu  <dxu@dxuuu.xyz>

	PR rust/26121
	* gdb.rust/modules.rs: Prevent linker from discarding test
	symbol.

Signed-off-by: Daniel Xu <dxu@dxuuu.xyz>
2020-07-11 16:08:28 -06:00
Philippe Waroquiers
0a278aa755 Fine tune exec-file-mismatch help and documentation.
It was deemed better to explicitly mention in help and doc that build IDs
are used for comparison, and that symbols are loaded when asking to
load the exec-file.

This is V2, fixing 2 typos and replacing 'If the user asks to load'
by 'If the user confirms loading', as suggested by Pedro.

gdb/ChangeLog
2020-07-11  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* exec.c (_initialize_exec): Update exec-file-mismatch help.

gdb/doc/ChangeLog
2020-07-11  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.texinfo (Attach): Update exec-file-mismatch doc.
2020-07-11 14:21:05 +02:00
Pedro Alves
cce20f1074 Fix crash if connection drops in scoped_restore_current_thread's ctor, part 2
Running the testsuite against an Asan-enabled build of GDB makes
gdb.base/multi-target.exp expose this bug.

scoped_restore_current_thread's ctor calls get_frame_id to record the
selected frame's ID to restore later.  If the frame ID hasn't been
computed yet, it will be computed on the spot, and that will usually
require accessing the target's memory and registers.  If the remote
connection closes, while we're computing the frame ID, the remote
target exits its inferiors, unpushes itself, and throws a
TARGET_CLOSE_ERROR error.  Exiting the inferiors deletes the
inferior's threads.

scoped_restore_current_thread increments the current thread's refcount
to prevent the thread from being deleted from under its feet.
However, the code that does that isn't considering the case of the
thread being deleted from within get_frame_id.  It only increments the
refcount _after_ get_frame_id returns.  So if the current thread is
indeed deleted, the

     tp->incref ();

statement references a stale TP pointer.

Incrementing the refcounts earlier fixes it.

We should probably also let the TARGET_CLOSE_ERROR error propagate in
this case.  That alone would fix it, though it seems better to tweak
the refcount handling too.  And to avoid having to manually decref
before throwing, convert to use gdb::ref_ptr.

Unfortunately, we can't define inferior_ref in inferior.h and then use
it in scoped_restore_current_thread, because
scoped_restore_current_thread is defined before inferior is
(inferior.h includes gdbthread.h).  To break that dependency, we would
have to move scoped_restore_current_thread to its own header.  I'm not
doing that here.

gdb/ChangeLog:

	* gdbthread.h (inferior_ref): Define.
	(scoped_restore_current_thread) <m_thread>: Now a thread_info_ref.
	(scoped_restore_current_thread) <m_inf>: Now an inferior_ref.
	* thread.c
	(scoped_restore_current_thread::restore):
	Adjust to gdb::ref_ptr.
	(scoped_restore_current_thread::~scoped_restore_current_thread):
	Remove manual decref handling.
	(scoped_restore_current_thread::scoped_restore_current_thread):
	Adjust to use
	inferior_ref::new_reference/thread_info_ref::new_reference.
	Incref the thread before calling get_frame_id instead of after.
	Let TARGET_CLOSE_ERROR propagate.
2020-07-10 23:55:44 +01:00
Pedro Alves
6d7aa59270 Fix crash if connection drops in scoped_restore_current_thread's ctor, part 1
Running the testsuite against an Asan-enabled build of GDB makes
gdb.base/multi-target.exp expose this bug.

scoped_restore_current_thread's ctor calls get_frame_id to record the
selected frame's ID to restore later.  If the frame ID hasn't been
computed yet, it will be computed on the spot, and that will usually
require accessing the target's memory and registers, which requires
remote accesses.  If the remote connection closes while we're
computing the frame ID, the remote target exits its inferiors,
unpushes itself, and throws a TARGET_CLOSE_ERROR error.

If that happens, GDB can currently crash, here:

> ==18555==ERROR: AddressSanitizer: heap-use-after-free on address 0x621004670aa8 at pc 0x0000007ab125 bp 0x7ffdecaecd20 sp 0x7ffdecaecd10
> READ of size 4 at 0x621004670aa8 thread T0
>     #0 0x7ab124 in dwarf2_frame_this_id src/binutils-gdb/gdb/dwarf2/frame.c:1228
>     #1 0x983ec5 in compute_frame_id src/binutils-gdb/gdb/frame.c:550
>     #2 0x9841ee in get_frame_id(frame_info*) src/binutils-gdb/gdb/frame.c:582
>     #3 0x1093faa in scoped_restore_current_thread::scoped_restore_current_thread() src/binutils-gdb/gdb/thread.c:1462
>     #4 0xaee5ba in fetch_inferior_event(void*) src/binutils-gdb/gdb/infrun.c:3968
>     #5 0xaa990b in inferior_event_handler(inferior_event_type, void*) src/binutils-gdb/gdb/inf-loop.c:43
>     #6 0xea61b6 in remote_async_serial_handler src/binutils-gdb/gdb/remote.c:14161
>     #7 0xefca8a in run_async_handler_and_reschedule src/binutils-gdb/gdb/ser-base.c:137
>     #8 0xefcd23 in fd_event src/binutils-gdb/gdb/ser-base.c:188
>     #9 0x15a7416 in handle_file_event src/binutils-gdb/gdbsupport/event-loop.cc:548
>     #10 0x15a7c36 in gdb_wait_for_event src/binutils-gdb/gdbsupport/event-loop.cc:673
>     #11 0x15a5dbb in gdb_do_one_event() src/binutils-gdb/gdbsupport/event-loop.cc:215
>     #12 0xbfe62d in start_event_loop src/binutils-gdb/gdb/main.c:356
>     #13 0xbfe935 in captured_command_loop src/binutils-gdb/gdb/main.c:416
>     #14 0xc01d39 in captured_main src/binutils-gdb/gdb/main.c:1253
>     #15 0xc01dc9 in gdb_main(captured_main_args*) src/binutils-gdb/gdb/main.c:1268
>     #16 0x414ddd in main src/binutils-gdb/gdb/gdb.c:32
>     #17 0x7f590110b82f in __libc_start_main ../csu/libc-start.c:291
>     #18 0x414bd8 in _start (build/binutils-gdb/gdb/gdb+0x414bd8)

What happens is that above, we're in dwarf2_frame_this_id, just after
the dwarf2_frame_cache call.  The "cache" variable that the
dwarf2_frame_cache function returned is already stale.  It's been
released here, from within the dwarf2_frame_cache:

(top-gdb) bt
#0  reinit_frame_cache () at src/gdb/frame.c:1855
#1  0x00000000014ff7b0 in switch_to_no_thread () at src/gdb/thread.c:1301
#2  0x0000000000f66d3e in switch_to_inferior_no_thread (inf=0x615000338180) at src/gdb/inferior.c:626
#3  0x00000000012f3826 in remote_unpush_target (target=0x6170000c5900) at src/gdb/remote.c:5521
#4  0x00000000013097e0 in remote_target::readchar (this=0x6170000c5900, timeout=2) at src/gdb/remote.c:9137
#5  0x000000000130be4d in remote_target::getpkt_or_notif_sane_1 (this=0x6170000c5900, buf=0x6170000c5918, forever=0, expecting_notif=0, is_notif=0x0) at src/gdb/remote.c:9683
#6  0x000000000130c8ab in remote_target::getpkt_sane (this=0x6170000c5900, buf=0x6170000c5918, forever=0) at src/gdb/remote.c:9790
#7  0x000000000130bc0d in remote_target::getpkt (this=0x6170000c5900, buf=0x6170000c5918, forever=0) at src/gdb/remote.c:9623
#8  0x000000000130838e in remote_target::remote_read_bytes_1 (this=0x6170000c5900, memaddr=0x7fffffffcdc0, myaddr=0x6080000ad3bc "", len_units=64, unit_size=1, xfered_len_units=0x7fff6a29b9a0) at src/gdb/remote.c:8860
#9  0x0000000001308bd2 in remote_target::remote_read_bytes (this=0x6170000c5900, memaddr=0x7fffffffcdc0, myaddr=0x6080000ad3bc "", len=64, unit_size=1, xfered_len=0x7fff6a29b9a0) at src/gdb/remote.c:8987
#10 0x0000000001311ed1 in remote_target::xfer_partial (this=0x6170000c5900, object=TARGET_OBJECT_MEMORY, annex=0x0, readbuf=0x6080000ad3bc "", writebuf=0x0, offset=140737488342464, len=64, xfered_len=0x7fff6a29b9a0) at src/gdb/remote.c:10988
#11 0x00000000014ba969 in raw_memory_xfer_partial (ops=0x6170000c5900, readbuf=0x6080000ad3bc "", writebuf=0x0, memaddr=140737488342464, len=64, xfered_len=0x7fff6a29b9a0) at src/gdb/target.c:918
#12 0x00000000014bb720 in target_xfer_partial (ops=0x6170000c5900, object=TARGET_OBJECT_RAW_MEMORY, annex=0x0, readbuf=0x6080000ad3bc "", writebuf=0x0, offset=140737488342464, len=64, xfered_len=0x7fff6a29b9a0) at src/gdb/target.c:1148
#13 0x00000000014bc3b5 in target_read_partial (ops=0x6170000c5900, object=TARGET_OBJECT_RAW_MEMORY, annex=0x0, buf=0x6080000ad3bc "", offset=140737488342464, len=64, xfered_len=0x7fff6a29b9a0) at src/gdb/target.c:1380
#14 0x00000000014bc593 in target_read (ops=0x6170000c5900, object=TARGET_OBJECT_RAW_MEMORY, annex=0x0, buf=0x6080000ad3bc "", offset=140737488342464, len=64) at src/gdb/target.c:1419
#15 0x00000000014bbd4d in target_read_raw_memory (memaddr=0x7fffffffcdc0, myaddr=0x6080000ad3bc "", len=64) at src/gdb/target.c:1252
#16 0x0000000000bf27df in dcache_read_line (dcache=0x6060001eddc0, db=0x6080000ad3a0) at src/gdb/dcache.c:336
#17 0x0000000000bf2b72 in dcache_peek_byte (dcache=0x6060001eddc0, addr=0x7fffffffcdd8, ptr=0x6020001231b0 "") at src/gdb/dcache.c:403
#18 0x0000000000bf3103 in dcache_read_memory_partial (ops=0x6170000c5900, dcache=0x6060001eddc0, memaddr=0x7fffffffcdd8, myaddr=0x6020001231b0 "", len=8, xfered_len=0x7fff6a29bf20) at src/gdb/dcache.c:484
#19 0x00000000014bafe9 in memory_xfer_partial_1 (ops=0x6170000c5900, object=TARGET_OBJECT_STACK_MEMORY, readbuf=0x6020001231b0 "", writebuf=0x0, memaddr=140737488342488, len=8, xfered_len=0x7fff6a29bf20) at src/gdb/target.c:1034
#20 0x00000000014bb212 in memory_xfer_partial (ops=0x6170000c5900, object=TARGET_OBJECT_STACK_MEMORY, readbuf=0x6020001231b0 "", writebuf=0x0, memaddr=140737488342488, len=8, xfered_len=0x7fff6a29bf20) at src/gdb/target.c:1076
#21 0x00000000014bb6b3 in target_xfer_partial (ops=0x6170000c5900, object=TARGET_OBJECT_STACK_MEMORY, annex=0x0, readbuf=0x6020001231b0 "", writebuf=0x0, offset=140737488342488, len=8, xfered_len=0x7fff6a29bf20) at src/gdb/target.c:1133
#22 0x000000000164564d in read_value_memory (val=0x60f000029440, bit_offset=0, stack=1, memaddr=0x7fffffffcdd8, buffer=0x6020001231b0 "", length=8) at src/gdb/valops.c:956
#23 0x0000000001680fff in value_fetch_lazy_memory (val=0x60f000029440) at src/gdb/value.c:3764
#24 0x0000000001681efd in value_fetch_lazy (val=0x60f000029440) at src/gdb/value.c:3910
#25 0x0000000001676143 in value_optimized_out (value=0x60f000029440) at src/gdb/value.c:1411
#26 0x0000000000e0fcb8 in frame_register_unwind (next_frame=0x6210066bfde0, regnum=16, optimizedp=0x7fff6a29c200, unavailablep=0x7fff6a29c240, lvalp=0x7fff6a29c2c0, addrp=0x7fff6a29c300, realnump=0x7fff6a29c280, bufferp=0x7fff6a29c3a0 "@\304)j\377\177") at src/gdb/frame.c:1144
#27 0x0000000000e10418 in frame_unwind_register (next_frame=0x6210066bfde0, regnum=16, buf=0x7fff6a29c3a0 "@\304)j\377\177") at src/gdb/frame.c:1196
#28 0x0000000000f00431 in i386_unwind_pc (gdbarch=0x6210043d0110, next_frame=0x6210066bfde0) at src/gdb/i386-tdep.c:1969
#29 0x0000000000e39724 in gdbarch_unwind_pc (gdbarch=0x6210043d0110, next_frame=0x6210066bfde0) at src/gdb/gdbarch.c:3056
#30 0x0000000000c2ea90 in dwarf2_tailcall_sniffer_first (this_frame=0x6210066bfde0, tailcall_cachep=0x6210066bfee0, entry_cfa_sp_offsetp=0x0) at src/gdb/dwarf2/frame-tailcall.c:423
#31 0x0000000000c36bdb in dwarf2_frame_cache (this_frame=0x6210066bfde0, this_cache=0x6210066bfdf8) at src/gdb/dwarf2/frame.c:1198
#32 0x0000000000c36eb3 in dwarf2_frame_this_id (this_frame=0x6210066bfde0, this_cache=0x6210066bfdf8, this_id=0x6210066bfe40) at src/gdb/dwarf2/frame.c:1226

Note that remote_target::readchar in frame #4 throws
TARGET_CLOSE_ERROR after the remote_unpush_target in frame #3 returns.

The problem is that the TARGET_CLOSE_ERROR is swallowed by
value_optimized_out in frame #25.

If we fix that one, then we run into dwarf2_tailcall_sniffer_first
swallowing the exception in frame #30 too.

The attached patch fixes it by making those spots swallow fewer kinds
of errors.

gdb/ChangeLog:

	* frame-tailcall.c (dwarf2_tailcall_sniffer_first): Only swallow
	NO_ENTRY_VALUE_ERROR / MEMORY_ERROR / OPTIMIZED_OUT_ERROR /
	NOT_AVAILABLE_ERROR.
	* value.c (value_optimized_out): Only swallow MEMORY_ERROR /
	OPTIMIZED_OUT_ERROR / NOT_AVAILABLE_ERROR.
2020-07-10 23:53:34 +01:00
Simon Marchi
b3e3a4c114 Fix GDB busy loop when interrupting non-stop program (PR 26199)
When interrupting a program in non-stop, the program gets interrupted
correctly, but GDB busy loops (the event loop is always woken up).

Here is how to reproduce it:

 1. Start GDB: ./gdb -nx --data-directory=data-directory -ex "set non-stop 1" --args  /bin/sleep 60
 2. Run the program with "run"
 3. Interrupt with ^C.
 4. Look into htop, see GDB taking 100% CPU

Debugging `handle_file_event`, we see that the event source that wakes
up the event loop is the linux-nat one:

 (top-gdb) p file_ptr.proc
 $5 = (handler_func *) 0xb9cccd <handle_target_event(int, gdb_client_data)>
				 ^^^^^^^^^^^^^^^^^^^
					 |
					 \-- the linux-nat callback

Debugging fetch_inferior_event and do_target_wait, we see that we
don't actually call `wait` on the linux-nat target, because
inferior_matches returns false:

 auto inferior_matches = [&wait_ptid] (inferior *inf)
   {
     return (inf->process_target () != NULL
	     && (threads_are_executing (inf->process_target ())
		 || threads_are_resumed_pending_p (inf))
	     && ptid_t (inf->pid).matches (wait_ptid));
   };

because `threads_are_executing` is false.

What happens is:

 1. User types ctrl-c, that writes in the linux-nat pipe, waking up
    the event source.

 2. linux-nat's wait gets called, the SIGINT event is returned, but
    before returning, it marks the pipe again, in order for wait to
    get called again:

    /* If we requested any event, and something came out, assume there
       may be more.  If we requested a specific lwp or process, also
       assume there may be more.  */
    if (target_is_async_p ()
	&& ((ourstatus->kind != TARGET_WAITKIND_IGNORE
	     && ourstatus->kind != TARGET_WAITKIND_NO_RESUMED)
	    || ptid != minus_one_ptid))
      async_file_mark ();

 3. The SIGINT event is handled, the program is stopped, the stop
    notification is printed.

 4. The event loop is woken up again because of the `async_file_mark`
    of step 2.

 5. Because `inferior_matches` returns false, we never call
    linux-nat's wait, so the pipe stays readable.

 6. Goto 4.

Pedro says:

This commit fixes it by letting do_target_wait call target_wait even
if threads_are_executing is false.  This will normally result in the
target returning TARGET_WAITKIND_NO_RESUMED, and _not_ marking its
event source again.  This results in infrun only calling into the
target only once (i.e., breaking the busy loop).

Note that the busy loop bug didn't trigger in all-stop mode because
all-stop handles this by unregistering the target from the event loop
as soon as it was all stopped -- see
inf-loop.c:inferior_event_handler's INF_EXEC_COMPLETE handling.  If we
remove that non-stop check from inferior_event_handler, and replace
the target_has_execution check for threads_are_executing instead, it
also fixes the issue for non-stop.  I considered that as the final
solution, but decided that the solution proposed here instead is just
simpler and more future-proof design.  With the
TARGET_WAITKIND_NO_RESUMED handling fixes done in the previous
patches, I think it should be possible to always keep the target
registered in the event loop, meaning we could eliminate the
target_async(0) call from inferior_event_handler as well as most of
the target_async(1) calls in the target backends.  That would allow in
the future e.g., the remote target reporting asynchronous
notifications even if all threads are stopped.  I haven't attempted
that, though.

gdb/ChangeLog:
yyyy-mm-dd  Simon Marchi  <simon.marchi@polymtl.ca>
	    Pedro Alves  <pedro@palves.net>

	PR gdb/26199
	* infrun.c (threads_are_resumed_pending_p): Delete.
	(do_target_wait): Remove threads_are_executing and
	threads_are_resumed_pending_p checks from the inferior_matches
	lambda.  Update comments.
2020-07-10 23:52:05 +01:00
Pedro Alves
4fdba23df6 Testcase for previous handle_no_resumed fixes
This adds a testcase that covers the scenarios described in the
previous two commits.

gdb/testsuite/ChangeLog:

	PR gdb/26199
	* gdb.multi/multi-target.c (exit_thread): New.
	(thread_start): Break loop if EXIT_THREAD.
	* gdb.multi/multi-target.exp (test_no_unwaited_for): New proc.
	(top level) Call test_no_resumed.
2020-07-10 23:51:11 +01:00
Pedro Alves
d6cc5d980a Make handle_no_resumed transfer terminal
Let's consider the same use case as in the previous commit:

Say you have two inferiors 1 and 2, each connected to a different
target, A and B.

Now say you set inferior 2 running, with "continue &".

Now you select a thread of inferior 1, say thread 1.2, and continue in
the foreground.  All other threads of inferior 1 are left stopped.
Thread 1.2 exits, and thus target A has no other resumed thread, so it
reports TARGET_WAITKIND_NO_RESUMED.

At this point, because the threads of inferior 2 are still executing
the TARGET_WAITKIND_NO_RESUMED event is ignored.

Now, the user types Ctrl-C.  Because GDB had previously put inferior 1
in the foreground, the kernel sends the SIGINT to that inferior.
However, no thread in that inferior is executing right now, so ptrace
never intercepts the SIGINT -- it is never dequeued by any thread.
The result is that GDB's CLI is stuck.  There's no way to get back the
prompt (unless inferior 2 happens to report some event).

The fix in this commit is to make handle_no_resumed give the terminal
to some other inferior that still has threads executing so that a
subsequent Ctrl-C reaches that target first (and then GDB intercepts
the SIGINT).  This is a bit hacky, but seems like the best we can do
with the current design.

I think that putting all native inferiors in their own session would
help fixing this in a clean way, since with that a Ctrl-C on GDB's
terminal will _always_ reach GDB first, and then GDB can decide how to
pause the inferior.  But that's a much larger change.

The testcase added by the following patch needs this fix.

gdb/ChangeLog:

	PR gdb/26199
	* infrun.c (handle_no_resumed): Transfer terminal to inferior with
	executing threads.
2020-07-10 23:50:39 +01:00
Pedro Alves
7d3badc6a8 Fix handle_no_resumed w/ multiple targets
handle_no_resumed is currently not considering multiple targets.

Say you have two inferiors 1 and 2, each connected to a different
target, A and B.

Now say you set inferior 2 running, with "continue &".

Now you select a thread of inferior 1, say thread 1.2, and continue in
the foreground.  All other threads of inferior 1 are left stopped.
Thread 1.2 exits, and thus target A has no other resumed thread, so it
reports TARGET_WAITKIND_NO_RESUMED.

At this point, if both inferiors were running in the same target,
handle_no_resumed would realize that threads of inferior 2 are still
executing, so the TARGET_WAITKIND_NO_RESUMED event should be ignored.
But because handle_no_resumed only walks the threads of the current
target, it misses noticing that threads of inferior 2 are still
executing.  The fix is just to walk over all threads of all targets.

A testcase covering the use case above will be added in a following
patch.  It can't be added yet because it depends on yet another fix to
handle_no_resumed not included here.

gdb/ChangeLog:

	PR gdb/26199
	* infrun.c (handle_no_resumed): Handle multiple targets.
2020-07-10 23:50:11 +01:00
Pedro Alves
42bd97a6b1 Avoid constant stream of TARGET_WAITKIND_NO_RESUMED
If we hit the synchronous execution command case described by
handle_no_resumed, and handle_no_resumed determines that the event
should be ignored, because it found a thread that is executing, we end
up in prepare_to_wait.

There, if the current target is not registered in the event loop right
now, we call mark_infrun_async_event_handler.  With that event handler
marked, the event loop calls again into fetch_inferior_event, which
calls target_wait, which returns TARGET_WAITKIND_NO_RESUMED, and we
end up in handle_no_resumed, again ignoring the event and marking
infrun_async_event_handler.  The result is that GDB is now always
keeping the CPU 100% busy in this loop, even though it continues to be
able to react to input and to real target events, because we still go
through the event-loop.

The problem is that marking of the infrun_async_event_handler in
prepare_to_wait.  That is there to handle targets that don't support
asynchronous execution.  So the correct predicate is whether async
execution is supported, not whether the target is async right now.

gdb/ChangeLog:

	PR gdb/26199
	* infrun.c (prepare_to_wait): Check target_can_async_p instead of
	target_is_async_p.
2020-07-10 23:49:34 +01:00
Pedro Alves
43667cc6f6 Fix latent bug in target_pass_ctrlc
We were checking the thr->executing of an exited thread.

gdb/ChangeLog:

	PR gdb/26199
	* target.c (target_pass_ctrlc): Look at the inferior's non-exited
	threads, not all threads.
2020-07-10 23:48:19 +01:00
Pedro Alves
96118d114e Fix spurious unhandled remote %Stop notifications
In non-stop mode, remote targets mark an async event source whose
callback is supposed to result in calling remote_target::wait_ns to
either process the event queue, or acknowledge an incoming %Stop
notification.

The callback in question is remote_async_inferior_event_handler, where
we call inferior_event_handler, to end up in fetch_inferior_event ->
target_wait -> remote_target::wait -> remote_target::wait_ns.

A problem here however is that when debugging multiple targets,
fetch_inferior_event can pull events out of any target picked at
random, for event fairness.  This means that when
remote_async_inferior_event_handler returns, remote_target::wait may
have not been called at all, and thus pending notifications may have
not been acked.  Because async event sources auto-clear, when
remote_async_inferior_event_handler returns the async event handler is
no longer marked, so the event loop won't automatically call
remote_async_inferior_event_handler again to try to process the
pending remote notifications/queue.  The result is that stop events
may end up not processed, e.g., "interrupt -a" seemingly not managing
to stop all threads.

Fix this by making remote_async_inferior_event_handler mark the event
handler again before returning, if necessary.

Maybe a better fix would be to make async event handlers not
auto-clear themselves, make that the responsibility of the callback,
so that the event loop would keep calling the callback automatically.
Or, we could try making so that fetch_inferior_event would optionally
handle events only for the target that it got passed down via
parameter.  However, I don't think now just before branching is the
time to try to do any such change.

gdb/ChangeLog:

	PR gdb/26199
	* remote.c (remote_target::open_1): Pass remote target pointer as
	data to create_async_event_handler.
	(remote_async_inferior_event_handler): Mark async event handler
	before returning if the remote target still has either pending
	events or unacknowledged notifications.
2020-07-10 23:39:34 +01:00
John Baldwin
54904d818b Enable multi-process mode in the FreeBSD native target.
gdb/ChangeLog:

	* fbsd-nat.h (fbsd_nat_target::supports_multi_process): New
	declaration.
	* fbsd-nat.c (fbsd_nat_target::supports_multi_process): New
	function.
2020-07-10 09:05:28 -07:00
John Baldwin
f37e5866aa Don't compare the pid returned from 'wait' against inferior_ptid.
'inf_ptrace::wait' needs to discard termination events reported by
detached child processes.  Previously it compared the returned pid
against the pid in inferior_ptid to determine if a termination event
should be discarded or reported.  The multi-target changes cleared
inferior_ptid to null_ptid in 'wait' target methods, so this was
always failing and never reporting exit events.  Instead, report
termination events whose pid matches any inferior belonging to the
current target.

Several tests started failing on FreeBSD after the multi-target
changes and pass again after this change.

gdb/ChangeLog:

	* inf-ptrace.c (inf_ptrace_target::wait): Don't compare against
	inferior_ptid.
2020-07-09 12:40:40 -07:00
John Baldwin
fc238d4a06 Support several new ELF auxiliary vector types on FreeBSD.
FreeBSD's kernel recently added several ELF auxiliary vector entries
to describe the arguments passed to new executable images during
exec().  The AT_FREEBSD_ARGC and AT_FREEBSD_ARGV entries give the
length and address of the process argument array.  AT_FREEBSD_ENVC and
AT_FREEBSD_ENVV entries give the length and address of the initial
process environment.  AT_FREEBSD_PS_STRINGS gives the address of the
'struct ps_strings' object.

include/ChangeLog:

	* elf/common.h (AT_FREEBSD_ARGC, AT_FREEBSD_ARGV, AT_FREEBSD_ENVC)
	(AT_FREEBSD_ENVV, AT_FREEBSD_PS_STRINGS): Define.

gdb/ChangeLog:

	* fbsd-tdep.c (fbsd_print_auxv_entry): Handle AT_FREEBSD_ARGC,
	AT_FREEBSD_ARGV, AT_FREEBSD_ENVC, AT_FREEBSD_ENVV,
	AT_FREEBSD_PS_STRINGS.
2020-07-09 09:39:05 -07:00
Hannes Domani
6e2469ff7a Handle Windows drives in auto-load script paths
Fixes this testsuite fail on Windows:
FAIL: gdb.base/auto-load.exp: print $script_loaded

Converts the debugfile path from c:/dir/file to /c/dir/file, so it can be
appended to the auto-load path.

gdb/ChangeLog:

2020-07-08  Hannes Domani  <ssbssa@yahoo.de>

	* auto-load.c (auto_load_objfile_script_1): Convert drive part
	of debugfile path on Windows.

gdb/doc/ChangeLog:

2020-07-08  Hannes Domani  <ssbssa@yahoo.de>

	* gdb.texinfo: Document Windows drive conversion of
	'set auto-load scripts-directory'.
2020-07-08 20:50:43 +02:00
John Baldwin
d1076c4151 Rename the 'obfd' argument to fbsd_nat_target::find_memory_regions.
The argument is passed as a generic cookie value to the supplied
callback and is not necessarily a pointer to a bfd.

gdb/ChangeLog:

	* fbsd-nat.c (fbsd_nat_target::find_memory_regions): Rename 'obfd'
	argument to 'data'.
2020-07-08 08:55:39 -07:00
Tom Tromey
15f3b07769 Use read_memory in ada_exception_message_1
Testing using the internal AdaCore test suite showed a regression from
the target string reading changes.  In particular, now
ada_exception_message_1 can get the wrong answer in some cases.  In
particular, when an Ada exception catchpoint is hit, sometimes the
exception name will be incorrect.  The case I was seeing changed from
the correct:

    Catchpoint 2, CONSTRAINT_ERROR (catch C_E) at [...]

to:

    Catchpoint 2, CONSTRAINT_ERROR (catch C_EE) at [...]

I was not able to reproduce this failure with the Fedora gnat.
Perhaps it is related to some local change to gnat; I do not know.

Meanwhile, because ada_exception_message_1 knows the length of the
string to read, we can use read_memory here.  This fixes the bug.

I've updated the test suite to at least exercise this code path.
However, as mentioned above, the new test does not actually provoke
the failure.

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

	* ada-lang.c (ada_exception_message_1): Use read_memory.

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

	* gdb.ada/catch_ex/foo.adb: Pass string to raise.
	* gdb.ada/catch_ex.exp: Examine catchpoint text.
2020-07-08 07:16:59 -06:00
Andrew Burgess
9fc501fdfe gdb: Python unwinders, inline frames, and tail-call frames
This started with me running into the bug described in python/22748,
in summary, if the frame sniffing code accessed any registers within
an inline frame then GDB would crash with this error:

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

The problem is that, when in the Python unwinder I write this:

  pending_frame.read_register ("register-name")

This is translated internally into a call to `value_of_register',
which in turn becomes a call to `value_of_register_lazy'.

Usually this isn't a problem, `value_of_register_lazy' requires the
next frame (more inner) to have a valid frame_id, which will be the
case (if we're sniffing frame #1, then frame #0 will have had its
frame-id figured out).

Unfortunately if frame #0 is inline within frame #1, then the frame-id
for frame #0 can't be computed until we have the frame-id for #1.  As
a result we can't create a lazy register for frame #1 when frame #0 is
inline.

Initially I proposed a solution inline with that proposed in bugzilla,
changing value_of_register to avoid creating a lazy register value.
However, when this was discussed on the mailing list I got this reply:

  https://sourceware.org/pipermail/gdb-patches/2020-June/169633.html

Which led me to look at these two patches:

  [1] https://sourceware.org/pipermail/gdb-patches/2020-April/167612.html
  [2] https://sourceware.org/pipermail/gdb-patches/2020-April/167930.html

When I considered patches [1] and [2] I saw that all of the issues
being addressed here were related, and that there was a single
solution that could address all of these issues.

First I wrote the new test gdb.opt/inline-frame-tailcall.exp, which
shows that [1] and [2] regress the inline tail-call unwinder, the
reason for this is that these two patches replace a call to
gdbarch_unwind_pc with a call to get_frame_register, however, this is
not correct.  The previous call to gdbarch_unwind_pc takes THIS_FRAME
and returns the $pc value in the previous frame.  In contrast
get_frame_register takes THIS_FRAME and returns the value of the $pc
in THIS_FRAME; these calls are not equivalent.

The reason these patches appear (or do) fix the regressions listed in
[1] is that the tail call sniffer depends on identifying the address
of a caller and a callee, GDB then looks for a tail-call sequence that
takes us from the caller address to the callee, if such a series is
found then tail-call frames are added.

The bug that was being hit, and which was address in patch [1] is that
in order to find the address of the caller, GDB ended up creating a
lazy register value for an inline frame with to frame-id.  The
solution in patch [1] is to instead take the address of the callee and
treat this as the address of the caller.  Getting the address of the
callee works, but we then end up looking for a tail-call series from
the callee to the callee, which obviously doesn't return any sane
results, so we don't insert any tail call frames.

The original patch [1] did cause some breakage, so patch [2] undid
patch [1] in all cases except those where we had an inline frame with
no frame-id.  It just so happens that there were no tests that fitted
this description _and_ which required tail-call frames to be
successfully spotted, as a result patch [2] appeared to work.

The new test inline-frame-tailcall.exp, exposes the flaw in patch [2].

This commit undoes patch [1] and [2], and replaces them with a new
solution, which is also different to the solution proposed in the
python/22748 bug report.

In this solution I propose that we introduce some special case logic
to value_of_register_lazy.  To understand what this logic is we must
first look at how inline frames unwind registers, this is very simple,
they do this:

  static struct value *
  inline_frame_prev_register (struct frame_info *this_frame,
                              void **this_cache, int regnum)
  {
    return get_frame_register_value (this_frame, regnum);
  }

And remember:

  struct value *
  get_frame_register_value (struct frame_info *frame, int regnum)
  {
    return frame_unwind_register_value (frame->next, regnum);
  }

So in all cases, unwinding a register in an inline frame just asks the
next frame to unwind the register, this makes sense, as an inline
frame doesn't really exist, when we unwind a register in an inline
frame, we're really just asking the next frame for the value of the
register in the previous, non-inline frame.

So, if we assume that we only get into the missing frame-id situation
when we try to unwind a register from an inline frame during the frame
sniffing process, then we can change value_of_register_lazy to not
create lazy register values for an inline frame.

Imagine this stack setup, where #1 is inline within #2.

  #3 -> #2 -> #1 -> #0
        \______/
         inline

Now when trying to figure out the frame-id for #1, we need to compute
the frame-id for #2.  If the frame sniffer for #2 causes a lazy
register read in #2, either due to a Python Unwinder, or for the
tail-call sniffer, then we call value_of_register_lazy passing in
frame #2.

In value_of_register_lazy, we grab the next frame, which is #1, and we
used to then ask for the frame-id of #1, which was not computed, and
this was our bug.

Now, I propose we spot that #1 is an inline frame, and so lookup the
next frame of #1, which is #0.  As #0 is not inline it will have a
valid frame-id, and so we create a lazy register value using #0 as the
next-frame-id.  This will give us the exact same result we had
previously (thanks to the code we inspected above).

Encoding into value_of_register_lazy the knowledge that reading an
inline frame register will always just forward to the next frame
feels.... not ideal, but this seems like the cleanest solution to this
recursive frame-id computation/sniffing issue that appears to crop
up.

The following two commits are fully reverted with this commit, these
correspond to patches [1] and [2] respectively:

  commit 5939967b35
  Date:   Tue Apr 14 17:26:22 2020 -0300

      Fix inline frame unwinding breakage

  commit 991a3e2e99
  Date:   Sat Apr 25 00:32:44 2020 -0300

      Fix remaining inline/tailcall unwinding breakage for x86_64

gdb/ChangeLog:

	PR python/22748
	* dwarf2/frame-tailcall.c (dwarf2_tailcall_sniffer_first): Remove
	special handling for inline frames.
	* findvar.c (value_of_register_lazy): Skip inline frames when
	creating lazy register values.
	* frame.c (frame_id_computed_p): Delete definition.
	* frame.h (frame_id_computed_p): Delete declaration.

gdb/testsuite/ChangeLog:

	PR python/22748
	* gdb.opt/inline-frame-tailcall.c: New file.
	* gdb.opt/inline-frame-tailcall.exp: New file.
	* gdb.python/py-unwind-inline.c: New file.
	* gdb.python/py-unwind-inline.exp: New file.
	* gdb.python/py-unwind-inline.py: New file.
2020-07-06 15:06:07 +01:00
Andrew Burgess
64cb3757a9 gdb/python: New method to access list of register groups
Add a new method gdb.Architecture.register_groups which returns a new
object of type gdb.RegisterGroupsIterator.  This new iterator then
returns objects of type gdb.RegisterGroup.

Each gdb.RegisterGroup object just wraps a single reggroup pointer,
and (currently) has just one read-only property 'name' that is a
string, the name of the register group.

As with the previous commit (adding gdb.RegisterDescriptor) I made
gdb.RegisterGroup an object rather than just a string in case we want
to add additional properties in the future.

gdb/ChangeLog:

	* NEWS: Mention additions to Python API.
	* python/py-arch.c (archpy_register_groups): New function.
	(arch_object_methods): Add 'register_groups' method.
	* python/py-registers.c (reggroup_iterator_object): New struct.
	(reggroup_object): New struct.
	(gdbpy_new_reggroup): New function.
	(gdbpy_reggroup_to_string): New function.
	(gdbpy_reggroup_name): New function.
	(gdbpy_reggroup_iter): New function.
	(gdbpy_reggroup_iter_next): New function.
	(gdbpy_new_reggroup_iterator): New function
	(gdbpy_initialize_registers): Register new types.
	(reggroup_iterator_object_type): Define new Python type.
	(gdbpy_reggroup_getset): New static global.
	(reggroup_object_type): Define new Python type.
	* python/python-internal.h

gdb/testsuite/ChangeLog:

	* gdb.python/py-arch-reg-groups.exp: New file.

gdb/doc/ChangeLog:

	* gdb.texi (Registers): Add @anchor for 'info registers
	<reggroup>' command.
	* python.texi (Architectures In Python): Document new
	register_groups method.
	(Registers In Python): Document two new object types related to
	register groups.
2020-07-06 15:06:06 +01:00
Andrew Burgess
0f767f942b gdb/python: Add gdb.Architecture.registers method
This commit adds a new method gdb.Architecture.registers that returns
an object of the new type gdb.RegisterDescriptorIterator.  This
iterator returns objects of the new type gdb.RegisterDescriptor.

A RegisterDescriptor is not a way to read the value of a register,
this is already covered by Frame.read_register, a RegisterDescriptor
is simply a way to discover from Python, which registers are
available for a given architecture.

I did consider just returning a string, the name of each register,
instead of a RegisterDescriptor, however, I'm aware that it we don't
want to break the existing Python API in any way, so if I return just
a string now, but in the future we want more information about a
register then we would have to add a second API to get that
information.  By going straight to a descriptor object now, it is easy
to add additional properties in the future should we wish to.

Right now the only property of a register that a user can access is
the name of the register.

In future we might want to be able to ask the register about is
register groups, or its type.

gdb/ChangeLog:

	* Makefile.in (SUBDIR_PYTHON_SRCS): Add py-registers.c
	* python/py-arch.c (archpy_registers): New function.
	(arch_object_methods): Add 'registers' method.
	* python/py-registers.c: New file.
	* python/python-internal.h
	(gdbpy_new_register_descriptor_iterator): Declare.
	(gdbpy_initialize_registers): Declare.
	* python/python.c (do_start_initialization): Call
	gdbpy_initialize_registers.
	* NEWS: Mention additions to the Python API.

gdb/testsuite/ChangeLog:

	* gdb.python/py-arch-reg-names.exp: New file.

gdb/doc/ChangeLog:

	* python.texi (Python API): Add new section the menu.
	(Frames In Python): Add new @anchor.
	(Architectures In Python): Document new registers method.
	(Registers In Python): New section.
2020-07-06 15:06:06 +01:00
Andrew Burgess
87dbc77459 gdb/python: Add architecture method to gdb.PendingFrame
It could be useful to determine the architecture of a frame being
unwound during the frame unwind process, that is, before we have a
gdb.Frame, but when we only have a gdb.PendingFrame.

The PendingFrame already has a pointer to the gdbarch internally, this
commit just exposes an 'architecture' method to Python, and has this
return a gdb.Architecture object (list gdb.Frame.architecture does).

gdb/ChangeLog:

	* NEWS: Mention new Python API method.
	* python/py-unwind.c (pending_framepy_architecture): New function.
	(pending_frame_object_methods): Add architecture method.

gdb/testsuite/ChangeLog:

	* gdb.python/py-unwind.py (TestUnwinder::__call__): Add test for
	gdb.PendingFrame.architecture method.

gdb/doc/ChangeLog:

	* python.texi (Unwinding Frames in Python): Document
	PendingFrame.architecture method.
2020-07-06 15:06:05 +01:00
Andrew Burgess
3bc98c0c83 gdb: Remove deprecated_set_gdbarch_data
There are currently two remaining uses of deprecated_set_gdbarch_data,
both of which are needed because during gdbarch initialisation we call
gdbarch_data for a data field that is registered using:

  gdbarch_data_register_post_init (....)

However, in both of these cases, the only thing that the call back
needs from the gdbarch struct is its obstack.  Given this there is
nothing stopping us changing the post-init hooks into pre-init hooks.
The pre-init hooks don't get passed the full gdbarch, they only get
passed its obstack.

The IA64 change is completely untested.  The user-regs change has been
tested a little by locally adding some user-regs to the x86-64 target,
and also by running the RISC-V tests, which do use user-regs.

gdb/ChangeLog:

	* gdbarch.c: Regenerate.
	* gdbarch.h: Regenerate.
	* gdbarch.sh (deprecated_set_gdbarch_data): Delete.
	(gdbarch_data): Use internal_error for the case where
	deprecated_set_gdbarch_data was originally needed.
	* ia64-libunwind-tdep.c (libunwind_descr_init): Update parameters,
	and use passed in obstack.
	(libunwind_frame_set_descr): Should no longer get back NULL from
	gdbarch_data.
	(_initialize_libunwind_frame): Register as a pre-init gdbarch data
	type.
	* user-regs.c (user_regs_init): Update parameters, and use passed
	in obstack.
	(user_reg_add): Should no longer get back NULL from gdbarch_data.
	(_initialize_user_regs): Register as a pre-init gdbarch data type.
2020-07-06 15:06:04 +01:00
Tom de Vries
d8cc8af6a1 [gdb/symtab] Fix line-table end-of-sequence sorting
Consider test-case gdb.dwarf2/dw2-ranges-base.exp.  It has (ignoring
non-sensical entries that are filtered out by buildsym_compunit::record_line)
a line-table for dw2-ranges-base.c like this:
...
 Line Number Statements:
  [0x0000014e]  Extended opcode 2: set Address to 0x4004ba
  [0x00000159]  Advance Line by 10 to 11
  [0x0000015b]  Copy
  [0x0000015c]  Advance PC by 12 to 0x4004c6
  [0x0000015e]  Extended opcode 1: End of Sequence

  [0x00000161]  Extended opcode 2: set Address to 0x4004ae
  [0x0000016c]  Advance Line by 20 to 21
  [0x0000016e]  Copy
  [0x0000016f]  Advance PC by 12 to 0x4004ba
  [0x00000171]  Extended opcode 1: End of Sequence

  [0x00000174]  Extended opcode 2: set Address to 0x4004a7
  [0x0000017f]  Advance Line by 30 to 31
  [0x00000181]  Copy
  [0x00000182]  Advance PC by 7 to 0x4004ae
  [0x00000184]  Extended opcode 1: End of Sequence
...

If we disable the sorting in buildsym_compunit::end_symtab_with_blockvector,
we have the unsorted line table:
...
INDEX  LINE   ADDRESS            IS-STMT
0      11     0x00000000004004ba Y
1      END    0x00000000004004c6 Y
2      21     0x00000000004004ae Y
3      END    0x00000000004004ba Y
4      31     0x00000000004004a7 Y
5      END    0x00000000004004ae Y
...
It contains 3 sequences, 11/END, 21/END and 31/END.

We want to sort the 3 sequences relative to each other, while sorting on
address, to get:
...
INDEX  LINE   ADDRESS            IS-STMT
0      31     0x00000000004004a7 Y
1      END    0x00000000004004ae Y
2      21     0x00000000004004ae Y
3      END    0x00000000004004ba Y
4      11     0x00000000004004ba Y
5      END    0x00000000004004c6 Y
...

However, if we re-enable the sorting, we have instead:
...
INDEX  LINE   ADDRESS            IS-STMT
0      31     0x00000000004004a7 Y
1      21     0x00000000004004ae Y
2      END    0x00000000004004ae Y
3      11     0x00000000004004ba Y
4      END    0x00000000004004ba Y
5      END    0x00000000004004c6 Y
...

This is a regression since commit 3d92a3e313 "gdb: Don't reorder line table
entries too much when sorting", that introduced sorting on address while
keeping entries with the same address in pre-sort order.

Indeed the entries 1 and 2 are in pre-sort order (they map to entries 2 and 5
in the unsorted line table), but entry 1 does not belong in the sequence
terminated by 2.

Fix this by handling End-Of-Sequence entries in the sorting function, such
that they are sorted before other entries with the same address.

Also, revert the find_pc_sect_line workaround introduced in commit 3d92a3e313,
since that's no longer necessary.

Tested on x86_64-linux.

gdb/ChangeLog:

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

	* buildsym.c (buildsym_compunit::end_symtab_with_blockvector): Handle
	End-Of-Sequence in lte_is_less_than.
	* symtab.c (find_pc_sect_line): Revert change from commit 3d92a3e313
	"gdb: Don't reorder line table entries too much when sorting".

gdb/testsuite/ChangeLog:

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

	* gdb.dwarf2/dw2-ranges-base.exp: Test line-table order.
2020-07-06 14:28:58 +02:00
Tom de Vries
947f759778 [gdb/tui,c++17] Fix NULL string_view in tui_partial_win_by_name
When building gdb with CFLAGS=-std=gnu17 and CXXFLAGS=-std=gnu++17 and running
test-case gdb.tui/new-layout.exp, we run into:
...
UNRESOLVED: gdb.tui/new-layout.exp: left window box after shrink (ll corner)
FAIL: gdb.tui/new-layout.exp: right window box after shrink (ll corner)
...

In a minimal form, we run into an abort when issuing a winheight command:
...
$ gdb -tui -ex "winheight src - 5"
   <tui stuff>
Aborted (core dumped)
$
...
with this backtrace at the abort:
...
\#0  0x0000000000438db0 in std::char_traits<char>::length (__s=0x0)
     at /usr/include/c++/9/bits/char_traits.h:335
\#1  0x000000000043b72e in std::basic_string_view<char, \
   std::char_traits<char> >::basic_string_view (this=0x7fffffffd4f0, \
   __str=0x0) at /usr/include/c++/9/string_view:124
\#2  0x000000000094971b in tui_partial_win_by_name (name="src")
     at src/gdb/tui/tui-win.c:663
...
due to a NULL comparison which constructs a string_view object from NULL:
...
   657  /* Answer the window represented by name.  */
   658  static struct tui_win_info *
   659  tui_partial_win_by_name (gdb::string_view name)
   660  {
   661    struct tui_win_info *best = nullptr;
   662
   663    if (name != NULL)
...

In gdbsupport/gdb_string_view.h, we either use:
- gdb's copy of libstdc++-v3/include/experimental/string_view, or
- the standard implementation of string_view, when built with C++17 or later
  (which in gcc's case comes from libstdc++-v3/include/std/string_view)

In the first case, there's support for constructing a string_view from a NULL
pointer:
...
      /*constexpr*/ basic_string_view(const _CharT* __str)
      : _M_len{__str == nullptr ? 0 : traits_type::length(__str)},
        _M_str{__str}
      { }
...
but in the second case, there's not:
...
      __attribute__((__nonnull__)) constexpr
      basic_string_view(const _CharT* __str) noexcept
      : _M_len{traits_type::length(__str)},
        _M_str{__str}
      { }
...

Fix this by removing the NULL comparison altogether.

Build on x86_64-linux with CFLAGS=-std=gnu17 and CXXFLAGS=-std=gnu++17, and
tested.

gdb/ChangeLog:

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

	PR tui/26205
	* tui/tui-win.c (tui_partial_win_by_name): Don't test for NULL name.
2020-07-06 09:54:43 +02:00
Tom de Vries
1e7c1b2242 [gdb/build,c++17] Fix use of deprecated std::uncaught_exception
When compiling gdb with -std=gnu++17, we run into:
...
../../gdb/inferior.h: In member function ‘void \
  infcall_suspend_state_deleter::operator()(infcall_suspend_state*) const’:
../../gdb/inferior.h:83:12: error: ‘bool std::uncaught_exception()’ is \
  deprecated [-Werror=deprecated-declarations]
   83 |  if (!std::uncaught_exception ())
...

Fix this by rewriting using std::uncaught_exceptions.

Tested on x86_64-linux with gcc 9.3.1 and -std=gnu17/gnu++17.

Tested with test-case from RFC patch
https://sourceware.org/pipermail/gdb-patches/2020-June/169970.html.

gdb/ChangeLog:

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

	PR build/26187
	* inferior.h (struct infcall_suspend_state_deleter): If available, use
	std::uncaught_exceptions instead of deprecated
	std::uncaught_exception.
2020-07-05 23:47:20 +02:00
Simon Marchi
a36158ec0c gdb: make macro_stringify return a gdb::unique_xmalloc_ptr<char>
The change to macro_stringify is straightforward.  This allows removing
the manual memory management in fixup_definition.

gdb/ChangeLog:

	* macroexp.h (macro_stringify): Return
	gdb::unique_xmalloc_ptr<char>.
	* macroexp.c (macro_stringify): Likewise.
	* macrotab.c (fixup_definition): Update.

Change-Id: Id7db8988bdbd569dd51c4f4655b00eb26db277cb
2020-07-03 22:27:09 -04:00
Simon Marchi
14d960c82a gdb: make macro_expand_next return a gdb::unique_xmalloc_ptr<char>
For some reason, macro_expand_next does not return a
gdb::unique_xmalloc_ptr<char>, like its counterparts macro_expand and
macro_expand_once.  This patch fixes that.

macro_buffer::release now returns a gdb::unique_xmalloc_ptr<char> too,
which required updating the other callers.  The `.release (). release
()` in macro_stringify looks a bit funny, but it's because one release
is for the macro_buffer, and the other is for the unique ptr.

I removed the ATTRIBUTE_UNUSED_RESULT on macro_buffer::release, I don't
really understand why it's there.  I don't see how this method could be
called without using the result, that would be an obvious memory leak.
The commit that introduced it (4e4a8b932b "Add ATTRIBUTE_UNUSED_RESULT
to macro_buffer") doesn't give any details.

gdb/ChangeLog:

	* c-exp.y (scan_macro_expansion): Don't free `expansion`.
	(lex_one_token): Update.
	* macroexp.c (struct macro_buffer) <release>: Return
	gdb::unique_xmalloc_ptr<char>.
	(macro_stringify): Update.
	(macro_expand): Update.
	(macro_expand_next): Return gdb::unique_xmalloc_ptr<char>.
	* macroexp.h (macro_expand_next): Likewise.

Change-Id: I67a74d0d479d2c20cdc82161ead7c54cea034f56
2020-07-03 22:27:09 -04:00
Simon Marchi
211d5b1c18 gdb: remove callback in macro expand functions
I started to look into changing the callbacks in macroexp.h to use
gdb::function_view.  However, I noticed that the passed lookup function
was always `standard_macro_lookup`, which looks up a macro in a
`macro_scope` object.  Since that doesn't look like a very useful
abstraction, it would be simpler to just pass the scope around and have
the various functions call standard_macro_lookup themselves.  This is
what this patch does.

gdb/ChangeLog:

	* macroexp.h (macro_lookup_ftype): Remove.
	(macro_expand, macro_expand_once, macro_expand_next): Remove
	lookup function parameters, add scope parameter.
	* macroexp.c (scan, substitute_args, expand, maybe_expand,
	macro_expand, macro_expand_once, macro_expand_next): Likewise.
	* macroscope.h (standard_macro_lookup): Change parameter type
	to macro_scope.
	* macroscope.c (standard_macro_lookup): Likewise.
	* c-exp.y (lex_one_token): Update.
	* macrocmd.c (macro_expand_command): Likewise.
	(macro_expand_once_command): Likewise.

Change-Id: Id2431b1489359e1b0274dc2b81e5ea5d225d730c
2020-07-03 22:27:08 -04:00
Pedro Alves
3c8ea5be24 Fix gdb.base/structs2.exp with Clang
gdb.base/structs2.exp fails to run with Clang, because of:

 gdb compile failed, /home/pedro/gdb/mygit/src/gdb/testsuite/gdb.base/structs2.c:16:14: warning:
       implicit conversion from 'int' to 'signed char' changes value from 130 to
       -126 [-Wconstant-conversion]
   param_reg (130, 120, 33000, 32000);
   ~~~~~~~~~  ^~~
 /home/pedro/gdb/mygit/src/gdb/testsuite/gdb.base/structs2.c:16:24: warning:
       implicit conversion from 'int' to 'short' changes value from 33000 to
       -32536 [-Wconstant-conversion]
   param_reg (130, 120, 33000, 32000);
   ~~~~~~~~~            ^~~~~
 2 warnings generated.

		 === gdb Summary ===

 # of untested testcases         1

Fix it by passing actual negative numbers.

gdb/testsuite/ChangeLog:

	* gdb.base/structs2.c (main): Adjust second parem_reg call to
	explicitly write negative numbers.
	* gdb.base/structs2.exp: Adjust expected output.
2020-07-03 15:01:22 +01:00
Pedro Alves
bf90c83acc Fix gdb.base/charset.exp with Clang
gdb.base/charset.exp fails to run with Clang, because of:

 gdb compile failed, /home/pedro/gdb/mygit/src/gdb/testsuite/gdb.base/charset.c:144:20: warning:
       implicit conversion from 'int' to 'char' changes value from 162 to -94
       [-Wconstant-conversion]
		11, 162, 17);
		    ^~~
 /home/pedro/gdb/mygit/src/gdb/testsuite/gdb.base/charset.c:151:16: warning:
       implicit conversion from 'int' to 'char' changes value from 167 to -89
       [-Wconstant-conversion]
		167,
		^~~
 /home/pedro/gdb/mygit/src/gdb/testsuite/gdb.base/charset.c:168:16: warning:
       implicit conversion from 'int' to 'char' changes value from 167 to -89
       [-Wconstant-conversion]
		167,
		^~~
 3 warnings generated.

		 === gdb Summary ===

 # of untested testcases         1

Fix it by changing init_string to take unsigned char parameters.

gdb/testsuite/ChangeLog:

	* gdb.base/charset.c (init_string): Change all char parameters to
	unsigned char parameters.
2020-07-03 15:00:08 +01:00
Pedro Alves
2eb8215700 Remove stale -DNO_PROTOTYPES bits from gdb testsuite
The gdb.base/call-sc.exp, gdb.base/structs.exp and
gdb.base/structs2.exp testcases still try compiling the sources with
-DNO_PROTOTYPES, but the corresponding sources don't have any #ifdef
NO_PROTOTYPES any longer.  Those were removed throughout years ago.

OTOH, gdb.base/ovlymgr.h does check for NO_PROTOTYPES, but no .exp
file compiles it with -DNO_PROTOTYPES.

gdb.base/reread.exp and gdb.base/varargs.exp set a 'prototypes'
global, which is a stale bit left behind when the "try-compiling
without and then with -DNO_PROTOTYPES" logic was around.

gdb/testsuite/ChangeLog:

	* gdb.base/call-sc.exp (start_scalars_test): Use
	prepare_for_testing and don't try compiling with -DNO_PROTOTYPES.
	* gdb.base/overlays.c: Remove references to PARAMS.
	* gdb.base/ovlymgr.h (PARAMS): Delete, and remove all references.
	* gdb.base/reread.exp: Don't set 'prototypes' global.
	* gdb.base/structs.exp (start_structs_test): Use
	prepare_for_testing and don't try compiling with -DNO_PROTOTYPES.
	* gdb.base/structs2.exp: Don't set 'prototypes' global.  Use
	prepare_for_testing and don't try compiling with -DNO_PROTOTYPES.
	Don't issue "set width 0".  Remove gdb_stop_suppressing_tests
	call.
	* gdb.base/varargs.exp: Don't set 'prototypes' global.
2020-07-03 14:58:20 +01:00
Pedro Alves
9adda7af10 Remove stale overlay testcase bits
D10V support was removed years ago, but the gdb.base/d10vovly.c file
stayed behind.  Looking a bit closer, I can't find anywhere that
references gdb.base/m32rovly.c either.

Both gdb.base/m32rovly.c and gdb.base/d10vovly.c seem to be older
copies of gdb.base/ovlymgr.c, that are exactly the same, except for
some cosmetic differences, and for missing _ovly_debug_event.  Note
that gdb.base/ovlymgr.c has the #ifdef __M32R__ bits too.  Note also
that gdb.base/overlays.exp is currently only supported on m32r, and
that uses ovlymgr.c not gdb.base/m32rovly.c.

gdb/testsuite/ChangeLog:

	* gdb.base/d10vovly.c: Delete.
	* gdb.base/m32rovly.c: Delete.
	* gdb.base/ovlymgr.c: Remove all code guarded by __D10V__.
2020-07-03 13:34:21 +01:00
Simon Marchi
b1a35af270 gdb: remove unused fetch_inferior_event and inferior_event_handler parameters
I noticed that fetch_inferior_event receives the client_data parameter
from its caller, inferior_event_handler, but doesn't actually need it.
This patch removes it.  In turn, inferior_event_handler doesn't use its
parameter, so remove it too.

The `data` argument used when registering
remote_async_inferior_event_handler is changed to NULL, to avoid
confusion.  It could make people think that the value passed is used
somewhere, when in fact it's not.

gdb/ChangeLog:

	* inf-loop.c (inferior_event_handler): Remove client_data param.
	* inf-loop.h (inferior_event_handler): Likewise.
	* infcmd.c (step_1): Adjust.
	* infrun.c (proceed): Adjust.
	(fetch_inferior_event): Remove client_data param.
	(infrun_async_inferior_event_handler): Adjust.
	* infrun.h (fetch_inferior_event): Remove `void *` param.
	* linux-nat.c (handle_target_event): Adjust.
	* record-btrace.c (record_btrace_handle_async_inferior_event):
	Adjust.
	* record-full.c (record_full_async_inferior_event_handler):
	Adjust.
	* remote.c (remote_async_inferior_event_handler): Adjust.

Change-Id: I3c2aa1eb0ea3e0985df096660d2dcd794674f2ea
2020-07-02 08:40:44 -04:00
Tom Tromey
1cdf9e33ea Make tui_win_info::name pure virtual
It seemed cleaner to me for tui_win_info::name to be pure virtual.
This meant adding a name method to the locator window; but this too
seems like an improvement.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-data.h (struct tui_win_info) <name>: Now pure virtual.
	* tui/tui-stack.h (struct tui_locator_window) <name>: New method.
2020-07-01 21:21:17 -06:00
Tom Tromey
32c1e21009 Remove tui_gen_win_info
This merges the tui_gen_win_info base class with tui_win_info;
renaming the resulting class to tui_win_info.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-wingeneral.c (tui_win_info::refresh_window): Move from
	tui_gen_win_info.
	(tui_win_info::make_window): Merge with
	tui_gen_win_info::make_window.
	(tui_win_info::make_visible): Move from tui_gen_win_info.
	* tui/tui-win.c (tui_win_info::max_width): Move from
	tui_gen_win_info.
	* tui/tui-layout.h (class tui_layout_window) <m_window>: Change
	type.
	<window_factory>: Likewise.
	* tui/tui-layout.c (tui_win_info::resize): Move from
	tui_gen_win_info.
	(make_standard_window): Change return type.
	(get_locator_window, tui_get_window_by_name): Likewise.
	(tui_layout_window::apply): Remove a cast.
	* tui/tui-data.h (MIN_WIN_HEIGHT): Move earlier.
	(struct tui_win_info): Merge with tui_gen_win_info.
	(struct tui_gen_win_info): Remove.
2020-07-01 21:21:17 -06:00
Tom Tromey
a30cb6dabb Derive tui_locator_window from tui_win_info
tui_locator_window is the last remaining concrete child class of
tui_gen_win_info.  It seems a bit cleaner to me to flatten the
hierarchy a bit; this patch prepares for that by changing
tui_locator_window to derive from tui_win_info.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-stack.h (struct tui_locator_window): Derive from
	tui_win_info.
	<do_scroll_horizontal, do_scroll_vertical>: New methods.
	<can_box>: New method.
2020-07-01 21:21:16 -06:00
Tom Tromey
1eb2161f83 Remove body of tui_locator_window constructor
The tui_locator_window constructor initializes the first character of
two of its members.  However, this is actually an error, since these
were changed to be std::string.  This removes the erroneous code.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-stack.h (struct tui_locator_window): Remove body.
2020-07-01 21:21:16 -06:00
Tom Tromey
7134f2eb92 Don't derive tui_data_item_window from tui_gen_win_info
There's no deep reason that tui_data_item_window should derive from
tui_gen_win_info -- it currently uses a curses window to render, but
that isn't truly needed, and it adds some hacks to other parts of the
TUI.

This patch changes tui_data_item_window so that it doesn't have a base
class, and updates the register window.  This simplifies the code and
enables a subsequent cleanup.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-regs.c (tui_data_window::display_registers_from)
	(tui_data_window::display_registers_from)
	(tui_data_window::first_data_item_displayed)
	(tui_data_window::delete_data_content_windows): Update.
	(tui_data_window::refresh_window, tui_data_window::no_refresh):
	Remove.
	(tui_data_window::check_register_values): Update.
	(tui_data_item_window::rerender): Add parameters.  Update.
	(tui_data_item_window::refresh_window): Remove.
	* tui/tui-data.h (struct tui_gen_win_info) <no_refresh>: No longer
	virtual.
	* tui/tui-regs.h (struct tui_data_item_window): Don't derive from
	tui_gen_win_info.
	<refresh_window, max_height, min_height>: Remove.
	<rerender>: Add parameters.
	<x, y, visible>: New members.
	(struct tui_data_window) <refresh_window, no_refresh>: Remove.
	<m_item_width>: New member.
2020-07-01 21:21:15 -06:00
Tom Tromey
22b7b0412b Rename tui_data_item_window::item_no
tui_data_item_window::item_no is misnamed -- it only can be used for a
register, but it references a "display" number as well.  (Based on
other comments I've seen in the past -- most since deleted -- I think
there were plans at one point to display variables in this window as
well.  However, this was never implemented.)

This patch renames this member to be more correct.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-regs.c (tui_data_window::show_register_group)
	(tui_data_window::check_register_values): Update.
	* tui/tui-regs.h (struct tui_data_item_window) <regno>: Rename
	from item_no.
2020-07-01 21:21:15 -06:00
Tom Tromey
c9753adb01 Remove useless "if' from tui-regs.c
tui_data_window::show_register_group had a useless "if" -- the
condition could never be false.  This patch removes it.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-regs.c (tui_data_window::show_register_group): Remove
	useless "if".
2020-07-01 21:21:14 -06:00
Tom Tromey
9ab26b4a0f Remove tui_data_window::name
The "name" member of tui_data_window was set, but never used.  This
removes it.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-regs.c (tui_data_window::show_register_group): Update.
	* tui/tui-regs.h (struct tui_data_item_window) <name>: Remove.
2020-07-01 21:21:14 -06:00
Tom Tromey
e555083f95 Move some code out of tui-data.h
This moves some code out of tui-data.h, to more closely related
places.  Some unused forward declarations are also removed.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-stack.c (SINGLE_KEY): Move from tui-data.h
	* tui/tui-winsource.h (enum tui_line_or_address_kind)
	(struct tui_line_or_address): Move from tui-data.h.
	* tui/tui-win.c (DEFAULT_TAB_LEN): Move from tui-data.h.
	* tui/tui-data.h (DEFAULT_TAB_LEN): Move to tui-win.c.
	(tui_cmd_window, tui_source_window_base, tui_source_window)
	(tui_disasm_window): Don't declare.
	(enum tui_line_or_address_kind, struct tui_line_or_address): Move
	to tui-winsource.h.
	(SINGLE_KEY): Move to tui-stack.c.
2020-07-01 21:21:13 -06:00
Tom Tromey
7a02bab704 Remove tui_expand_tabs
tui_expand_tabs only has a single caller.  This patch removes this
function, in favor of a tab-expanding variant of string_file.  This
simplifies the code somewhat.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-regs.h (struct tui_data_item_window) <content>: Now a
	std::string.
	* tui/tui-regs.c (class tab_expansion_file): New.
	(tab_expansion_file::write): New method.
	(tui_register_format): Change return type.  Use
	tab_expansion_file.
	(tui_get_register, tui_data_window::display_registers_from)
	(tui_data_item_window::rerender): Update.
	* tui/tui-io.h (tui_expand_tabs): Don't declare.
	* tui/tui-io.c (tui_expand_tabs): Remove.
2020-07-01 21:21:13 -06:00
Tom Tromey
ea68593bd2 Use complete_on_enum in tui_reggroup_completer
tui_reggroup_completer has an "XXXX" comment suggesting the use of
complete_on_enum.  This patch implements this suggestion.

gdb/ChangeLog
2020-07-01  Tom Tromey  <tom@tromey.com>

	* tui/tui-regs.c (tui_reggroup_completer): Use complete_on_enum.
2020-07-01 21:21:12 -06:00
Fangrui Song
a8caed5d7f Recognize -1 as a tombstone value in .debug_line
LLD from 11 onwards (https://reviews.llvm.org/D81784) uses -1 to
represent a relocation in .debug_line referencing a discarded symbol.
Recognize -1 to fix gdb.base/break-on-linker-gcd-function.exp when the
linker is a newer LLD.

gdb/ChangeLog:

	* dwarf2/read.c (lnp_state_machine::check_line_address): Test -1.
2020-07-01 12:31:44 -07:00
Alok Kumar Sharma
9cdf98207c Allow reference form for DW_AT_associated and DW_AT_allocated attributes
Currently, GDB rejects the (die) reference form while it accepts exprloc
form. It is allowed in DWARF standard. "Table 7.5: Attribute encodings"
in DWARF5 standard. Flang compiler assigns (die) reference to
DW_AT_associated and DW_AT_allocated for some cases.

gdb/ChangeLog

	* dwarf2/read.c (set_die_type): Removed conditions to restrict
	forms for DW_AT_associated and DW_AT_allocated attributes,
	which is already checked in function attr_to_dynamic_prop.
2020-07-01 16:57:17 +05:30
Philippe Waroquiers
2a17c803f6 Fix test breakages caused by removal of gdb_py_test_multiple.
Tom de Vries detected that some python tests were broken as
they were still using gdb_py_test_multiple that was replaced
by gdb_test_multiline.  Repair these tests by using the new function.

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

	* gdb.python/py-breakpoint.exp: use gdb_test_multiline instead
	of gdb_py_test_multiple.
	* gdb.python/py-cmd.exp: Likewise.
	* gdb.python/py-events.exp: Likewise.
	* gdb.python/py-function.exp: Likewise.
	* gdb.python/py-inferior.exp: Likewise.
	* gdb.python/py-infthread.exp: Likewise.
	* gdb.python/py-linetable.exp: Likewise.
	* gdb.python/py-parameter.exp: Likewise.
	* gdb.python/py-value.exp: Likewise.
2020-06-30 18:40:21 +02:00
Tom Tromey
a1520ad8fc Fix bug in quirk_rust_enum
Tom de Vries pointed out that some Rust tests were failing after the
variant part rewrite.  He sent an executable, which helped track down
this bug.

quirk_rust_enum was passing 1 to alloc_rust_variant in one case.
However, a comment earlier says:

      /* We don't need a range entry for the discriminant, but we do
	 need one for every other field, as there is no default
	 variant.  */

In this case, we must pass -1 for this parameter.  That is what this
patch implements.

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

	* dwarf2/read.c (quirk_rust_enum): Correctly call
	alloc_rust_variant for default-less enum.
2020-06-30 07:57:35 -06:00
Tom Tromey
5ac588997c Do not define basic_string_view::to_string
gdb's copy of basic_string_view includes a to_string method.  However,
according to cppreference, this is not a method on the real
std::basic_string_view:

https://en.cppreference.com/w/cpp/string/basic_string_view

This difference matters because gdb_string_view.h will use the
standard implementation when built with a C++17 or later.  This caused
PR build/26183.

This patch fixes the problem by changing the method to be a standalone
helper function, and then rewriting the uses.  Tested by rebuilding
with a version of GCC that defaults to C++17.

(Note that the build still is not clean; and also I noticed that the
libstdc++ string_view forbids the use of nullptr ... I wonder if gdb
violates that.)

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

	PR build/26183:
	* ada-lang.c (ada_lookup_name_info::ada_lookup_name_info): Use
	gdb::to_string.

gdbsupport/ChangeLog
2020-06-30  Tom Tromey  <tromey@adacore.com>

	PR build/26183:
	* gdb_string_view.h (basic_string_view::to_string): Remove.
	(gdb::to_string): New function.
2020-06-30 07:53:03 -06:00
Tom de Vries
b011fe1a72 [gdb/testsuite] Handle early_flags in gdb_default_target_compile
In gdb_default_target_compile, we use dejagnu's default_target_compile, unless
we need support for languages that are not yet support in the used dejagnu
version, in which case we use a local default_target_compile:
gdb_default_target_compile_1.

However, there's another reason to use the local default_target_compile: when
early_flags is used, because there's no dejagnu release available yet
supporting this.

Fix this by detecting and handling early_flags in gdb_default_target_compile.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

2020-06-30  Tom de Vries  <tdevries@suse.de>

	PR testsuite/26175
	* lib/future.exp (gdb_default_target_compile): Detect and handle
	early_flags.
2020-06-30 09:23:09 +02:00
Simon Marchi
19b187a978 gdb: fix documentation of gdbarch_displaced_step_copy_insn
I spotted something that looks wrong in the doc of
gdbarch_displaced_step_copy_insn.

It says that if the function returns NULL, it means that it has emulated
the behavior of the instruction and written the result to REGS.
However, it says below that the function may return NULL to indicate
that the instruction can't be single-stepped out-of-line, in which case
the core steps the instruction in-line.  The two are contradictory.

The right one is the latter, if the function returns NULL, the core
falls back to in-line stepping. I checked all the implementations of
this function and they all agree with this.

gdb/ChangeLog:

	* gdbarch.sh (displaced_step_copy_insn): Update doc.
	* gdbarch.h: Re-generate.

Change-Id: I98163cdd38970cde4c77680e249b10f5d2d5bf9b
2020-06-29 11:27:46 -04:00
Simon Marchi
df5b887608 gdb/testsuite: better handle failures in simavr board, reap simavr process
This patch makes a few adjustments to the simavr.exp to handle tests
that error out more gracefully.  I put all the changes in the same patch
because right now it's in a very bad shape, so it's very painful to do
small incremental adjustements.  I found that with these changes, it
becomes reasonably stable.

For example, the gdb.base/step-over-syscall.exp test is a bit buggy
(stuff for another patch...), in that it calls gdb_load (through
clean_restart) with a file that doesn't exist.  The gdb_load
implementation in simavr.exp gets called with a file that doesn't exist,
and simavr (expectedly) fails to start.

When this happens, we currently leave the $simavr_spawn_id variable set.
However, because the simavr process has terminated, its spawn id is
closed.  When the next test tries to close the previous connection to
simavr, it fails to, and this error is thrown:

    ERROR: close: spawn id exp86 not open
        while executing
    "close -i $simavr_spawn_id"
        (procedure "gdb_load" line 18)
        invoked from within

In other words, any test ran after step-over-syscall.exp will have
simavr.exp's gdb_load fail on it.

This patch tries to make sure that simavr.exp's gdb_load only leaves
simavr_spawn_id set if everything went fine.  If we couldn't start
simavr, don't see the expected output, or fail to connect to it, we
close the spawn id (if needed) and unset simavr_spawn_id.

As an additional precaution, I added a catch around the "close the
previous connection" code.  Ideally, this shouldn't be necessary, but I
bet there are other similar scenarios where we might try to close an
already close spawn id.  So I think displaying a warning is better than
messing up all following tests.

Also, the board never wait'ed for the simavr process, resulting in tons
of zombie simavr processes hanging around.  This patch adds some calls
to "wait" whenever we close the connection (or realize it is already
closed), which seems to fix the problem.

Finally I switched a `gdb_expect` to bare `expect`, where we wait for
the "listening" message from simavr.  I found it necessary because
gdb_expect (through remote_expect) adds a `-i <gdb spawn id> -timeout
10`.  So if for some reason the GDB process has crashed in the mean
time, this expect will unexpectedly error out with a `spawn id <gdb
spawn id> not open`.  Therefore, change `gdb_expect` to `expect` so that
we only deal with simavr's spawn id here.

Here are the results on TESTS="gdb.base/*.exp" before:

    # of expected passes		4816
    # of unexpected failures	4433
    # of known failures		2
    # of unresolved testcases	300
    # of untested testcases		143
    # of unsupported tests		7
    # of paths in test names	2
    # of duplicate test names	10

and after:

    # of expected passes		21957
    # of unexpected failures	1564
    # of expected failures		8
    # of unknown successes		1
    # of known failures		31
    # of unresolved testcases	532
    # of untested testcases		153
    # of unsupported tests		28
    # of paths in test names	2
    # of duplicate test names	32

I tested using simavr's current master (7c254e2081b5).

gdb/testsuite/ChangeLog:

	* boards/simavr.exp (gdb_load): Catch errors when closing
	previous connection.  Close connection, wait for process and
	unset simavr_spawn_id on failure.

Change-Id: I695fc765e1c22e1d1dc0b08e0f5141244986b868
2020-06-29 10:19:43 -04:00
Tom de Vries
a3ca48cdda [gdb/testsuite] Emit unresolved for unknown proc
Since commit 26783bce15 "[gdb/testsuite] Don't abort testrun for invalid
command in test-case" we don't abort the testrun when encountering an invalid
command.  However, since we don't report errors in the summary, there's a
chance that the error goes unnoticed.

Make the invalid command error more visible by marking the test-case
unresolved, such that we have f.i.:
...
PASS: gdb.python/py-breakpoint.exp: test_bkpt_internal: Test watchpoint write
UNRESOLVED: gdb.python/py-breakpoint.exp: test_bkpt_eval_funcs: \
  testcase aborted due to invalid command name: gdb_py_test_multiple
ERROR: tcl error sourcing py-breakpoint.exp.
ERROR: invalid command name "gdb_py_test_multiple"
    while executing
  ...
                === gdb Summary ===

nr of expected passes            56
nr of unresolved testcases       1
...

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

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

	* lib/gdb.exp (unknown): Make test-case unresolved.
2020-06-29 13:59:19 +02:00
Tom de Vries
b0237c0eab [gdb/testsuite] Expect conformation question in gdb.server/solib-list.exp
Before commit a8654e7d78 'Fixes PR 25475: ensure exec-file-mismatch "ask"
always asks in case of mismatch', there was a difference in behaviour in
test-case gdb.server/solib-list.exp.

If the executable did not contain debug info (as is usually the case), gdb
would detect a mismatch but not ask for confirmation:
...
(gdb) target remote localhost:2346^M
Remote debugging using localhost:2346^M
warning: Mismatch between current exec-file solib-list^M
and automatically determined exec-file /lib64/ld-2.26.so^M
exec-file-mismatch handling is currently "ask"^M
Reading symbols from /lib64/ld-2.26.so...^M
Reading symbols from /usr/lib/debug/lib64/ld-2.26.so.debug...^M
0x00007ffff7dd7ea0 in _start () at rtld.c:745^M
745     }^M
(gdb) PASS: gdb.server/solib-list.exp: non-stop 0: target remote
...

If the executable did contain debug info (as happens to be the case for
openSUSE), gdb would detect a mismatch and ask for confirmation:
...
(gdb) PASS: gdb.server/solib-list.exp: non-stop 0: file binfile
target remote localhost:2346^M
Remote debugging using localhost:2346^M
warning: Mismatch between current exec-file solib-list^M
and automatically determined exec-file /lib64/ld-2.26.so^M
exec-file-mismatch handling is currently "ask"^M
Load new symbol table from "/lib64/ld-2.26.so"? (y or n) y^M
Reading symbols from /lib64/ld-2.26.so...^M
Reading symbols from /usr/lib/debug/lib64/ld-2.26.so.debug...^M
0x00007ffff7dd7ea0 in _start () at rtld.c:745^M
745     }^M
(gdb) PASS: gdb.server/solib-list.exp: non-stop 0: target remote
...

After commit a8654e7d78, the confirmation is now also asked in case there's
no debug info.

Tighten the test-case by verifying that the confirmation question is asked, as
suggested in the log message of commit a8654e7d78:
...
we can remove the bypass introduced by Tom in 6b9374f1, in order to always
answer to the 'load' question.
...

gdb/testsuite/ChangeLog:

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

	PR gdb/25475
	* gdb.server/solib-list.exp: Verify that the symbol reload
	confirmation question is asked.
2020-06-29 11:02:06 +02:00
Tom Tromey
cd4c4c07f4 Remove "cmd_type" function
The cmd_type function only has a single caller, which is in the CLI
implementation code.  This patch removes the function, and moves the
cmd_types enum definition from command.h to cli-decode.h, fixing an 18
year old FIXME.

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

	* command.h (cmd_types): Remove.
	(cmd_type): Don't declare.
	* cli/cli-decode.h (enum cmd_types): Uncomment.  No longer a
	typedef.
	* cli/cli-cmds.c (setting_cmd): Use cmd->type directly.
	* cli/cli-decode.c (cmd_type): Remove.
2020-06-28 10:33:07 -06:00
Pedro Alves
05779d57f9 Make {get,set}_inferior_io_terminal inferior methods
This converts the get_inferior_io_terminal and
set_inferior_io_terminal free functions to inferior methods.

Since the related commands are called "tty", "{set,show}
inferior-tty", and MI's "-inferior-tty-{set,show}", to make the
connection between the commands and the code more obvious, the methods
are named set_tty/tty instead of set_io_terminal/io_terminal.

gdb/ChangeLog:

	* fork-child.c (prefork_hook): Adjust.
	* infcmd.c (set_inferior_io_terminal, get_inferior_io_terminal):
	Delete.
	(set_inferior_tty_command, show_inferior_tty_command): Adjust.
	* inferior.c (inferior::set_tty, inferior::tty): New methods.
	* inferior.h (set_inferior_io_terminal, get_inferior_io_terminal):
	Remove declarations.
	(struct inferior) <set_tty, tty>: New methods.
	(struct inferior) <terminal>: Rename to ...
	(struct inferior) <m_terminal>: ... this and make private.
	* main.c (captured_main_1): Adjust.
	* mi/mi-cmd-env.c (mi_cmd_inferior_tty_set): Adjust.
	(mi_cmd_inferior_tty_show): Adjust.
	* nto-procfs.c (nto_procfs_target::create_inferior): Adjust.
	* windows-nat.c (windows_nat_target::create_inferior): Adjust.
2020-06-27 14:56:05 +01:00
Philippe Waroquiers
c0b3b3bdc6 Make test names unique in python.exp and guile.exp
Version 2, handles the comments of Simon and Pedro.

Note that gdb_test_multiline and gdb_py_test_multiple are using
the "input line" as the test name, and so when there is a duplicated
input line (such as a line containing "end"), we have duplicated test
names => as gdb_test_multiline and gdb_py_test_multiple are identical,
as indicated in FIXME, move this to gdb.exp, and make the test name unique
by adding the inputnr to the pass message for each input.

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

	* lib/gdb.exp (gdb_test_multiline): New, moved from gdb-guile.exp,
	have a input seq nr in each pass message.
        * lib/gdb-guile.exp (gdb_test_multiline): Move to gdb.exp.
	* lib/gdb-python.exp (gdb_py_test_multiple): Remove.
	* gdb.python/python.exp: Make test names unique,
	use gdb_test_multiline instead of gdb_py_test_multiple,
	use $gdb_test_name.
	* gdb.guile/guile.exp: Make test names unique, use $gdb_test_name
2020-06-26 22:04:46 +02:00
Nick Alcock
1776e3e59c Fix --enable-libctf and --disable-static
This fixes test runs and compilation when --disable-libctf,
--disable-static, or --enable-shared are passed.

Changes since v2: Use GCC_ENABLE and fix indentation.  Fix prototype
using 'void'.  Use 'unsupported' and gdb_caching_proc.

Changes since v3: Adapt to upstream changes providing skip_ctf_tests.

Changes since v4: Adapt to upstream changes in the seven months (!)
since I last looked at this.

gdb/ChangeLog
	* configure.ac: Add --enable-libctf: handle --disable-static
	properly.
	* acinclude.m4: sinclude ../config/enable.m4.
	* Makefile.in (aclocal_m4_deps): Adjust accordingly.
	(LIBCTF): Substitute in.
	(CTF_DEPS): New, likewise.
	(CLIBS): libctf needs symbols from libbfd: move earlier.
	(CDEPS): Use CTF_DEPS, not LIBCTF, now LIBCTF can include rpath
	flags.
	* ctfread.c: Surround in ENABLE_LIBCTF.
	(elfctf_build_psymtabs) [!ENABLE_LIBCTF]: New stub.
	* configure: Regenerate.
	* config.in: Likewise.

gdb/testsuite/ChangeLog
	* configure.ac: Add --enable-libctf.
	* aclocal.m4: sinclude ../config/enable.m4.
	* Makefile.in (site.exp): Add enable_libctf to site.exp.
	* lib/gdb.exp (skip_ctf_tests): Use it.
	* gdb.base/ctf-constvars.exp: Error message tweak.
	* gdb.base/ctf-ptype.exp: Likewise.
	* configure: Regenerate.
2020-06-26 15:56:38 +01:00
Gary Benson
f53b3eeb67 Fix -Wstring-compare testcase build failure
Clang fails to compile the file gdb/testsuite/gdb.cp/try_catch.cc
with the following error:
  warning: result of comparison against a string literal is
  unspecified (use strncmp instead) [-Wstring-compare]

This commit fixes the error, replacing the pointer comparison with
a call to strcmp.  This commit also adds a final check: the test
program is run to the final return statement, and the value of
"test" is checked to ensure it is still "true" at that point.

gdb/testsuite/ChangeLog:

	* gdb.cp/try_catch.cc: Include string.h.
	(main): Replace comparison against string literal with
	strcmp, avoiding build failure with -Wstring-compare.
	Add "marker test-complete".
	* gdb.cp/try_catch.exp: Run the test to the above marker,
	then verify that the value of "test" is still true.
2020-06-26 14:53:28 +01:00
Eli Zaretskii
edf92af0fb Improve documentation of which shell is used by GDB's shell commands
gdb/doc/ChangeLog:

2020-06-26  Eli Zaretskii  <eliz@gnu.org>

	* gdb.texinfo (Shell Commands): More accurate description of use
	of $SHELL.  Reported by Sandra Loosemore <sandra@codesourcery.com>.
2020-06-26 09:51:45 +03:00
Simon Marchi
58373b80f3 gdb: use make_unique_xstrdup in set_inferior_io_terminal
gdb/ChangeLog:

	* infcmd.c (set_inferior_io_terminal): Use make_unique_xstrdup.

Change-Id: I38b6e753f58947531fe4a293d574bc27ec128f47
2020-06-25 17:06:18 -04:00
Simon Marchi
277474eea0 gdb: make inferior::terminal a unique ptr
This changes the inferior::terminal field to be a unique pointer, so its
deallocation is automatically managed.

gdb/ChangeLog:

	* inferior.h (struct inferior) <terminal>: Change type to
	gdb::unique_xmalloc_ptr<char>.
	* inferior.c (inferior::~inferior): Don't free inf->terminal.
	* infcmd.c (set_inferior_io_terminal): Don't free terminal
	field, adjust to unique pointer.
	(get_inferior_io_terminal): Adjust to unique pointer.

Change-Id: Iedb6459b4f9eeae812b0cb9d514b5707d5107cdb
2020-06-25 14:44:35 -04:00
Andrew Burgess
6d74da72da gdb/riscv: Loop over all registers for 'info all-registers'
Currently the 'info all-registers' command only loops over those
registers that are known to GDB.  Any registers that are unknown, that
is, are mentioned in the target description, but are not something GDB
otherwise knows, will not be displayed.

This feels wrong, so this commit fixes this mistake.  The output of
'info all-registers' now matches 'info registers all'.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_print_registers_info): Loop over all
	registers, not just the known core set of registers.

gdb/testsuite/ChangeLog:

	* gdb.arch/riscv-tdesc-regs.exp: New test cases.
2020-06-25 18:07:33 +01:00
Andrew Burgess
2e52d03824 gdb/riscv: Record information about unknown tdesc registers
Making use of the previous commit, record information about unknown
registers in the target description, and use this to resolve two
issues.

1. Some targets (QEMU) are reporting three register fflags, frm, and
   fcsr, twice, once in the FPU feature, and once in the CSR feature.
   GDB does create two registers with identical names, but this
   is (sort of) fine, we only ever use the first one, and as both
   registers access the same target state things basically work OK.
   The only real problem is that the register names show up twice in
   'info registers all' output.

   In this commit we spot the duplicates of these registers and then
   return NULL when asked for the name of these registers.  This
   causes GDB to hide these registers from the user, fixing this
   problem.

2. Some targets (QEMU) advertise CSRs that GDB then can't read.  The
   problem is these targets also say these CSRs are part of the
   save/restore register groups.

   This means that before an inferior call GDB tries to save all of
   these CSRs, and a failure to read one causes the inferior call to
   be abandoned.

   We already work around this issue to some degree, known CSRs are
   removed from the save/restore groups, despite what the target might
   say.  However, any unknown CSRs are (currently) not removed in this
   way.

   After this commit we keep a log of the register numbers for all
   unknown CSRs, then when asked about the register groups, we
   override the group information for unknown CSRs, removing them from
   the save and restore groups.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_register_name): Return NULL for duplicate
	fflags, frm, and fcsr registers.
	(riscv_register_reggroup_p): Remove unknown CSRs from save and
	restore groups.
	(riscv_tdesc_unknown_reg): New function.
	(riscv_gdbarch_init): Pass riscv_tdesc_unknown_reg to
	tdesc_use_registers.
	* riscv-tdep.h (struct gdbarch_tdep): Add
	unknown_csrs_first_regnum, unknown_csrs_count,
	duplicate_fflags_regnum, duplicate_frm_regnum, and
	duplicate_fcsr_regnum fields.

gdb/testsuite/ChangeLog:

	* gdb.arch/riscv-tdesc-regs.exp: Extend test case.
2020-06-25 18:07:32 +01:00
Andrew Burgess
be64fd0776 gdb: Extend target description processing of unknown registers
This commit adds a new step to the processing of a target description
done in tdesc_use_registers, this new step is about how unknown
registers are processed.

Currently an architecture looks through the target description and
calls tdesc_numbered_register for each register is was expecting (or
hoping) to find.  This builds up a map from GDB's register numbers to
the tdesc_reg object.  Later the architecture calls
tdesc_use_registers.

In tdesc_use_registers we build a hash with keys being all the
tdesc_reg object pointers, from this hash we remove all of the
tdesc_reg objects that were assigned register numbers using
tdesc_numbered_register.

Finally we walk through all of the tdesc_reg objects, and if it was
not already assigned a number we assign that register the next
available number.

The problem with this is that the architecture has no visibility of
which unknown registers exist, and which tdesc_feature the register
came from, in some cases this might be important.

For example, on RISC-V GDB overrides the use of
tdesc_register_reggroup_p, with riscv_register_reggroup_p to modify
some of the register group choices.  In this function GDB wants to
treat all registers from a particular feature in a certain way.  This
is fine for registers that GDB knows might be in that feature, but for
unknown registers the RISC-V parts of GDB have no easy way to figure
out which unknown registers exist, and what numbers they were
assigned.

We could figure this information out by probing the register
structures after calling tdesc_use_registers, but this would be
horrible, much better to have tdesc_use_registers tell the
architecture about unknown registers.

This is what this commit does.  A new phase of tdesc_use_registers,
just before the unknown registers are assigned a number, we loop over
each tdesc_reg object, if it has not been assigned a number then we
figure out what number would be assigned and then call back into the
architecture passing the tdesc_feature, register name, and the
proposed register number.

The architecture is free to return the proposed register number, or it
can return a different number (which has a result identical to having
called tdesc_numbered_register).  Alternatively the architecture can
return -1 to indicate the register should be numbered later.

After calling the callback for every tdesc_reg object any registers
still don't have a number assigned (because the architecture returned
-1), then a new register number is assigned, which might be different
from the proposed number that was suggested earlier.

This commit adds the general target-description parts of this
mechanism.  No targets are currently using this code.  The RISC-V
target will make use of this in the next commit.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* target-descriptions.c (tdesc_use_registers): Add new parameter a
	callback, use the callback (when not null) to help number unknown
	registers.
	* target-descriptions.h (tdesc_unknown_register_ftype): New typedef.
	(tdesc_use_registers): Add extra parameter to declaration.
2020-06-25 18:07:31 +01:00
Andrew Burgess
3b9fce9660 gdb/riscv: Improve support for matching against target descriptions
For the RISC-V target it is desirable if the three floating pointer
status CSRs fflags, frm, and fcsr can be placed into either the FPU
feature or the CSR feature.  This allows different targets to build
the features in a way that better reflects their target.

The change to support this within GDB is fairly simple, so this is
done in this commit, and some tests added to check this new
functionality.

gdb/ChangeLog:

	* riscv-tdep.c (value_of_riscv_user_reg): Moved to here from later
	in the file.
	(class riscv_pending_register_alias): Likewise.
	(riscv_register_feature::register_info): Change 'required_p' field
	to 'required', and change its type.  Add 'check' member function.
	(riscv_register_feature::register_info::check): Define new member
	function.
	(riscv_xreg_feature): Change initialisation of 'required' field.
	(riscv_freg_feature): Likewise.
	(riscv_virtual_feature): Likewise.
	(riscv_csr_feature): Likewise.
	(riscv_check_tdesc_feature): Take extra parameter, the csr
	tdesc_feature, rewrite the function to use the new
	riscv_register_feature::register_info::check function.
	(riscv_gdbarch_init): Pass the csr tdesc_feature where needed.

gdb/testsuite/ChangeLog:

	* gdb.arch/riscv-tdesc-loading-01.xml: New file.
	* gdb.arch/riscv-tdesc-loading-02.xml: New file.
	* gdb.arch/riscv-tdesc-loading-03.xml: New file.
	* gdb.arch/riscv-tdesc-loading-04.xml: New file.
	* gdb.arch/riscv-tdesc-loading.exp: New file.
2020-06-25 18:07:31 +01:00
Andrew Burgess
865bad2602 gdb/riscv: Remove CSR feature file
There is currently a bug in the RISC-V CSR/FPU feature files.  The
CSRs containing the FPU status registers are mentioned in both the FPU
feature file and the CSR feature file.

My original thinking when adding the FPU feature file was that it made
more sense to group the FPU status registers with the other FPU
state.  This opened up the possibility of debugging very
simple (possibly simulator only) targets that had little more than CPU
and FPU available for GDB to access.

When I then added code to automatically generate the CSR XML file I
forgot to filter out the FPU status CSRs, so these registers were
mentioned twice.

Now for GDB's default RISC-V target descriptions this doesn't actually
matter.  I did consider adding the CSRs to the default target
description, but in the end I didn't bother.  The reasoning again was
simplicity; the default target description is only to be used when the
target doesn't supply its own description, and NOT supplying the CSRs
actually serves to encourage targets to supply an accurate
description.  Combine this with the fact that the CSRs change from
revision to revision, sometimes in non-backward compatible ways, then
having a "default" set of CSRs just feels like a path to confusion and
complaints.

However, having a broken CSR XML file in the GDB source tree has had
one negative effect, QEMU has copied this file into its source tree,
and is using this as its description that it passes to GDB.  That is
QEMU announces the FPU status registers twice, once in the FPU
feature, and once in the CSR feature.

This commit starts along the path back to sanity by deleting the
default CSR XML files from within GDB.  These files were not used in
any way by current GDB, so there is absolutely no loss of
functionality with this change.

gdb/ChangeLog:

	* features/Makefile: Remove all references to the deleted files
	below.
	* features/riscv/32bit-csr.c: Deleted.
	* features/riscv/32bit-csr.xml: Deleted.
	* features/riscv/64bit-csr.c: Deleted.
	* features/riscv/64bit-csr.xml: Deleted.
	* features/riscv/rebuild-csr-xml.sh: Deleted.
2020-06-25 18:07:30 +01:00
Andrew Burgess
ed69cbc8ef gdb/riscv: Take CSR names from target description
First, consider the RISC-V register $x1.  This register has an alias
$ra.  When GDB processes an incoming target description we allow the
target to use either register name to describe the target.

However, within GDB's UI we want to use the $ra alias in preference to
the $x1 architecture name.

To achieve this GDB overrides the tdesc_register_name callback with
riscv_register_name.  In riscv_register_name we ensure that we always
return the preferred name, so in this case "ra".

To ensure the user can still access the register as $x1 if they want
to, when in riscv_check_tdesc_feature we spot that the target has
supplied the register, we add aliases for every name except the
preferred one, so in this case we add the alias "x1".

This scheme seems to work quite well, the targets have the flexibility
to be architecture focused if they wish (using x0 - x31) while GDB is
still using the ABI names ra, sp, gp, etc.

When this code was originally added there was an attempt made to
include the CSRs in the same scheme.  At the time the CSRs only had
two names, one pulled from riscv-opc.h, and one generated in GDB that
had the pattern csr%d.

The idea was that if the remote targets description described the CSRs
as csr%d then GDB would rename these back to the real CSR name.  This
code was only included because if followed the same pattern as the
x-regs and f-regs, not because I was actually aware of any target that
did this.

However, recent changes to add additional CSR aliases has made me
rethink the position here.

Lets consider the CSR $dscratch0.  This register has an alias
'csr1970' (1970 is 0x7b2, which is the offset of the CSR register into
the CSR address space).  However, this register was originally called
just 'dscratch', and so, after recent commits, this register also has
the alias 'dscratch'.

As the riscv-opc.h file calls this register 'dscratch0' GDB's
preferred name for this register is 'dscratch0'.

So, if the remote target description includes the register
'dscratch0', then GDB will add the aliases 'dscratch', and 'csr1970'.
In the UI GDB will describe the register as 'dscratch0', and all it
good.

The problem I see in this case is where the target describes the
register as 'dscratch'.  In this case GDB will still spot the register
and add the aliases 'dscratch', and 'csr1970', GDB will then give the
register the preferred name 'dscratch0'.

I don't like this.  For the CSRs I think that we should stick with the
naming scheme offered by the remote target description.  As the RISC-V
specification evolves and CSR register names evolve, insisting on
referring to registers by the most up to date name makes it harder for
a target to provide a consistent target description for an older
version of the RISC-V architecture spec.

In this precise case the target offers 'dscratch', which is from an
older version of the RISC-V specification, the newer version of the
spec has two registers 'dscratch0' and 'dscratch1'.  If we insist on
using 'dscratch0' it is then a little "weird" (or seems so to me) when
'dscratch1' is missing.

This patch makes a distinction between the x and f registers and the
other register sets.  For x and f we still make use of the renaming
scheme, forcing GDB to prefer the ABI name.  But after this patch the
CSR register group, and also the virtual register group, will always
prefer to use the name given in the target description, adding other
names as aliases, but not making any other name the preferred name.

gdb/ChangeLog:

	* riscv-tdep.c (struct riscv_register_feature::register_info): Fix
	whitespace error for declaration of names member variable.
	(struct riscv_register_feature): Add new prefer_first_name member
	variable, and fix whitespace error in declaration of registers.
	(riscv_xreg_feature): Initialize prefer_first_name field.
	(riscv_freg_feature): Likewise.
	(riscv_virtual_feature): Likewise.
	(riscv_csr_feature): Likewise.
	(riscv_register_name): Expand on comments.  Remove register name
	modifications for CSR and virtual registers.

gdb/testsuite/ChangeLog:

	* gdb.arch/riscv-tdesc-regs.exp: Extend test case.
2020-06-25 18:07:30 +01:00
Andrew Burgess
4445e8f59a gdb/riscv: Fix whitespace error
Should be 'std::vector<type>' not 'std::vector <type>'.

gdb/ChangeLog:

	* riscv-tdep.c (struct riscv_register_feature): Fix whitespace
	errors.
2020-06-25 18:07:29 +01:00
Andrew Burgess
767a879e31 gdb/riscv: Improved register alias name creation
This commit does two things:

 1. Makes use of the DECLARE_CSR_ALIAS definitions in riscv-opc.h to
 add additional aliases for CSRs.

 2. Only creates aliases for registers that are actually present on
 the target (as announced in the target XML description).

This means that the 'csr%d' aliases that exist will only be created
for those CSRs the target actually has, which is a nice improvement,
as accessing one of the CSRs that didn't exist would cause GDB to
crash with this error:

  valprint.c:1560: internal-error: bool maybe_negate_by_bytes(const gdb_byte*, unsigned int, bfd_endian, gdb::byte_vector*): Assertion `len > 0' failed.

When we look at the DECLARE_CSR_ALIAS lines in riscv-opc.h, these can
be split into three groups:

 DECLARE_CSR_ALIAS(misa, 0xf10, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P9P1)

The 'misa' register used to exist of offset 0xf10, but was moved to
its current offset (0x301) in with privilege spec 1.9.1.  We don't
want GDB to create an alias called 'misa' as we will already have a
'misa' register created by the DECLARE_CSR(misa ....) call earlier in
riscv-opc.h

 DECLARE_CSR_ALIAS(ubadaddr, CSR_UTVAL, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P10)
 DECLARE_CSR_ALIAS(sbadaddr, CSR_STVAL, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P10)
 DECLARE_CSR_ALIAS(sptbr, CSR_SATP, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P10)
 DECLARE_CSR_ALIAS(mbadaddr, CSR_MTVAL, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P10)
 DECLARE_CSR_ALIAS(mucounteren, CSR_MCOUNTINHIBIT, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P10)

These aliases are all CSRs that were removed in privilege spec 1.10,
and whose addresses were reused by new CSRs.  The names meaning of the
old names is totally different to the new CSRs that have taken their
place.  I don't believe we should add these as aliases into GDB.  If
the new CSR exists in the target then that should be enough.

 DECLARE_CSR_ALIAS(dscratch, CSR_DSCRATCH0, CSR_CLASS_I, PRIV_SPEC_CLASS_1P9, PRIV_SPEC_CLASS_1P11)

In privilege spec 1.11 the 'dscratch' register was renamed to
'dscratch0', however the meaning of the register didn't change.
Adding the 'dscratch' alias makes sense I think.

Looking then at the final PRIV_SPEC_CLASS_* field for each alias then
we can see that currently we only want to take the alias from
PRIV_SPEC_CLASS_1P11.  For now then this is what I'm using to filter
the aliases within GDB.

In the future there's no telling how DECLARE_CSR_ALIAS will be used.
I've heard it said that future RISC-V privilege specs will not reuse
CSR offsets again.  But it could happen.  We just don't know.

If / when it does we may need to revisit how aliases are created for
GDB, but for now this seems to be OK.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_create_csr_aliases): Handle csr aliases from
	riscv-opc.h.
	(class riscv_pending_register_alias): New class.
	(riscv_check_tdesc_feature): Take vector of pending aliases and
	populate it as appropriate.
	(riscv_setup_register_aliases): Delete.
	(riscv_gdbarch_init): Create vector of pending aliases and pass it
	to riscv_check_tdesc_feature in all cases.  Use the vector to
	create the register aliases.

gdb/testsuite/ChangeLog:

	* gdb.arch/riscv-tdesc-regs-32.xml: New file.
	* gdb.arch/riscv-tdesc-regs-64.xml: New file.
	* gdb.arch/riscv-tdesc-regs.c: New file.
	* gdb.arch/riscv-tdesc-regs.exp: New file.
2020-06-25 18:07:29 +01:00
Rainer Orth
bb6e55f3ee Remove obsolete gdbarch_static_transform_name
gdbarch_static_transform_name is completely Solaris-specific or rather
specific to the Studio compilers.  Studio cc has deprecated Stabs support
in the 12.4 release back in 2015, GCC has defaulted to DWARF-2 on Solaris
7+ since 2004 and Stabs themselves are pretty much obsolete, so the whole
code can go.

Tested on sparcv9-sun-solaris2.11 and x86_64-pc-linux-gnu with
--enable-targets=all.

	* sol2-tdep.c (sol2_static_transform_name): Remove.
	(sol2_init_abi): Don't register it.
	* gdbarch.sh (static_transform_name): Remove.
	* gdbarch.c, gdbarch.h: Regenerate.

	* dbxread.c (read_dbx_symtab) <'S'>: Remove call to
	gdbarch_static_transform_name.
	* mdebugread.c (parse_partial_symbols) <'S'>: Likewise.
	* stabsread.c (define_symbol) <'X'>: Remove.
	(define_symbol) <'S'>: Remove gdbarch_static_transform_name
	handling.
	<'V'>: Likewise.
	* xcoffread.c (scan_xcoff_symtab): Remove gdbarch.
	<'S'>: Remove call to gdbarch_static_transform_name.
2020-06-25 17:56:12 +02:00
Rainer Orth
c6d3683661 Use fork instead of vfork on Solaris
The gdb.mi/mi-exec-run.exp test never completed/timed out on Solaris for
quite some time:

FAIL: gdb.mi/mi-exec-run.exp: inferior-tty=main: mi=main: force-fail=1: run failure detected (timeout)

This is for gdb trying to exec mi-exec-run.nox, a copy of mi-exec-run
with execute permissions removed.

The process tree at this point looks like this:

          21254 /vol/gcc/bin/expect -- /vol/gcc/share/dejagnu/runtest.exp GDB_PARALLEL=yes --outdir=outputs/gdb.mi/mi-exec-run-vfork gdb.mi/mi-exec-run.exp
            21300 <defunct>
            21281 <defunct>
            21294 $obj/gdb/testsuite/../../gdb/gdb -nw -nx -data-directory $obj/gdb/testsuite/../data-directory -i=mi
              21297 $obj/gdb/testsuite/../../gdb/gdb -nw -nx -data-directory $obj/gdb/testsuite/../data-directory -i=mi

The parent gdb hangs here:

21294:  $obj/gdb/testsuite/../../gdb/gdb -nw
------------  lwp# 1 / thread# 1  ---------------
 0000000000000000 SYS#0    ()
 0000000000daeccd procfs_target::create_inferior(char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char**, int) () + 97 (procfs.c:2853)
 0000000000ca63a7 run_command_1(char const*, int, run_how) () + 349 (basic_string.h:187)
 0000000000ca6516 start_command(char const*, int) () + 26 (infcmd.c:584)
 0000000000b3ca8e do_const_cfunc(cmd_list_element*, char const*, int) () + f (cli-decode.c:96)
 0000000000b3ed77 cmd_func(cmd_list_element*, char const*, int) () + 32 (cli-decode.c:2113)
 0000000000f2d219 execute_command(char const*, int) () + 455 (top.c:657)
 0000000000d4ad77 mi_execute_cli_command(char const*, int, char const*) () + 242 (basic_string.h:187)
 0000000000d4ae80 mi_cmd_exec_run(char const*, char**, int) () + ba (mi-main.c:473)

with these process flags

21294:	$obj/gdb/testsuite/../../gdb/gdb -nw
	data model = _LP64  flags = VFORKP|ORPHAN|MSACCT|MSFORK
	sigpend = 0x00004103,0x00000000,0x00000000
 /1:	flags = 0
	sigmask = 0xffbffeff,0xffffffff,0x000000ff
	cursig = SIGKILL
 /2:	flags = DETACH|STOPPED|ASLEEP  lwp_park(0x0,0x0,0x0)
	why = PR_SUSPENDED
	sigmask = 0x000a2002,0x00000000,0x00000000
[...]

while the child sits at

21297:  $obj/gdb/testsuite/../../gdb/gdb -nw
 00007fffbf078a0b execve   (7fffbffff756, 7fffbfffec58, 7fffbfffec90, 0)
 00007fffbef84cf6 execvpex () + f6
 00007fffbef84f45 execvp () + 15
 0000000000d60a44 fork_inferior(char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char**, void (*)(), gdb::function_view<void (int)>, void (*)(), char const*, void (*)(char const*, char* const*, char* const*)) () + 47f (fork-inferior.c:423)
 0000000000daeccd procfs_target::create_inferior(char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char**, int) () + 97 (procfs.c:2853)
 0000000000ca63a7 run_command_1(char const*, int, run_how) () + 349 (basic_string.h:187)
 0000000000ca6516 start_command(char const*, int) () + 26 (infcmd.c:584)
 0000000000b3ca8e do_const_cfunc(cmd_list_element*, char const*, int) () + f (cli-decode.c:96)
 0000000000b3ed77 cmd_func(cmd_list_element*, char const*, int) () + 32 (cli-decode.c:2113)
 0000000000f2d219 execute_command(char const*, int) () + 455 (top.c:657)
 0000000000d4ad77 mi_execute_cli_command(char const*, int, char const*) () + 242 (basic_string.h:187)
 0000000000d4ae80 mi_cmd_exec_run(char const*, char**, int) () + ba (mi-main.c:473)

with

21297:	$obj/gdb/testsuite/../../gdb/gdb -nw
	data model = _LP64  flags = MSACCT|MSFORK
	exitset  = 0x00000000 0x04000000 0x00000000 0x00000000
	           0x00000000 0x00000000 0x00000000 0x00000000
 /1:	flags = STOPPED|ISTOP  execve(0x7fffbffff756,0x7fffbfffec58,0x7fffbfffec90,0x0)
	why = PR_SYSEXIT  what = execve

We have a deadlock here: the execve in the child cannot return until the
parent has handled the PR_SYSEXIT while the parent cannot run with a
vfork'ed child as documented in proc(4):

       The child of a vfork(2) borrows the  parent's  address  space.  When  a
       vfork(2) is executed by a traced process, all watched areas established
       for the parent are suspended until the child terminates or performs  an
       exec(2).  Any  watched areas established independently in the child are
       cancelled when the parent resumes  after  the  child's  termination  or
       exec(2).  PCWATCH  fails  with  EBUSY  if  applied  to  the parent of a
       vfork(2) before the child has terminated or performed an  exec(2).  The
       PR_VFORKP  flag  is  set  in  the  pstatus  structure for such a parent
       process.

In that situation, the parent cannot be killed even with SIGKILL (as
runtest will attempt once the timeout occurs; the pending signal can be
seen in the pflags output above), so the whole test hangs until one
manually kills the child process.

Fortunately, there's an easy way out: when using fork instead of vfork,
the problem doesn't occur, and this is what the current patch does: it
calls fork_inferior with a dummy pre_trace_fun arg.

Tested on amd64-pc-solaris2.11 and sparcv9-sun-solaris2.11.

	* procfs.c (procfs_pre_trace): New function.
	(procfs_target::create_inferior): Pass it to fork_inferior.
2020-06-25 17:48:14 +02:00
Rainer Orth
a7e6196bb8 Don't include *sol2-tdep.o on Linux/sparc*
Linux/sparc* currently links Solaris-specific files (sparc-sol2-tdep.o,
sparc64-sol2-tdep.o, sol2-tdep.o) for no apparent reason.  It has no
business doing so, and none of the functions/variables defined there are
used explicitly.  If support for the Solaris OSABI were desired, this
should be done using --enable-targets instead.

Since neither sparc{32,64}_sol2_init_abi currently declared in common
headers (sparc*-tdep.h) are used outside their source files, they are made
static and the declarations removed.

Tested on sparcv9-sun-solaris2.11 and sparc64-unknown-linux-gnu.

	* configure.tgt <sparc-*-linux*> (gdb_target_obs): Remove
	sparc-sol2-tdep.o, sol2-tdep.o, sparc64-sol2-tdep.o.
	<sparc64-*-linux*> (gdb_target_obs): Remove sparc64-sol2-tdep.o,
	sol2-tdep.o, sparc-sol2-tdep.o.
	* sparc-sol2-tdep.c (sparc32_sol2_init_abi): Make static.
	* sparc-tdep.h (sparc32_sol2_init_abi): Remove.
	* sparc64-sol2-tdep.c (sparc64_sol2_init_abi): Make static.
	* sparc64-tdep.h (sparc64_sol2_init_abi): Remove.
2020-06-25 13:54:42 +02:00
Rainer Orth
d412e69677 Move common handlers to sol2_init_abi
There's some overlap and duplication between 32 and 64-bit Solaris/SPARC
and x86 tdep files, in particular

        sol2_core_pid_to_str
	*_sol2_sigtramp_p
        sol2_skip_solib_resolver
        *_sol2_static_transform_name (forgotten on amd64)
        set_gdbarch_sofun_address_maybe_missing (likewise)

This patch avoids this by centralizing common code in sol2-tdep.c.
While sparc_sol2_pc_in_sigtramp and sparc_sol2_static_transform_name
were declared in the shared sparc-tdep.h, they were only used in Solaris
files.

Tested on amd64-pc-solaris2.11, i386-pc-solaris2.11,
sparcv9-sun-solaris2.11, and sparc-sun-solaris2.11, and
sparc64-unknown-linux-gnu.

	* amd64-sol2-tdep.c (amd64_sol2_sigtramp_p): Remove.
	(amd64_sol2_init_abi): Use sol2_sigtramp_p.
	Call sol2_init_abi.
 	Remove calls to set_gdbarch_skip_solib_resolver,
	set_gdbarch_core_pid_to_str.
	* i386-sol2-tdep.c (i386_sol2_sigtramp_p): Remove.
	(i386_sol2_static_transform_name): Remove.
	(i386_sol2_init_abi): Call sol2_init_abi.
	Remove calls to set_gdbarch_sofun_address_maybe_missing,
	set_gdbarch_static_transform_name,
	set_gdbarch_skip_solib_resolver, set_gdbarch_core_pid_to_str.
	Use sol2_sigtramp_p.
	* sol2-tdep.c (sol2_pc_in_sigtramp): New function.
	(sol2_sigtramp_p): New function.
	(sol2_static_transform_name): New function.
	(sol2_skip_solib_resolver, sol2_core_pid_to_str): Make static.
	(sol2_init_abi): New function.
	* sol2-tdep.h (sol2_sigtramp_p, sol2_init_abi): Declare.
	(sol2_skip_solib_resolver, sol2_core_pid_to_str): Remove.
	* sparc-sol2-tdep.c (sparc_sol2_pc_in_sigtramp): Remove.
	(sparc32_sol2_sigtramp_frame_sniffer): Just call sol2_sigtramp_p.
	(sparc_sol2_static_transform_name): Remove.
	(sparc32_sol2_init_abi): Call sol2_init_abi.
	Remove calls to set_gdbarch_sofun_address_maybe_missing,
	set_gdbarch_static_transform_name,
	set_gdbarch_skip_solib_resolver,
	set_gdbarch_core_pid_to_str.
	* sparc-tdep.h (sparc_sol2_pc_in_sigtramp)
	(sparc_sol2_static_transform_name): Remove
	* sparc64-sol2-tdep.c (sparc64_sol2_sigtramp_frame_sniffer): Just
	call sol2_sigtramp_p.
	(sparc64_sol2_init_abi): Call sol2_init_abi.
	Remove calls to set_gdbarch_sofun_address_maybe_missing,
	set_gdbarch_static_transform_name,
	set_gdbarch_skip_solib_resolver, set_gdbarch_core_pid_to_str.
2020-06-25 13:43:46 +02:00
Pedro Alves
221db974e6 W/ Clang, compile/link C++ test programs with "-x c++"
Some testcases want to compile .c files with a C++ compiler.  So they
pass the "c++" option to gdb_compile.  That works fine with GCC, but
with Clang, it results in:

  gdb compile failed, clang-5.0: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated [-Wdeprecated]

and the testcase is skipped with UNTESTED.

A previous patch fixed a case like that in
gdb.compile/compile-cplus.exp, by adding -Wno-deprecated to the build
options.  However, there are other testcases that use the same
pattern, and all fail for the same reason.  For example:

 gdb.base/info-types-c++.exp
 gdb.base/max-depth-c++.exp
 gdb.base/msym-lang.exp
 gdb.base/whatis-ptype-typedefs.exp
 gdb.btrace/rn-dl-bind.exp

Fix this in a central place, within gdb_compile, by passing "-x c++"
to the compiler driver when we're compiling/linking C++.

This revealed that gdb.compile/compile-cplus.exp and
gdb.arch/amd64-entry-value-paramref.exp tests are compiling an
assembly file with the "c++" option, which would now fail to compile,
with the C++ compiler not grokking the assembly, of course.  We just
need to not pass "c++" and all the other related C++ options when
compiling an assembly file.

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

	* gdb.arch/amd64-entry-value-paramref.exp: Use
	prepare_for_testing_full and don't pass "c++" for the .S file
	build spec.
	* gdb.compile/compile-cplus.exp: Don't compile $srcfile3 with
	$options, since it's an assembly file.  Remove -Wno-deprecated.
	* lib/gdb.exp (gdb_compile): Pass "-x c++" explicitly when
	compiling C++ programs.
2020-06-24 23:18:19 +01:00
Pedro Alves
331733cd4e W/ Clang, compile C/C++ testcases with -Wno-unknown-warning-option
Some C/C++ testcases unconditionally pass -Wno-foo as additional
options to disable some warning.  That is OK with GCC, because GCC
accepts -Wno-foo silently even if it doesn't support -Wfoo.  This is a
feature which allows disabling warnings with newer compilers without
breaking builds with older compilers.  Clang however warns about
unknown -Wno-foo by default, unless you pass
-Wno-unknown-warning-option as well:

 $ gcc -Wno-foo test.c
 * nothing, compiles successfuly *

 $ clang -Wno-foo test.c
 warning: unknown warning option '-Wno-foo [-Wunknown-warning-option]

This commit adds -Wunknown-warning-option centrally in gdb_compile, so
that individual testcases don't have to worry about breaking older
Clangs.

IOW, this avoids this problematic scenario:

#1 - A testcase compiles successfully with Clang version X.
#2 - Clang version "X + 1" adds a new warning, enabled by default,
     which breaks the test.
#3 - We add -Wno-newwarning to the testcase, fixing the testcase with
     clang "X + 1".
#4 - Now building the test with Clang version X no longer works, due
     to "unknown warning option".

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

	* lib/gdb.exp (gdb_compile): Update intro comment.  If C/C++ with
	Clang, add "-Wno-unknown-warning-option" to the options.
2020-06-24 23:18:19 +01:00
Philippe Waroquiers
a8654e7d78 Fixes PR 25475: ensure exec-file-mismatch "ask" always asks in case of mismatch.
As explained in https://sourceware.org/bugzilla/show_bug.cgi?id=25475,
when the currently loaded file has no debug symbol,
symbol_file_add_with_addrs does not ask a confirmation to the user
before loading the new symbol file.  The behaviour is not consistent
when symbol_file_add_with_addrs is called due to exec-file-mismatch "ask"
setting.

The PR discusses several solutions/approaches.
The preferred approach (suggested by Joel) is to ensure that GDB always asks
a confirmation when it loads a new symbol file due to exec-file-mismatch,
using a new SYMFILE add-flag.

I tested this manually.  If OK, we can remove the bypass introduced by Tom
in 6b9374f1, in order to always answer to the 'load' question.

gdb/ChangeLog
2020-06-24  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* symfile-add-flags.h: New flag SYMFILE_ALWAYS_CONFIRM.
	* exec.c (validate_exec_file): If from_tty, set both
	SYMFILE_VERBOSE (== from_tty) and SYMFILE_ALWAYS_CONFIRM.
	* symfile.c (symbol_file_add_with_addrs): if always_confirm
	and from_tty, unconditionally ask a confirmation.
2020-06-24 22:21:07 +02:00
Andrew Burgess
caa7fd04f6 gdb: New maintenance command to print XML target description
This commit adds a new maintenance command that dumps the current
target description as an XML document.  This is a maintenance command
as I currently only see this being useful for GDB developers, or for
people debugging a new remote target.

By default the command will print whatever the current target
description is, whether this was delivered by the remote, loaded by
the user from a file, or if it is a built in target within GDB.

The command can also take an optional filename argument.  In this case
GDB loads a target description from the file, and then reprints it.
This could be useful for testing GDB's parsing of target descriptions,
or to check that GDB can successfully parse a particular XML
description.

It is worth noting that the XML description printed will not be an
exact copy of the document fed into GDB.  For example this minimal
input file:

  <target>
    <feature name="abc">
      <reg name="r1" bitsize="32"/>
    </feature>
  </target>

Will produce this output:

  (gdb) maint print xml-tdesc path/to/file.xml
  <?xml version="1.0"?>
  <!DOCTYPE target SYSTEM "gdb-target.dtd">
  <target>
    <feature name="abc">
      <reg name="r1" bitsize="32" type="int" regnum="0"/>
    </feature>
  </target>

Notice that GDB filled in both the 'type' and 'regnum' fields of the
<reg>.  I think this is actually a positive as it means we get to
really understand how GDB processed the document, if GDB made some
assumptions that differ to those the user expected then hopefully this
will bring those issues to the users attention.

To implement this I have tweaked the output produced by the
print_xml_feature which is defined within the gdbsupport/ directory.
The changes I have made to this class are:

  1. The <architecture>...</architecture> tags are now not produced if
  the architecture name is NULL.

  2. The <osabi>...</osabi> tags get a newline at the end.

  3. And, the whole XML document is indented using white space in a
  nested fashion (as in the example output above).

I think that these changes should be fine, the print_xml_feature class
is used:

  1. In gdbserver to generate an XML document to send as the target
  description to GDB.

  2. In GDB as part of a self-check function, a target_desc is
  converted to XML then parsed back into a target_desc.  We then check
  the before and after target_desc objects are the same.

  3. In the new 'maint print xml-tdesc' command.

In all of these use cases adding the extra white space should be fine.

gdbsupport/ChangeLog:

	* tdesc.cc (print_xml_feature::visit_pre): Use add_line to add
	output content, and call indent as needed in all overloaded
	variants.
	(print_xml_feature::visit_post): Likewise.
	(print_xml_feature::visit): Likewise.
	(print_xml_feature::add_line): Two new overloaded functions.
	* tdesc.h (print_xml_feature::indent): New member function.
	(print_xml_feature::add_line): Two new overloaded member
	functions.
	(print_xml_feature::m_depth): New member variable.

gdb/ChangeLog:

	* target-descriptions.c (tdesc_architecture_name): Protect against
	NULL pointer dereference.
	(maint_print_xml_tdesc_cmd): New function.
	(_initialize_target_descriptions): Register new 'maint print
	xml-tdesc' command and give it the filename completer.
	* NEWS: Mention new 'maint print xml-tdesc' command.

gdb/testsuite/ChangeLog:

	* gdb.xml/tdesc-reload.c: New file.
	* gdb.xml/tdesc-reload.exp: New file.
	* gdb.xml/maint-xml-dump-01.xml: New file.
	* gdb.xml/maint-xml-dump-02.xml: New file.
	* gdb.xml/maint-xml-dump.exp: New file.

gdb/doc/ChangeLog:

	* gdb.texinfo (Maintenance Commands): Document new 'maint print
	xml-desc' command.
2020-06-23 22:17:20 +01:00
Andrew Burgess
fbf42f4e6d gdb: Print compatible information within print_xml_feature
The gdbsupport directory contains a helper class print_xml_feature
that is shared between gdb and gdbserver.  This class is used for
printing an XML representation of a target_desc object.

Currently this class doesn't have the ability to print the
<compatible> entities that can appear within a target description, I
guess no targets have needed that functionality yet.

The print_xml_feature classes API is based around operating on the
target_desc class, however, the sharing between gdb and gdbserver is
purely textural, we rely on their being a class called target_desc in
both gdb and gdbserver, but there is no shared implementation.  We
then have a set of functions declared that operate on an object of
type target_desc, and again these functions have completely separate
implementations.

Currently then the gdb version of target_desc contains a vector of
bfd_arch_info pointers which represents the compatible entries from a
target description.  The gdbserver version of target_desc has no such
information.  Further, the gdbserver code doesn't seem to include the
bfd headers, and so doesn't know about the bfd types.

I was reluctant to include the bfd headers into gdbserver just so I
can reference the compatible information, which isn't (currently) even
needed in gdbserver.

So, the approach I take in this patch is to wrap the compatible
information into a new helper class.  This class is declared in the
gdbsupport library, but implemented separately in both gdb and
gdbserver.

In gdbserver the class is empty.  The compatible information within
the gdbserver is an empty list, of empty classes.

In gdb the class contains a pointer to the bfd_arch_info object.

With this in place we can now add support to print_xml_feature for
printing the compatible information if it is present.  In the
gdbserver code this will never happen, as the gdbserver never has any
compatible information.  But in gdb, this code will trigger when
appropriate.

gdb/ChangeLog:

	* target-descriptions.c (class tdesc_compatible_info): New class.
	(struct target_desc): Change type of compatible vector.
	(tdesc_compatible_p): Update for change in type of
	target_desc::compatible.
	(tdesc_compatible_info_list): New function.
	(tdesc_compatible_info_arch_name): New function.
	(tdesc_add_compatible): Update for change in type of
	target_desc::compatible.
	(print_c_tdesc::visit_pre): Likewise.

gdbserver/ChangeLog:

	* tdesc.cc (struct tdesc_compatible_info): New struct.
	(tdesc_compatible_info_list): New function.
	(tdesc_compatible_info_arch_name): New function.

gdbsupport/ChangeLog:

	* tdesc.cc (print_xml_feature::visit_pre): Print compatible
	information.
	* tdesc.h (struct tdesc_compatible_info): Declare new struct.
	(tdesc_compatible_info_up): New typedef.
	(tdesc_compatible_info_list): Declare new function.
	(tdesc_compatible_info_arch_name): Declare new function.
2020-06-23 22:17:19 +01:00
Andrew Burgess
20821f4ed1 gdb: Allow target description to be dumped even when it is remote
The maintenance command 'maintenance print c-tdesc' can only print the
target description if it was loaded from a local file, or if the local
filename is passed to the maintenance command as an argument.

Sometimes it would be nice to know what target description GDB was
given by the remote, however, if I connect to a remote target and try
this command I see this:

  (gdb) maintenance print c-tdesc
  The current target description did not come from an XML file.
  (gdb)

Which is not very helpful.

This commit changes things so that if the description came from the
remote end then GDB will use a fake filename 'fetched from target' as
the filename for the description, GDB will then create the C
description of the target as though it came from this file.  Example
output would look like this (I snipped the feature creation from the
middle as that hasn't changed):

  (gdb) maintenance print c-tdesc
  /* THIS FILE IS GENERATED.  -*- buffer-read-only: t -*- vi:set ro:
    Original: fetched from target */

  #include "defs.h"
  #include "osabi.h"
  #include "target-descriptions.h"

  struct target_desc *tdesc_fetched_from_target;
  static void
  initialize_tdesc_fetched_from_target (void)
  {
    struct target_desc *result = allocate_target_description ();
    struct tdesc_feature *feature;

    /* ... features created here ... */

    tdesc_fetched_from_target = result;
  }
  (gdb)

In order to support using 'fetched from target' I had to update the
print_c_tdesc code to handle filenames that include a space.  This has
the benefit that we can now print out real files with spaces in the
name, for example the file 'with space.xml':

  (gdb) maint print c-tdesc with space.xml

I originally added this functionality so I could inspect the
description passed to GDB by the remote target.  After using this for
a while I realised that actually having GDB recreate the XML would be
even better, so a later commit will add that functionality too.

Still, given how small this patch is I thought it might be nice to
include this in GDB anyway.

While I was working on this anyway I've added filename command
completion to this command.

gdb/ChangeLog:

	* target-descriptions.c (print_c_tdesc::print_c_tdesc): Change
	whitespace to underscore.
	(maint_print_c_tdesc_cmd): Use fake filename for target
	descriptions that came from the target.
	(_initialize_target_descriptions): Add filename command completion
	for 'maint print c-tdesc'.
2020-06-23 22:17:18 +01:00
Simon Marchi
1fb5ee6203 gdb: add some more empty lines in loc.c
Add some empty lines at places I forgot in the previous patch.

gdb/ChangeLog:

	* dwarf2/loc.c (decode_debug_loclists_addresses): Add empty
	lines.

Change-Id: I8a9f3766ede1ce750e0703023285dca873bce0da
2020-06-23 15:40:24 -04:00
Simon Marchi
fc3ecb3e61 gdb: add empty lines in loc.c
I always found that some switch statements in this file were a bit too
packed.  I think having empty lines between each case helps with
reading.  I'm pushing this as obvious, I hope it won't be too
controversial.

gdb/ChangeLog:

	* dwarf2/loc.c (decode_debug_loc_dwo_addresses): Add empty
	lines.
	(dwarf2_find_location_expression): Likewise.
	(call_site_parameter_matches): Likewise.
	(dwarf2_compile_expr_to_ax): Likewise.
	(disassemble_dwarf_expression): Likewise.
	(loclist_describe_location): Likewise.

Change-Id: I381366a0468ff1793faa612c46ef48a9d4773192
2020-06-23 15:34:45 -04:00
Pedro Alves
236ef0346d Fix "maint selftest" regression, add struct scoped_mock_context
This commit:

 commit 3922b30264
 Author:     Pedro Alves <palves@redhat.com>
 AuthorDate: Thu Jun 18 21:28:37 2020 +0100

    Decouple inferior_ptid/inferior_thread(); dup ptids in thread list (PR 25412)

caused a regression for gdb.gdb/unittest.exp when GDB is configured
with --enable-targets=all.  The failure is:

  gdb/thread.c:95: internal-error: thread_info* inferior_thread(): Assertion `current_thread_ != nullptr' failed.

The problem is in this line in regcache.c:cooked_read_test:

  /* Switch to the mock thread.  */
  scoped_restore restore_inferior_ptid
    = make_scoped_restore (&inferior_ptid, mock_ptid);

Both gdbarch-selftest.c and regcache.c set up a similar mock context,
but the series the patch above belongs to only updated the
gdbarch-selftest.c context to not write to inferior_ptid directly, and
missed updating regcache.c's.

Instead of copying the fix over to regcache.c, share the mock context
setup code in a new RAII class, based on gdbarch-selftest.c's version.

Also remove the "target already pushed" error from regcache.c, like it
had been removed from gdbarch-selftest.c in the multi-target series.
That check is unnecessary because each inferior now has its own target
stack, and the unit test pushes a target on a separate (mock)
inferior, not the current inferior on entry.

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

	* gdbarch-selftests.c: Don't include inferior.h, gdbthread.h or
	progspace-and-thread.h.  Include scoped-mock-context.h instead.
	(register_to_value_test): Use scoped_mock_context.
	* regcache.c: Include "scoped-mock-context.h".
	(cooked_read_test): Don't error out if a target is already pushed.
	Use scoped_mock_context.  Adjust.
	* scoped-mock-context.h: New file.
2020-06-23 18:57:03 +01:00
Sandra Loosemore
bb8d126033 Adjust command completion output when TUI is disabled
The history-scrolling commands "+", "-", "<" and ">" are only known to
GDB when TUI is enabled.  This means the "complete pipe " command
produces different output depending on whether TUI is present, which
in turn caused

FAIL: gdb.base/shell.exp: cmd complete "pipe "

This patch provides different patterns for that test depending on
whether or not TUI is available.

2020-06-23  Sandra Loosemore  <sandra@codesourcery.com>

	gdb/testsuite/
	* lib/completion-support.exp (test_gdb_completion_offers_commands):
	Adjust for omitted commands when TUI is disabled.
2020-06-23 09:33:31 -07:00
Gary Benson
7e4b9c4cd3 Improve -Wunused-value testcase build failures fix
This commit improves upon my previous -Wunused-value fix by
replacing the various dummy variables with casts to void, as
suggested by Pedro.

gdb/testsuite/ChangeLog:

	* gdb.cp/namespace.cc: Improve -Wunused-value fix.
	* gdb.cp/nsimport.cc: Likewise.
	* gdb.cp/nsnested.cc: Likewise.
	* gdb.cp/nsnoimports.cc: Likewise.
	* gdb.cp/nsusing.cc: Likewise.
	* gdb.cp/smartp.cc: Likewise.
	* gdb.python/py-pp-integral.c: Likewise.
	* gdb.python/py-pp-re-notag.c: Likewise.
2020-06-23 15:11:27 +01:00
Andrew Burgess
39e7eccae6 gdb: Convert language la_is_string_type_p field to a method
This commit changes the language_data::la_is_string_type_p function
pointer member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (ada_language_data): Delete la_is_string_type_p
	initializer.
	(ada_language::is_string_type_p): New member function.
	* c-lang.c (c_language_data): Delete la_is_string_type_p
	initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	* f-lang.c (f_is_string_type_p): Delete function, implementation
	moved to f_language::is_string_type_p.
	(f_language_data): Delete la_is_string_type_p initializer.
	(f_language::is_string_type_p): New member function,
	implementation from f_is_string_type_p.
	* go-lang.c (go_is_string_type_p): Delete function, implementation
	moved to go_language::is_string_type_p.
	(go_language_data): Delete la_is_string_type_p initializer.
	(go_language::is_string_type_p): New member function,
	implementation from go_is_string_type_p.
	* language.c (language_defn::is_string_type_p): Define new member
	function.
	(default_is_string_type_p): Make static, add comment copied from
	header file.
	(unknown_language_data): Delete la_is_string_type_p initializer.
	(unknown_language::is_string_type_p): New member function.
	(auto_language_data): Delete la_is_string_type_p initializer.
	(auto_language::is_string_type_p): New member function.
	* language.h (language_data): Delete la_is_string_type_p field.
	(language_defn::is_string_type_p): Declare new function.
	(default_is_string_type_p): Delete desclaration, move comment to
	definition.
	* m2-lang.c (m2_is_string_type_p): Delete function, implementation
	moved to m2_language::is_string_type_p.
	(m2_language_data): Delete la_is_string_type_p initializer.
	(m2_language::is_string_type_p): New member function,
	implementation from m2_is_string_type_p.
	* objc-lang.c (objc_language_data): Delete la_is_string_type_p
	initializer.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_is_string_type_p): Delete function,
	implementation moved to pascal_language::is_string_type_p.
	(pascal_language_data): Delete la_is_string_type_p initializer.
	(pascal_language::is_string_type_p): New member function,
	implementation from pascal_is_string_type_p.
	* rust-lang.c (rust_is_string_type_p): Delete function,
	implementation moved to rust_language::is_string_type_p.
	(rust_language_data): Delete la_is_string_type_p initializer.
	(rust_language::is_string_type_p): New member function,
	implementation from rust_is_string_type_p.
	* valprint.c (val_print_scalar_or_string_type_p): Update call to
	is_string_type_p.
2020-06-23 13:34:11 +01:00
Andrew Burgess
4ffc13fb0e gdb: Convert language la_print_typedef field to a method
This commit changes the language_data::la_print_typedef function
pointer member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (ada_language_data): Delete la_print_typedef
	initializer.
	(ada_language::print_typedef): New member function.
	* c-lang.c (c_language_data): Delete la_print_typedef initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	* f-lang.c (f_language_data): Likewise.
	(f_language::print_typedef): New member function.
	* go-lang.c (go_language_data): Delete la_print_typedef
	initializer.
	* language.c (language_defn::print_typedef): Define member
	function.
	(unknown_language_data): Delete la_print_typedef initializer.
	(unknown_language::print_typedef): New member function.
	(auto_language_data): Delete la_print_typedef initializer.
	(auto_language::print_typedef): New member function.
	* language.h (language_data): Delete la_print_typedef field.
	(language_defn::print_typedef): Declare new member function.
	(LA_PRINT_TYPEDEF): Update call to print_typedef.
	(default_print_typedef): Delete declaration.
	* m2-lang.c (m2_language_data): Delete la_print_typedef
	initializer.
	(m2_language::print_typedef): New member function.
	* objc-lang.c (objc_language_data): Delete la_print_typedef
	initializer.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_language_data): Likewise.
	(pascal_language::print_typedef): New member function.
	* rust-lang.c (rust_print_typedef): Delete function,
	implementation moved to rust_language::print_typedef.
	(rust_language): Delete la_print_typedef initializer.
	(rust_language::print_typedef): New member function,
	implementation from rust_print_typedef.
	* typeprint.c (default_print_typedef): Delete.
2020-06-23 13:34:11 +01:00
Andrew Burgess
d711ee67ac gdb: Convert language la_printstr field to a method
This commit changes the language_data::la_printstr function pointer
member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (ada_language_data): Delete la_printstr initializer.
	(ada_language::printstr): New member function.
	* c-lang.c (c_language_data): Delete la_printstr initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	* f-lang.c (f_printstr): Rename to f_language::printstr.
	(f_language_data): Delete la_printstr initializer.
	(f_language::printstr): New member function, implementation from
	f_printstr.
	* go-lang.c (go_language_data): Delete la_printstr initializer.
	* language.c (language_defn::printstr): Define new member
	function.
	(unk_lang_printstr): Delete.
	(unknown_language_data): Delete la_printstr initializer.
	(unknown_language::printstr): New member function.
	(auto_language_data): Delete la_printstr initializer.
	(auto_language::printstr): New member function.
	* language.h (language_data): Delete la_printstr field.
	(language_defn::printstr): Declare new member function.
	(LA_PRINT_STRING): Update call to printstr.
	* m2-lang.c (m2_printstr): Rename to m2_language::printstr.
	(m2_language_data): Delete la_printstr initializer.
	(m2_language::printstr): New member function, implementation from
	m2_printstr.
	* objc-lang.c (objc_language_data): Delete la_printstr
	initializer.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_printstr): Rename to pascal_language::printstr.
	(pascal_language_data): Delete la_printstr initializer.
	(pascal_language::printstr): New member function, implementation
	from pascal_printstr.
	* p-lang.h (pascal_printstr): Delete declaration.
	* rust-lang.c (rust_printstr): Update header comment.
	(rust_language_data): Delete la_printstr initializer.
	(rust_language::printstr): New member function.
2020-06-23 13:34:11 +01:00
Andrew Burgess
52b50f2c1b gdb: Convert language la_printchar field to a method
This commit changes the language_data::la_printchar function pointer
member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (ada_language_data): Delete la_printchar initializer.
	(ada_language::printchar): New member function.
	* c-lang.c (c_language_data): Delete la_printchar initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	* f-lang.c (f_printchar): Rename to f_language::printchar.
	(f_language_data): Delete la_printchar initializer.
	(f_language::printchar): New member function, implementation from
	f_printchar.
	* go-lang.c (go_language_data): Delete la_printchar initializer.
	* language.c (unk_lang_printchar): Delete.
	(language_defn::printchar): Define new member function.
	(unknown_language_data): Delete la_printchar initializer.
	(unknown_language::printchar): New member function.
	(auto_language_data): Delete la_printchar initializer.
	(auto_language::printchar): New member function.
	* language.h (language_data): Delete la_printchar field.
	(language_defn::printchar): Declare new member function.
	(LA_PRINT_CHAR): Update call to printchar.
	* m2-lang.c (m2_language_data): Delete la_printchar initializer.
	(m2_language::printchar): New member function.
	* objc-lang.c (objc_language_data): Delete la_printchar
	initializer.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_language_data): Delete la_printchar
	initializer.
	(pascal_language::printchar): New member function.
	* rust-lang.c (rust_printchar): Rename to
	rust_language::printchar.
	(rust_language_data): Delete la_printchar initializer.
	(rust_language::printchar): New member function, implementation
	from rust_printchar.
2020-06-23 13:34:11 +01:00
Andrew Burgess
ec8cec5b96 gdb: Convert language la_emitchar field to a method
This commit changes the language_data::la_emitchar function pointer
member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (emit_char): Renamed to ada_language::emitchar.
	(ada_language_data): Delete la_emitchar initializer.
	(ada_language::emitchar): New member function, implementation from
	emit_char.
	* c-lang.c (c_language_data): Delete la_emitchar initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	* f-lang.c (f_emit_char): Rename to f_language::emitchar.
	(f_language_data): Delete la_emitchar initializer.
	(f_language::emitchar): New member function, implementation from
	f_emit_char.
	* go-lang.c (go_language_data): Delete la_emitchar initializer.
	* language.c (unk_lang_emit_char): Delete.
	(language_defn::emitchar): New member function definition.
	(unknown_language_data): Delete la_emitchar initializer.
	(unknown_language::emitchar): New member function.
	(auto_language_data): Delete la_emitchar initializer.
	(auto_language::emitchar): New member function.
	* language.h (language_data): Delete la_emitchar field.
	(language_defn::emitchar): New member field declaration.
	(LA_EMIT_CHAR): Update call to emitchar.
	* m2-lang.c (m2_emit_char): Rename to m2_language::emitchar.
	(m2_language_data): Delete la_emitchar initializer.
	(m2_language::emitchar): New member function, implementation from
	m2_emit_char.
	* objc-lang.c (objc_language_data): Delete la_emitchar
	initializer.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_emit_char): Rename to pascal_language::emitchar.
	(pascal_language_data): Delete la_emitchar initializer.
	(pascal_language::emitchar): New member function, implementation
	from pascal_emit_char.
	* rust-lang.c (rust_emitchar): Rename to rust_language::emitchar.
	(rust_language_data): Delete la_emitchar initializer.
	(rust_language::emitchar): New member function, implementation
	from rust_emitchar.
2020-06-23 13:34:11 +01:00
Andrew Burgess
1bf9c36374 gdb: Convert language la_post_parser field to a method
This commit changes the language_data::la_post_parser function pointer
member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (resolve): Rename to ada_language::post_parser.
	(ada_language_data): Delete la_post_parser initializer.
	(ada_language::post_parser): New member function.
	* c-lang.c (c_language_data): Delete la_post_parser initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	* f-lang.c (f_language_data): Likewise.
	* go-lang.c (go_language_data): Likewise.
	* language.c (unknown_language_data): Likewise.
	(auto_language_data): Likewise.
	* language.h (language_data): Delete la_post_parser field.
	(language_defn::post_parser): New member function.
	* m2-lang.c (m2_language_data): Delete la_post_parser initializer.
	* objc-lang.c (objc_language_data): Likewise.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_language_data): Likewise.
	* parse.c (parse_exp_in_context): Update call to post_parser.
	(null_post_parser): Delete definition.
	* parser-defs.h (null_post_parser): Delete declaration.
	* rust-lang.c (rust_language_data): Delete la_post_parser
	initializer.
2020-06-23 13:34:11 +01:00
Andrew Burgess
87afa6523b gdb: Convert language la_parser field to a method
This commit changes the language_data::la_parser function pointer
member variable into a member function of language_defn.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* ada-lang.c (parse): Rename to ada_language::parser.
	(ada_language_data): Delete la_parser initializer.
	(ada_language::parser): New member function, implementation from
	parse.
	* c-lang.c (c_language_data): Delete la_parser initializer.
	(cplus_language_data): Likewise.
	(asm_language_data): Likewise.
	(minimal_language_data): Likewise.
	* d-lang.c (d_language_data): Likewise.
	(d_language::parser): New member function.
	* f-lang.c (f_language_data): Delete la_parser initializer.
	(f_language::parser): New member function.
	* go-lang.c (go_language_data): Delete la_parser initializer.
	(go_language::parser): New member function.
	* language.c (unk_lang_parser): Delete.
	(language_defn::parser): Define new member function.
	(unknown_language_data): Delete la_parser initializer.
	(unknown_language::parser): New member function.
	(auto_language_data): Delete la_parser initializer.
	(auto_language::parser): New member function.
	* language.h (language_data): Delete la_parser field.
	(language_defn::parser): Declare new member function.
	* m2-lang.c (m2_language_data): Delete la_parser initializer.
	(m2_language::parser): New member function.
	* objc-lang.c (objc_language_data): Delete la_parser initializer.
	* opencl-lang.c (opencl_language_data): Likewise.
	* p-lang.c (pascal_language_data): Likewise.
	(pascal_language::parser): New member function.
	* parse.c (parse_exp_in_context): Update call to parser.
	* rust-lang.c (rust_language_data): Delete la_parser initializer.
	(rust_language::parser): New member function.
2020-06-23 13:34:10 +01:00
Gary Benson
2e573c0a3f Avoid testcase build failures with -Wunused-value
A number of testcases fail to build with -Wunused-value enabled.
This commit adds dummy values to avoid this.

gdb/testsuite/ChangeLog:

	* gdb.cp/namespace.cc: Avoid build failure with -Wunused-value.
	* gdb.cp/nsimport.cc: Likewise.
	* gdb.cp/nsnested.cc: Likewise.
	* gdb.cp/nsnoimports.cc: Likewise.
	* gdb.cp/nsusing.cc: Likewise.
	* gdb.cp/smartp.cc: Likewise.
	* gdb.python/py-pp-integral.c: Likewise.
	* gdb.python/py-pp-re-notag.c: Likewise.
2020-06-23 12:25:34 +01:00
Andrew Burgess
378258006c gdb: Add --with-python-libdir to gdb's --configuration output
Commit:

  commit d13c7322fe
  Date:   Fri Jan 17 00:10:22 2020 +0000

      gdb: Allow more control over where to find python libraries

Added a new configuration option --with-python-libdir, but failed to
add this option to the output of 'gdb --configuration'.  This commit
fixes this mistake.

gdb/ChangeLog:

	* top.c (print_gdb_configuration): Print --with-python-libdir
	configuration value.
2020-06-23 10:06:20 +01:00
Philippe Waroquiers
5b860c93e3 NEWS and documentation for alias default-args related concept and commands.
gdb/ChangeLog
2020-06-22  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* NEWS: Mention change to the alias command.

gdb/doc/ChangeLog
2020-06-22  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.texinfo (Command aliases default args): New node documenting
	how to use default args for a command using aliases.
	(Aliases): Document the new 'DEFAULT-ARGS...' option.
	(Help): Update help aliases text and describe when full alias
	definition is provided.
2020-06-22 21:16:25 +02:00
Philippe Waroquiers
746ebfe8dd Add tests for new alias default-args related commands and arguments.
Test the new default-args behaviour and completion for the alias command.
Note that gdb.base/default-args.exp is somewhat copied from
with.exp (the test of the with command), while default-exp.c
is a plain copy of with.c.

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

	* gdb.base/default-args.exp: New test.
	* gdb.base/default-args.c: New file.
	* gdb.base/alias.exp: Update expected error msg for alias foo=bar.
	* gdb.base/default.exp: Update to new help text.
	* gdb.base/help.exp: Likewise.
	* gdb.base/page.exp: Likewise.
	* gdb.base/style.exp: Likewise.
	* gdb.guile/guile.exp: Likewise.
	* gdb.python/python.exp: Likewise.
2020-06-22 21:15:14 +02:00
Philippe Waroquiers
cf00cd6faf default-args: allow to define default arguments for aliases
Currently, a user can define an alias, but cannot have default
arguments for this alias.

This patch modifies the 'alias' command so that default args can
be provided.
    (gdb) h alias
    Define a new command that is an alias of an existing command.
    Usage: alias [-a] [--] ALIAS = COMMAND [DEFAULT-ARGS...]
    ALIAS is the name of the alias command to create.
    COMMAND is the command being aliased to.

    Options:
      -a
        Specify that ALIAS is an abbreviation of COMMAND.
        Abbreviations are not used in command completion..

    GDB will automatically prepend the provided DEFAULT-ARGS to the list
    of arguments explicitly provided when using ALIAS.
    Use "help aliases" to list all user defined aliases and their default args.

    Examples:
    Make "spe" an alias of "set print elements":
      alias spe set print elements
    Make "elms" an alias of "elements" in the "set print" command:
      alias -a set print elms set print elements
    Make "btf" an alias of "backtrace -full -past-entry -past-main" :
      alias btf = backtrace -full -past-entry -past-main
    Make "wLapPeu" an alias of 2 nested "with":
      alias wLapPeu = with language pascal -- with print elements unlimited --
    (gdb)

The way 'default-args' is implemented makes it trivial to set default
args also for GDB commands (such as "backtrace") and for GDB pre-defined
aliases (such as "bt").  It was however deemed better to not allow to
define default arguments for pre-defined commands and aliases, to avoid
users believing that e.g. default args for "backtrace" would apply to "bt".

If needed, default-args could be allowed for GDB predefined commands
and aliases by adding a command
'set default-args GDB_COMMAND_OR_PREDEFINED_ALIAS [DEFAULT-ARGS...]'.

* 'alias' command now has a completer that helps to complete:
     - ALIAS (if the user defines an alias after a prefix),
     - the aliased COMMAND
     - the possible options for the aliased COMMAND.

* Help and apropos commands show the definitions of the aliases
  that have default arguments, e.g.
        (gdb) help backtrace
        backtrace, btf, where, bt
          alias btf = backtrace -full -past-entry -past-main
        Print backtrace of all stack frames, or innermost COUNT frames.
        Usage: backtrace [OPTION]... [QUALIFIER]... [COUNT | -COUNT]

        Options:
          -entry-values no|only|preferred|if-needed|both|compact|default
            Set printing of function arguments at function entry.
        ...

gdb/ChangeLog
2020-06-22  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-cmds.c (lookup_cmd_for_default_args)
	(alias_command_completer)
	(make_alias_options_def_group): New functions.
	(alias_opts, alias_option_defs): New struct and array.
	(alias_usage_error): Update usage.
	(alias_command): Handles optional DEFAULT-ARGS... arguments.
	Use option framework.
	(_initialize_cli_cmds): Update alias command help.
	Update aliases command help.
	(show_user):
	Add NULL for new default_args lookup_cmd argument.
	(valid_command_p): Rename to validate_aliased_command.
	Add NULL for new default_args lookup_cmd argument.  Verify that the
	aliased_command has no default args.
	* cli/cli-decode.c (help_cmd): Show aliases definitions.
	(lookup_cmd_1, lookup_cmd): New argument default_args.
	(add_alias_cmd):
	Add NULL for new default_args lookup_cmd argument.
	(print_help_for_command): Show default args under the layout
	 alias some_alias = some_aliased_cmd some_alias_default_arg.
	* cli/cli-decode.h (struct cmd_list_element): New member default_args.
	xfree default_args in destructor.
	* cli/cli-script.c (process_next_line, do_define_command):
	Add NULL for new default_args lookup_cmd argument.
	* command.h: Declare new default_args argument in lookup_cmd
	and lookup_cmd_1.
	* completer.c (complete_line_internal_1):
	Add NULL for new default_args lookup_cmd or lookup_cmd_1 argument.
	* guile/scm-cmd.c (gdbscm_parse_command_name): Likewise.
	* guile/scm-param.c (add_setshow_generic, pascm_parameter_defined_p):
	Likewise.
	* infcmd.c (_initialize_infcmd): Likewise.
	* python/py-auto-load.c (gdbpy_initialize_auto_load): Likewise.
	* python/py-cmd.c (gdbpy_parse_command_name): Likewise.
	* python/py-param.c (add_setshow_generic): Likewise.
	* remote.c (_initialize_remote): Likewise.
	* top.c (execute_command): Prepend default_args if command has some.
	(set_verbose):
	Add NULL for new default_args lookup_cmd or lookup_cmd_1 argument.
	* tracepoint.c (validate_actionline, encode_actions_1):
	Add NULL for new default_args lookup_cmd or lookup_cmd_1 argument.
2020-06-22 21:14:13 +02:00
Sandra Loosemore
e822f2cda9 Disable parts of gdb.base/source-dir.exp on remote host
One set of tests in this file does a lot of complicated directory
manipulations to force a specific DW_AT_comp_dir format and gdb
directory search path.  As it's written, everything assumes host ==
build, and it does not seem to me that there is any obvious way to
rewrite this so it will work in general on remote host.  For instance,
our harness for testing on remote Windows host normally does all
compilation and GDB execution in $cwd using relative pathnames and I'm
not sure all these directory tricks would set up the scenario it's
trying to test even if they were correctly performed on host rather
than build.  So I think it's reasonable just to disable this on remote
host instead.

I also noted that it's using the wrong search path syntax for Windows
host in the "set directories" command and conditionalized that while I
was looking at it.  That's a necessary fix to make this work in a
situation where host == build and it's Windows, but I'm not actually
set up to test that it's sufficient, too.

2020-06-22  Sandra Loosemore  <sandra@codesourcery.com>

	gdb/testsuite/
	* gdb.base/source-dir.exp (test_truncated_comp_dir): Skip on
	remote host.  Fix search path syntax on Windows host.
2020-06-22 10:10:02 -07:00
Tankut Baris Aktemur
bd920864f3 gdb/jit: return bool in jit_breakpoint_re_set_internal and jit_read_descriptor
This is a minor refactoring that converts the return type of
jit_read_descriptor and jit_breakpoint_re_set_internal functions
from 'int' to 'bool'.

The return value logic of jit_breakpoint_re_set_internal has been
reversed.  With this patch it now returns true if the jit breakpoint
has been successfully initialized.

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

	* jit.c (jit_read_descriptor): Use bool as the return type.
	(jit_breakpoint_re_set_internal): Use bool as the return type.
	Invert the return value logic; return true if the jit breakpoint
	has been successfully initialized.
	(jit_inferior_init): Update the call to
	jit_breakpoint_re_set_internal.
2020-06-22 14:03:33 +02:00
Pedro Alves
f809832224 Solaris, target_wait(), don't rely on inferior_ptid
Debugging on Solaris is broken, with the procfs target backend failing
with:

 procfs: couldn't find pid 0 in procinfo list.

as soon as you start a program.

The problem is procfs_target::wait assuming that inferior_ptid is
meaningful on entry, but, since the multi-target series, inferior_ptid
is null_ptid before we call target_wait, in infrun.c:

  static ptid_t
  do_target_wait_1 (inferior *inf, ptid_t ptid,
		    target_waitstatus *status, int options)
  {
...
    /* We know that we are looking for an event in the target of inferior
       INF, but we don't know which thread the event might come from.  As
       such we want to make sure that INFERIOR_PTID is reset so that none of
       the wait code relies on it - doing so is always a mistake.  */
    switch_to_inferior_no_thread (inf);

This patch tweaks the backend to remove the assumption that
inferior_ptid points at something.  sol-thread.c (the thread_stratum
that sits on top of procfs.c) also has the same issue.

Some spots in procfs_target::wait were returning
TARGET_WAITKIND_SPURIOUS+inferior_ptid.  This commit replaces those
with waiting again without returning to the core.  This fixes the
relying on inferior_ptid, and also should fix the issue discussed
here:
  https://sourceware.org/pipermail/gdb/2020-May/048616.html
  https://sourceware.org/pipermail/gdb/2020-June/048660.html

gdb/ChangeLog:
2020-06-22  Pedro Alves  <palves@redhat.com>

	PR gdb/25939
	* procfs.c (procfs_target::wait): Don't reference inferior_ptid.
	Use the current inferior instead.  Don't return
	TARGET_WAITKIND_SPURIOUS/inferior_ptid -- instead continue and
	wait again.
	* sol-thread.c (sol_thread_target::wait): Don't reference
	inferior_ptid.
	(ps_lgetregs, ps_lsetregs, ps_lgetfpregs, ps_lsetfpregs)
	(sol_update_thread_list_callback): Use the current inferior's pid
	instead of inferior_ptid.
2020-06-22 11:10:49 +01:00
Rainer Orth
196535a69c Various procfs.c cleanups
While reading through procfs.c, I noticed a couple of cleanup
opportunities:

* Some comments and code allowed for portability across different
  targets.  Since procfs.c is Solaris-only for some time now, those can
  go.

* Likewise, there were some references to the old ioctl-based /proc left.

* The code still allowed for SYS_exec.  However, it is no longer present
  in either Solaris 11.3, 11.4, or Illumos.  Checking the OpenSolaris
  sources, I found that it had already been removed in 2010 well before
  the Solaris 11 release.

* Some blocks of #if 0 code can go:

** References to struct procinfo.{g,fp}regs_dirty which are no longer
   defined.

** Code handling the PR_ASLWP flag where <sys/procfs.h> has

#define	PR_ASLWP   0x00000040	/* obsolete flag; never set */

Tested on amd64-pc-solaris2.11.

	* procfs.c: Cleanup many comments.

	(READ_WATCHFLAG, WRITE_WATCHFLAG, EXEC_WATCHFLAG)
	(AFTER_WATCHFLAG): Replace by value.

	(MAIN_PROC_NAME_FORMAT): Inline ...
	(create_procinfo): ... here.

	(procfs_debug_inferior): Remove SYS_exec handling.
	(syscall_is_exec): Likewise.
	(procfs_set_exec_trap): Likewise.

	(syscall_is_lwp_exit): Inline in callers.
	(syscall_is_exit): Likewise.
	(syscall_is_exec): Likewise.
	(syscall_is_lwp_create): Likewise.

	(invalidate_cache): Remove #if 0 code.

	(make_signal_thread_runnable):  Remove.
	(procfs_target::resume): Remove #if 0 code.
2020-06-21 18:51:58 +02:00
Rainer Orth
cf6f3e86de [PR gdb/25939] Move push_target call earlier in procfs.c
Since the multi-target patch, the run command fails on Solaris with an
assertion failure even for a trivial program:

$ ./gdb -D ./data-directory ./hello
GNU gdb (GDB) 10.0.50.20200106-git
[...]
Reading symbols from ./hello...
(gdb) run
Starting program: /vol/obj/gnu/gdb/gdb/reghunt/no-resync/122448/gdb/hello
/vol/src/gnu/gdb/hg/master/reghunt/gdb/thread.c:336: internal-error:
thread_info::thread_info(inferior*, ptid_t): Assertion `inf_ != NULL'
failed.

Here's the start of the corresponding stack trace:

#0  internal_error (
    file=file@entry=0x966150
"/vol/src/gnu/gdb/hg/master/reghunt/gdb/thread.c", line=line@entry=336,
fmt=0x9ddb94 "%s: Assertion `%s' failed.")
    at /vol/src/gnu/gdb/hg/master/reghunt/gdb/gdbsupport/errors.c:51
#1  0x0000000000ef81f4 in thread_info::thread_info (this=0x1212020,
    inf_=<optimized out>, ptid_=...)
    at /vol/src/gnu/gdb/hg/master/reghunt/gdb/thread.c:344
#2  0x0000000000ef82cd in new_thread (inf=inf@entry=0x0, ptid=...)
    at /vol/src/gnu/gdb/hg/master/reghunt/gdb/thread.c:239
#3  0x0000000000efac3c in add_thread_silent (
    targ=targ@entry=0x11b0940 <the_procfs_target>, ptid=...)
    at /vol/src/gnu/gdb/hg/master/reghunt/gdb/thread.c:304
#4  0x0000000000d90692 in procfs_target::create_inferior (
    this=0x11b0940 <the_procfs_target>,
    exec_file=0x13dbef0
"/vol/obj/gnu/gdb/gdb/reghunt/no-resync/122448/gdb/hello", allargs="",
env=0x13c48f0, from_tty=<optimized out>)
    at /vol/src/gnu/gdb/hg/master/reghunt/gdb/gdbsupport/ptid.h:47
#5  0x0000000000c84e64 in run_command_1 (args=<optimized out>, from_tty=1,
    run_how=run_how@entry=RUN_NORMAL)
    at /vol/gcc-9/include/c++/9.1.0/bits/basic_string.h:263
#6  0x0000000000c85007 in run_command (args=<optimized out>,
    from_tty=<optimized out>)
    at /vol/src/gnu/gdb/hg/master/reghunt/gdb/infcmd.c:687

Looking closer, I found that in add_thread_silent as called from
procfs.c (procfs_target::create_inferior) find_inferior_ptid returns
NULL.  The all_inferiors (targ) iterator comes up empty.

Going from there, I see that in add_thread_silent

m_target_stack = {m_top = file_stratum, m_stack = {0x20190e0
<the_dummy_target>, 0x200b8c0 <exec_ops>, 0x0, 0x0, 0x0, 0x0, 0x0}}}

i.e. the_procfs_target is missing compared to the_amd64_linux_nat_target
on Linux/x86_64.

Moving the push_target call earlier allows debugging to get over the
initial assertion failure.  I run instead into

procfs: couldn't find pid 0 in procinfo list.

which is fixed by

	https://sourceware.org/pipermail/gdb-patches/2020-June/169674.html

Both patches tested together on amd64-pc-solaris2.11.

	PR gdb/25939
	* procfs.c (procfs_target::procfs_init_inferior): Move push_target
	call ...
	(procfs_target::create_inferior): ... here.
2020-06-21 18:32:27 +02:00
Philippe Waroquiers
48e9cc8405 Ensure 'exec-file has changed' check has priority over 'exec-file-mismatch' check
Following the implementation of exec-file-mismatch based on build-id,
an attach to a process that runs a modified exec-file was triggering
the exec-file-mismatch handling, giving a warning such as:
  warning: Mismatch between current exec-file /bd/home/philippe/gdb/git/build_termours/gdb/testsuite/outputs/gdb.base/attach/attach
  and automatically determined exec-file /bd/home/philippe/gdb/git/build_termours/gdb/testsuite/outputs/gdb.base/attach/attach
  exec-file-mismatch handling is currently "ask"
as the build-ids differ when an exec-file is recompiled.

This patch ensures that the exec-file-mismatch check is done with an up to date
build-id.  With this, exec-file-mismatch check will only trigger when the
PID file really differs from the (build-id refreshed) current exec-file.
Note that the additional check does not (yet) reload the symbols if
the exec-file is changed: this reload will happen later if needed.

gdb/ChangeLog
2020-06-21  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* exec.c (validate_exec_file): Ensure the build-id is up to
	date by calling reopen_exec_file (that checks file timestamp
	to decide to re-read the file).

gdb/testsuite/ChangeLog

2020-06-21  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/attach.exp: Test priority of 'exec-file' changed
	over 'exec-file-mismatch'.
	* gdb.base/attach.c: Mark should_exit volatile.
	* gdb.base/attach2.c: Likewise.  Add a comment explaining
	why the sleep cannot be big.
	* gdb.base/attach3.c: New file.
2020-06-21 12:48:18 +02:00
Sandra Loosemore
160f8a8f32 Adjust gdb.mi/mi-sym-info.exp filename patterns.
2020-06-20  Sandra Loosemore  <sandra@codesourcery.com>

	* gdb.mi/mi-sym-info.exp: Adjust filename patterns to make directory
	prefix optional.
2020-06-20 19:37:49 -07:00
Sandra Loosemore
4d91c2a467 Fix gdb.base/list-missing-source.exp on remote host.
2020-06-20  Sandra Loosemore  <sandra@codesourcery.com>

	gdb/testsuite/
	* gdb.base/list-missing-source.exp: Correct $srcfile manipulation
	for remote host.
2020-06-20 17:23:53 -07:00
Sandra Loosemore
87f83f2002 Fixes for gdb.xml/tdesc-regs.exp.
2020-06-19  Sandra Loosemore  <sandra@codesourcery.com>
	    Hafiz Abid Qadeer  <abidh@codesourcery.com>

	* gdb.xml/tdesc-regs.exp (load_description): Correct pathname of
	file sent to remote host.
	(top level): Allow int32_t as type of 32-bit register.
2020-06-19 09:15:38 -07:00
Tom de Vries
37ab86550b [gdb/testsuite] Limit default_target_compile override
The file lib/future.exp contains an override of dejagnu's
default_target_compile.

The override is activated if dejagnu's default_target_compile is missing
support for one or more languages.

However, if the override is activated, it's active for all languages.

This unnecessarily extends the scope of potential problems in the override to
languages that don't need the override.

Fix this by limiting the scope of the override.

Also add a note stating for which languages the override is active, as a
reminder that support for those languages needs to be ported to dejagnu.  With
my system dejagnu 1.6.1, as well as with current dejagnu trunk, that gives us:
...
NOTE: Dejagnu's default_target_compile is missing support for Go, using \
  local override
NOTE: Dejagnu's default_target_compile is missing support for Rust, using \
  local override
...

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

2020-06-19  Tom de Vries  <tdevries@suse.de>

	* lib/gdb.exp (gdb_note): New proc.
	* lib/future.exp (gdb_default_target_compile_1): Factor out of ...
	(gdb_default_target_compile): ... here.  Only call
	gdb_default_target_compile_1 if use_gdb_compile(<lang>) is set.
	(use_gdb_compile): Change to array.
	(toplevel): Update sets of use_gdb_compile to specify language.
	Warn about default_target_compile override.  Store dejagnu's version
	of default_target_compile in dejagnu_default_target_compile.
2020-06-19 17:55:52 +02:00
Pedro Alves
3922b30264 Decouple inferior_ptid/inferior_thread(); dup ptids in thread list (PR 25412)
In PR 25412, Simon noticed that after the multi-target series, the
tid-reuse.exp testcase manages to create a duplicate thread in the
thread list.  Or rather, two threads with the same PTID.

add_thread_silent has code in place to detect the case of a new thread
reusing some older thread's ptid, but it doesn't work correctly
anymore when the old thread is NOT the current thread and it has a
refcount higher than 0.  Either condition prevents a thread from being
deleted, but the refcount case wasn't being considered.  I think the
reason that case wasn't considered is that that code predates
thread_info refcounting.  Back when it was originally written,
delete_thread always deleted the thread.

That add_thread_silent code in question has some now-unnecessary
warts, BTW.  For instance, this:

  /* Make switch_to_thread not read from the thread.  */
  new_thr->state = THREAD_EXITED;

... used to be required because switch_to_thread would update
'stop_pc' otherwise.  I.e., it would read registers from an exited
thread otherwise.  switch_to_thread no longer reads the stop_pc, since:

  commit f2ffa92bbc
  Author:     Pedro Alves <palves@redhat.com>
  AuthorDate: Thu Jun 28 20:18:24 2018 +0100

      gdb: Eliminate the 'stop_pc' global

Also, if the ptid of the now-gone current thread is reused, we
currently return from add_thread_silent with the current thread
pointing at the _new_ thread.  Either pointing at the old thread, or
at no thread selected would be reasonable.  But pointing at an
unrelated thread (the new thread that happens to reuse the ptid) is
just broken.  Seems like I was the one who wrote it like that but I
have no clue why, FWIW.

Currently, an exited thread kept in the thread list still holds its
original ptid.  The idea was that we need the ptid to be able to
temporarily switch to another thread and then switch back to the
original thread, because thread switching is really inferior_ptid
switching.  Switching back to the original thread requires a ptid
lookup.

Now, in order to avoid exited threads with the same ptid as a live
thread in the same thread list, one thing I considered (and tried) was
to change an exited thread's ptid to minus_one_ptid.  However, with
that, there's a case that we won't handle well, which is if we end up
with more than one exited thread in the list, since then all exited
threads will all have the same ptid.  Since inferior_thread() relies
on inferior_ptid, may well return the wrong thread.

My next attempt to address this, was to switch an exited thread's ptid
to a globally unique "exited" ptid, which is a ptid with pid == -1 and
tid == 'the thread's global GDB thread number'.  Note that GDB assumes
that the GDB global thread number is monotonically increasing and
doesn't wrap around.  (We should probably make GDB thread numbers
64-bit to prevent that happening in practice; they're currently signed
32-bit.)  This attempt went a long way, but still ran into a number of
issues.  It was a major hack too, obviously.

My next attempt is the one that I'm proposing, which is to bite the
bullet and break the connection between inferior_ptid and
inferior_thread(), aka the current thread.  I.e., make the current
thread be a global thread_info pointer that is written to directly by
switch_to_thread, etc., and making inferior_thread() return that
pointer, instead of having inferior_thread() lookup up the
inferior_ptid thread, by ptid_t.  You can look at this as a
continuation of the effort of using more thread_info pointers instead
of ptids when possible.

By making the current thread a global thread_info pointer, we can make
switch_to_thread simply write to the global thread pointer, which
makes scoped_restore_current_thread able to restore back to an exited
thread without relying on unrelyable ptid look ups.  I.e., this makes
it not a real problem to have more than one thread with the same ptid
in the thread list.  There will always be only one live thread with a
given ptid, so code that looks up a live thread by ptid will always be
able to find the right one.

This change required auditing the whole codebase for places where we
were writing to inferior_ptid directly to change the current thread,
and change them to use switch_to_thread instead or one of its
siblings, because otherwise inferior_thread() would return a thread
unrelated to the changed-to inferior_ptid.  That was all (hopefully)
done in previous patches.

After this, inferior_ptid is mainly used by target backend code.  It
is also relied on by a number of target methods.  E.g., the
target_resume interface and the memory reading routines -- we still
need it there because we need to be able to access memory off of
processes for which we don't have a corresponding inferior/thread
object, like when handling forks.  Maybe we could pass down a context
explicitly to target_read_memory, etc.

gdb/ChangeLog:
2020-06-18  Pedro Alves  <palves@redhat.com>

	PR gdb/25412
	* gdbthread.h (delete_thread, delete_thread_silent)
	(find_thread_ptid): Update comments.
	* thread.c (current_thread_): New global.
	(is_current_thread): Move higher, and reimplement.
	(inferior_thread): Reimplement.
	(set_thread_exited): Use bool.  Add assertions.
	(add_thread_silent): Simplify thread-reuse handling by always
	calling delete_thread.
	(delete_thread): Remove intro comment.
	(find_thread_ptid): Skip exited threads.
	(switch_to_thread_no_regs): Write to current_thread_.
	(switch_to_no_thread): Check CURRENT_THREAD_ instead of
	INFERIOR_PTID.  Clear current_thread_.
2020-06-18 23:18:36 +01:00
Pedro Alves
6dbdab44e5 Don't write to inferior_ptid in aix-thread.c
There are other writes in the file, but they seem more harmless.  This
one is changing the current thread permanently.

gdb/ChangeLog:
2020-06-18  Pedro Alves  <palves@redhat.com>

	* aix-thread.c (pd_update): Use switch_to_thread.
2020-06-18 23:18:08 +01:00
Pedro Alves
2da4b788f7 Don't write to inferior_ptid in ravenscar-thread.c
gdb/ChangeLog:
2020-06-18  Pedro Alves  <palves@redhat.com>

	* ravenscar-thread.c (ravenscar_thread_target): Update.
	(ravenscar_thread_target::update_inferior_ptid): Rename to ...
	(ravenscar_thread_target::add_active_thread): ... this.  Don't
	set m_base_ptid here.  Update to avoid referencing inferior_ptid.
	(ravenscar_thread_target::wait): Don't write to inferior_ptid.
2020-06-18 23:17:31 +01:00
Pedro Alves
50838d1be7 Don't write to inferior_ptid in windows-nat.c, part II
Writing to inferior_ptid in
windows_nat_target::get_windows_debug_event is just incorrect and not
necessary.  We'll report the event to GDB's core, which then takes
care of switching inferior_ptid / current thread.

Related (see windows_nat_target::get_windows_debug_event), there's
also a "current_windows_thread" global that is just begging to get out
of sync with core GDB's current thread.  This patch removes it.
gdbserver already does not have an equivalent global in win32-low.cc.

gdb/ChangeLog:
2020-06-18  Pedro Alves  <palves@redhat.com>

	* nat/windows-nat.c (current_windows_thread): Remove.
	* nat/windows-nat.h (current_windows_thread): Remove.
	* windows-nat.c (windows_nat_target::stopped_by_sw_breakpoint):
	Adjust.
	(display_selectors): Adjust to fetch the current
	windows_thread_info based on inferior_ptid.
	(fake_create_process): No longer write to current_windows_thread.
	(windows_nat_target::get_windows_debug_event):
	Don't set inferior_ptid or current_windows_thread.
	(windows_nat_target::wait): Adjust to not rely on
	current_windows_thread.
	(do_initial_windows_stuff): Now a method of windows_nat_target.
	Switch to the last_ptid thread.
	(windows_nat_target::attach): Adjust.
	(windows_nat_target::detach): Use switch_to_no_thread instead of
	writing to inferior_ptid directly.
	(windows_nat_target::create_inferior): Adjust.
2020-06-18 23:17:01 +01:00
Pedro Alves
31ce04e9e0 Don't write to inferior_ptid in windows-nat.c, part I
The inferior_ptid hack in do_initial_win32_stuff, added back in 2008:

  https://sourceware.org/ml/gdb-patches/2008-10/msg00012.html

with:

  commit 9f9d052e60
  Author:     Pierre Muller <muller@sourceware.org>
  AuthorDate: Thu Oct 2 14:20:07 2008 +0000

	      * win32-nat.c (do_initial_win32_stuff): Set inferior_ptid.

is no longer needed.  Back then, current_inferior looked like this:

  struct inferior*
  current_inferior (void)
  {
    struct inferior *inf = find_inferior_pid (ptid_get_pid (inferior_ptid));
    gdb_assert (inf);
    return inf;
  }

Nowadays, current_inferior() just returns the global current_inferior_
pointer, which didn't exist back then.

gdb/ChangeLog:
2020-06-18  Pedro Alves  <palves@redhat.com>

	* windows-nat.c (do_initial_windows_stuff): No longer set inferior_ptid.
2020-06-18 23:16:25 +01:00