Commit Graph

42143 Commits

Author SHA1 Message Date
Tom Tromey 3a6ae42d4e Remove cleanups from linespec.c
This removes the remaining cleanups from linespec.c.  This adds a
constructor and destructor to linespec_parser, but in a minimal way --
the parser could still benefit from a bit more C++-ification.

gdb/ChangeLog
2019-01-02  Tom Tromey  <tom@tromey.com>

	* linespec.c (struct linespec_parser): Rename from ls_parser.  Add
	constructor, destructor.
	(linespec_parser): Remove typedef.
	(~linespec_parser): Rename from linespec_parser_delete.
	(linespec_lex_to_end, linespec_complete_label)
	(linespec_complete): Update.
	(decode_line_full): Remove cleanups.
	(decode_line_1): Update.
2019-01-02 16:38:59 -07:00
Tom Tromey 61fd3e7389 Change inferior_to_inferior_object to return a gdbpy_ref
Most callers of inferior_to_inferior_object already use a gdbpy_ref,
so this changes inferior_to_inferior_object to return one.  Doing this
revealed that create_thread_object was not correctly handling the case
where inferior_to_inferior_object failed, so this patch fixes this as
well.

gdb/ChangeLog
2019-01-02  Tom Tromey  <tom@tromey.com>

	* python/python-internal.h (inferior_to_inferior_object): Change
	return type.
	* python/py-exitedevent.c (create_exited_event_object): Update.
	* python/py-inferior.c (inferior_to_inferior_object): Return
	gdbpy_ref.
	(python_new_inferior, python_inferior_deleted)
	(thread_to_thread_object, delete_thread_object)
	(build_inferior_list, gdbpy_selected_inferior): Update.
	* python/py-infthread.c (create_thread_object): Update.  Also fail
	if inferior_to_inferior_object fails.
2019-01-02 16:28:33 -07:00
Simon Marchi d20172fc53 Place displaced step data directly in inferior structure
This patch moves the per-inferior data related to displaced stepping to
be directly in the inferior structure, rather than in a container on the
side.

On notable difference is that previously, we deleted the state on
inferior exit, which guaranteed a clean state if re-using the inferior
for a new run or attach.  We now need to reset the state manually.

At the same time, I changed step_saved_copy to be a gdb::byte_vector, so
it is automatically freed on destruction (which should plug the leak
reported here [1]).

[1] https://sourceware.org/ml/gdb-patches/2018-11/msg00202.html

gdb/ChangeLog:

	* inferior.h (class inferior) <displaced_step_state>: New field.
	* infrun.h (struct displaced_step_state): Move here from
	infrun.c.  Initialize fields, add constructor.
	<inf>: Remove field.
	<reset>: New method.
	* infrun.c (struct displaced_step_inferior_state): Move to
	infrun.h.
	(displaced_step_inferior_states): Remove.
	(get_displaced_stepping_state): Adust.
	(displaced_step_in_progress_any_inferior): Adjust.
	(displaced_step_in_progress_thread): Adjust.
	(displaced_step_in_progress): Adjust.
	(add_displaced_stepping_state): Remove.
	(get_displaced_step_closure_by_addr): Adjust.
	(remove_displaced_stepping_state): Remove.
	(infrun_inferior_exit): Call displaced_step_state.reset.
	(use_displaced_stepping): Don't check for NULL.
	(displaced_step_prepare_throw): Call
	get_displaced_stepping_state.
	(displaced_step_fixup): Don't check for NULL.
	(prepare_for_detach): Don't check for NULL.
2019-01-02 17:31:08 -05:00
Philippe Waroquiers e331924073 Fix leak of struct call_thread_fsm in call_function_by_hand_dummy.
When the call does not complete, the call_thread_fsm allocated
by new_call_thread_fsm is not cleaned up and deleted, which causes
the following leak e.g. in gdb.base/callfuncs.exp:

==29263== 560 bytes in 7 blocks are definitely lost in loss record 2,833 of 3,341
==29263==    at 0x4C2E0BC: calloc (vg_replace_malloc.c:762)
==29263==    by 0x405110: xcalloc (common-utils.c:84)
==29263==    by 0x4E67EB: xcnew<call_thread_fsm> (poison.h:122)
==29263==    by 0x4E67EB: new_call_thread_fsm (infcall.c:516)
==29263==    by 0x4E67EB: call_function_by_hand_dummy(value*, type*, gdb::array_view<value*>, void (*)(void*, int), void*) (infcall.c:1154)
==29263==    by 0x4E784E: call_function_by_hand(value*, type*, gdb::array_view<value*>) (infcall.c:693)
==29263==    by 0x496111: eval_call(expression*, noside, int, value**, char const*, type*) [clone .isra.5] (eval.c:835)

Fix the leak by similarly doing cleanup/destroy when restoring
previous state machine.

Tested on debian/amd64, natively and under valgrind.

2019-01-02  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* infcall.c (call_function_by_hand_dummy): cleanup/destroy sm
	 in case of call that did not complete.
2019-01-02 22:10:39 +01:00
Andrey Utkin 5d36dfb949 Fix search of debug files for remote debuggee
When using remote debugging server, and when debuggee filename is
inferred via qXfer:exec-file:read request, or sysroot starts with
"target:", this "target:" prefix of filepaths is not treated correctly
during debug file search - it appears in the middle of the looked up
paths.

In the following example, unpatched GDB can't find separate debug files for
neither the executable, nor standard libraries:

     $ gdb -ex 'set debug separate-debug-file 1' -ex 'set sysroot target:/' -ex 'set debug-file-directory /usr/lib/debug:/home/j/hide' -ex 'target remote :3333' -ex 'break main' -ex 'continue' -ex 'bt' -ex 'info sharedlibrary' -ex 'set confirm off' -ex 'quit'
    GNU gdb (Gentoo 9999 vanilla) 8.2.50.20181109-git
    Copyright (C) 2018 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.
    Type "show copying" and "show warranty" for details.
    This GDB was configured as "x86_64-pc-linux-gnu".
    Type "show configuration" for configuration details.
    For bug reporting instructions, please see:
    <https://bugs.gentoo.org/>.
    Find the GDB manual and other documentation resources online at:
        <http://www.gnu.org/software/gdb/documentation/>.

    For help, type "help".
    Type "apropos word" to search for commands related to "word".
    Remote debugging using :3333
    Reading /home/j/test from remote target...
    warning: File transfers from remote targets can be slow. Use "set sysroot" to access files locally instead.
    Reading /home/j/test from remote target...
    Reading symbols from target:/home/j/test...

    Looking for separate debug info (debug link) for target:/home/j/test
      Trying target:/home/j/test.debug
    Reading /home/j/test.debug from remote target...
      Trying target:/home/j/.debug/test.debug
    Reading /home/j/.debug/test.debug from remote target...
      Trying /usr/lib/debug/target:/home/j/test.debug
      Trying /home/j/hide/target:/home/j/test.debug
    (No debugging symbols found in target:/home/j/test)
    Reading /lib64/ld-linux-x86-64.so.2 from remote target...
    Reading /lib64/ld-linux-x86-64.so.2 from remote target...
    Reading symbols from target:/lib64/ld-linux-x86-64.so.2...

    Looking for separate debug info (debug link) for target:/lib64/ld-linux-x86-64.so.2
      Trying target:/lib64/ld-2.27.so.debug
    Reading /lib64/ld-2.27.so.debug from remote target...
      Trying target:/lib64/.debug/ld-2.27.so.debug
    Reading /lib64/.debug/ld-2.27.so.debug from remote target...
      Trying /usr/lib/debug/target:/lib64/ld-2.27.so.debug
      Trying /home/j/hide/target:/lib64/ld-2.27.so.debug
    (No debugging symbols found in target:/lib64/ld-linux-x86-64.so.2)

    Looking for separate debug info (build-id) for system-supplied DSO at 0x7ffff7ffa000
      Trying /usr/lib/debug/.build-id/fd/03d584bc1a90ba28be457635a02662c9f9c1f2.debug
      Trying /home/j/hide/.build-id/fd/03d584bc1a90ba28be457635a02662c9f9c1f2.debug
    0x00007ffff7dd7000 in ?? () from target:/lib64/ld-linux-x86-64.so.2
    Breakpoint 1 at 0x4005eb
    Continuing.
    Reading /lib64/libpthread.so.0 from remote target...
    Reading /lib64/libc.so.6 from remote target...

    Looking for separate debug info (debug link) for target:/lib64/libpthread.so.0
      Trying target:/lib64/libpthread-2.27.so.debug
    Reading /lib64/libpthread-2.27.so.debug from remote target...
      Trying target:/lib64/.debug/libpthread-2.27.so.debug
    Reading /lib64/.debug/libpthread-2.27.so.debug from remote target...
      Trying /usr/lib/debug/target:/lib64/libpthread-2.27.so.debug
      Trying /home/j/hide/target:/lib64/libpthread-2.27.so.debug

    Looking for separate debug info (debug link) for target:/lib64/libc.so.6
      Trying target:/lib64/libc-2.27.so.debug
    Reading /lib64/libc-2.27.so.debug from remote target...
      Trying target:/lib64/.debug/libc-2.27.so.debug
    Reading /lib64/.debug/libc-2.27.so.debug from remote target...
      Trying /usr/lib/debug/target:/lib64/libc-2.27.so.debug
      Trying /home/j/hide/target:/lib64/libc-2.27.so.debug

    Breakpoint 1, 0x00000000004005eb in main ()
    #0  0x00000000004005eb in main ()
    From                To                  Syms Read   Shared Object Library
    0x00007ffff7dd6e80  0x00007ffff7df4650  Yes (*)     target:/lib64/ld-linux-x86-64.so.2
    0x00007ffff7bbbb70  0x00007ffff7bcbfee  Yes (*)     target:/lib64/libpthread.so.0
    0x00007ffff780f200  0x00007ffff7962d7c  Yes (*)     target:/lib64/libc.so.6
    (*): Shared library is missing debugging information.

With current fix, the paths used always have target: in the beginning
and this helps to find all debug files:

     $ gdb -ex 'set debug separate-debug-file 1' -ex 'set sysroot target:/' -ex 'set debug-file-directory /usr/lib/debug:/home/j/hide' -ex 'target remote :3333' -ex 'break main' -ex 'continue' -ex 'bt' -ex 'info sharedlibrary' -ex 'set confirm off' -ex 'quit'
    GNU gdb (Gentoo 9999 vanilla) 8.2.50.20181109-git
    Copyright (C) 2018 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.
    Type "show copying" and "show warranty" for details.
    This GDB was configured as "x86_64-pc-linux-gnu".
    Type "show configuration" for configuration details.
    For bug reporting instructions, please see:
    <https://bugs.gentoo.org/>.
    Find the GDB manual and other documentation resources online at:
        <http://www.gnu.org/software/gdb/documentation/>.

    For help, type "help".
    Type "apropos word" to search for commands related to "word".
    Remote debugging using :3333
    Reading /home/j/test from remote target...
    warning: File transfers from remote targets can be slow. Use "set sysroot" to access files locally instead.
    Reading /home/j/test from remote target...
    Reading symbols from target:/home/j/test...

    Looking for separate debug info (debug link) for target:/home/j/test
      Trying target:/home/j/test.debug
    Reading /home/j/test.debug from remote target...
      Trying target:/home/j/.debug/test.debug
    Reading /home/j/.debug/test.debug from remote target...
      Trying target:/usr/lib/debug//home/j/test.debug
    Reading /usr/lib/debug//home/j/test.debug from remote target...
      Trying target:/home/j/hide//home/j/test.debug
    Reading /home/j/hide//home/j/test.debug from remote target...
    Reading /home/j/hide//home/j/test.debug from remote target...
    Reading symbols from target:/home/j/hide//home/j/test.debug...
    Reading /lib64/ld-linux-x86-64.so.2 from remote target...
    Reading /lib64/ld-linux-x86-64.so.2 from remote target...
    Reading symbols from target:/lib64/ld-linux-x86-64.so.2...

    Looking for separate debug info (debug link) for target:/lib64/ld-linux-x86-64.so.2
      Trying target:/lib64/ld-2.27.so.debug
    Reading /lib64/ld-2.27.so.debug from remote target...
      Trying target:/lib64/.debug/ld-2.27.so.debug
    Reading /lib64/.debug/ld-2.27.so.debug from remote target...
      Trying target:/usr/lib/debug//lib64/ld-2.27.so.debug
    Reading /usr/lib/debug//lib64/ld-2.27.so.debug from remote target...
    Reading /usr/lib/debug//lib64/ld-2.27.so.debug from remote target...
    Reading symbols from target:/usr/lib/debug//lib64/ld-2.27.so.debug...

    Looking for separate debug info (build-id) for system-supplied DSO at 0x7ffff7ffa000
      Trying /usr/lib/debug/.build-id/fd/03d584bc1a90ba28be457635a02662c9f9c1f2.debug
      Trying /home/j/hide/.build-id/fd/03d584bc1a90ba28be457635a02662c9f9c1f2.debug
    0x00007ffff7dd7000 in _start () from target:/lib64/ld-linux-x86-64.so.2
    Breakpoint 1 at 0x4005ef: file test/test16.c, line 13.
    Continuing.
    Reading /lib64/libpthread.so.0 from remote target...
    Reading /lib64/libc.so.6 from remote target...

    Looking for separate debug info (debug link) for target:/lib64/libpthread.so.0
      Trying target:/lib64/libpthread-2.27.so.debug
    Reading /lib64/libpthread-2.27.so.debug from remote target...
      Trying target:/lib64/.debug/libpthread-2.27.so.debug
    Reading /lib64/.debug/libpthread-2.27.so.debug from remote target...
      Trying target:/usr/lib/debug//lib64/libpthread-2.27.so.debug
    Reading /usr/lib/debug//lib64/libpthread-2.27.so.debug from remote target...
    Reading /usr/lib/debug//lib64/libpthread-2.27.so.debug from remote target...

    Looking for separate debug info (debug link) for target:/lib64/libc.so.6
      Trying target:/lib64/libc-2.27.so.debug
    Reading /lib64/libc-2.27.so.debug from remote target...
      Trying target:/lib64/.debug/libc-2.27.so.debug
    Reading /lib64/.debug/libc-2.27.so.debug from remote target...
      Trying target:/usr/lib/debug//lib64/libc-2.27.so.debug
    Reading /usr/lib/debug//lib64/libc-2.27.so.debug from remote target...
    Reading /usr/lib/debug//lib64/libc-2.27.so.debug from remote target...

    Breakpoint 1, main () at test/test16.c:13
    13          for ( i=0; i<10; ++i)
    #0  main () at test/test16.c:13
    From                To                  Syms Read   Shared Object Library
    0x00007ffff7dd6e80  0x00007ffff7df4650  Yes         target:/lib64/ld-linux-x86-64.so.2
    0x00007ffff7bbbb70  0x00007ffff7bcbfee  Yes         target:/lib64/libpthread.so.0
    0x00007ffff780f200  0x00007ffff7962d7c  Yes         target:/lib64/libc.so.6

gdb/ChangeLog:

2018-11-09  Andrey Utkin  <autkin@undo.io>

        * symfile.c (find_separate_debug_file): Fix search of debug files for
        remote debuggee.

Signed-off-by: Andrey Utkin <autkin@undo.io>
2019-01-02 14:53:01 -05:00
Tom Tromey 8833fbf05c Style improvements in gdb/python
This fixes a few minor style issues I found in gdb/python: some
unnecessary casts, the removal of an unnecessary local variable, and
one instance of incorrect formatting.

Tested by rebuilding and re-running gdb.python.

gdb/ChangeLog
2019-01-02  Tom Tromey  <tom@tromey.com>

	* python/py-inferior.c (gdbpy_initialize_inferior): Fix
	indentation.
	* python/py-frame.c (frapy_older): Remove cast.
	(frapy_newer): Likewise.
	* python/py-breakpoint.c (local_setattro): Remove cast.
	* python/py-arch.c (archpy_name): Remove local variable.
	* python/py-type.c (gdbpy_lookup_type): Remove cast.
2019-01-02 09:32:06 -07:00
Joel Brobecker 4ada3dfd5c Fix year range in unittests/.../char/empty.cc copyright header
The year range in the copyright header of that file was incorrect:

    // Copyright (C) 3 Free Software Foundation, Inc.

Tracing the origin of this file down, I found that it was copied
from GCC's libstdc++-v3 testsuite:

    Adapt and integrate string_view tests
    https://www.sourceware.org/ml/gdb-patches/2018-04/msg00113.html

Looking at the version in GCC, I found the same issue, so sent
a fix there:

    https://gcc.gnu.org/ml/gcc-patches/2019-01/msg00000.html

Now that the fix is in GCC, this commit applies the same fix
to our copy.

gdb/ChangeLog:

	* unittests/basic_string_view/element_access/char/empty.cc:
	Fix year range in copyright header.
2019-01-02 10:11:41 +04:00
Andrew Burgess 113b7b8142 gdb/riscv: Split ISA and ABI features
The goal of this commit is to allow RV64 binaries compiled for the 'F'
extension to run on a target that supports both the 'F' and 'D'
extensions.

The 'D' extension depends on the 'F' extension and chapter 9 of the
RISC-V ISA manual implies that running a program compiled for 'F' on
a 'D' target should be fine.

To support this the gdbarch now holds two feature sets, one represents
the features that are present on the target, and one represents the
features requested in the ELF flags.

The existing error checks are relaxed slightly to allow binaries
compiled for 32-bit 'F' extension to run on targets with the 64-bit
'D' extension.

A new set of functions called riscv_abi_{xlen,flen} are added to
compliment the existing riscv_isa_{xlen,flen}, and some callers to the
isa functions now call the abi functions when that is appropriate.

In riscv_call_arg_struct two asserts are removed, these asserts no
longer make sense.  The asserts were both like this:

    gdb_assert (TYPE_LENGTH (ainfo->type)
                <= (cinfo->flen + cinfo->xlen));

And were made in two cases, when passing structures like these:

   struct {
     integer field1;
     float   field2;
   };

or,

   struct {
     float   field1;
     integer field2;
   };

When running on an RV64 target which only has 32-bit float then the
integer field could be 64-bits, while if the float field is 32-bits
the overall size of the structure can be 128-bits (with 32-bits of
padding).  In this case the assertion would fail, however, the code
isn't incorrect, so its safe to just remove the assertion.

This was tested by running on an RV64IMFDC target using a compiler
configured for RV64IMFC, and comparing the results with those obtained
when using a compiler configured for RV64IMFDC.  The only regressions
I see (now) are in gdb.base/store.exp and are related too different
code generation choices GCC makes between the two targets.

Finally, this commit does not make any attempt to support running
binaries compiled for RV32 on an RV64 target, though nothing in here
should prevent that being supported in the future.

gdb/ChangeLog:

	* arch/riscv.h (struct riscv_gdbarch_features) <hw_float_abi>:
	Delete.
	<operator==>: Update with for removed field.
	<hash>: Likewise.
	* riscv-tdep.h (struct gdbarch_tdep) <features>: Renamed to...
	<isa_features>: ...this.
	<abi_features>: New field.
	(riscv_isa_flen): Update comment.
	(riscv_abi_xlen): New declaration.
	(riscv_abi_flen): New declaration.
	* riscv-tdep.c (riscv_isa_xlen): Update to get answer from
	isa_features.
	(riscv_abi_xlen): New function.
	(riscv_isa_flen): Update to get answer from isa_features.
	(riscv_abi_flen): New function.
	(riscv_has_fp_abi): Update to get answer from abi_features.
	(riscv_call_info::riscv_call_info): Use abi xlen and flen, not isa
	xlen and flen.
	(riscv_call_info) <xlen, flen>: Update comment.
	(riscv_call_arg_struct): Remove invalid assertions
	(riscv_features_from_gdbarch_info): Update now hw_float_abi field
	is removed.
	(riscv_gdbarch_init): Gather isa features and abi features
	separately, ensure both match on the gdbarch when reusing an old
	gdbarch.  Relax an error check to allow 32-bit abi float to run on
	a target with 64-bit float hardware.
2019-01-01 22:56:16 +00:00
Philippe Waroquiers b18ca5148b Fix 'Invalid read of size 4' in search_command_helper
Valgrind detects the below error in gdb.base/list.exp.
==14763== Invalid read of size 4
==14763==    at 0x60B584: search_command_helper(char const*, int, bool) [clone .constprop.91] (source.c:1601)
==14763==    by 0x408888: cmd_func(cmd_list_element*, char const*, int) (cli-decode.c:1892)
==14763==    by 0x668550: execute_command(char const*, int) (top.c:630)
==14763==    by 0x4B2F7B: command_handler(char const*) (event-top.c:583)
==14763==    by 0x4B326C: command_line_handler(std::unique_ptr<char, gdb::xfree_deleter<char> >&&) (event-top.c:772)
...
==14763==  Address 0x6d9f09c is 4 bytes before a block of size 156 alloc'd
==14763==    at 0x4C2E2B3: realloc (vg_replace_malloc.c:836)
==14763==    by 0x41904C: xrealloc (common-utils.c:62)
==14763==    by 0x60A300: find_source_lines(symtab*, int) (source.c:1203)
==14763==    by 0x608219: source_cache::get_plain_source_lines(symtab*, int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*) (source-cache.c:51)
==14763==    by 0x60A46B: print_source_lines_base(symtab*, int, int, enum_flags<print_source_lines_flag>) (source.c:1350)
==14763==    by 0x404E2D: list_command(char const*, int) (cli-cmds.c:1080)
....

Add the missing condition to end the loop once line 1 has been
reversed-searched.

gdb/ChangeLog
2019-01-01  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* source.c (search_command_helper): Stop reverse search
	when line 1 has been searched.
2019-01-01 20:30:43 +01:00
Philippe Waroquiers ec70d8db32 Fix leak in record-full.c
valgrind detects leaks in several gdb.reverse tests,
such as the below in gdb.reverse/watch-precsave.exp.

Fix the leak by rewriting the loop that frees
record_full_core_buf_list.

gdb/ChangeLog
2019-01-01  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* record-full.c (record_full_base_target::close): Rewrite
	record_full_core_buf_list free logic.

==18847== VALGRIND_GDB_ERROR_BEGIN
==18847== 4,120 (24 direct, 4,096 indirect) bytes in 1 blocks are definitely lost in loss record 3,094 of 3,199
==18847==    at 0x4C2BE6D: malloc (vg_replace_malloc.c:309)
==18847==    by 0x405097: xmalloc (common-utils.c:44)
==18847==    by 0x5AF8EA: xnew<record_full_core_buf_entry> (poison.h:110)
==18847==    by 0x5AF8EA: record_full_core_target::xfer_partial(target_object, char const*, unsigned char*, unsigned char const*, unsigned long, unsigned long, unsigned long*) (record-full.c:2182)
==18847==    by 0x64677D: raw_memory_xfer_partial(target_ops*, unsigned char*, unsigned char const*, unsigned long, long, unsigned long*) (target.c:956)
==18847==    by 0x64691E: memory_xfer_partial_1(target_ops*, target_object, unsigned char*, unsigned char const*, unsigned long, unsigned long, unsigned long*) (target.c:1086)
2019-01-01 20:28:55 +01:00
Philippe Waroquiers 5b38f9c16e Fix leak in print_one_catch_syscall.
The last text produced was not freed, causing the below leak
(e.g. in gdb.base/catch-syscall.exp):

==24970== 56 bytes in 12 blocks are definitely lost in loss record 626 of 3,289
==24970==    at 0x4C2BE6D: malloc (vg_replace_malloc.c:309)
==24970==    by 0x66B9C3F: __vasprintf_chk (vasprintf_chk.c:80)
==24970==    by 0x405181: vasprintf (stdio2.h:210)
==24970==    by 0x405181: xstrvprintf(char const*, __va_list_tag*) (common-utils.c:122)
==24970==    by 0x40524B: xstrprintf(char const*, ...) (common-utils.c:113)
==24970==    by 0x3B49DB: print_one_catch_syscall(breakpoint*, bp_location**) (break-catch-syscall.c:275)
==24970==    by 0x3C698F: print_one_breakpoint_location(breakpoint*, bp_location*, int, bp_location**, int) (breakpoint.c:6076)
==24970==    by 0x3C75B1: print_one_breakpoint(breakpoint*, bp_location**, int) (breakpoint.c:6373)
==24970==    by 0x3C7D0E: breakpoint_1(char const*, int, int (*)(breakpoint const*)) (breakpoint.c:6571)
==24970==    by 0x3C822C: info_breakpoints_command(char const*, int) (breakpoint.c:6625)

2019-01-01  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* break-catch-syscall.c (print_one_catch_syscall): xfree
	the last text.
2019-01-01 20:26:18 +01:00
Joel Brobecker 66d91b3908 update copyright year printed by gdb, gdbserver and gdbreplay
gdb/ChangeLog:

	* top.c (print_gdb_version): Update Copyright year in version
	message.

gdb/gdbserver/ChangeLog:

	* gdbreplay.c (gdbreplay_version): Update copyright year in
	version message.
	* server.c (gdbserver_version): Likewise.
2019-01-01 10:09:59 +04:00
Joel Brobecker 42a4f53d2b Update copyright year range in all GDB files.
This commit applies all changes made after running the gdb/copyright.py
script.

Note that one file was flagged by the script, due to an invalid
copyright header
(gdb/unittests/basic_string_view/element_access/char/empty.cc).
As the file was copied from GCC's libstdc++-v3 testsuite, this commit
leaves this file untouched for the time being; a patch to fix the header
was sent to gcc-patches first.

gdb/ChangeLog:

	Update copyright year range in all GDB files.
2019-01-01 10:01:51 +04:00
Joel Brobecker 5bbd631dca rotate gdb/ChangeLog 2019-01-01 09:59:27 +04:00
Philippe Waroquiers 2139e8dc9f Use gdb::unique_xmalloc_ptr<char> in command_line_input to fix a leak
Following the change of logic where the input_handler gets a
gdb::unique_xmalloc_ptr<char>, a call to readline directly
followed by a call to handle_line_of_input is missing a free,
and causes the below leak.

Use gdb::unique_xmalloc_ptr<char> to solve the leak.

==16291== VALGRIND_GDB_ERROR_BEGIN
==16291== 64 bytes in 1 blocks are definitely lost in loss record 1,815 of 4,111
==16291==    at 0x4C2E2B3: realloc (vg_replace_malloc.c:836)
==16291==    by 0x41EB1C: xrealloc (common-utils.c:62)
==16291==    by 0x41DBD3: buffer_grow(buffer*, char const*, unsigned long) [clone .part.1] (buffer.c:40)
==16291==    by 0x66E8FF: buffer_grow_char (buffer.h:40)
==16291==    by 0x66E8FF: gdb_readline_no_editing (top.c:798)
==16291==    by 0x66E8FF: command_line_input(char const*, char const*) (top.c:1249)
==16291==    by 0x66EBD8: read_command_file(_IO_FILE*) (top.c:421)
==16291==    by 0x412C0C: script_from_file(_IO_FILE*, char const*) (cli-script.c:1547)
==16291==    by 0x40BE90: source_script_from_stream (cli-cmds.c:569)
==16291==    by 0x40BE90: source_script_with_search(char const*, int, int) (cli-cmds.c:606)
==16291==    by 0x54D567: catch_command_errors(void (*)(char const*, int), char const*, int) (main.c:379)
==16291==    by 0x54EA84: captured_main_1 (main.c:994)
==16291==    by 0x54EA84: captured_main (main.c:1167)
==16291==    by 0x54EA84: gdb_main(captured_main_args*) (main.c:1193)
==16291==    by 0x29DA27: main (gdb.c:32)
==16291==
==16291== VALGRIND_GDB_ERROR_END

gdb/ChangeLog
2018-12-31  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* top.c (command_line_input): Use unique_xmalloc_ptr to
	manage memory allocated by readline.
2018-12-31 17:28:54 +01:00
Tom Tromey 95bc9f0bf0 Change input_handler to take a unique_xmalloc_ptr
This changes ui::input_handler to take a unique_xmalloc_ptr.  This
clarifies the ownership transfer of input_handler's argument.

gdb/ChangeLog
2018-12-30  Tom Tromey  <tom@tromey.com>

	* event-top.h (command_line_handler): Update.
	* top.c (class gdb_readline_wrapper_cleanup) <m_handler_orig>:
	Update.
	(gdb_readline_wrapper_line): Update.
	* top.h (struct ui) <input_handler>: Take a unique_xmalloc_ptr.
	(handle_line_of_input): Update.
	* event-top.c: Update.
	(gdb_readline_no_editing_callback): Update.
	(command_line_handler): Take a unique_xmalloc_ptr.
	(handle_line_of_input): Take a const char *.
	(command_line_append_input_line): Take a const char *.
2018-12-30 08:54:13 -07:00
Philippe Waroquiers ecad3b215d Fix 'help set/show style' strange layouts/results.
The layout for 'help set address|variable' is strange, e.g.:
  (gdb) help set style address
  style address

  List of show Address display styling
  Configure address colors and display intensity subcommands:

  show Address display styling
  Configure address colors and display intensity background -- Set the background color for this property
  show Address display styling
  Configure address colors and display intensity foreground -- Set the foreground color for this property
  show Address display styling
  Configure address colors and display intensity intensity -- Set the display intensity color for this property

  Type "help show Address display styling
  Configure address colors and display intensity" followed by show Address display styling
  Configure address colors and display intensity subcommand name for full documentation.
  Type "apropos word" to search for commands related to "word".
  Command name abbreviations are allowed if unambiguous.
  (gdb)

The help for 'set style function|filename' gives help for 'Show':
  (gdb) help set style filename
  Filename display styling
  Configure filename colors and display intensity.

  List of show style filename subcommands:

  show style filename background -- Set the background color for this property
  show style filename foreground -- Set the foreground color for this property
  show style filename intensity -- Set the display intensity color for this property

The help for 'show style function|filename' is equally strange, as it speaks
about commands, instead of sub commands:
  (gdb) help show style filename
  Filename display styling
  Configure filename colors and display intensity.

  List of commands:

  background -- Show the background color for this property
  foreground -- Show the foreground color for this property
  intensity -- Show the display intensity color for this property

  Type "help" followed by command name for full documentation.
  Type "apropos word" to search for commands related to "word".
  Command name abbreviations are allowed if unambiguous.
  (gdb)

This patch fixes all this.

Note that the 'set style' and 'show style' have the same prefix_doc:
  (gdb) help show style
  Style-specific settings
  Configure various style-related variables, such as colors
  ...
  (gdb) help set style
  Style-specific settings
  Configure various style-related variables, such as colors
  ...

Other similar commands (such as set|show history) have typically
a more specific prefix:
  (gdb) help show history
  Generic command for showing command history parameters.
  ...
  (gdb) help set history
  Generic command for setting command history parameters.
  ...

This could be fixed by having set_prefix_doc and show_prefix_doc instead of
the single prefix_doc argument to cli_style_option::add_setshow_commands.
That could be improved if deemed better.

2018-12-29  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* cli/cli-style.c (cli_style_option::add_setshow_commands):
	Initialize m_set_prefix with "set", instead of re-assigning
	m_show_prefix.  Use m_set_prefix for set_list and m_show_prefix
	for show_list.
	(_initialize_cli_style): Correct the order of arguments in
	variable_name_style.add_setshow_commands and
	address_style.add_setshow_commands calls.
2018-12-30 09:26:21 +01:00
Tom Tromey 64c45143db Fix the build when GNU Source Highlight is not available
The builder pointed out that, when GNU Source Highlight is not
available, get_language_name is not used.  This patch makes it
conditional, fixing the build problem.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* source-cache.c (get_language_name): Conditionally compile.
2018-12-28 21:07:24 -07:00
Tom Tromey 2cd8cc0b66 Fix a crash in jit.c
A user at Mozilla pointed out a crash in jit.c.  In his situation, an
inferior using the JIT API exec'd an executable that did not use it.
This caused an assertion failure when jit.c:free_objfile_data called
delete_breakpoint with NULL.

This patch fixes the problem in the obvious way.  New test case
included.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* jit.c (free_objfile_data): Only delete breakpoint if non-null.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>
	    Simon Marchi <simark@simark.ca>

	* gdb.base/jit-exec.exp: New file.
	* gdb.base/jit-exec.c: New file.
	* gdb.base/jit-execd.c: New file.
2018-12-28 14:08:03 -07:00
Tom Tromey 140a4bc099 Document the "set style" commands
This documents the new "set style" commands.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* NEWS: Mention terminal styling.

gdb/doc/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.texinfo (Output Styling): New node.
2018-12-28 12:49:54 -07:00
Tom Tromey 62f29fda90 Highlight source code using GNU Source Highlight
This changes gdb to highlight source using GNU Source Highlight, if it
is available.

This affects the output of the "list" command and also the TUI source
window.

No new test because I didn't see a way to make it work when Source
Highlight is not found.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* utils.h (can_emit_style_escape): Declare.
	* utils.c (can_emit_style_escape): No longer static.
	* cli/cli-style.c (set_style_enabled): New function.
	(_initialize_cli_style): Use it.
	* tui/tui-winsource.c (tui_show_source_line): Use tui_puts.
	(tui_alloc_source_buffer): Change how source lines are allocated.
	* tui/tui-source.c (copy_source_line): New function.
	(tui_set_source_content): Use source cache.
	* tui/tui-io.h (tui_puts): Update.
	* tui/tui-io.c (tui_puts_internal): Add window parameter.
	(tui_puts): Likewise.
	(tui_redisplay_readline): Update.
	* tui/tui-data.c (free_content_elements): Change how source window
	contents are freed.
	* source.c (forget_cached_source_info): Clear the source cache.
	(print_source_lines_base): Use the source cache.
	* source-cache.h: New file.
	* source-cache.c: New file.
	* configure.ac: Check for GNU Source Highlight library.
	* configure: Update.
	* config.in: Update.
	* Makefile.in (SRCHIGH_LIBS, SRCHIGH_CFLAGS): New variables.
	(INTERNAL_CFLAGS_BASE): Add SRCHIGH_CFLAGS.
	(CLIBS): Add SRCHIGH_LIBS.
	(COMMON_SFILES): Add source-cache.c.
	(HFILES_NO_SRCDIR): Add source-cache.h.
2018-12-28 12:49:54 -07:00
Tom Tromey 4a3045920b Use wclrtoeol in tui_show_source_line
This changes tui_show_source_line to use wclrtoeol rather than
manually emitting a sequence of spaces.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* tui/tui-winsource.c (tui_show_source_line): Use wclrtoeol.
2018-12-28 12:49:53 -07:00
Tom Tromey 1d1d0bf76f Make ANSI terminal escape sequences work in TUI
PR tui/14126 notes that ANSI terminal escape sequences don't affect
the colors shown in the TUI.  A simple way to see this is to try the
extended-prompt example from the gdb manual.

Curses does not pass escape sequences through to the terminal.
Instead, it replaces non-printable characters with a visible
representation, for example "^[" for the ESC character.

This patch fixes the problem by adding a simple ANSI terminal sequence
parser to gdb.  These sequences are decoded and those that are
recognized are turned into the appropriate curses calls.

The curses approach to color handling is unusual and so there are some
oddities in the implementation.

Standard curses has no notion of the default colors of the terminal.
So, if you set the foreground color, it is not possible to reset it --
you have to pick some other color.  ncurses provides an extension to
handle this, so this patch updates configure and uses it when
available.

Second, in curses, colors always come in pairs: you cannot set just
the foreground.  This patch handles this by tracking actually-used
pairs of colors and keeping a table of these for reuse.

Third, there are a limited number of such pairs available.  In this
patch, if you try to use too many color combinations, gdb will just
ignore some color changes.

Finally, in addition to limiting the number of color pairs, curses
also limits the number of colors.  This means that, when using
extended 8- or 24-bit color sequences, it may be possible to exhaust
the curses color table.

I am very sour on the curses design now.

I do not know how to write a test for this, so I did not.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	PR tui/14126:
	* tui/tui.c (tui_enable): Call start_color and
	use_default_colors.
	* tui/tui-io.c (struct color_pair): New.
	(color_pair_map, last_color_pair, last_style): New globals.
	(tui_setup_io): Clean up color map when shutting down.
	(curses_colors): New constant.
	(get_color_pair, apply_ansi_escape): New functions.
	(tui_write): Rewrite.
	(tui_puts_internal): New function, from tui_puts.  Add "height"
	parameter.
	(tui_puts): Use tui_puts_internal.
	(tui_redisplay_readline): Use tui_puts_internal.
	(_initialize_tui_io): New function.
	(color_map): New globals.
	(get_color): New function.
	* configure.ac: Check for use_default_colors.
	* config.in, configure: Rebuild.
2018-12-28 12:49:53 -07:00
Tom Tromey 35fb8261b9 Style addresses
This changes gdb to style addresses.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* ui-out.h (enum class ui_out_style_kind) <ADDRESS>: New
	constant.
	* ui-out.c (ui_out::field_core_addr): Add styling.
	* stack.c (print_frame): Add styling.
	* printcmd.c (print_address): Add styling.
	(print_address_demangle, info_address_command): Likewise.
	* cli/cli-style.h (address_style): Declare.
	* cli/cli-style.c (address_style): New global.
	(_initialize_cli_style): Register new commands.
	* cli-out.c (cli_ui_out::do_field_string): Update.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Update test to check for address styling.
2018-12-28 12:49:52 -07:00
Tom Tromey 47fd17cdc1 Style the "Reading symbols" message
The "Reading symbols" message does not use ui-out (perhaps it
should?), so this styles it using the low-level API.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* symfile.c (symbol_file_add_with_addrs): Style file name.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Add test for styling of "Reading symbols"
	message.
2018-12-28 12:49:52 -07:00
Tom Tromey d47032b7ca Style the gdb welcome message
This changes gdb to style the welcome message that is shown by
default.  The styling is only done interactively.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* top.c (print_gdb_version): Style gdb version number.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Add test for version number styling.
2018-12-28 12:49:51 -07:00
Tom Tromey af79b68d7f Style print_address_symbolic
print_address_symbolic does not use ui-out, so it did not style
function names.  This patch changes it to use the low-level style code
directly.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* printcmd.c (print_address_symbolic): Style function name.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Add test for print_address_symbolic.
2018-12-28 12:49:51 -07:00
Tom Tromey 0bb296cb5f Style locations when setting a breakpoint
say_where does not use ui-out, so function and file names printed by
it were not styled.  This patch changes say_where to use the low-level
style code directly.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* breakpoint.c (say_where): Style file name.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Add test for breakpoint setting.
2018-12-28 12:49:50 -07:00
Tom Tromey 80ae204359 Style variable names
This adds style support for variable names.  For the time being, this
is only done in backtraces, not in ptype or print; those places do not
use ui-out and so would need ad hoc changes.

This also adds styling to the names printed for local variables in
"backtrace full".  This code does not use ui-out, so the styling is
done using the low-level API.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* ui-out.h (enum class ui_out_style_kind) <VARIABLE>: New global.
	* stack.c (print_frame_arg): Style name.
	* printcmd.c (print_variable_and_value): Style variable name.
	* cli/cli-style.h (variable_name_style): Declare.
	* cli/cli-style.c (variable_name_style): New global.
	(_initialize_cli_style): Update.
	* cli-out.c (cli_ui_out::do_field_string): Update.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: Add test for variable names.
2018-12-28 12:49:50 -07:00
Tom Tromey ef1dfa3644 Reset terminal styles
This adds a function that can be used to reset terminal styles,
regardless of what style the low-level output routines currently think
is applied.

This is used to make "echo" and "printf" work properly when emitting
ANSI terminal escapes -- now gdb will reset the style at the end of
the command.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* utils.h (reset_terminal_style): Declare.
	* utils.c (can_emit_style_escape): New function.
	(set_output_style): Use it.
	(reset_terminal_style): New function.
	* printcmd.c (printf_command): Call reset_terminal_style.
	* cli/cli-cmds.c (echo_command): Call reset_terminal_style.
2018-12-28 12:49:49 -07:00
Tom Tromey cbe5657196 Add output styles to gdb
This adds some output styling to the CLI.

A style is currently a foreground color, a background color, and an
intensity (dim or bold).  (This list could be expanded depending on
terminal capabilities.)

A style can be applied while printing.  For ui-out, this is done by
passing the style constant as an argument.  For low-level cases,
fprintf_styled and fputs_styled are provided.

Users can control the style via a number of new set/show commands.  In
the interest of not typing many nearly-identical documentation
strings, I automated this.  On the down side, this is not very
i18n-friendly.

I've chose some default colors to use.  I think it would be good to
enable this by default, so that when users start the new gdb, they
will see the new feature.

Stylizing is done if TERM is set and is not "dumb".  This could be
improved when the TUI is available by using the curses has_colors
call.  That is, the lowest layer could call this without committing to
using curses everywhere; see my other patch for TUI colorizing.

I considered adding a new "set_style" method to ui_file.  However,
because the implementation had to interact with the pager code, I
didn't take this approach.  But, one idea might be to put the isatty
check there and then have it defer to the lower layers.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* utils.h (set_output_style, fprintf_styled)
	(fputs_styled): Declare.
	* utils.c (applied_style, desired_style): New globals.
	(emit_style_escape, set_output_style): New function.
	(prompt_for_continue): Emit style escapes.
	(fputs_maybe_filtered): Likewise.
	(fputs_styled, fprintf_styled): New functions.
	* ui-out.h (enum class ui_out_style_kind): New.
	(class ui_out) <field_string, field_stream, do_field_string>: Add
	style parameter.
	* ui-out.c (ui_out::field_stream, ui_out::field_string): Add style
	parameter.
	* tui/tui-out.h (class tui_ui_out) <do_field_string>: Add style
	parameter.
	* tui/tui-out.c (tui_ui_out::do_field_string): Add style
	parameter.
	(tui_ui_out::do_field_string): Update.
	* tracepoint.c (print_one_static_tracepoint_marker): Style
	output.
	* stack.c (print_frame_info, print_frame): Style output.
	* source.c (print_source_lines_base): Style output.
	* skip.c (info_skip_command): Style output.
	* record-btrace.c (btrace_call_history_src_line): Style output.
	(btrace_call_history): Likewise.
	* python/py-framefilter.c (py_print_frame): Style output.
	* mi/mi-out.h (class mi_ui_out) <do_field_string>: Add style
	parameter.
	* mi/mi-out.c (mi_ui_out::do_table_header)
	(mi_ui_out::do_field_int): Update.
	(mi_ui_out::do_field_string): Update.
	* disasm.c (gdb_pretty_print_disassembler::pretty_print_insn):
	Style output.
	* cli/cli-style.h: New file.
	* cli/cli-style.c: New file.
	* cli-out.h (class cli_ui_out) <do_field_string>: Add style
	parameter.
	* cli-out.c (cli_ui_out::do_table_header)
	(cli_ui_out::do_field_int, cli_ui_out::do_field_skip): Update.
	(cli_ui_out::do_field_string): Add style parameter.  Style the
	output.
	* breakpoint.c (print_breakpoint_location): Style output.
	(update_static_tracepoint): Likewise.
	* Makefile.in (SUBDIR_CLI_SRCS): Add cli-style.c.
	(HFILES_NO_SRCDIR): Add cli-style.h.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* gdb.base/style.exp: New file.
	* gdb.base/style.c: New file.
2018-12-28 12:49:49 -07:00
Tom Tromey 9162a27c5f Change gdb test suite's TERM setting
This changes the gdb test suite to set TERM to "dumb" by default.
This setting disables terminal styling, so that the existing tests do
not need to be updated.

gdb/testsuite/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* lib/gdb.exp (gdb_init): Set the TERM environment variable to
	"dumb".
	* gdb.base/readline.exp (operate_and_get_next): Save and restore
	the TERM environment variable.
2018-12-28 12:49:48 -07:00
Tom Tromey eedeedd2a5 Introduce ui_file_style
This introduces the new ui_file_style class and various helpers.  This
class represents a terminal style and provides methods for parsing and
emitting the corresponding ANSI terminal escape sequences.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* unittests/style-selftests.c: New file.
	* ui-style.c: New file.
	* ui-style.h: New file.
	* ui-file.h: Include ui-style.h.
	* Makefile.in (COMMON_SFILES): Add ui-style.c.
	(HFILES_NO_SRCDIR): Add ui-style.h.
	(SUBDIR_UNITTESTS_SRCS): Add style-selftests.c.
2018-12-28 12:49:48 -07:00
Tom Tromey 7170dadf59 Add a "context" argument to add_setshow_enum_cmd
This adds a "context" argument to add_setshow_enum_cmd.  Now
add_setshow_enum_cmd will call set_cmd_context on both of the new
commands.  This is used in a later patch.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* command.h (add_setshow_enum_cmd): Add "context" argument.
	* cli/cli-decode.c (add_setshow_enum_cmd): Add "context"
	argument.  Call set_cmd_context.
2018-12-28 12:49:47 -07:00
Tom Tromey c5603d5063 Change wrap buffering to use a std::string
Currently wrap buffering is implemented by allocating a string that is
the same width as the window, and then writing characters into it.
However, if gdb emits terminal escapes, then these could possibly
overflow the buffer.

To prevent this, change the wrap buffer to be a std::string and update
the various uses.

This also changes utils.c to always emit characters to the wrap
buffer.  This simplifies future patches which emit terminal escape
sequences, and also makes it possible for the "echo" and "printf"
commands to be used to emit terminal escapes and have these work in
the TUI.

gdb/ChangeLog
2018-12-28  Tom Tromey  <tom@tromey.com>

	* utils.c (filter_initialized): New global.
	(wrap_buffer): Now a std::string.
	(wrap_pointer): Remove.
	(flush_wrap_buffer): New function.
	(filtered_printing_initialized, set_width, wrap_here)
	(fputs_maybe_filtered): Update.
2018-12-28 12:49:47 -07:00
Philippe Waroquiers 94f2c73066 Fix leak of set/show verbose doc, avoid xfree of static string
In the tests
  py-pp-registration/gdb.log
  default/gdb.log
  foll-fork/gdb.log
  setshow/gdb.log
  break-interp/gdb.log
Valgrind detects a leak of the doc strings for the set and show verbose cmd.

Here is the stacktrace of the leaked set doc:
==25548== 15 bytes in 1 blocks are definitely lost in loss record 101 of 3,120
==25548==    at 0x4C2BE6D: malloc (vg_replace_malloc.c:309)
==25548==    by 0x409C27: xmalloc (common-utils.c:44)
==25548==    by 0x778AF9: xstrdup (xstrdup.c:34)
==25548==    by 0x3F860F: add_setshow_cmd_full(char const*, command_class, var_types, void*, char const*, char const*, char const*, void (*)(char const*, int, cmd_list_element*), void (*)(ui_file*, int, cmd_list_element*, char const*), cmd_list_element**, cmd_list_element**, cmd_list_element**, cmd_list_element**) [clone .constprop.10] (cli-decode.c:495)
==25548==    by 0x3F8ADB: add_setshow_boolean_cmd(char const*, command_class, int*, char const*, char const*, char const*, void (*)(char const*, int, cmd_list_element*), void (*)(ui_file*, int, cmd_list_element*, char const*), cmd_list_element**, cmd_list_element**) (cli-decode.c:593)
==25548==    by 0x3F7442: _initialize_cli_cmds() (cli-cmds.c:1768)
==25548==    by 0x69EED3: initialize_all_files() (init.c:365)
==25548==    by 0x658A84: gdb_init(char*) (top.c:2163)
==25548==    by 0x5403E1: captured_main_1 (main.c:863)
==25548==    by 0x5403E1: captured_main (main.c:1167)
==25548==    by 0x5403E1: gdb_main(captured_main_args*) (main.c:1193)
==25548==    by 0x289CA7: main (gdb.c:32)

The leak is created by top.c set_verbose 'elaborate joke':
the doc string is changed according to the verbosity:
  (gdb) help set verbose
  Set verbosity.
  (gdb) set verbose on
  (gdb) help set verbose
  Set verbose printing of informational messages.
  (gdb)

set_verbose creates the leak as it replaces the string allocated in
the above stacktrace by a static (non translated) string:
...
  if (info_verbose)
    {
      c->doc = "Set verbose printing of informational messages.";
...

Also, this can possibly trigger a call to 'free' of a static string,
as c->doc_allocated is kept true, while the string is not allocated anymore.

This patch:
 * fixes the leak by freeing the previous docs if doc_allocated.
 * internationalize the messages.
 * properly sets doc_allocated to 0 once doc strings are static.

gdb/ChangeLog
2018-12-28  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* top.c (set_verbose): Free previous docs if doc_allocated.
	Internationalize messages.  Set doc_allocated to 0.
2018-12-28 12:19:59 +01:00
Eli Zaretskii 156f236692 Avoid internal errors when stepping outside 'main' on MinGW
When one steps with "next" past the 'main's 'return' statement
in MinGW programs built by mingw.org's tools, PC lands in a
function whose symbol is not in any symtab.  GDB then looks
up the nearest symbol, and should find none, because all those
with addresses below PC are not real functions.  Having
unresolved symbols, whose address is zero, in minsyms tricked
GDB into using these bogus symbols, which then caused
assertion violation and internal_error.  See the discussion at
https://sourceware.org/ml/gdb-patches/2018-12/msg00176.html
for more details.

gdb/ChangeLog
2018-12-28  Eli Zaretskii  <eliz@gnu.org>

	* coffread.c (coff_symtab_read): Don't record in minsyms symbols
	that are unresolved.  This avoids triggering an internal error
	when stepping outside of 'main' in MinGW programs.
2018-12-28 09:02:04 +02:00
Tom Tromey bc543c902f Translate PyExc_KeyboardInterrupt to gdb "quit"
A while back I typed "info pretty-printers" with a large number of
printers installed, and I typed "q" to stop the pagination.  I noticed
that gdb printed a Python exception in this case.

It seems to me that, instead, quitting pagination (or control-c'ing a
Python command generally) should be handled the same way that gdb
normally handles a quit.

This patch implements this idea by changing gdbpy_handle_exception to
treat PyExc_KeyboardInterrupt specially.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* python/py-utils.c (gdbpy_handle_exception): Translate
	PyExc_KeyboardInterrupt to quit.

gdb/testsuite/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* gdb.python/py-cmd.exp (test_python_inline_or_multiline): Add
	pagination test.
2018-12-27 13:34:39 -07:00
Tom Tromey 6ef2312a17 Consolidate some Python exception-printing functions
A few places in the Python code would either call gdbpy_print_stack,
or throw a gdb "quit", depending on the pending exception.  This patch
consolidates these into a helper function.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* python/python-internal.h (gdbpy_print_stack_or_quit): Declare.
	* python/py-unwind.c (pyuw_sniffer): Use
	gdbpy_print_stack_or_quit.
	* python/py-framefilter.c (throw_quit_or_print_exception):
	Remove.
	(gdbpy_apply_frame_filter): Use gdbpy_print_stack_or_quit.
	* python/python.c (gdbpy_print_stack_or_quit): New function.
2018-12-27 13:34:39 -07:00
Tom Tromey ec9c2750b7 Use gdbpy_convert_exception in a few more spots
I noticed a few places were converting a gdb exception to a Python
exception "by hand".  It's better to use the existing
gdbpy_convert_exception helper function, as this handles memory errors
correctly, and in the future may be enhanced in other ways.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* python/py-value.c (convert_value_from_python): Use
	gdbpy_convert_exception.
	* python/py-param.c (parmpy_init): Use gdbpy_convert_exception.
	* python/py-cmd.c (cmdpy_init): Use gdbpy_convert_exception.
	* python/py-breakpoint.c (bppy_init): Use
	gdbpy_convert_exception.
2018-12-27 13:34:38 -07:00
Tom Tromey 6987262214 Build gdb "nat" files in subdirectory
This moves the various "nat" object files into the nat/ subdirectory.
This allows for the removal of a pattern rule from the gdb Makefile,
which is a small cleanup.

I made the configure.nat change in a (semi-) automated way, hopefully
meaning that it is more likely to be correct than had I done it by
hand.

Eventually I would like for the various configure scripts to only
mention source files, and let the Makefile compute the object file
names.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* configure.nat (NATDEPFILES): Use nat/ prefix.
	* Makefile.in (CONFIG_SRC_SUBDIR): Add nat.
	(%.o: ${srcdir}/nat/%.c): Remove rule.
	(INIT_FILES): Do not filter out NATDEPFILES.
2018-12-27 13:15:31 -07:00
Tom Tromey b180d0a254 Make init.c depend on source files
I noticed that init.c depends on the object files that go into gdb.
Because init.c actually only requires the contents of the
corresponding source files, this unnecessarily serializes the step
that builds init.c.

This patch changes gdb's Makefile to make init.c depend on the source
files.  This also simplifies the rule to build init.c.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* Makefile.in (INIT_FILES): Redefine.
	(stamp-init): Remove sed, tr invocations.  Use for loop.  Don't
	set LANG or LC_ALL.
2018-12-27 13:15:31 -07:00
Tom Tromey c88c222e3c Remove gdbtypes special case from init.c rule
The rule to make init.c has a special case for gdbtypes, with a long
explanatory comment.  All of this is obsolete, as the globals referred
to by the comment no longer exist.  This patch simplifies the rule.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* Makefile.in (stamp-init): Remove gdbtypes special case.
2018-12-27 13:15:31 -07:00
John Baldwin 47db57fd4e Remove empty nm-fbsd.h header for FreeBSD/i386 native target.
gdb/ChangeLog:

	* config/i386/nm-fbsd.h: Remove file.
	* Makefile.in (HFILES_NO_SRCDIR): Remove config/i386/nm-fbsd.h.
	* configure.nat: Remove NAT_FILE for FreeBSD/i386.
2018-12-27 11:42:32 -08:00
Tom Tromey af9a216102 Use DISABLE_COPY_AND_ASSIGN in minimal_symbol_reader
This changes minimal_symbol_reader to use DISABLE_COPY_AND_ASSIGN,
rather than the manual approach it currently uses.

Tested by rebuilding.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* minsyms.h (class minimal_symbol_reader): Use
	DISABLE_COPY_AND_ASSIGN.
2018-12-27 12:29:48 -07:00
Tom Tromey 075c55e0cc Remove more calls to xfree from Python
This changes the Python code to remove some more calls to xfree, in
favor of self-managing data structures.

Tested on x86-64 Fedora 28.

gdb/ChangeLog
2018-12-27  Tom Tromey  <tom@tromey.com>

	* python/python.c (python_interactive_command): Use std::string.
	(gdbpy_parameter): Likewise.
	* python/py-utils.c (unicode_to_encoded_string): Update comment.
	* python/py-symtab.c (salpy_str): Use PyString_FromFormat.
	* python/py-record-btrace.c (recpy_bt_insn_data): Use
	byte_vector.
	* python/py-objfile.c (objfpy_get_build_id): Use
	unique_xmalloc_ptr.
	* python/py-inferior.c (infpy_read_memory): Use
	unique_xmalloc_ptr.
	* python/py-cmd.c (gdbpy_parse_command_name): Use std::string.
2018-12-27 10:50:43 -07:00
Philippe Waroquiers 293bf1a719 Fix gdb.ada/fun_renaming.exp by using more unique names.
The test fails due to conflict between var 'next' and s-pooloc.adb next:
(gdb) print next(1)
Multiple matches for next
[0] cancel
[1] pack.next (integer) return integer at /bd/home/philippe/gdb/git/binutils-gdb/gdb/testsuite/gdb.ada/fun_renaming/pack.adb:19
[2] system.pool_local.next (system.address) return system.pool_local.acc_address at s-pooloc.adb:151
> FAIL: gdb.ada/fun_renaming.exp: print next(1) (timeout)

Fix by making the names and renamings more unique.

gdb/testsuite/ChangeLog
2018-12-26  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.ada/fun_renaming/pack.ads (Next): Rename to Fun_Rename_Test_Next.
	(Renamed_Next): Rename to Renamed_Fun_Rename_Test_Next.
	gdb.ada/fun_renaming/pack.adb (Next): Rename to Fun_Rename_Test_Next.
	gdb.ada/fun_renaming/fun_renaming.adb (N): Rename to Fun_Rename_Test_N.
	gdb.ada/fun_renaming.exp: Update accordingly.
2018-12-27 10:47:00 +01:00
Philippe Waroquiers 3cf139964e Fix gdb.ada/assign_arr.exp by using more unique names.
The test fails (timeout) due to conflict between var 'input' and s-ststop.adb 'input':
(gdb) print input.u2 := (0.25,0.5,0.75)
Multiple matches for input
[0] cancel
[1] system.strings.stream_ops.storage_array_ops.input (access ada.streams.root_stream_type; system.strings.stream_ops.io_kind; natural) return system.storage_elements.storage_array at s-ststop.adb:127
[2] system.strings.stream_ops.stream_element_array_ops.input (access ada.streams.root_stream_type; system.strings.stream_ops.io_kind; natural) return ada.streams.stream_element_array at s-ststop.adb:127
[3] system.strings.stream_ops.string_ops.input (access ada.streams.root_stream_type; system.strings.stream_ops.io_kind; natural) return string at s-ststop.adb:127
[4] system.strings.stream_ops.wide_string_ops.input (access ada.streams.root_stream_type; system.strings.stream_ops.io_kind; natural) return wide_string at s-ststop.adb:127
[5] system.strings.stream_ops.wide_wide_string_ops.input (access ada.streams.root_stream_type; system.strings.stream_ops.io_kind; natural) return wide_wide_string at s-ststop.adb:127
[6] target_wrapper.input at /bd/home/philippe/gdb/git/info_t/gdb/testsuite/gdb.ada/assign_arr/target_wrapper.ads:24
> FAIL: gdb.ada/assign_arr.exp: print input.u2 := (0.25,0.5,0.75) (timeout)

gdb/testsuite/ChangeLog
2018-12-26  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.ada/assign_arr/target_wrapper.ads (Input): Rename to
	Assign_Arr_Input.
	main_p324_051.adb: Update accordingly.
	gdb.ada/assign_arr.exp: Likewise.
2018-12-27 10:47:00 +01:00
Philippe Waroquiers afcfda091e Improve gdb.ada/rename_subscript_param.exp by using more unique names.
With old compilers, the test fails because no debug info is generated
for 'B' and GDB finds some 'b' in atnat.h:

(gdb) print b
Multiple matches for b
[0] cancel
[1] b at ../sysdeps/ieee754/dbl-64/atnat.h:106
[2] b at ../sysdeps/ieee754/dbl-64/atnat.h:106
[3] b at ../sysdeps/ieee754/dbl-64/atnat.h:106
> FAIL: gdb.ada/rename_subscript_param.exp: print b before changing its value (timeout)

Avoid the timeout by renaming 'b' to rename_subscript_param_b.

Also, change 'before' to 'after' in the gdb_test message that prints
the value after changing it.

The test still fails with old compilers that do not properly
generate debug info for this renaming:
(gdb) print rename_subscript_param_b
No definition of "rename_subscript_param_b" in current context.
(gdb) FAIL: gdb.ada/rename_subscript_param.exp: print rename_subscript_param_b before changing its value

Note: if the compiler would generate the correct debug info, the test should
succeed with the name B.  However, waiting for this fix, changing the name
ensures that the test fails directly, instead of causing a timeout.

2018-12-26  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	PR ada/23381
	* gdb.ada/rename_subscript_param/pkg.adb (B): Rename to
	Rename_Subscript_Param_B.  All users updated.
	gdb.ada/rename_subscript_param.exp: Test names made unique.
	Note that PR ada/23381 is only fully fixed when using a recent
	compiler.
2018-12-27 10:47:00 +01:00
Philippe Waroquiers 2ab54467f8 Fix gdb.ada/packed_array_assign.exp by using more unique names.
The test gdb.ada/packed_array_assign fails due to conflict between component 'w'
and system.dim.mks.w:

(gdb) print pra := ((x => 2, y => 0, w => 17), pr, (x => 7, y => 1, w => 23))
Unknown component name: system.dim.mks.w.
(gdb) FAIL: gdb.ada/packed_array_assign.exp: print pra := ((x => 2, y => 0, w => 17), pr, (x => 7, y => 1, w => 23))

Also, depending on the compiler version, the component w might be reordered
and placed before components x and y.
So, change the component order in the source, so that both an old
compiler (GNATMAKE 6.3.0, gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516)
and a new compiler (GNATMAKE Pro 20.0w (20181210-82), based on gcc 8.2.1)
produce the same component order (checked by using -gnatR3s).

So, update to test the new (more unique) names in the source order.

2018-12-26  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.ada/packed_array_assign/aggregates.ads (Packed_Rec):
	Rename components to Packed_Array_Assign_[X|Y|W].  Place
	component Packed_Array_Assign_W as first component, to ensure
	old and new compilers have the same representation.
	All users updated.
2018-12-27 10:47:00 +01:00
Simon Marchi 84b68c77e7 target.c: Remove struct keyword in range-based for
I get this when compiling with a gcc 6.3.0-based cross-compiler:

  CXX    target.o
/home/simark/src/binutils-gdb/gdb/target.c: In static member function 'static void target_terminal::restore_inferior()':
/home/simark/src/binutils-gdb/gdb/target.c:396:10: error: types may not be defined in a for-range-declaration [-Werror]
     for (struct inferior *inf : all_inferiors ())
          ^~~~~~

Accomodate it by dropping the unnecessary struct keyword.  Actually, I used
"::inferior", otherwise it resolves to the inferior method of the
target_terminal class.

gdb/ChangeLog:

	* target.c (target_terminal::restore_inferior): Remove struct keyword.
2018-12-26 20:14:18 -05:00
Simon Marchi 50794b45a2 Improve "set debug separate-debug-file"
"set debug separate-debug-file" shows which candidates are considered,
when trying to find separate debug info.  But it's not clear if GDB used
a certain candidate, and if not, why not.  This patch adds some
precision:

Before:

  Looking for separate debug info (debug link) for /lib/x86_64-linux-gnu/libc.so.6
    Trying /lib/x86_64-linux-gnu/libc-2.23.so
    Trying /lib/x86_64-linux-gnu/.debug/libc-2.23.so
    Trying /usr/lib/debug//lib/x86_64-linux-gnu/libc-2.23.so

After:

  Looking for separate debug info (debug link) for /lib/x86_64-linux-gnu/libc.so.6
    Trying /lib/x86_64-linux-gnu/libc-2.23.so... no, same file as the objfile.
    Trying /lib/x86_64-linux-gnu/.debug/libc-2.23.so... no, unable to open.
    Trying /usr/lib/debug//lib/x86_64-linux-gnu/libc-2.23.so... yes!

gdb/ChangeLog:

	* build-id.c (build_id_to_debug_bfd): Enhance debug output.
	* symfile.c (separate_debug_file_exists): Likewise.
2018-12-26 11:49:51 -05:00
Andrew Burgess 6f0ffe50c8 gdb: Allow struct fields named double
The 64-bit RISC-V target currently models the floating point registers
as having the following type:

    union riscv_double
    {
        builtin_type_ieee_single float;
        builtin_type_ieee_double double;
    }

Notice the choice of names for the fields of this struct, possibly not
ideal choices, as these are not valid field names in C.  However, this
type is only ever defined within GDB (or in the target description),
and no restriction seems to exist on the field names in that case.

The problem though is that currently:

    (gdb) info registers $ft0
    ft0            {float = 0, double = 0}	(raw 0x0000000000000000)
    (gdb) p $ft0.float
    $1 = 0
    (gdb) p $ft0.double
    A syntax error in expression, near `double'.

We can access the 'float' field, but not the 'double' field.  This is
because the string 'double' is handled differently to the string
'float' in c-exp.y.

In both cases the string '$ft0' is parsed as a VARIABLE expression.

In the 'float' case, the string 'float' becomes a generic NAME token
in 'lex_one_token', which then allows the rule "exp '.' name" to match
and the field name lookup to occur.

The 'double' case is different.  In order to allow parsing of the type
string 'long double', the 'double' string becomes the token
DOUBLE_KEYWORD.  At this point there's no rule to match "exp '.'
DOUBLE_KEYWORD", so we can never lookup the field named 'double'.

We could rename the fields for RISC-V, and maybe that would be the
best solution.  However, its not hard to allow for fields named
'double', which is what this patch does.

A new case is added to the 'field_name' rule to match the
DOUBLE_KEYWORD, and create a suitable 'struct stoken'.  With this done
the "exp '.'  field_name" pattern can now match, and we can lookup the
double field.

With this patch in place I now see this behaviour:

    (gdb) info registers $ft0
    ft0            {float = 0, double = 0}	(raw 0x0000000000000000)
    (gdb) p $ft0.float
    $1 = 0
    (gdb) p $ft0.double
    $2 = 0

I've gone ahead and handled INT_KEYWORD, LONG, SHORT, SIGNED_KEYWORD,
and UNSIGNED as well within field_name.

I've added a new test for this functionality.

This change was tested on x86-64 GNU/Linux with no regressions.

gdb/ChangeLog:

	* c-exp.y (field_name): Allow DOUBLE_KEYWORD, INT_KEYWORD, LONG,
	SHORT, SIGNED_KEYWORD, and UNSIGNED tokens to act as a field
	names.
	(typename_stoken): New function.

gdb/testsuite/ChangeLog:

	* gdb.dwarf2/dw2-unusual-field-names.c: New file.
	* gdb.dwarf2/dw2-unusual-field-names.exp: New file.
2018-12-24 17:25:25 +00:00
Andrew Burgess 0f5d3f636a gdb: Add new parser rule for structure field names
Introduces a new rule in c-exp.y for matching structure field names.

This is a restructure in preparation for the next commit, this commit
shouldn't result in any user visible changes.

gdb/ChangeLog:

	* c-exp.y (field_name): New %token, and new rule.
	(exp): Replace uses of 'name' with 'field_name' where appropriate.
2018-12-24 17:25:25 +00:00
Andrew Burgess b6c95c0cc5 gdb: Extend the comments in c-exp.y
In an attempt to fix PR gdb/13368 this commit adds some comments to
c-exp.y which hopefully makes the type parsing code a little clearer.
There are no code changes here, so there should be no user visible
changes after this commit.

gdb/ChangeLog:

	PR gdb/13368
	* c-exp.y (typebase): Extend the comment.
	(ident_tokens): Likewise.
2018-12-24 17:25:25 +00:00
Tom Tromey 45b8ae0c33 Simplify dwarf2_find_containing_comp_unit
In an earlier patch discussion we noticed that
dwarf2_find_containing_comp_unit takes the address of sect_off, but
doesn't actually need to.  This is a leftover from before
C++-ification.  This patch simplifies the function.

Tested using gdb.dwarf2 on x86-64 Fedora 28.

gdb/ChangeLog
2018-12-18  Tom Tromey  <tom@tromey.com>

	* dwarf2read.c (dwarf2_find_containing_comp_unit): Don't take
	address of sect_off.
2018-12-24 09:58:53 -07:00
Philippe Waroquiers b5a1e55720 Fix gdb.ada bp_fun_addr failure due to conflict between fun 'a' and s-dimmks.ads 'A'.
The test fails (timeout) due to:
  (gdb) PASS: gdb.ada/bp_fun_addr.exp: break *a'address
  run
  Starting program: /bd/home/philippe/gdb/git/build_info_t/gdb/testsuite/outputs/gdb.ada/bp_fun_addr/a
  Multiple matches for a
  [0] cancel
  [1] a at /bd/home/philippe/gdb/git/info_t/gdb/testsuite/gdb.ada/bp_fun_addr/a.adb:18
  [2] system.dim.mks.a at s-dimmks.ads:115
  > FAIL: gdb.ada/bp_fun_addr.exp: run until breakpoint at a'address (timeout)
  testcase /home/philippe/gdb/git/build_info_t/gdb/testsuite/../../../info_t/gdb/testsuite/gdb.ada/bp_fun_addr.exp completed in 10 seconds

Fix this by using a fun name that has more chances to be unique.

2018-12-24  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.ada/bp_fun_addr/a.adb (a): Rename to bp_fun_addr.
	Filename a.adb changed to bp_fun_addr.adb.
	gdb.ada/bp_fun_addr.exp: Update test accordingly.
2018-12-24 13:11:12 +01:00
Joel Brobecker 03eccf7a34 Document the GDB 8.2.1 release in gdb/ChangeLog
gdb/ChangeLog:

	GDB 8.2.1 released.
2018-12-23 10:02:17 +04:00
Andrew Burgess 74e3300d8a gdb/riscv: Prevent buffer overflow in riscv_return_value
The existing code for reading and writing the return value can
overflow the passed in buffers in a couple of situations.  This commit
aims to resolve these issues.

The problems were detected using valgrind, here are two examples,
first from gdb.base/structs.exp:

    (gdb) p/x fun9()
    ==31353== Invalid write of size 8
    ==31353==    at 0x4C34153: memmove (vg_replace_strmem.c:1270)
    ==31353==    by 0x632EBB: memcpy (string_fortified.h:34)
    ==31353==    by 0x632EBB: readable_regcache::raw_read(int, unsigned char*) (regcache.c:538)
    ==31353==    by 0x659D3F: riscv_return_value(gdbarch*, value*, type*, regcache*, unsigned char*, unsigned char const*) (riscv-tdep.c:2593)
    ==31353==    by 0x583641: get_call_return_value (infcall.c:448)
    ==31353==    by 0x583641: call_thread_fsm_should_stop(thread_fsm*, thread_info*) (infcall.c:546)
    ==31353==    by 0x59BBEC: fetch_inferior_event(void*) (infrun.c:3883)
    ==31353==    by 0x53890B: check_async_event_handlers (event-loop.c:1064)
    ==31353==    by 0x53890B: gdb_do_one_event() [clone .part.4] (event-loop.c:326)
    ==31353==    by 0x6CA34B: wait_sync_command_done() (top.c:503)
    ==31353==    by 0x584653: run_inferior_call (infcall.c:621)
    ...

And from gdb.base/call-sc.exp:

    (gdb) advance fun
    fun () at /gdb/gdb/testsuite/gdb.base/call-sc.c:41
    41	  return foo;
    (gdb) finish
    ==1968== Invalid write of size 8
    ==1968==    at 0x4C34153: memmove (vg_replace_strmem.c:1270)
    ==1968==    by 0x632EBB: memcpy (string_fortified.h:34)
    ==1968==    by 0x632EBB: readable_regcache::raw_read(int, unsigned char*) (regcache.c:538)
    ==1968==    by 0x659D01: riscv_return_value(gdbarch*, value*, type*, regcache*, unsigned char*, unsigned char const*) (riscv-tdep.c:2576)
    ==1968==    by 0x5891E4: get_return_value(value*, type*) (infcmd.c:1640)
    ==1968==    by 0x5892C4: finish_command_fsm_should_stop(thread_fsm*, thread_info*) (infcmd.c:1808)
    ==1968==    by 0x59BBEC: fetch_inferior_event(void*) (infrun.c:3883)
    ==1968==    by 0x53890B: check_async_event_handlers (event-loop.c:1064)
    ==1968==    by 0x53890B: gdb_do_one_event() [clone .part.4] (event-loop.c:326)
    ==1968==    by 0x6CA34B: wait_sync_command_done() (top.c:503)
    ...

There are a couple of problems with the existing code, that are all
related.

In riscv_call_arg_struct we incorrectly rounded up the size of a
structure argument.  This is unnecessary, and caused GDB to read too
much data into the output buffer when extracting a struct return
value.

In fixing this it became clear that we were incorrectly assuming that
any value being placed in a register (or read from a register) would
always access the entire register.  This is not true, for example a
9-byte struct on a 64-bit target places 8-bytes in one registers and
1-byte in a second register (assuming available registers).  To handle
this I switch from using cooked_read to cooked_read_part.

Finally, when processing basic integer return value types these are
extended to xlen sized types and then passed in registers.  We
currently don't handle this type expansion in riscv_return_value, but
we do in riscv_push_dummy_call.  The result is that small integer
types (like char) result in a full xlen sized register being written
into the output buffer, which results in buffer overflow.  To address
this issue we now create a value of the expanded type and use this
values contents buffer to hold the return value before casting the
value down to the smaller expected type.

This patch resolves all of the valgrind issues I have found so far,
and causes no regressions.  Tested against RV32/64 with and without
floating point support.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_call_arg_struct): Don't adjust size before
	assigning locations.
	(riscv_return_value): Take more care not to read/write outside of
	argument buffer.  Cast return value between the declared type and
	the abi type.
2018-12-22 10:06:50 +00:00
Andrew Burgess ecc82c0590 gdb/riscv: Add float status registers to save and restore reggroups
We should save and restore the floating point status registers.  This
became an issue when testing 32-bit float on a target with 64-bit with
the gdb.base/callfuncs.exp test.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_register_reggroup_p): Save and restore fcsr,
	fflags, and frm registers.
2018-12-22 10:02:20 +00:00
Andrew Burgess fb44d95af6 gdb/riscv: Add gdb to dwarf register number mapping
Provide a mapping between GDB's register numbers and DWARF's register
numbers.  This resolves some failures that I was seeing on
gdb.base/store.exp when running on an rv64imfdc target.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_dwarf_reg_to_regnum): New function.
	(riscv_gdbarch_init): Register new function with gdbarch.
	* riscv-tdep.h: New enum to define RISC-V DWARF register numbers.
2018-12-22 10:02:20 +00:00
Simon Marchi e08b849efa Add debug output for recorded minsyms
While discussing this issue:

  https://sourceware.org/ml/gdb-patches/2018-12/threads.html#00082

I added a printf gated by "set debug symtab-create" to be able to
quickly see all minimal symbols recorded by GDB.  I thought it would be
useful to have it built-in, for the future.  Here's how the output
looks:

  Recording minsym:  mst_data                         0x400780    15  _IO_stdin_used
  Recording minsym:  mst_text                         0x400700    13  __libc_csu_init
  Recording minsym:  mst_bss                          0x601058    25  _end

gdb/ChangeLog:

	* minsyms.c (mst_str): New.
	(minimal_symbol_reader::record_full): Add debug output.
2018-12-21 21:19:18 -05:00
Jan Vrany 6e8b1ab2fd Fix various tests to use -no-pie linker flag when needed
Various tests use test code written in i386 / x86_64 assembly that cannot
be used to create PIE executables. Therefore compilation of test programs
failed on systems where the compiler default is to create PIE executable.

The solution is to use -no-pie linker flag, however, such flag may not
(is not) supported by all compilers GDB needs to support (e.g. gcc 4.8).
To handle this, introduce a new flag to gdb_compile - nopie - which
inserts -no-pie linker flag where supported and is no-op where it is
not. By default, -no-pie flag is inserted since most modern compiler do
support it.
2018-12-21 15:53:08 -05:00
John Baldwin 6d78332e77 Workaround a FreeBSD kernel bug resulting in spurious SIGTRAP events.
The ptrace command PT_LWPINFO to request detailed information about a
stopped thread can return stale signal information from an earlier
stop.  Events which are reporting an intercepted signal will always
report the correct information, but signal stops for some other events
such as system call enter/exit events might include stale siginfo from
an earlier signal.  In particular, if a thread reports a system call
entry or exit event after previously reporting a single-step or
breakpoint event via SIGTRAP, fbsd_handle_debug_trap believed the
system call event was the previous event and claimed it resulting in a
spurious SIGTRAP event.

True breakpoint and single-step events will never report another event
in the pl_flags member of struct ptrace_lwpinfo.  Use this to detect
stale siginfo by requiring pl_flags to have only the PL_FLAG_SI flag
and no other flags before treating a SIGTRAP as a single-step or
breakpoint trap.

gdb/ChangeLog:

	* fbsd-nat.c (fbsd_handle_debug_trap): Require pl.pl_flags to
	equal PL_FLAG_SI.
	(fbsd_nat_target::stopped_by_sw_breakpoint): Likewise.
2018-12-21 10:18:11 -08:00
Paul Marechal d00a27c5ad gdb: Fix "info os <unknown>" command
Running `info os someUnknownOsType` is crashing when gdb is built with
-D_GLIBCXX_DEBUG:

	/usr/include/c++/5/debug/vector:439:error: attempt to
	access an element in an empty container.

In target_read_stralloc from target.c, the call to
target_read_alloc_1 can return an empty vector, we then call vector::back on
this vector, which is invalid.

This commit adds a check for emptiness before trying to call
vector::back on it. It also adds test to check for `info os <unknown>`
to return the proper error message.

This is a regression in gdb 8.2 and this patch restores the behavior of
previous versions.

gdb/ChangeLog:

	PR gdb/23974
	* target.c (target_read_stralloc): Check for empty vector.

gdb/testsuite/ChangeLog:

	PR gdb/23974
	* gdb.base/info-os.exp: Check return for unknown "info os" type.
2018-12-21 13:04:43 -05:00
Дилян Палаузов 50c7c5b8df when printing the GDB config, explicitly say if configured without python
When using the --configuration command line switch, or using
the "show configuration" command with a version of GDB which
was configured without Python supoprt, this patch changes
the resulting output to include...

    --without-python

... instead of not printing anything about Python support.

gdb/ChangeLog:

        * top.c (print_gdb_configuration): Print "--without-python"
        if GDB was configured without Python.

Tested on x86_64-linux by rebuilding GDB with and without Python,
and checking the output of "gdb --configuration" in both cases.
2018-12-21 21:59:09 +04:00
Andrew Burgess a96bd1ccc0 gdb/riscv: Format CORE_ADDR as a string for printing
Avoid compiler errors caused by trying to print CORE_ADDR using '%ld'
format, instead convert to a string and print that instead.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_scan_prologue): Use plongest to format
	a signed offset as a string.
2018-12-21 17:06:27 +00:00
Dave Murphy 3dcfdc5865 Fix compile error with clang 3.8
When compiling with clang 3.8 (default clang version on Debian
Stretch, the current stable), we get errors like this:

  CXX    dtrace-probe.o
../../binutils-gdb/gdb/dtrace-probe.c:103:31: error: default initialization of an object of const type 'const dtrace_static_probe_ops' without a user-provided default constructor
const dtrace_static_probe_ops dtrace_static_probe_ops;
                              ^

Silence them by value-initializing those objects.  It's not necessary
with other compilers (later clang versions, gcc), but it shouldn't
hurt either.
2018-12-21 11:45:16 -05:00
Philippe Waroquiers 161d081c56 Ensure deterministic result order in gdb.ada/info_auto_lang.exp
standard_ada_testfile, standard_test_file and the explicit
csrcfile assignment in info_auto_lang.exp all gives similar pathnames
prefix for a source, such as
/home/philippe/gdb/git/build_binutils-gdb/gdb/testsuite/../../../binutils-gdb/gdb/testsuite/gdb.<something>.

Note that the above pathnames contain ../ which appears when a relative
pathname is used to call configure.

In any case, the gnat compiler normalizes Ada sources path when compiling.
So, the 'Ada' .o object are referencing a pathname such as
/home/philippe/gdb/git/binutils-gdb/gdb/testsuite/gdb.ada/info_auto_lang/proc_in_ada.adb,
while the 'C' .o object still references the not normalized pathname.

As the results of 'info functions | ...' are sorted by pathname first,
the order of the results depends on the comparison between different directories,
leading to results that can change depending on these directories.

=> Ensure the result order is always the same, by normalising the C source file,
which makes the results independent of the way configure is launched.

Tested by running the testcase in 2 different builds, that without normalize
were giving different results.

Note: such 'set csrcfile' is used in 4 other tests mixing Ada and C.
After discussion, it was deemed sufficient to just normalize the pathname
for this test.

gdb/testsuite/ChangeLog
2018-12-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.ada/info_auto_lang.exp: Normalize some_c source file.
	Update order of results accordingly.
2018-12-20 21:52:31 +01:00
Andrew Burgess 8bcb520897 gdb: Add default frame methods to gdbarch
Supply default gdbarch methods for gdbarch_dummy_id,
gdbarch_unwind_pc, and gdbarch_unwind_sp.  This patch doesn't actually
convert any targets to use these methods, and so, there will be no
user visible changes after this commit.

The implementations for default_dummy_id and default_unwind_sp are
fairly straight forward, these just take on the pattern used by most
targets.  Once these default methods are in place then most targets
will be able to switch over.

The implementation for default_unwind_pc is also fairly straight
forward, but maybe needs some explanation.

This patch has gone through a number of iterations:

  https://sourceware.org/ml/gdb-patches/2018-03/msg00165.html
  https://sourceware.org/ml/gdb-patches/2018-03/msg00306.html
  https://sourceware.org/ml/gdb-patches/2018-06/msg00090.html
  https://sourceware.org/ml/gdb-patches/2018-09/msg00127.html

and the implementation of default_unwind_pc has changed over this
time.  Originally, I took an implementation like this:

    CORE_ADDR
    default_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
    {
      int pc_regnum = gdbarch_pc_regnum (gdbarch);
      return frame_unwind_register_unsigned (next_frame, pc_regnum);
    }

This is basically a clone of default_unwind_sp, but using $pc.  It was
pointed out that we could potentially do better, and in version 2 the
implementation became:

    CORE_ADDR
    default_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
    {
      struct type *type;
      int pc_regnum;
      CORE_ADDR addr;
      struct value *value;

      pc_regnum = gdbarch_pc_regnum (gdbarch);
      value = frame_unwind_register_value (next_frame, pc_regnum);
      type = builtin_type (gdbarch)->builtin_func_ptr;
      addr = extract_typed_address (value_contents_all (value), type);
      addr = gdbarch_addr_bits_remove (gdbarch, addr);
      release_value (value);
      value_free (value);
      return addr;
    }

The idea was to try split out some of the steps of unwinding the $pc,
steps that are on some (or many) targets no-ops, and so allow targets
that do override these methods, to make use of default_unwind_pc.

This implementation remained in place for version 2, 3, and 4.

However, I realised that I'd made a mistake, most targets simply use
frame_unwind_register_unsigned to unwind the $pc, and this throws an
error if the register value is optimized out or unavailable.  My new
proposed implementation doesn't do this, I was going to end up
breaking many targets.

I considered duplicating the code from frame_unwind_register_unsigned
that throws the errors into my new default_unwind_pc, however, this
felt really overly complex.  So, what I instead went with was to
simply revert back to using frame_unwind_register_unsigned.  Almost
all existing targets already use this. Some of the ones that don't can
be converted to, which means almost all targets could end up using the
default.

One addition I have made over the version 1 implementation is to add a
call to gdbarch_addr_bits_remove.  For most targets this is a no-op,
but for a handful, having this call in place will mean that they can
use the default method.  After all this, the new default_unwind_pc now
looks like this:

    CORE_ADDR
    default_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
    {
      int pc_regnum = gdbarch_pc_regnum (gdbarch);
      CORE_ADDR pc = frame_unwind_register_unsigned (next_frame, pc_regnum);
      pc = gdbarch_addr_bits_remove (gdbarch, pc);
      return pc;
    }

gdb/ChangeLog:

	* gdb/dummy-frame.c (default_dummy_id): Defined new function.
	* gdb/dummy-frame.h (default_dummy_id): Declare new function.
	* gdb/frame-unwind.c (default_unwind_pc): Define new function.
	(default_unwind_sp): Define new function.
	* gdb/frame-unwind.h (default_unwind_pc): Declare new function.
	(default_unwind_sp): Declare new function.
	* gdb/frame.c (frame_unwind_pc): Assume gdbarch_unwind_pc is
	available.
	(get_frame_sp): Assume that gdbarch_unwind_sp is available.
	* gdb/gdbarch.c: Regenerate.
	* gdb/gdbarch.h: Regenerate.
	* gdb/gdbarch.sh: Update definition of dummy_id, unwind_pc, and
	unwind_sp.  Add additional header files to be included in
	generated file.
2018-12-19 20:59:38 +00:00
Dimitar Dimitrov 7406a50077 Fix build with latest GCC 9.0 tree
A recent patch [1] to fix a GCC PR [2] actually broke the GDB build.
To fix, remove the stack pointer clobber. GCC will ignore the clobber
marker, and will not save or restore the stack pointer.

I ran "make check-gdb" on x86_64 to ensure there are no regressions.

gdb/ChangeLog:

2018-12-17  Dimitar Dimitrov  <dimitar@dinux.eu>

	* nat/linux-ptrace.c (linux_ptrace_test_ret_to_nx): Remove sp clobbers.

[1] https://gcc.gnu.org/ml/gcc-patches/2018-12/msg00532.html
[2] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52813

Signed-off-by: Dimitar Dimitrov <dimitar@dinux.eu>
2018-12-19 10:44:23 -05:00
Andrew Burgess 9068261f1c gdb/dwarf: Convert some predicates from int to bool
In the dwarf reader we have a set of predicates, these include the
different producer predicates and also some control predicates. The
older ones are declared as integers, while newer ones (added since the
C++ conversion) are bool.

This commit makes them all bool for consistency.  There should be no
user visible change after this commit.

gdb/ChangeLog:

	* dwarf2read.c (struct dwarf2_cu): Convert the fields 'mark',
	'has_loclist', 'checked_producer', 'producer_is_gxx_lt_4_6',
	'producer_is_gcc_lt_4_3', 'producer_is_icc_lt_14',
	'processing_has_namespace_info' from unsigned int to bool.  Update
	comments.
	(producer_is_icc_lt_14): Update return type.
	(producer_is_gcc_lt_4_3): Likewise.
	(producer_is_gxx_lt_4_6): Likewise.
	(process_die): Write true instead of 1 into predicate fields.
	(dwarf2_start_symtab): Likewise.
	(var_decode_location): Likewise.
	(dwarf2_mark_helper): Likewise.
	(dwarf2_mark): Likewise.
	(dwarf2_clear_marks): Write false instead of 0 into predicate
	field.
	(dwarf2_cu::dwarf2_cu): Initialise predicate fields to false, not
	0.
2018-12-17 23:36:05 +00:00
Szabolcs Nagy 51b4f73a37 AArch64: Fix the gdb build with musl libc
Including asm/sigcontext.h together with libc headers is not valid. In
general linux headers may not work with libc headers, so mixing them
should be avoided, especially when the linux header defines types that
are also exposed in libc headers.

In case of asm/sigcontext.h glibc happens to work because glibc signal.h
directly includes it, but e.g. in musl libc signal.h replicates the
sigcontext.h definitions in an abi compatible way which are in conflict
with the linux definitions when both headers are included.

Since old linux headers or old libc headers may not have the necessary
definitions, gdb has to replicate the definitions it relies on anyway.
Which is fine since all definitions must be ABI stable. For linux apis
that are not available via libc headers, replicating the definitions in
gdb is the most reliable way to use them.

Note: asm/ptrace.h includes asm/sigcontext.h in some versions of linux
headers, which is just as problematic and should be fixed in linux.

gdb/ChangeLog:

	* nat/aarch64-sve-linux-ptrace.h: Include signal.h instead of
	asm/sigcontext.h.
2018-12-17 10:34:26 +00:00
Philippe Waroquiers 4ef5dbe493 OBVIOUS: Fix ARI warning by removing warning trailing new line
2018-12-17  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* nat/linux-ptrace.c (kill_child): Fix ARI warning by removing
	warning trailing new line.
2018-12-17 06:52:15 +01:00
Philippe Waroquiers a65f68357f Factorize killing the children in linux-ptrace.c, and fix a 'process leak'.
Running the gdb testsuite under Valgrind started to fail after 100+ tests,
due to out of memory caused by lingering processes.

The lingering processes are caused by the combination
of a limitation in Valgrind signal handling when using PTRACE_TRACEME
and a (minor) bug in GDB.

The Valgrind limitation is : when a process is ptraced and raises
a signal, Valgrind will replace the raised signal by SIGSTOP as other
signals are masked by Valgrind when executing a system call.
Removing this limitation seems far to be trivial, valgrind signal
handling is very complex.

Due to this valgrind limitation, GDB linux_ptrace_test_ret_to_nx gets
a SIGSTOP signal instead of the expected SIGTRAP or SIGSEGV.
In such a case, linux_ptrace_test_ret_to_nx does an early return, but
does not kill the child (running under valgrind), child stays in a STOP-ped
state.
These lingering processes then eat the available system memory,
till launching a new process starts to fail.

This patch fixes the GDB minor bug by killing the child in case
linux_ptrace_test_ret_to_nx does an early return.

nat/linux-ptrace.c has 3 different logics to kill a child process.
So, this patch factorizes killing a child in the function kill_child.

The 3 different logics are:
* linux_ptrace_test_ret_to_nx is calling both kill (child, SIGKILL)
  and ptrace (PTRACE_KILL, child, ...), and then is calling once
  waitpid.
* linux_check_ptrace_features is calling ptrace (PTRACE_KILL, child, ...)
  + my_waitpid in a loop, as long as the waitpid status was WIFSTOPPED.
* linux_test_for_tracefork is calling once ptrace (PTRACE_KILL, child, ...)
  + my_waitpid.

The linux ptrace documentation indicates that PTRACE_KILL is deprecated,
and tells to not use it, as it might return success but not kill the tracee.
The documentation indicates to send SIGKILL directly.

I suspect that linux_ptrace_test_ret_to_nx calls both kill and ptrace just
to be sure ...
I suspect that linux_check_ptrace_features calls ptrace in a loop
to bypass the PTRACE_KILL limitation.
And it looks like linux_test_for_tracefork does not handle the PTRACE_KILL
limitation.
Also, 2 of the 3 logics are calling my_waitpid, which seems better,
as this is protecting the waitpid syscall against EINTR.

So, the logic in kill_child is just using kill (child, SIGKILL)
+ my_waitpid, and then does a few verifications to see everything worked
accordingly to the plan.

Tested on Debian/x86_64.

2018-12-16  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* nat/linux-ptrace.c (kill_child): New function.
	(linux_ptrace_test_ret_to_nx): Use kill_child instead of local code.
	Add a call to kill_child in case of early return after fork.
	(linux_check_ptrace_features): Use kill_child instead of local code.
	(linux_test_for_tracefork): Likewise.
2018-12-16 21:24:29 +01:00
Tom Tromey 7ff6138b00 Minor gdb/Makefile.in cleanups
This removes an IMO not very useful comment in gdb/Makefile.in about
"alloca".  It also removes INFOFILES, which I think probably has not
been useful since whenever the manual was moved into a subdirectory.

gdb/ChangeLog
2018-12-14  Tom Tromey  <tom@tromey.com>

	* Makefile.in: Remove "alloca" comment.
	(INFOFILES): Remove.
	(local-maintainer-clean): Don't use INFOFILES.
2018-12-14 18:58:32 -07:00
John Baldwin 64fdde094a Update the FreeBSD system call table to match FreeBSD 12.0.
Add a script to generate the FreeBSD XML system call table from the
sys/sys/syscall.h file in the kernel source tree.  For ABI
compatiblity system calls used by older binaries (such as
freebsd11_kevent()), the original system call name is used as an
alias.

Run this script against the current syscall.h file in FreeBSD's head
branch which is expected to be the file used in 12.0 (head is
currently in code freeze as part of the 12.0 release process).

gdb/ChangeLog:

	* syscalls/update-freebsd.sh: New file.
	* syscalls/freebsd.xml: Regenerate.
2018-12-13 11:36:42 -08:00
John Baldwin e9076973c8 Add an optional "alias" attribute to syscall entries.
When setting a syscall catchpoint by name, catch syscalls whose name
or alias matches the requested string.

When the ABI of a system call is changed in the FreeBSD kernel, this
is implemented by leaving a compatibility system call using the old
ABI at the existing "slot" and allocating a new system call for the
version using the new ABI.  For example, new fields were added to the
'struct kevent' used by the kevent() system call in FreeBSD 12.  The
previous kevent() system call in FreeBSD 12 kernels is now called
freebsd11_kevent() and is still used by older binaries compiled
against the older ABI.  The freebsd11_kevent() system call can be
tagged with an "alias" attribute of "kevent" permitting 'catch syscall
kevent' to catch both system calls and providing the expected user
behavior for both old and new binaries.  It also provides the expected
behavior if GDB is compiled on an older host (such as a FreeBSD 11
host).

gdb/ChangeLog:

	* NEWS: Add entry documenting system call aliases.
	* break-catch-syscall.c (catch_syscall_split_args): Pass 'result'
	to get_syscalls_by_name.
	* gdbarch.sh (UNKNOWN_SYSCALL): Remove.
	* gdbarch.h: Regenerate.
	* syscalls/gdb-syscalls.dtd (syscall): Add alias attribute.
	* xml-syscall.c [!HAVE_LIBEXPAT] (get_syscalls_by_name): Rename
	from get_syscall_by_name.  Now accepts a pointer to a vector of
	integers and returns a bool.
	[HAVE_LIBEXPAT] (struct syscall_desc): Add alias member.
	(syscall_create_syscall_desc): Add alias parameter and pass it to
	syscall_desc constructor.
	(syscall_start_syscall): Handle alias attribute.
	(syscall_attr): Add alias attribute.
	(xml_get_syscalls_by_name): Rename from xml_get_syscall_number.
	Now accepts a pointer to a vector of integers and returns a
	bool.  Add syscalls whose alias or name matches the requested
	name.
	(get_syscalls_by_name): Rename from get_syscall_by_name.  Now
	accepts a pointer to a vector of integers and returns a bool.
	* xml-syscall.h (get_syscalls_by_name): Likewise.

gdb/doc/ChangeLog:

	* gdb.texinfo (Set Catchpoints): Add an anchor for 'catch syscall'.
	(Native): Add a FreeBSD subsection.
	(FreeBSD): Document use of system call aliases for compatibility
	system calls.
2018-12-13 11:36:42 -08:00
John Baldwin 4794efbfdc Change get_syscalls_by_group to append to an existing vector of integers.
This removes the need for the caller to explicitly manage the memory
for the returned system call list.  The sole caller only needed the
system call numbers rather than the full syscall structures.

get_syscalls_by_group now uses a boolean return value to indicate if
the requested group exists.

gdb/ChangeLog:

	* break-catch-syscall.c (catch_syscall_split_args): Pass 'result'
	to get_syscalls_by_group.
	* xml-syscall.c [!HAVE_LIBEXPAT] (get_syscalls_by_group): Return
	false.
	[HAVE_LIBEXPAT] (xml_list_syscalls_by_group): Append syscall
	numbers to an existing vector of integers and return a bool.
	(get_syscalls_by_group): Accept pointer to vector of integers
	and change return type to bool.
	* xml-syscall.h (get_syscalls_by_group): Likewise.
2018-12-13 11:36:42 -08:00
Jim Wilson b7c8601a7f RISC-V: Correct printing of MSTATUS and MISA.
* riscv-tdep.c (riscv_print_one_register_info): For MSTATUS, add
	comment for SD field, and correct xlen calculation.  For MISA, add
	comment for MXL field, add call to register_size, and correct base
	calculation.
2018-12-13 10:48:23 -08:00
Stafford Horne 66ac1ae906 gdb: Update NEWS for OpenRISC Linux support
gdb/ChangeLog:

	* NEWS(New targets): Add or1k*-*-linux*.
2018-12-13 06:06:12 +09:00
Philippe Waroquiers c8749e5810 OBVIOUS: Forward declare linux_xfer_osdata_info_os_types on one line to fix ARI warning.
2018-12-12  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* nat/linux-osdata.c (linux_xfer_osdata_info_os_types): Forward
	declare on one line to fix ARI warning.
2018-12-12 21:14:48 +01:00
Andrew Burgess b001de2320 gdb: Update test pattern to deal with native-extended-gdbserver
When running the test gdb.base/annota1.exp with:

  make check-gdb RUNTESTFLAGS="--target_board=native-extended-gdbserver gdb.base/annota1.exp"

I would see a failure due to some unexpected lines in GDB's output.
The extra lines (when compared with a native run) were about file
transfer from the remote back to GDB.

This commit extends the regexp for this test to allow for these extra
lines, and also splits the rather long regexp up into a list of parts.

With this change in place I see no failures for gdb.base/annota1.exp
when using the native-extended-gdbserver target board, nor with a
native run on X86-64/Linux.

gdb/testsuite/ChangeLog:

	* gdb.base/annota1.exp: Update a test regexp.
2018-12-12 17:33:52 +00:00
Andrew Burgess 6bf78e29a1 gdb/infcall: Make infcall_suspend_state into a class
I ran into a situation where attempting to make an inferior function
call would trigger an assertion, like this:

    (gdb) call some_inferior_function ()
    ../../src/gdb/regcache.c:310: internal-error: void regcache::restore(readonly_detached_regcache*): Assertion `src != NULL' failed.
    A problem internal to GDB has been detected,
    further debugging may prove unreliable.
    Quit this debugging session? (y or n)

The problem that triggers the assertion is that in the function
save_infcall_suspend_state, we basically did this:

    1. Create empty infcall_suspend_state object.
    2. Fill fields of infcall_suspend_state object.

The problem is causes is that if filling any of the fields triggered
an exception then the infcall_suspend_state object would be deleted
while in a partially filled in state.

In the specific case I encountered, I had a remote RISC-V target that
claimed in its target description to support floating point registers.
However, this was not true, and when GDB tried to read a floating
point register the remote sent back an error.  This error would cause
an exception to be thrown while creating the
readonly_detached_regcache, which in turn caused GDB to try and delete
an infcall_suspend_state which didn't have any register state, and
this triggered the assertion.

To prevent this problem we have two possibilities, either, rewrite the
restore code the handle partially initialised infcall_suspend_state
objects, or, prevent partially initialised infcall_suspend_state
objects from existing.  The second of these seems like a better
solution.

So, in this patch, I move the filling in of the different
infcall_suspend_state fields within a new constructor for
infcall_suspend_state.  Now, if generating one of those fields fails
the destructor for infcall_suspend_state will not be executed and GDB
will not try to restore the partially saved state.

With this patch in place GDB now behaves like this:

    (gdb) call some_inferior_function ()
    Could not fetch register "ft0"; remote failure reply 'E99'
    (gdb)

The inferior function call is aborted due to the error.

This has been tested against x86-64/Linux native, native-gdbserver,
and native-extended-gdbserver with no regressions.  I've manually
tested this against my baddly behaving target and confirmed the
inferior function call is aborted as described above.

gdb/ChangeLog:

	* infrun.c (infcall_suspend_state::infcall_suspend_state): New.
	(infcall_suspend_state::registers): New.
	(infcall_suspend_state::restore): New.
	(infcall_suspend_state::thread_suspend): Rename to...
	(infcall_suspend_state::m_thread_suspend): ...this.
	(infcall_suspend_state::registers): Rename to...
	(infcall_suspend_state::m_registers): ...this.
	(infcall_suspend_state::siginfo_gdbarch): Rename to...
	(infcall_suspend_state::m_siginfo_gdbarch): ...this.
	(infcall_suspend_state::siginfo_data): Rename to...
	(infcall_suspend_state::m_siginfo_data): ...this.
	(save_infcall_suspend_state): Rewrite to use infcall_suspend_state
	constructor.
	(restore_infcall_suspend_state): Rewrite to use
	infcall_suspend_state::restore method.
	(get_infcall_suspend_state_regcache): Use
	infcall_suspend_state::registers method.
2018-12-12 17:33:14 +00:00
Andrew Burgess 4de3d8d066 gdb/riscv: Handle passing variadic floating point arguments
This commit fixes some test failures in gdb.base/varargs.exp when
running on targets with floating point hardware.  Floating point
unnamed (variadic) arguments should be passed in integer registers
according to the abi.

After this commit I see no failures in gdb.base/varargs.exp on 32 or
64 bit targets with floating point hardware.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_call_arg_scalar_float): Unnamed (variadic)
	arguments are passed in integer registers.
	(riscv_call_arg_complex_float): Likewise.
2018-12-12 14:21:31 +00:00
Philippe Waroquiers 750b258ef8 Fix leaks in all the linux osdata annex transfers + code factorization.
Valgrind reports leaks in all linux osdata annex transfers of linux-osdata.c.

A typical leak (this one is of gdb.base/info-os) is:
==10592== VALGRIND_GDB_ERROR_BEGIN
==10592== 65,536 bytes in 1 blocks are definitely lost in loss record 3,175 of 3,208
==10592==    at 0x4C2E273: realloc (vg_replace_malloc.c:826)
==10592==    by 0x409B0C: xrealloc (common-utils.c:62)
==10592==    by 0x408BC3: buffer_grow(buffer*, char const*, unsigned long) [clone .part.1] (buffer.c:40)
==10592==    by 0x5263DF: linux_xfer_osdata_processes(unsigned char*, unsigned long, unsigned long) (linux-osdata.c:370)
==10592==    by 0x520875: linux_nat_xfer_osdata (linux-nat.c:4214)
...

The leaks are created because the linux_xfer_osdata_* functions
transfer the ownership of their 'static struct buffer' memory
to their 'static char *buf' local var, but then call buffer_free
instead of xfree-ing buf.

I see no reason why the ownership of the memory has to be transferred
from a local var to another local var, so the fix consists in dropping
the 'static char *buf' and accessing the struct buffer memory where needed.

Also, because this bug was replicated in all functions, and there was
a non neglectible amount of duplicated code, the setup and usage
of the 'static struct buffer' is factorized in a new function
common_getter.  The buffer for a specific annex is now a member
of the struct osdata_type instead of being a static var of each
linux_xfer_osdata_* function.

Thanks to this, all the linux_xfer_osdata_* do not have
anymore any logic related to the partial transfer of data: they now
only build the xml data in a struct buffer.
This all removes about 300 SLOC.

Note: git diff/git format-patch shows a lot of differences only due
to space changes/indentation changes.
So, git diff -w helps to look only at the relevant differences.

gdb/ChangeLog
2018-12-11  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* nat/linux-osdata.c (common_getter): New function.
	(struct osdata_type): Change getter to take_snapshot.
	Add LONGEST len_avail and struct buffer buffer.
	Change all elements in the initializer.
	Add an element for the list of types.
	(linux_xfer_osdata_info_os_types): New function.
	(linux_common_xfer_osdata): Use common_getter for the list of types.
	Replace getter call by common_getter.
	(linux_xfer_osdata_cpus): Remove args READBUF, OFFSET, LEN.
	Add arg BUFFER.  Only keep the code that adds data in BUFFER.
	(linux_xfer_osdata_fds): Likewise.
	(linux_xfer_osdata_modules): Likewise.
	(linux_xfer_osdata_msg): Likewise.
	(linux_xfer_osdata_processes): Likewise.
	(linux_xfer_osdata_processgroups): Likewise.
	(linux_xfer_osdata_sem): Likewise.
	(linux_xfer_osdata_shm): Likewise.
	(linux_xfer_osdata_isockets): Likewise.
	(linux_xfer_osdata_threads): Likewise.
2018-12-11 23:00:47 +01:00
Philippe Waroquiers 9f37501839 Fix the date in the ChangeLog 2018-12-11 22:35:19 +01:00
Philippe Waroquiers 326b0c1289 PATCH/OBVIOUS Remove various trailing spaces in linux-osdata.c 2018-12-11 22:32:54 +01:00
Andrew Burgess 99e1a184a7 gdb/riscv: Update test to handle targets without an fpu
The FPU is optional on RISC-V.  The gdb.base/float.exp test currently
assumes that an fpu is always available on RISC-V.  Update the test so
that this is not the case.

gdb/testsuite/ChangeLog:

	* gdb.base/float.exp: Handle RISC-V targets without an FPU.
2018-12-11 11:36:52 +00:00
Andrew Burgess 69cb29528e gdb/riscv: Remove whitespace before #include line
This fixes an ARI warning in riscv-tdep.c that whitespace before a

gdb/ChangeLog:

	* riscv-tdep.c (riscv_register_name): Fix ARI warning by removing
	leading whitespace before #include line.
2018-12-10 10:18:46 +00:00
Philippe Waroquiers 7a81c1e2d4 Fix tid-reuse sometimes blocks for a very long (infinite?) time.
A failure that seems to cause a long/infinite time is the following:

For a not clear reason, tid-reuse.c spawner thread sometimes gets an error:
     tid-reuse: /bd/home/philippe/gdb/git/build_moreaa/gdb/testsuite/../../../moreaa/gdb/testsuite/gdb.threads/tid-reuse.c:58: spawner_thread_func: Assertion `rc == 0' failed.

which causes a SIGABRT to be trapped by gdb, and tid-reuse does not reach the
after_count breakpoint:
  Thread 2 "tid-reuse" received signal SIGABRT, Aborted.
  [Switching to Thread 0x7ffff7518700 (LWP 10368)]
  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51
  51	../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
  (gdb) FAIL: gdb.threads/tid-reuse.exp: continue to breakpoint: after_count

After that, tid-reuse.exp gets the value of reuse_time, but this one kept its
initial value of -1 (as unsigned) :
  print reuse_time
  $1 = 4294967295
  (gdb) PASS: gdb.threads/tid-reuse.exp: get reuse_time

tid-reuse then dies, and the .exp script continues (with some FAIL)
till it executes:
  set timeout [expr $reuse_time * 2]

leading to the error:

  (gdb) ERROR: integer value too large to represent as non-long integer
      while executing
  "expect {
  -i exp8 -timeout 8589934590
          -re ".*A problem internal to GDB has been detected" {
              fail "$message (GDB internal error)"
              gdb_intern..."
      ("uplevel" body line 1)
      invoked from within
  "uplevel $body" ARITH IOVERFLOW {integer value too large to represent as non-long integer} integer value too large to represent as non-long integer
  ERROR: GDB process no longer exists

and then everything blocks.
This last 'GDB process no longer exists' is strange, as I still see the gdb
when this all blocks, e.g.
philippe 16058 31085  0 20:30 pts/15   00:00:00                         /bin/bash -c rootme=`pwd`; export rootme; srcdir=../../../binutils-gdb/gdb/testsuite ; export srcdir ; EXPECT=`if [
philippe 16386 16058  0 20:30 pts/15   00:00:00                           expect -- /usr/share/dejagnu/runtest.exp --status GDB_PARALLEL=yes --outdir=outputs/gdb.threads/tid-reuse gdb.thre
philippe 24848 16386  0 20:30 pts/20   00:00:00                             /bd/home/philippe/gdb/git/build_binutils-gdb/gdb/testsuite/../../gdb/gdb -nw -nx -data-directory /bd/home/philip

This patch gives a default value of 60, so that if ever something wrong happens
in tid-reuse, then the value retrieved by the .exp script stays in a reasonable
range.

Simon verified the patch by:
"I replaced the pthread_create call with the value 1 to simulate a
failure, and the test succeeds to fail quickly with your patch applied.
Without your patch, I get the infinite hang that you describe."

Compared to V1:
As suggested by Pedro, this version checks the pthread calls return
code (in particular of pthread_create) and reports the failure reason,
instead of just aborting.

gdb/testsuite/ChangeLog

2018-12-09  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.threads/tid-reuse.c (REUSE_TIME_CAP): Declare as 60.
	(reuse_time): Initialize to REUSE_TIME_CAP.
	(check_rc): New function.
	(main): Use REUSE_TIME_CAP instead of hardcoded 60.
	Check pthread_create rc.
	(spawner_thread_func): Check pthread_create and pthread_join rc.
2018-12-09 09:24:27 +01:00
Simon Marchi 2578ecb1b5 Look for tgetent in libtinfow
On some systems where ncurses is only available in the "wide" version
(compiled with --with-widec), there might be no libtinfo.so, only a
libtinfow.so.  Look for libtinfow in addition to libtinfo.

gdb/ChangeLog:

YYYY-MM-DD  Simon Marchi  <simon.marchi@ericsson.com>
        Дилян Палаузов  <dilyan.palauzov@aegee.org>

    PR gdb/23950
    * configure.ac: Search for tgetent in libtinfow.
    * configure: Re-generate.
2018-12-08 19:36:19 -05:00
Philippe Waroquiers a2419b98d9 Fix leak by using td_ta_delete() to deregister target process and deallocate internal process handle.
Valgrind reports the below leak:

==25327== VALGRIND_GDB_ERROR_BEGIN
==25327== 672 bytes in 1 blocks are definitely lost in loss record 2,759 of 3,251
==25327==    at 0x4C2E07C: calloc (vg_replace_malloc.c:752)
==25327==    by 0x7FDCB3E: ???
==25327==    by 0x532A7A: try_thread_db_load_1 (linux-thread-db.c:828)
==25327==    by 0x532A7A: try_thread_db_load(char const*, int) (linux-thread-db.c:997)
==25327==    by 0x53354D: try_thread_db_load_from_sdir (linux-thread-db.c:1074)
==25327==    by 0x53354D: thread_db_load_search (linux-thread-db.c:1129)
==25327==    by 0x53354D: thread_db_load() (linux-thread-db.c:1187)
==25327==    by 0x611AF1: operator() (functional:2127)
==25327==    by 0x611AF1: notify (observable.h:106)
==25327==    by 0x611AF1: symbol_file_add_with_addrs(bfd*, char const*, enum_flags<symfile_add_flag>, std::vector<other_sections, std::allocator<other_sections> >*, enum_flags<objfile_flag>, objfile*) (symfile.c:1158)
==25327==    by 0x5F5C4A: solib_read_symbols(so_list*, enum_flags<symfile_add_flag>) (solib.c:691)
==25327==    by 0x5F6A8B: solib_add(char const*, int, int) (solib.c:1003)
==25327==    by 0x5F6BF7: handle_solib_event() (solib.c:1281)
==25327==    by 0x3D0A94: bpstat_stop_status(address_space const*, unsigned long, thread_info*, target_waitstatus const*, bpstats*) (breakpoint.c:5417)
==25327==    by 0x4FF133: handle_signal_stop(execution_control_state*) (infrun.c:5874)
==25327==    by 0x502C29: handle_inferior_event_1 (infrun.c:5300)
==25327==    by 0x502C29: handle_inferior_event(execution_control_state*) (infrun.c:5335)
==25327==    by 0x5041DB: fetch_inferior_event(void*) (infrun.c:3868)
==25327==    by 0x4A1E7C: gdb_wait_for_event(int) (event-loop.c:859)
...

This leak is created because a call to td_ta_new allocates some resources
that must be freed with td_ta_delete, and that was missing.

With this patch, the nr of GDB executions leaking during regression tests
decreases further from 566 to 380.

Note that the gdbserver equivalent code is properly calling
td_ta_delete: see thread_db_mourn in thread-db.c.

Tests run natively on debian/amd64, and run under valgrind.

gdb/ChangeLog
2018-12-08  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* linux-thread-db.c (struct thread_db_info): Add td_ta_delete_p.
	(thread_db_err_str): Forward declare.
	(delete_thread_db_info): Call td_ta_delete_p if available.
	(try_thread_db_load_1): Acquire td_ta_delete address.
	* nat/gdb_thread_db.h (td_ta_delete_ftype): Declare.
2018-12-08 17:06:09 +01:00
Pedro Alves 73e8dc90a8 Merge forward-search/reverse-search, use gdb::def_vector, remove limit
Back in:

 commit 85ae1317ad
 Author:     Stan Shebs <shebs@codesourcery.com>
 AuthorDate: Thu Dec 8 02:27:47 1994 +0000

	     * source.c: Various cosmetic changes.
	     (forward_search_command): Handle very long source lines correctly.

a buffer with a hard limit was converted to a heap buffer:

  @@ -1228,15 +1284,26 @@ forward_search_command (regex, from_tty)
     stream = fdopen (desc, FOPEN_RT);
     clearerr (stream);
     while (1) {
  -/* FIXME!!!  We walk right off the end of buf if we get a long line!!! */
  -    char buf[4096];            /* Should be reasonable??? */
  -    register char *p = buf;
  +    static char *buf = NULL;
  +    register char *p;
  +    int cursize, newsize;
  +
  +    cursize = 256;
  +    buf = xmalloc (cursize);
  +    p = buf;

However, reverse_search_command has the exact same problem, and that
wasn't fixed.  We still have that "we walk right off" comment...

Recently, the xmalloc above was replaced with a xrealloc, because as
can be seen above, that 'buf' variable above was a static local,
otherwise we'd be leaking.  This commit replaces that and the
associated manual buffer growing with a gdb::def_vector<char>.  I
don't think there's much point in reusing the buffer across command
invocations.

While doing this, I realized that reverse_search_command is almost
identical to forward_search_command.  So this commit factors out a
common helper function instead of duplicating a lot of code.

There are some tests for "forward-search" in gdb.base/list.exp, but
since they use the "search" alias, they were a bit harder to find than
expected.  That's now fixed, both by testing both variants, and by
adding some commentary.  Also, there are no tests for the
"reverse-search" command, so this commit adds some for that too.

gdb/ChangeLog:
2018-12-08  Pedro Alves  <palves@redhat.com>

	* source.c (forward_search_command): Rename to ...
	(search_command_helper): ... this.  Add 'forward' parameter.
	Tweak to use a gdb::def_vector<char> instead of a xrealloc'ed
	buffer.  Handle backward searches too.
	(forward_search_command, reverse_search_command): Reimplement by
	calling search_command_helper.

gdb/testsuite/ChangeLog:
2018-12-08  Pedro Alves  <palves@redhat.com>

	* gdb.base/list.exp (test_forward_search): Rename to ...
	(test_forward_reverse_search): ... this.  Also test reverse-search
	and the forward-search alias.
2018-12-08 15:03:29 +00:00
Andrew Burgess d9c859da9f gdb/emacs/dir-locals: Update settings for c++-mode
The current .dir-locals file for GDB causes files that would usually
open in c-mode (for example, files ending in .c) to open in c++-mode.
However, all of the other settings applied for c-mode appear to get
reset when the file is switched over to c++-mode.

For example, we currently say:

 (c-mode . ((c-file-style . "GNU")
	    (mode . c++)
	    (indent-tabs-mode . t)
	    (tab-width . 8)
	    (c-basic-offset . 2)
	    (eval . (c-set-offset 'innamespace 0))
	    ))
 (c++-mode . ((eval . (when (fboundp 'c-toggle-comment-style)
			(c-toggle-comment-style 1)))))

So, when we enter c++-mode `indent-tabs-mode` is reset to its global
value, as are all of the other settings listed for c-mode.

This commit copies all of the settings (except the `mode` setting)
from the c-mode list to the c++-mode list.

The emacs documentation doesn't mention that `mode` causes this
resetting behaviour, so, in case this is an emacs bug, I'm using emacs
version 26.1.  Having the settings duplicated shouldn't cause any
problems except for a slight maintenance overhead.

gdb/ChangeLog:

	* .dir-locals.el: Copy most of the settings from c-mode over to
	c++-mode.
2018-12-07 23:20:30 +00:00
Stafford Horne 42e151bf4c gdb/or1k: Add linux debugging support
Up until now OpenRISC GDB only has supported bare metal debugging.  This
patch adds linux userspace debugging and core dump analysis support.

The changes are loosely based on nios2 and riscv implementations.

This was tested with linux 4.20 core dumps for executables linked
against musl libc.

bfd/ChangeLog:

	* elf32-or1k.c (or1k_grok_prstatus): New function.
	(or1k_grok_psinfo): Likewise.

gdb/ChangeLog:

	* Makefile.in (ALL_TARGET_OBS): Add or1k-linux-tdep.o.
	* configure.tgt: Add or1k*-*-linux*.
	* or1k-linux-tdep.c: New file.
	* or1k-tdep.c (or1k_gdbarch_init): Call gdbarch_init_osabi.
2018-12-08 07:07:36 +09:00
Pedro Alves 8bebfcda34 Fix gdb build on 32-bit hosts w/ --enable-64-bit-bfd
Building for x86_64/-m32 with --enable-64-bit-bfd, compilation fails
with:

 src/gdb/dwarf2read.c: In instantiation of ‘gdb::array_view<const unsigned char> get_gdb_index_contents_from_section(objfile*, T*) [with T = dwarf2_per_objfile]’:
 src/gdb/dwarf2read.c:6266:54:   required from here
 src/gdb/dwarf2read.c:6192:37: error: narrowing conversion of ‘section->dwarf2_section_info::size’ from ‘bfd_size_type {aka long long unsigned int}’ to ‘size_t {aka unsigned int}’ inside { } [-Werror=narrowing]
    return {section->buffer, section->size};
			     ~~~~~~~~~^~~~

This fixes it.

gdb/ChangeLog:
2018-12-07  Pedro Alves  <palves@redhat.com>

	* dwarf2read.c (get_gdb_index_contents_from_section): Use
	gdb::make_array_view.
2018-12-07 19:54:19 +00:00
Philippe Waroquiers 4a8110007b Fix a (one shot small) leak in language.c
Valgrind detects the following leak:
==28395== VALGRIND_GDB_ERROR_BEGIN
==28395== 5 bytes in 1 blocks are definitely lost in loss record 20 of 2,770
==28395==    at 0x4C2BE2D: malloc (vg_replace_malloc.c:299)
==28395==    by 0x41D9E7: xmalloc (common-utils.c:44)
==28395==    by 0x78BF39: xstrdup (xstrdup.c:34)
==28395==    by 0x51F1AC: _initialize_language() (language.c:1175)
==28395==    by 0x6B3356: initialize_all_files() (init.c:308)
==28395==    by 0x66D194: gdb_init(char*) (top.c:2159)
==28395==    by 0x554C11: captured_main_1 (main.c:863)
==28395==    by 0x554C11: captured_main (main.c:1167)
==28395==    by 0x554C11: gdb_main(captured_main_args*) (main.c:1193)
==28395==    by 0x29D837: main (gdb.c:32)
==28395==
==28395== VALGRIND_GDB_ERROR_END

This is a very small leak (1 block/5 bytes), happening only once
per GDB startup as far as I can see. But this fix make the nr of leaking
GDB in the testsuite decreasing from 628 to 566.

It is unclear why a xstrdup-ed value is assigned to 'language'
at initialization time, while a static "auto" string is assigned
as part of the set_language_command.
So, that shows that it is ok to initialize 'language' directly
with "auto".
Also, I cannot find any place where 'language' is xfree-d.
No leak was detected for 'range' and 'case_sensitive', but
similarly, no indication why a static string cannot be assigned.

Regression-tested on debian/x86_64.
Also, full testsuite run under valgrind, less tests leaking,
and no dangling pointer problem detected.

gdb/ChangeLog
2018-12-05  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* language.c (_initialize_language): Fix leak by assigning
	a static string to language.  Same for range and case_sensitive,
	even if no leak is detected for these variables.
2018-12-07 16:32:23 +01:00
John Baldwin 2861ee4fde Use separate sed expressions to escape auto-load directories.
Not all sed implementations support alternation via \| in the default
regular expressions.  Instead, resort to separate sed expressions via
-e for $debugdir and $datadir.  This fixes the default setting of the
auto-load directories on FreeBSD.  Previously on FreeBSD the sed
invocation was a no-op causing the debugdir and datadir values to be
expanded yielding an autoload path of ':${prefix}/share/gdb'.

gdb/ChangeLog:

	* configure: Re-generate.
	* configure.ac: Use separate sed expressions to escape variables
	in auto-load directories.
2018-12-05 10:51:16 -08:00
Andrew Burgess 90af06793e gdb/riscv: Improve logic for when h/w float abi should be used
Currently, if the target announces that it has floating point
registers in its target description then GDB assumes that the hardware
float ABI should be used.  However, there's nothing stopping a user
compiling a program for the soft-float abi, and then trying to run
this on a target with hardware floating point registers.

This commit adjusts the logic that decides if GDB should use the
hardware float abi.  The primary decision now is based on what the ELF
currently being executed says in its headers.  If the file was
compiled for h/w float abi, then GDB uses h/w float abi, otherwise s/w
float is used.

If the current BFD is not an ELF then we don't currently have a
mechanism for figuring out if the file was compiled for float or not.
In this case we disable the h/w float abi.  This shouldn't be a
problem as, right now, the RISC-V linker can only produce ELFs.

If there is NO current BFD (can this happen?) then we will enable h/w
float abi if the target has floating point hardware, otherwise, s/w
float abi is used.

This commit also adds some sanity checking that the features requested
in the BFD (xlen and flen) match the target description.

For testing I ran the testsuite on a target that returns a target
description containing both integer and floating point registers, but
used a compiler that didn't have floating point support.  Before this
commit I would see failures on may tests that made inferior calls
using floating point arguments, after this commit, all of these issues
are resolved.  One example from the testsuite is
gdb.base/infcall-nested-structs.exp.

gdb/ChangeLog:

	* riscv-tdep.c (riscv_features_from_gdbarch_info): New function.
	(riscv_find_default_target_description): Use new function to
	extract feature from gdbarch_info.
	(riscv_gdbarch_init): Add error checks for xlen and flen between
	target description and bfd headers.  Be smarter about when we
	think the hardware floating point abi should be used.
2018-12-05 13:23:23 +00:00
Andrew Burgess 13f2ed32e1 gdb/testsuite/sim: Remove redundant setting of timeout
In the config/sim.exp file two functions are defined.  Both of these
functions define local timeout variables and then call gdb_expect,
which (through a call to get_largest_timeout) will find the local
definition of timeout.

However, both of these functions set the local timeout to some
arbitrary value and print a log message for this "new" timeout just
before returning.

As in both cases, the timeout is a local variable, this final setting
of the timeout has no effect and can be removed.

As having log messages about the timeout being adjusted could cause
confusion I've removed all logging related to timeouts in this
function, timeouts are adjusted throughout the testsuite without any
logging, there doesn't seem to be any good reason why these functions
should get their own logging.

With the logging gone there seems to be little need to a local timeout
variable at all, and so I've folded the local timeout directly into
the call to gdb_expect.

gdb/testsuite/ChangeLog:

	* config/sim.exp (gdb_target_sim): Remove redundant adjustment of
	local timeout variable before return, and remove all local timeout
	variable entirely.
	(gdb_load): Likewise.
2018-12-05 11:53:28 +00:00
Alan Hayward 754e316898 AArch64: Racy: Don't set empty set of hardware BPs/WPs on new thread
On some heavily loaded AArch64 boxes, GDB will sometimes hang forever when
the inferior creates a thread.  This hang happens inside the kernel during
the ptrace call to set hardware watchpoints or hardware breakpoints.
Currently, GDB will always set hw wp/bp at the start of each thread even if
there are none set in the process.

This patch works around the issue by avoiding setting hw wp/bp if there
are none set for the process.

On an effected machine, this fix drastically reduces the racy nature of the
gdb.threads test set.  I ran the entire gdb test suite across all processors
for 100 iterations, then ran the results through the racy tests script.
Without the patch, 58 .exp files in gdb.threads were marked as racy.  After
the patch this reduced to the same ~14 tests as the non effected boxes.

Clearly GDB will still be subject to hangs on an effect box if hw wp/bp's are
used prior to creating inferior threads on a heavily loaded system.

To enable this in gdbserver, the sequence in gdbserver add_lwp() is switched
to the same as gdb order as gdb, to ensure the thread is registered before
calling new_thread().  This allows aarch64_linux_new_thread() to read the
ptid.

gdb/ChangeLog:

	* nat/aarch64-linux-hw-point.c
	(aarch64_linux_any_set_debug_regs_state): New function.
	* nat/aarch64-linux-hw-point.h
	(aarch64_linux_any_set_debug_regs_state): New declaration.
	* nat/aarch64-linux.c (aarch64_linux_new_thread): Check if any
	BPs or WPs are set.

gdb/gdbserver/ChangeLog:

	* linux-low.c (add_lwp): Switch ordering.
2018-12-05 10:44:03 +00:00
Tom de Vries 64d27cfc97 [gdb/testsuite] Add gdb-caching-proc.exp testcase
When caching a proc using gdb_caching_proc, it will become less likely to
be executed, and consequently it's going to be harder to detect that the
proc is racy.  OTOH, in general the proc is easy to rerun.  So, add a
test-case to run all uncached gdb_caching_procs a number of times and detect
inconsistent results.

The purpose of caching is to reduce runtime, so rerunning is somewhat
counter-productive in that aspect, but it's better than uncached, because the
number of reruns is constant-bounded, and the increase in runtime is bound to
this test-case, and can be disabled on slow targets.

Tested on x86_64-linux.

gdb/testsuite/ChangeLog:

2018-12-01  Tom de Vries  <tdevries@suse.de>

	* gdb.base/gdb-caching-proc.exp: New file.
2018-12-01 08:56:56 +01:00
John Baldwin 93579f6f90 Use kinfo_getfile to implement fdwalk on FreeBSD.
kinfo_getfile() requires a couple of system calls to fetch the list of
open file descriptors.  This can be much cheaper than invoking fstat
on all of the values from 0 to the open file resource limit maximum.

gdb/ChangeLog:

	* common/filestuff.c [HAVE_KINFO_GETFILE]: Include headers.
	(fdwalk) [HAVE_KINFO_GETFILE]: Use kinfo_getfile.
2018-11-30 15:14:18 -08:00
Simon Marchi 4717cec4fe Fix leak in linespec parser
Valgrind reports this leak:

  ==798== VALGRIND_GDB_ERROR_BEGIN
  ==798== 32 (24 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 447 of 3,143
  ==798==    at 0x4C2C48C: operator new(unsigned long) (vg_replace_malloc.c:334)
  ==798==    by 0x51D401: linespec_parser_new(ls_parser*, int, language_defn const*, program_space*, symtab*, int, linespec_result*) (linespec.c:2756)
  ==798==    by 0x524BF7: decode_line_full(event_location const*, int, program_space*, symtab*, int, linespec_result*, char const*, char const*) (linespec.c:3271)
  ==798==    by 0x3E8893: parse_breakpoint_sals(event_location const*, linespec_result*) (breakpoint.c:9067)
  ==798==    by 0x3E4E7F: create_breakpoint(gdbarch*, event_location const*, char const*, int, char const*, int, int, bptype, int, auto_boolean, breakpoint_ops const*, int, int, int, unsigned int) (breakpoint.c:9248)
  ==798==    by 0x3E55F5: break_command_1(char const*, int, int) (breakpoint.c:9434)
  ==798==    by 0x40BA68: cmd_func(cmd_list_element*, char const*, int) (cli-decode.c:1888)
  ==798==    by 0x665300: execute_command(char const*, int) (top.c:630)
  ...

linespec_parser_new allocates a std::vector<symtab *> at line 2756, and stores
the pointer to this vector in PARSER_RESULT (parser)->file_symtabs.  At 3
different places in linespec.c, another std::vector is assigned to a
linespec->file_symtabs, without first deleting the current value.

The leak is fixed by assigning the vector itself instead of the pointer.
Everything should be moved, so there is no significant data copy
involved.

Tested on debian/amd64, + a bunch of tests re-run under valgrind
(including the test that throws an error).

gdb/ChangeLog:

	* linespec.c (symtab_vector_up): Remove.
	(symtabs_from_filename): Change return type to std::vector.
	(collect_symtabs_from_filename): Likewise.
	(create_sals_line_offset): Assign return value of
	collect_symtabs_from_filename to *ls->file_symtabs.
	(convert_explicit_location_to_linespec): Remove call to release.
	(parse_linespec): Likewise.
	(symtab_collector) <symtab_collector>: Remove initialization of
	m_symtabs.
	<release_symtabs>: Change return type to std::vector<symtab *>.
	<operator ()>: Adjust.
2018-11-30 16:51:28 -05:00
John Baldwin f8eb6a9e89 Update the conditionals in fbsd-nat.h so they are always honored.
Not all of the architecture-specific FreeBSD target files were
including the right headers to enable conditionals in fbsd-nat.h after
the C++ target conversion.  As a result, certain operations like 'info
auxv' and 'p $_siginfo' were not working for some native targets
(noticed on RISC-V).  Fix this in a couple of ways:

1) Declare fbsd_nat_target::xfer_partial unconditionally and only use
   conditionals in the function body for individual target objects.

   Originally this function was only used to read the ELF auxiliary
   vector, so the entire function was conditional on a macro required
   for that object (KERN_AUXV_PROC).  However, xfer_partial has since
   grown support for additional objects.  Making the function
   unconditional avoids needing to add the right header to fbsd-nat.h
   and allows each target object to use independent requirements.

   This did require using a more explicit conditional test for the
   $_siginfo support.  Removing the "outer" KERN_PROC_AUXV test
   enabled $_siginfo for all kernels with PT_LWPINFO, but some older
   kernels (FreeBSD 6.0) exposed PT_LWPINFO with a different siginfo
   format.  Instead use an explicit test for when the current siginfo
   format was adopted (shipped in FreeBSD 7.0).  This actually enables
   $_siginfo on a wider range of kernels as KERN_PROC_AUXV wasn't
   introduced until FreeBSD 9.1/10.0.

2) Include <sys/proc.h> in fbsd-nat.h for the definition of
   TDP_RFPPWAIT that governs support for fork following.

gdb/ChangeLog:

	* fbsd-nat.c [__FreeBSD_version >= 700009] (USE_SIGINFO): Macro
	defined.
	(union sigval32, struct siginfo32, fbsd_siginfo_size)
	(fbsd_convert_siginfo): Make conditional on USE_SIGINFO instead
	of KERN_PROC_AUXV and PT_LWPINFO.
	(fbsd_nat_target::xfer_partial): Define method unconditionally.
	Make TARGET_OBJECT_SIGNAL_INFO conditional on USE_SIGINFO.
	Make TARGET_OBJECT_AUXV conditional on KERN_PROC_AUXV.
	Make TARGET_OBJECT_FREEBSD_VMMAP and
	TARGET_OBJECT_FREEBSD_PS_STRINGS conditional on KERN_PROC_VMMAP
	and KERN_PROC_PS_STRINGS.
	* fbsd-nat.h: Include <sys/proc.h>.
	(fbsd_nat_target::xfer_partial): Declare method unconditionally.
2018-11-30 13:21:19 -08:00
Andrew Burgess 92528b6772 gdb/riscv: Add read_description method for riscv_linux_nat_target
Adds riscv_linux_nat_target::read_description method to find a
suitable target description for the native linux target we are running
on.

Currently this will supply a suitably sized set of x-registers, and
will probe the kernel to see if the f-registers are readable.  If they
are readable then we currently assume that the f-registers are the
same size as the x-registers as I don't know of a good way to probe
the f-register length.  This will obviously need fixing in future.

As of Linux 4.19 there is no ptrace support for reading the
f-registers, this should appear in 4.20, so right now we only return
target descriptions without f-registers.

gdb/ChangeLog:

	* riscv-linux-nat.c: Add 'inferior.h' and 'target-descriptions.h'
	header files.
	(riscv_linux_nat_target::read_description): New method.
2018-11-30 18:13:43 +00:00
Andrew Burgess 634494366c gdb/riscv: Create each unique target description only once
GDB relies on the fact that if two target descriptions have the same
contents, then they will be the same object instance (having the same
address).  One place where this is a requirement is in
GDBARCH_LIST_LOOKUP_BY_INFO which is used to find previously created
gdbarch objects.

In GDBARCH_LIST_LOOKUP_BY_INFO a pointer comparison is made on the
gdbarch's target description, if the pointers are different then it is
assumed the gdbarches have different, non-compatible target
descriptions.

Previously we would create duplicate target descriptions in the belief
that RISCV_GDBARCH_INIT would spot this duplication and discard the
second instance.  However, this was incorrect, and instead we ended up
creating duplicate gdbarch objects.

With this commit every unique feature set will create one and only one
target description, the feature set and resulting target description
is then cached so that the same target description object can be
returned later.

Many other target avoid this problem by creating a small number of
named target descriptions, and returning one of these.  However, we
currently have 8 possible target descriptions (32 vs 64 bit for x-reg
and f-reg, and h/w or s/w float abi) and creating each of these just
to avoid a dynamic cache seems pointless.

gdb/ChangeLog:

	* arch/riscv.h (riscv_gdbarch_features::hash): New method.
	* arch/riscv.c (struct riscv_gdbarch_features_hasher): New.
	(riscv_tdesc_cache): New global.
	(riscv_create_target_description): Look in the cache before
	creating a new target description.
2018-11-30 18:13:43 +00:00
Andrew Burgess 65a4b37326 gdb/riscv: Add equality operators to riscv_gdb_features
Add '==' and '!=' operators for the struct riscv_gdb_features,
allowing a small simplification.

gdb/ChangeLog:

	* arch/riscv.h (riscv_gdb_features::operator==): New.
	(riscv_gdb_features::operator!=): New.
	* riscv-tdep.c (riscv_gdbarch_init): Make use of the inequality
	operator.
2018-11-30 18:13:42 +00:00
Andrew Burgess 0ff80bf7b9 gdb/riscv: Make some target description functions constant
Makes more of the interface related to fetching target descriptions
constant.

gdb/ChangeLog:

	* arch/riscv.h (riscv_create_target_description): Make return type
	const.
	* arch/riscv.c (riscv_create_target_description): Likewise.
	* riscv-tdep.c (riscv_find_default_target_description): Likewise.
2018-11-30 18:13:42 +00:00
Sergio Durigan Junior 81fbbaf962 Fix dwarf2read.c:dwarf2_find_containing_comp_unit's binary search
First of all, I would like to express my gratitude to Keith Seitz, Jan
Kratochvil and Tom Tromey, who were really kind and helped a lot with
this bug.  The patch itself was authored by Jan.

This all began with:

  https://bugzilla.redhat.com/show_bug.cgi?id=1639242
  py-bt is broken, results in exception

In summary, the error reported by the bug above is:

  $ gdb -args python3
  GNU gdb (GDB) Fedora 8.1.1-3.fc28
  (...)
  Reading symbols from python3...Reading symbols from /usr/lib/debug/usr/bin/python3.6-3.6.6-1.fc28.x86_64.debug...done.
  done.
  Dwarf Error: could not find partial DIE containing offset 0x316 [in module /usr/lib/debug/usr/bin/python3.6-3.6.6-1.fc28.x86_64.debug]

After a long investigation, and after thinking that the problem might
actually be on DWZ's side, we were able to determine that there's
something wrong going on when
dwarf2read.c:dwarf2_find_containing_comp_unit performs a binary search
over all of the CUs belonging to an objfile in order to find the CU
which contains a DIE at an specific offset.  The current algorithm is:

  static struct dwarf2_per_cu_data *
  dwarf2_find_containing_comp_unit (sect_offset sect_off,
				    unsigned int offset_in_dwz,
				    struct dwarf2_per_objfile *dwarf2_per_objfile)
  {
    struct dwarf2_per_cu_data *this_cu;
    int low, high;
    const sect_offset *cu_off;

    low = 0;
    high = dwarf2_per_objfile->all_comp_units.size () - 1;
    while (high > low)
      {
	struct dwarf2_per_cu_data *mid_cu;
	int mid = low + (high - low) / 2;

	mid_cu = dwarf2_per_objfile->all_comp_units[mid];
	cu_off = &mid_cu->sect_off;
	if (mid_cu->is_dwz > offset_in_dwz
	    || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
	  high = mid;
	else
	  low = mid + 1;
      }

For the sake of this example, let's consider that "sect_off =
0x7d".

There are a few important things going on here.  First,
"dwarf2_per_objfile->all_comp_units ()" will be sorted first by
whether the CU is a DWZ CU, and then by cu->sect_off.  In this
specific bug, "offset_in_dwz" is false, which means that, for the most
part of the loop, we're going to do "high = mid" (i.e, we'll work with
the lower part of the vector).

In our particular case, when we reach the part where "mid_cu->is_dwz
== offset_in_dwz" (i.e, both are false), we end up with "high = 2" and
"mid = 1".  I.e., there are only 2 elements in the vector who are not
DWZ.  The vector looks like this:

  #0: cu->sect_off = 0;   length = 114;  is_dwz = false  <-- low
  #1: cu->sect_off = 114; length = 7796; is_dwz = false  <-- mid
  #2: cu->sect_off = 0;   length = 28;   is_dwz = true   <-- high
  ...

The CU we want is #1, which is exactly where "mid" is.  Also, #1 is
not DWZ, which is also exactly what we want.  So we perform the second
comparison:

  (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off)
                                      ^^^^^^^^^^^^^^^^^^^

Because "*cu_off = 114" and "sect_off = 0x7d", this evaluates to
false, so we end up with "low = mid + 1 = 2", which actually gives us
the wrong CU (i.e., a CU that is DWZ).  Next in the code, GDB does:

    gdb_assert (low == high);
    this_cu = dwarf2_per_objfile->all_comp_units[low];
    cu_off = &this_cu->sect_off;
    if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      {
	if (low == 0 || this_cu->is_dwz != offset_in_dwz)
	  error (_("Dwarf Error: could not find partial DIE containing "
		 "offset %s [in module %s]"),
		 sect_offset_str (sect_off),
		 bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
	...

Triggering the error we saw in the original bug report.

It's important to notice that we see the error message because the
selected CU is a DWZ one, but we're looking for a non-DWZ CU here.
However, even when the selected CU is *not* a DWZ (and we don't see
any error message), we still end up with the wrong CU.  For example,
suppose that the vector had:

  #0: cu->sect_off = 0;    length = 114;  is_dwz = false
  #1: cu->sect_off = 114;  length = 7796; is_dwz = false
  #2: cu->sect_off = 7910; length = 28;   is_dwz = false
  ...

I.e., #2's "is_dwz" is false instead of true.  In this case, we still
want #1, because that's where the DIE is located.  After the loop ends
up in #2, we have "is_dwz" as false, which is what we wanted, so we
compare offsets.  In this case, "7910 >= 0x7d", so we set "mid = high
= 2".  Next iteration, we have "mid = 0 + (2 - 0) / 2 = 1", and thus
we examining #1.  "is_dwz" is still false, but "114 >= 0x7d" also
evaluates to false, so "low = mid + 1 = 2", which makes the loop stop.
Therefore, we end up choosing #2 as our CU, even though #1 is the
right one.

The problem here is happening because we're comparing "sect_off"
directly against "*cu_off", while we should actually be comparing
against "*cu_off + mid_cu->length" (i.e., the end offset):

  ...
  || (mid_cu->is_dwz == offset_in_dwz
      && *cu_off + mid_cu->length >= sect_off))
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ...

And this is what the patch does.  The idea is that if GDB is searching
for an offset that falls above the *end* of the CU being
analyzed (i.e., "mid"), then the next iteration should try a
higher-offset CU next.  The previous algorithm was using
the *beginning* of the CU.

Unfortunately, I could not devise a testcase for this problem, so I am
proposing a fix with this huge explanation attached to it in the hope
that it is sufficient.  After talking a bit to Keith (our testcase
guru), it seems that one would have to create an objfile with both DWZ
and non-DWZ sections, which may prove very hard to do, I think.

I ran this patch on our BuildBot, and no regressions were detected.

gdb/ChangeLog:
2018-11-30  Jan Kratochvil  <jan.kratochvil@redhat.com>
	    Keith Seitz  <keiths@redhat.com>
	    Tom Tromey  <tom@tromey.com>
	    Sergio Durigan Junior  <sergiodj@redhat.com>

	https://bugzilla.redhat.com/show_bug.cgi?id=1613614
	* dwarf2read.c (dwarf2_find_containing_comp_unit): Add
	'mid_cu->length' to '*cu_off' when checking if 'sect_off' is
	inside the CU.
2018-11-30 13:03:25 -05:00
Pedro Alves 66b4deae03 target_ops::to_stratum -> target_ops::stratum() virtual method
Given that a target's stratum is a property of the type, and not of an
instance of the type, get rid of to_stratum data field and replace it
with a virtual method.

I.e., when we have e.g., 10 target remote instances active, there's no
need for each of the instances to have their own to_stratum copy.

gdb/ChangeLog:
2018-11-30  Pedro Alves  <palves@redhat.com>

	* aix-thread.c (aix_thread_target) <aix_thread_target>: Delete.
	<stratum>: New override.
	* bfd-target.c (aix_thread_target) <aix_thread_target>: Delete.
	<stratum>: New override.
	* bsd-uthread.c (bsd_uthread_target) <bsd_uthread_target>: Delete.
	<stratum>: New override.
	* exec.c (exec_target) <exec_target>: Delete.
	<stratum>: New override.
	* gdbarch-selftests.c (register_to_value_test): Adjust to use the
	stratum method instead of the to_stratum field.
	* linux-thread-db.c (thread_db_target) <thread_db_target>: Delete.
	<stratum>: New override.
	(thread_db_target::thread_db_target): Delete.
	* make-target-delegates (print_class): Don't print a ctor
	declaration.  Print a stratum method override declaration.
	* process-stratum-target.h (process_stratum_target)
	<process_stratum_target>: Delete.
	<stratum>: New override.
	* ravenscar-thread.c (ravenscar_thread_target)
	<ravenscar_thread_target>: Delete.
	<stratum>: New override.
	* record-btrace.c (record_btrace_target)
	<record_btrace_target>: Delete.
	<stratum>: New override.
	* record-full.c (record_full_base_target)
	<record_full_base_target>: Delete.
	<stratum>: New override.
	* record.c (record_disconnect, record_detach)
	(record_mourn_inferior, record_kill): Adjust to use the stratum
	method instead of the to_stratum field.
	* regcache.c (cooked_read_test, cooked_write_test): Likewise.
	* sol-thread.c (sol_thread_target)
	<sol_thread_target>: Delete.
	<stratum>: New override.
	* spu-multiarch.c (spu_multiarch_target)
	<spu_multiarch_target>: Delete.
	<stratum>: New override.
	* target-delegates.c: Regenerate.
	* target.c (target_stack::push, target_stack::unpush)
	(pop_all_targets_above, pop_all_targets_at_and_above)
	(info_target_command, target_require_runnable)
	(target_stack::find_beneath): Adjust to use the stratum method
	instead of the to_stratum field.
	(dummy_target::dummy_target): Delete.
	(dummy_target::stratum): New.
	(debug_target::debug_target): Delete.
	(debug_target::stratum): New.
	(maintenance_print_target_stack): Adjust to use the stratum method
	instead of the to_stratum field.
	* target.h (struct target_ops) <stratum>: New method.
	<to_stratum>: Delete.
	<is_pushed>: Adjust to use the stratum method
	instead of the to_stratum field.
2018-11-30 17:49:49 +00:00
Pedro Alves f3d11a9a96 Convert default_child_has_foo functions to process_stratum_target methods
This patch converts the default_child_has_foo functions to
process_stratum_target methods.  This simplifies "regular"
non-inf_child process_stratum targets, since they no longer have to
override the target_ops::has_foo methods to call the default_child_foo
functions.  A couple targets need to override the new defaults
(corelow and tracefiles), but it still seems like a good tradeoff,
since those are expected to be little different (target doesn't run).

gdb/ChangeLog:
2018-11-30  Pedro Alves  <palves@redhat.com>

	* corelow.c (core_target) <has_all_memory, has_execution>: New
	overrides.
	* inf-child.c (inf_child_target::has_all_memory)
	(inf_child_target::has_memory, inf_child_target::has_stack)
	(inf_child_target::has_registers)
	(inf_child_target::has_execution): Delete.
	* inf-child.h (inf_child_target) <has_all_memory, has_memory,
	has_stack, has_registers, has_execution>: Delete.
	* process-stratum-target.c
	(process_stratum_target::has_all_memory)
	(process_stratum_target::has_memory)
	(process_stratum_target::has_stack)
	(process_stratum_target::has_registers)
	(process_stratum_target::has_execution): New.
	* process-stratum-target.h (process_stratum_target)
	<has_all_memory, has_memory, has_stack, has_registers,
	has_execution>: New method overrides.
	* ravenscar-thread.c (ravenscar_thread_target) <has_all_memory,
	has_memory, has_stack, has_registers, has_execution>: Delete.
	* remote-sim.c (gdbsim_target) <has_stack, has_registers,
	has_execution>: Delete.
	* remote.c (remote_target) <has_all_memory, has_memory, has_stack,
	has_registers, has_execution>: Delete.
	* target.c (default_child_has_all_memory)
	(default_child_has_memory, default_child_has_stack)
	(default_child_has_registers, default_child_has_execution):
	Delete.
	* target.h (default_child_has_all_memory)
	(default_child_has_memory, default_child_has_stack)
	(default_child_has_registers, default_child_has_execution):
	Delete.
	* tracefile.h (tracefile_target) <has_execution>: New override.
2018-11-30 16:28:11 +00:00
Pedro Alves 3b3dac9b3f Introduce process_stratum_target
This adds a base class that all process_stratum targets inherit from.

default_thread_address_space/default_thread_architecture only make
sense for process_stratum targets, so they are transformed to
process_stratum_target methods/overrides.

gdb/ChangeLog:
2018-11-30  Pedro Alves  <palves@redhat.com>

	* Makefile.in (COMMON_SFILES): Add process-stratum-target.c.
	* bsd-kvm.c: Include "process-stratum-target.h".
	(bsd_kvm_target): Now inherits from process_stratum_target.
	(bsd_kvm_target::bsd_kvm_target): Default it.
	* corelow.c: Include "process-stratum-target.h".
	(core_target): Now inherits from process_stratum_target.
	(core_target::core_target): Don't set to_stratum here.
	* inf-child.c (inf_child_target::inf_child_target): Delete.
	* inf-child.h: Include "process-stratum-target.h".
	(inf_child_target): Inherit from process_stratum_target.
	(inf_child_target) <inf_child_target>: Default it.
	<can_async_p, supports_non_stop, supports_disable_randomization>:
	Delete overrides.
	* process-stratum-target.c: New file.
	* process-stratum-target.h: New file.
	* remote-sim.c: Include "process-stratum-target.h".
	(gdbsim_target): Inherit from process_stratum_target.
	<gdbsim_target>: Default it.
	* remote.c: Include "process-stratum-target.h".
	(remote_target): Inherit from process_stratum_target.
	<remote_target>: Default it.
	* target.c (default_thread_address_space)
	(default_thread_architecture): Delete.
	* target.h (target_ops) <thread_architecture>: Now returns NULL by
	default.
	<thread_address_space>: Ditto.
	* test-target.h: Include "process-stratum-target.h" instead of
	"target.h".
	(test_target_ops): Inherit from process_stratum_target.
	<test_target_ops>: Default it.
	* tracefile.c (tracefile_target::tracefile_target): Delete.
	* tracefile.h: Include "process-stratum-target.h".
	(tracefile_target): Inherit from process_stratum_target.
	<tracefile_target>: Default it.
	* target-delegates.c: Regenerate.
2018-11-30 16:27:26 +00:00
Pedro Alves c180496d2a Move test_target_ops to a separate file
There's no need to have all target.h users seeing this type.

Also helps with a follow up patch.

gdb/ChangeLog:
2018-11-30  Pedro Alves  <palves@redhat.com>

	* Makefile.in (COMMON_SFILES): Add test-target.c.
	* gdbarch-selftests.c: Include "test-target.h".
	* regcache.c: Include "test-target.h".
	* target.c (test_target_info, test_target_ops::info): Move to ...
	* test-target.c: ... this new file.
	* target.h (test_target_ops): Move to ...
	* test-target.h: ... this new file.
2018-11-30 14:53:38 +00:00
Philippe Waroquiers 95b1f9ac6b Fix leak in forward-search
Valgrind reports the below leak.
Fix the leak by using xrealloc, even for the first allocation,
as buf is static.

==29158== 5,888 bytes in 23 blocks are definitely lost in loss record 3,028 of 3,149
==29158==    at 0x4C2BE2D: malloc (vg_replace_malloc.c:299)
==29158==    by 0x41B557: xmalloc (common-utils.c:44)
==29158==    by 0x60B7D9: forward_search_command(char const*, int) (source.c:1563)
==29158==    by 0x40BA68: cmd_func(cmd_list_element*, char const*, int) (cli-decode.c:1888)
==29158==    by 0x665300: execute_command(char const*, int) (top.c:630)
...

gdb/ChangeLog
2018-11-29  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* source.c (forward_search_command): Fix leak by using
	xrealloc even for the first allocation in the loop, as buf
	is static.
2018-11-29 23:33:18 +01:00
Rajendra SY e61667ef14 Implement the "gdb_signal_to/from_target" gdbarch methods for FreeBSD.
This fixes failures in the gdb.base/exitsignal.exp test.

gdb/ChangeLog:

	PR gdb/23093
	* gdb/fbsd-tdep.c (fbsd_gdb_signal_from_target)
	(fbsd_gdb_signal_to_target): New.
	(fbsd_init_abi): Install gdbarch "signal_from_target" and
	"signal_to_target" methods.
2018-11-29 13:26:31 -08:00
Tom Tromey 3d5500e958 Avoid buffer overflow in value_x_unop
Commit 6b1747cd1 ("invoke_xmethod & array_view") contains this change:

-  argvec = (struct value **) alloca (sizeof (struct value *) * 4);
+  value *argvec_storage[3];
+  gdb::array_view<value *> argvec = argvec_storage;

However, value_x_unop still does:

      argvec[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
      argvec[3] = 0;

This triggers an error with -fsanitize=address from userdef.exp:

ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffdcf185068 at pc 0x000000e4f912 bp 0x7ffdcf184d80 sp 0x7ffdcf184d70
WRITE of size 8 at 0x7ffdcf185068 thread T0
    #0 0xe4f911 in value_x_unop(value*, exp_opcode, noside) ../../binutils-gdb/gdb/valarith.c:557
[...]

I think the two assignments to argvec[3] should just be removed, and
that this was intended in the earlier patch but just missed.

This passes userdef.exp with -fsanitize=address.

gdb/ChangeLog
2018-11-29  Tom Tromey  <tom@tromey.com>

	* valarith.c (value_x_unop): Don't set argvec[3].
2018-11-29 10:49:38 -07:00
Tom Tromey d105de22fc Fix use-after-free in gdbserver
-fsanitize=address pointed out a use-after-free in gdbserver.  In
particular, handle_detach could reference "process" after it was
deleted by detach_inferior.  Avoiding this also necessitated changing
target_ops::join to take a pid rather than a process_info*.

Tested by the buildbot using a few of the gdbserver builders.

gdb/gdbserver/ChangeLog
2018-11-29  Tom Tromey  <tom@tromey.com>

	* win32-low.c (win32_join): Take pid, not process.
	* target.h (struct target_ops) <join>: Change argument type.
	(join_inferior): Change argument name.
	* spu-low.c (spu_join): Take pid, not process.
	* server.c (handle_detach): Preserve pid before destroying
	process.
	* lynx-low.c (lynx_join): Take pid, not process.
	* linux-low.c (linux_join): Take pid, not process.
2018-11-29 10:47:42 -07:00
Simon Marchi ed2df75c51 Fix spurious semicolon in sparc-linux-nat.c
Remove a semicolon that should not be there, as reported in PR 23917:

  CXX    sparc-linux-nat.o
/home/emaisin/src/binutils-gdb/gdb/sparc-linux-nat.c:39:3: error: expected unqualified-id before ‘{’ token
   { sparc_store_inferior_registers (regcache, regnum); }
   ^

Tested by rebuilding the file manually (make sparc-linux-nat.o) in a
sparc64-linux-gnu build.

gdb/ChangeLog:

	PR gdb/23917
	* sparc-linux-nat.c (sparc_linux_nat_target): Remove extraneous
	semicolon.
2018-11-26 14:35:11 -05:00
Pedro Alves 24bce9bbe5 Fix Solaris build
The recent commit 0803633106 ("Per-inferior thread list, thread
ranges/iterators, down with ALL_THREADS, etc.") removed the
definitions of is_running/is_stopped/is_exited but missed updating a
couple uses of is_exited in Solaris-specific code.

Tested by Rainer Orth on amd64-pc-solaris2.11.

gdb/ChangeLog:
2018-11-26  Pedro Alves  <palves@redhat.com>

	* procfs.c (procfs_notice_thread): Replace uses of
	in_thread_list/is_exited with find_thread_ptid/THREAD_EXITED.
	* sol-thread.c (sol_thread_target::wait)
	(sol_update_thread_list_callback): Likewise.
2018-11-26 13:16:26 +00:00
Sergio Durigan Junior f63c03b470 Implement timestamp'ed output on "make check"
It is unfortunately not uncommon to have tests hanging on some of the
BuildBot workers.  For example, the ppc64be/ppc64le+gdbserver builders
are especially in a bad state when it comes to testing GDB/gdbserver,
and we can have builds that take an absurd amount of time to
finish (almost 1 week for one single build, for example).

It may be hard to diagnose these failures, because sometimes we don't
have access to the faulty systems, and other times we're just too busy
to wait and check which test is actually hanging.  During one of our
conversations about the topic, someone proposed that it would be a
good idea to have a timestamp put together with stdout output, so that
we can come back later and examine which tests are taking too long to
complete.

Here's my proposal to do this.  The very first thing I tried to do was
to use "ts(1)" to achieve this feature, and it obviously worked, but
the problem is that I'm afraid "ts(1)" may not be widely available on
every system we support.  Therefore, I decided to implement a *very*
simple version of "ts(1)", in Python 3, which basically does the same
thing: iterate over the stdin lines, and prepend a timestamp onto
them.

As for testsuite/Makefile.in, the user can now specify two new
variables to enable timestamp'ed output: TS (which enables the
output), and TS_FORMAT (optional, used to specify another timestamp
format according to "strftime").

Here's an example of how the output looks like:

  ...
  [Nov 22 17:07:19] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/call-strs.exp ...
  [Nov 22 17:07:19] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/step-over-no-symbols.exp ...
  [Nov 22 17:07:20] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/all-architectures-6.exp ...
  [Nov 22 17:07:20] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/hashline3.exp ...
  [Nov 22 17:07:20] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/max-value-size.exp ...
  [Nov 22 17:07:20] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/quit-live.exp ...
  [Nov 22 17:07:46] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/paginate-bg-execution.exp ...
  [Nov 22 17:07:56] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/gcore-buffer-overflow.exp ...
  [Nov 22 17:07:56] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/gcore-relro.exp ...
  [Nov 22 17:07:56] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/watchpoint-delete.exp ...
  [Nov 22 17:07:56] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/breakpoint-in-ro-region.exp ...
  [Nov 22 17:07:56] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/vla-sideeffect.exp ...
  [Nov 22 17:07:57] [1234] Running binutils-gdb/gdb/testsuite/gdb.base/unload.exp ...
  ...

(What, gdb.base/quit-live.exp is taking 26 seconds to complete?!)

Output to stderr is not timestamp'ed, but I don't think that will be a
problem for us.  If it is, we can revisit the solution and extend it.

gdb/testsuite/ChangeLog:
2018-11-25  Sergio Durigan Junior  <sergiodj@redhat.com>

	* Makefile.in (TIMESTAMP): New variable.
	(check-single): Add $(TIMESTAMP) to the end of $(DO_RUNTEST)
	command.
	(check-single-racy): Likewise.
	(check/%.exp): Likewise.
	(check-racy/%.exp): Likewise.
	(workers/%.worker): Likewise.
	(build-perf): Likewise.
	(check-perf): Likewise.
	* README: Describe new "TS" and "TS_FORMAT" variables.
	* print-ts.py: New file.
2018-11-25 18:21:26 -05:00
Tom Tromey b5b12e1dbe Remove obsolete comments from field_fmt
This removes some comments that I believe were made obsolete by the
recent change to cli_ui_out::do_field_fmt.  The comment in mi_ui_out
probably was just copy/paste, because I think aligning never made
sense in an MI context.

gdb/ChangeLog
2018-11-25  Tom Tromey  <tom@tromey.com>

	* ui-out.c (ui_out::field_fmt): Remove comment.
	* tui/tui-out.c (tui_ui_out::do_field_fmt): Remove comment.
	* mi/mi-out.c (mi_ui_out::do_field_fmt): Remove comment.
2018-11-25 15:29:35 -07:00
Philippe Waroquiers 5446094655 Re-fix leak in source.c (open_source_file).
Leak fixed in '8e6a5953e1d Fix 4K leak in open_source_file' has been partially
undone by '2179fbc36d23 Return scoped_fd from open_source_file'. Re-add the
transfer of current s->fullname to the unique_xmalloc_ptr fullname given to
find_and_open_source.
2018-11-24 12:42:24 +01:00
Alan Hayward 5013824590 gdbserver: AArch64: Remove cannot_fetch/store_register
The cannot store/fetch register functions are only used for checking
if a register can be accessed using PEEKUSER/POKEUSER.
The AArch64 port doesn't support this method of access, so remove the
unused functions.

gdb/gdbserver:
	* linux-aarch64-low.c (aarch64_cannot_store_register): Remove.
	(aarch64_cannot_fetch_register): Likewise.
	(struct linux_target_ops): Update references.
2018-11-23 14:12:46 +00:00
Pedro Alves 6af05e645a Remove declarations of is_running/is_stopped/is_exited
The recent commit 0803633106 ("Per-inferior thread list, thread
ranges/iterators, down with ALL_THREADS, etc.") removed the
definitions of is_running/is_stopped/is_exited but missed removing the
declarations.

gdb/ChangeLog:
2018-11-23  Pedro Alves  <palves@redhat.com>

	* gdbthread.h (enum thread_state): Move comments here.
	(is_running, is_stopped, is_exited): Remove declarations.
2018-11-23 13:36:59 +00:00
Pedro Alves 0803633106 Per-inferior thread list, thread ranges/iterators, down with ALL_THREADS, etc.
As preparation for multi-target, this patch makes each inferior have
its own thread list.

This isn't absolutely necessary for multi-target, but simplifies
things.  It originally stemmed from the desire to eliminate the
init_thread_list calls sprinkled around, plus it makes it more
efficient to iterate over threads of a given inferior (no need to
always iterate over threads of all inferiors).

We still need to iterate over threads of all inferiors in a number of
places, which means we'd need adjust the ALL_THREADS /
ALL_NON_EXITED_THREADS macros.  However, naively tweaking those macros
to have an extra for loop, like:

     #define ALL_THREADS (thr, inf) \
       for (inf = inferior_list; inf; inf = inf->next) \
	 for (thr = inf->thread_list; thr; thr = thr->next)

causes problems with code that does "break" or "continue" within the
ALL_THREADS loop body.  Plus, we need to declare the extra "inf" local
variable in order to pass it as temporary variable to ALL_THREADS
(etc.)

It gets even trickier when we consider extending the macros to filter
out threads matching a ptid_t and a target.  The macros become tricker
to read/write.  Been there.

An alternative (which was my next attempt), is to replace the
ALL_THREADS etc. iteration style with for_each_all_threads,
for_each_non_exited_threads, etc. functions which would take a
callback as parameter, which would usually be passed a lambda.
However, I did not find that satisfactory at all, because the
resulting code ends up a little less natural / more noisy to read,
write and debug/step-through (due to use of lambdas), and in many
places where we use "continue;" to skip to the next thread now need to
use "return;".  (I ran into hard to debug bugs caused by a
continue/return confusion.)

I.e., before:

    ALL_NON_EXITED_THREADS (tp)
      {
	if (tp->not_what_I_want)
	  continue;
	// do something
      }

would turn into:

    for_each_non_exited_thread ([&] (thread_info *tp)
      {
	if (tp->not_what_I_want)
	  return;
	// do something
      });

Lastly, the solution I settled with was to replace the ALL_THREADS /
ALL_NON_EXITED_THREADS / ALL_INFERIORS macros with (C++20-like) ranges
and iterators, such that you can instead naturaly iterate over
threads/inferiors using range-for, like e.g,.:

   // all threads, including THREAD_EXITED threads.
   for (thread_info *tp : all_threads ())
     { .... }

   // all non-exited threads.
   for (thread_info *tp : all_non_exited_threads ())
     { .... }

   // all non-exited threads of INF inferior.
   for (thread_info *tp : inf->non_exited_threads ())
     { .... }

The all_non_exited_threads() function takes an optional filter ptid_t as
parameter, which is quite convenient when we need to iterate over
threads matching that filter.  See e.g., how the
set_executing/set_stop_requested/finish_thread_state etc. functions in
thread.c end up being simplified.

Most of the patch thus is about adding the infrustructure for allowing
the above.  Later on when we get to actual multi-target, these
functions/ranges/iterators will gain a "target_ops *" parameter so
that e.g., we can iterate over all threads of a given target that
match a given filter ptid_t.

The only entry points users needs to be aware of are the
all_threads/all_non_exited_threads etc. functions seen above.  Thus,
those functions are declared in gdbthread.h/inferior.h.  The actual
iterators/ranges are mainly "internals" and thus are put out of view
in the new thread-iter.h/thread-iter.c/inferior-iter.h files.  That
keeps the gdbthread.h/inferior.h headers quite a bit more readable.

A common/safe-iterator.h header is added which adds a template that
can be used to build "safe" iterators, which are forward iterators
that can be used to replace the ALL_THREADS_SAFE macro and other
instances of the same idiom in future.

There's a little bit of shuffling of code between
gdbthread.h/thread.c/inferior.h in the patch.  That is necessary in
order to avoid circular dependencies between the
gdbthread.h/inferior.h headers.

As for the init_thread_list calls sprinkled around, they're all
eliminated by this patch, and a new, central call is added to
inferior_appeared.  Note how also related to that, there's a call to
init_wait_for_inferior in remote.c that is eliminated.
init_wait_for_inferior is currently responsible for discarding skipped
inline frames, which had to be moved elsewhere.  Given that nowadays
we always have a thread even for single-threaded processes, the
natural place is to delete a frame's inline frame info when we delete
the thread.  I.e., from clear_thread_inferior_resources.

gdb/ChangeLog:
2018-11-22  Pedro Alves  <palves@redhat.com>

	* Makefile.in (COMMON_SFILES): Add thread-iter.c.
	* breakpoint.c (breakpoints_should_be_inserted_now): Replace
	ALL_NON_EXITED_THREADS with all_non_exited_threads.
	(print_one_breakpoint_location): Replace ALL_INFERIORS with
	all_inferiors.
	* bsd-kvm.c: Include inferior.h.
	* btrace.c (btrace_free_objfile): Replace ALL_NON_EXITED_THREADS
	with all_non_exited_threads.
	* common/filtered-iterator.h: New.
	* common/safe-iterator.h: New.
	* corelow.c (core_target_open): Don't call init_thread_list here.
	* darwin-nat.c (thread_info_from_private_thread_info): Replace
	ALL_THREADS with all_threads.
	* fbsd-nat.c (fbsd_nat_target::resume): Replace
	ALL_NON_EXITED_THREADS with inf->non_exited_threads.
	* fbsd-tdep.c (fbsd_make_corefile_notes): Replace
	ALL_NON_EXITED_THREADS with inf->non_exited_threads.
	* fork-child.c (postfork_hook): Don't call init_thread_list here.
	* gdbarch-selftests.c (register_to_value_test): Adjust.
	* gdbthread.h: Don't include "inferior.h" here.
	(struct inferior): Forward declare.
	(enum step_over_calls_kind): Moved here from inferior.h.
	(thread_info::deletable): Definition moved to thread.c.
	(find_thread_ptid (inferior *, ptid_t)): Declare.
	(ALL_THREADS, ALL_THREADS_BY_INFERIOR, ALL_THREADS_SAFE): Delete.
	Include "thread-iter.h".
	(all_threads, all_non_exited_threads, all_threads_safe): New.
	(any_thread_p): Declare.
	(thread_list): Delete.
	* infcmd.c (signal_command): Replace ALL_NON_EXITED_THREADS with
	all_non_exited_threads.
	(proceed_after_attach_callback): Delete.
	(proceed_after_attach): Take an inferior pointer instead of an
	integer PID.  Adjust to use range-for.
	(attach_post_wait): Pass down inferior pointer instead of pid.
	Use range-for instead of ALL_NON_EXITED_THREADS.
	(detach_command): Remove init_thread_list call.
	* inferior-iter.h: New.
	* inferior.c (struct delete_thread_of_inferior_arg): Delete.
	(delete_thread_of_inferior): Delete.
	(delete_inferior, exit_inferior_1): Use range-for with
	inf->threads_safe() instead of iterate_over_threads.
	(inferior_appeared): Call init_thread_list here.
	(discard_all_inferiors): Use all_non_exited_inferiors.
	(find_inferior_id, find_inferior_pid): Use all_inferiors.
	(iterate_over_inferiors): Use all_inferiors_safe.
	(have_inferiors, number_of_live_inferiors): Use
	all_non_exited_inferiors.
	(number_of_inferiors): Use all_inferiors and std::distance.
	(print_inferior): Use all_inferiors.
	* inferior.h: Include gdbthread.h.
	(enum step_over_calls_kind): Moved to gdbthread.h.
	(struct inferior) <thread_list>: New field.
	<threads, non_exited_threads, threads_safe>: New methods.
	(ALL_INFERIORS): Delete.
	Include "inferior-iter.h".
	(ALL_NON_EXITED_INFERIORS): Delete.
	(all_inferiors_safe, all_inferiors, all_non_exited_inferiors): New
	functions.
	* inflow.c (child_interrupt, child_pass_ctrlc): Replace
	ALL_NON_EXITED_THREADS with all_non_exited_threads.
	* infrun.c (follow_exec): Use all_threads_safe.
	(clear_proceed_status, proceed): Use all_non_exited_threads.
	(init_wait_for_inferior): Don't clear inline frame state here.
	(infrun_thread_stop_requested, for_each_just_stopped_thread): Use
	all_threads instead of ALL_NON_EXITED_THREADS.
	(random_pending_event_thread): Use all_non_exited_threads instead
	of ALL_NON_EXITED_THREADS.  Use a lambda for repeated code.
	(clean_up_just_stopped_threads_fsms): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	(handle_no_resumed): Use all_non_exited_threads instead of
	ALL_NON_EXITED_THREADS.  Use all_inferiors instead of
	ALL_INFERIORS.
	(restart_threads, switch_back_to_stepped_thread): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* linux-nat.c (check_zombie_leaders): Replace ALL_INFERIORS with
	all_inferiors.
	(kill_unfollowed_fork_children): Use inf->non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	* linux-tdep.c (linux_make_corefile_notes): Use
	inf->non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* linux-thread-db.c (thread_db_target::update_thread_list):
	Replace ALL_INFERIORS with all_inferiors.
	(thread_db_target::thread_handle_to_thread_info): Use
	inf->non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* mi/mi-interp.c (multiple_inferiors_p): New.
	(mi_on_resume_1): Simplify using all_non_exited_threads and
	multiple_inferiors_p.
	* mi/mi-main.c (mi_cmd_thread_list_ids): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	* nto-procfs.c (nto_procfs_target::open): Don't call
	init_thread_list here.
	* record-btrace.c (record_btrace_target_open)
	(record_btrace_target::stop_recording)
	(record_btrace_target::close)
	(record_btrace_target::record_is_replaying)
	(record_btrace_target::resume, record_btrace_target::wait)
	(record_btrace_target::record_stop_replaying): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* record-full.c (record_full_wait_1): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	* regcache.c (cooked_read_test): Remove reference to global
	thread_list.
	* remote-sim.c (gdbsim_target::create_inferior): Don't call
	init_thread_list here.
	* remote.c (remote_target::update_thread_list): Use
	all_threads_safe instead of ALL_NON_EXITED_THREADS.
	(remote_target::process_initial_stop_replies): Replace
	ALL_INFERIORS with all_non_exited_inferiors and use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	(remote_target::open_1): Don't call init_thread_list here.
	(remote_target::append_pending_thread_resumptions)
	(remote_target::remote_resume_with_hc): Use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	(remote_target::commit_resume)
	(remote_target::remove_new_fork_children): Replace ALL_INFERIORS
	with all_non_exited_inferiors and use all_non_exited_threads
	instead of ALL_NON_EXITED_THREADS.
	(remote_target::kill_new_fork_children): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.  Remove
	init_thread_list and init_wait_for_inferior calls.
	(remote_target::remote_btrace_maybe_reopen)
	(remote_target::thread_handle_to_thread_info): Use
	all_non_exited_threads instead of ALL_NON_EXITED_THREADS.
	* target.c (target_terminal::restore_inferior)
	(target_terminal_is_ours_kind): Replace ALL_INFERIORS with
	all_non_exited_inferiors.
	* thread-iter.c: New file.
	* thread-iter.h: New file.
	* thread.c: Include "inline-frame.h".
	(thread_list): Delete.
	(clear_thread_inferior_resources): Call clear_inline_frame_state.
	(init_thread_list): Use all_threads_safe instead of
	ALL_THREADS_SAFE.  Adjust to per-inferior thread lists.
	(new_thread): Adjust to per-inferior thread lists.
	(add_thread_silent): Pass inferior to find_thread_ptid.
	(thread_info::deletable): New, moved from the header.
	(delete_thread_1): Adjust to per-inferior thread lists.
	(find_thread_global_id): Use inf->threads().
	(find_thread_ptid): Use find_inferior_ptid and pass inferior to
	find_thread_ptid.
	(find_thread_ptid(inferior*, ptid_t)): New overload.
	(iterate_over_threads): Use all_threads_safe.
	(any_thread_p): New.
	(thread_count): Use all_threads and std::distance.
	(live_threads_count): Use all_non_exited_threads and
	std::distance.
	(valid_global_thread_id): Use all_threads.
	(in_thread_list): Use find_thread_ptid.
	(first_thread_of_inferior): Adjust to per-inferior thread lists.
	(any_thread_of_inferior, any_live_thread_of_inferior): Use
	inf->non_exited_threads().
	(prune_threads, delete_exited_threads): Use all_threads_safe.
	(thread_change_ptid): Pass inferior pointer to find_thread_ptid.
	(set_resumed, set_running): Use all_non_exited_threads.
	(is_thread_state, is_stopped, is_exited, is_running)
	(is_executing): Delete.
	(set_executing, set_stop_requested, finish_thread_state): Use
	all_non_exited_threads.
	(print_thread_info_1): Use all_inferiors and all_threads.
	(thread_apply_all_command): Use all_non_exited_threads.
	(thread_find_command): Use all_threads.
	(update_threads_executing): Use all_non_exited_threads.
	* tid-parse.c (parse_thread_id): Use inf->threads.
	* x86-bsd-nat.c (x86bsd_dr_set): Use inf->non_exited_threads ().
2018-11-22 16:13:23 +00:00
Pedro Alves c4c17fb0f5 Fix follow_exec latent problem
A following commit to make each inferior have its own thread list
exposes a problem with bf93d7ba99 ("Add thread after updating gdbarch
when exec'ing"), which is that we can't defer adding the thread
because that breaks try_open_exec_file which deep inside ends up
calling inferior_thread():

 #5  0x0000000000637c78 in internal_error(char const*, int, char const*, ...) (file=0xc151f8 "src/gdb/thread.c", line=165, fmt=0xc15180 "%s: Assertion `%s' failed.") at src/gdb/common/errors.c:55
 #6  0x00000000008a3d80 in inferior_thread() () at src/gdb/thread.c:165
 #7  0x0000000000456f91 in try_thread_db_load_1(thread_db_info*) (info=0x277eb00) at src/gdb/linux-thread-db.c:830
 #8  0x0000000000457554 in try_thread_db_load(char const*, int) (library=0xb01a4f "libthread_db.so.1", check_auto_load_safe=0)
     at src/gdb/linux-thread-db.c:1002
 #9  0x0000000000457861 in try_thread_db_load_from_sdir() () at src/gdb/linux-thread-db.c:1079
 #10 0x0000000000457b72 in thread_db_load_search() () at src/gdb/linux-thread-db.c:1134
 #11 0x0000000000457d29 in thread_db_load() () at src/gdb/linux-thread-db.c:1192
 #12 0x0000000000457e51 in check_for_thread_db() () at src/gdb/linux-thread-db.c:1244
 #13 0x0000000000457ed2 in thread_db_new_objfile(objfile*) (objfile=0x270ff60) at src/gdb/linux-thread-db.c:1273
 #14 0x000000000045a92e in std::_Function_handler<void (objfile*), void (*)(objfile*)>::_M_invoke(std::_Any_data const&, objfile*&&) (__functor=..., __args#0=@0x7ffef3efe140: 0x270ff60) at /usr/include/c++/7/bits/std_function.h:316
 #15 0x00000000007bbebf in std::function<void (objfile*)>::operator()(objfile*) const (this=0x24e1d18, __args#0=0x270ff60)
     at /usr/include/c++/7/bits/std_function.h:706
 #16 0x00000000007bba86 in gdb::observers::observable<objfile*>::notify(objfile*) const (this=0x117ce80 <gdb::observers::new_objfile>, args#0=0x270ff60) at src/gdb/common/observable.h:106
 #17 0x0000000000856000 in symbol_file_add_with_addrs(bfd*, char const*, symfile_add_flags, section_addr_info*, objfile_flags, objfile*) (abfd=0x1d7dae0, name=0x254bfc0 "/ho

The problem is latent currently because inferior_thread() at that
point manages to return a thread, even though it's the wrong one (of
the old inferior).

The problem originally fixed by bf93d7ba99 was:

    (...) we should avoid doing register reads
    after a process does an exec and before we've updated that inferior's
    gdbarch.  Otherwise, we may interpret the registers using the wrong
    architecture.

    (...) The call to "add_thread" done just after adding the inferior is
    problematic, because it ends up reading the registers (because the ptid
    is re-used, we end up doing a switch_to_thread to it, which tries to
    update stop_pc). (...)

The register-reading issue is no longer a problem nowadays, ever since
switch_to_thread stopped reading the stop_pc in git commit
f2ffa92bbc ("gdb: Eliminate the 'stop_pc' global").

So this commit basically reverts bf93d7ba99.

gdb/ChangeLog:
2018-11-22  Pedro Alves  <palves@redhat.com>

	* infrun.c (follow_exec) <set follow-exec new>: Add thread and
	switch to it before calling into try_open_exec_file.
2018-11-22 16:12:54 +00:00
Pedro Alves 151bb4a505 Avoid find_thread_ptid with null_ptid
With a following patch, find_thread_ptid will first find the inferior
for the passed-in ptid, using find_inferior_pid, and then look for the
thread in that inferior's thread list.  If we pass down null_ptid to
find_thread_ptid then that means we'll end up passing 0 to
find_inferior_pid, which hits this assertion:

>   struct inferior *
>   find_inferior_pid (int pid)
>   {
>     struct inferior *inf;
>
>     /* Looking for inferior pid == 0 is always wrong, and indicative of
>	a bug somewhere else.  There may be more than one with pid == 0,
>	for instance.  */
>     gdb_assert (pid != 0);

This patch prepares for the change, by avoiding passing down null_ptid
to find_thread_ptid or to functions that naturally use it, such as the
target_pid_to_str call in inferior.c:add_inferior.  In that latter
case, the patch changes GDB output,

from:
 (gdb) add-inferior
 [New inferior 2 (process 0)]

to:
 (gdb) add-inferior
 [New inferior 2]

which seems like a good change to me.  It might not even make sense to
talk about "process" for the current target, for example.

The python_on_normal_stop change ends up avoiding looking up the
same thread twice (inferior_thread also does a look up).

gdb/ChangeLog:
2018-11-22  Pedro Alves  <palves@redhat.com>

	* cli/cli-interp.c (cli_on_user_selected_context_changed): Use
	inferior_thread instead of find_thread_ptid, and only when
	inferior_ptid is not null_ptid.
	* inferior.c (add_inferior): Don't include target_pid_to_str
	output when the inferior is not started.
	* python/py-inferior.c (python_on_normal_stop): Don't use
	find_thread_ptid.
	(tui_on_user_selected_context_changed): Use inferior_thread
	instead of find_thread_ptid, and only when inferior_ptid is not
	null_ptid.
2018-11-22 16:09:12 +00:00
Benno Fünfstück 1c97054b87 Make command-repeat work after gdb.execute
Since commit

  56bcdbea2b ("Let gdb.execute handle multi-line commands")

command repetition after using the `gdb.execute` Python function
fails (the previous command is not repeated anymore). This happens
because read_command_lines_1 sets dont_repeat, but the call to
prevent_dont_repeat in execute_gdb_command is later.

The fix is to move the call to prevent_dont_repeat to the beginning of
the function.

Tested on my laptop (ArchLinux-x86_64).

gdb/ChangeLog:

	PR python/23714
	* gdb/python/python.c (execute_gdb_command): Call
	prevent_dont_repeat earlier to avoid affecting dont_repeat.

gdb/testuite/ChangeLog:

	PR python/23714
	* gdb.python/python.exp: Test command repetition after
	gdb.execute.
2018-11-21 17:06:05 +00:00
Andrew Burgess b5ffee3181 gdb/riscv: Add target description support
This commit adds target description support for riscv.

I've used the split feature approach for specifying the architectural
features, and the CSR feature is auto-generated from the riscv-opc.h
header file.

If the target doesn't provide a suitable target description then GDB
will build one by looking at the bfd headers.

This commit does not implement target description creation for the
Linux or FreeBSD native targets, both of these will need to add
read_description methods into their respective target classes, which
probe the target features, and then call
riscv_create_target_description to build a suitable target
description.  Until this is done Linux and FreeBSD will get the same
default target description based on the bfd that bare-metal targets
get.

I've only added feature descriptions for 32 and 64 bit registers, 128
bit registers (for RISC-V) are not supported in the reset of GDB yet.

This commit removes the special reading of the MISA register in order
to establish the target features, this was only used for figuring out
the f-register size, and even that wasn't done consistently.  We now
rely on the target to tell us what size of registers it has (or look
in the BFD as a last resort).  The result of this is that we should
now support RV64 targets with 32-bit float, though I have not
extensively tested this combination yet.

	* Makefile.in (ALL_TARGET_OBS): Add arch/riscv.o.
	(HFILES_NO_SRCDIR): Add arch/riscv.h.
	* arch/riscv.c: New file.
	* arch/riscv.h: New file.
	* configure.tgt: Add cpu_obs list of riscv, move riscv-tdep.o into
	this list, and add arch/riscv.o.
	* features/Makefile: Add riscv features.
	* features/riscv/32bit-cpu.c: New file.
	* features/riscv/32bit-cpu.xml: New file.
	* features/riscv/32bit-csr.c: New file.
	* features/riscv/32bit-csr.xml: New file.
	* features/riscv/32bit-fpu.c: New file.
	* features/riscv/32bit-fpu.xml: New file.
	* features/riscv/64bit-cpu.c: New file.
	* features/riscv/64bit-cpu.xml: New file.
	* features/riscv/64bit-csr.c: New file.
	* features/riscv/64bit-csr.xml: New file.
	* features/riscv/64bit-fpu.c: New file.
	* features/riscv/64bit-fpu.xml: New file.
	* features/riscv/rebuild-csr-xml.sh: New file.
	* riscv-tdep.c: Add 'arch/riscv.h' include.
	(riscv_gdb_reg_names): Delete.
	(csr_reggroup): New global.
	(struct riscv_register_alias): Delete.
	(struct riscv_register_feature): New structure.
	(riscv_register_aliases): Delete.
	(riscv_xreg_feature): New global.
	(riscv_freg_feature): New global.
	(riscv_virtual_feature): New global.
	(riscv_csr_feature): New global.
	(riscv_create_csr_aliases): New function.
	(riscv_read_misa_reg): Delete.
	(riscv_has_feature): Delete.
	(riscv_isa_xlen): Simplify, just return cached xlen.
	(riscv_isa_flen): Simplify, just return cached flen.
	(riscv_has_fp_abi): Update for changes in struct gdbarch_tdep.
	(riscv_register_name): Update to make use of tdesc_register_name.
	Look up xreg and freg names in the new globals riscv_xreg_feature
	and riscv_freg_feature.  Don't supply csr aliases here.
	(riscv_fpreg_q_type): Delete.
	(riscv_register_type): Use tdesc_register_type in almost all
	cases, override the returned type in a few specific cases only.
	(riscv_print_one_register_info): Handle errors reading registers.
	(riscv_register_reggroup_p): Use tdesc_register_in_reggroup_p for
	registers that are otherwise unknown to GDB.  Also check the
	csr_reggroup.
	(riscv_print_registers_info): Remove assert about upper register
	number, and use gdbarch_register_reggroup_p instead of
	short-cutting.
	(riscv_find_default_target_description): New function.
	(riscv_check_tdesc_feature): New function.
	(riscv_add_reggroups): New function.
	(riscv_setup_register_aliases): New function.
	(riscv_init_reggroups): New function.
	(_initialize_riscv_tdep): Add calls to setup CSR aliases, and
	setup register groups.  Register new riscv debug variable.
	* riscv-tdep.h: Add 'arch/riscv.h' include.
	(struct gdbarch_tdep): Remove abi union, and add
	riscv_gdbarch_features field.  Remove cached quad floating point
	type, and provide initialisation for double type field.
	* target-descriptions.c (maint_print_c_tdesc_cmd): Add riscv to
	the list of targets using the feature based target descriptions.
	* NEWS: Mention target description support.

gdb/doc/ChangeLog:

	* gdb.texinfo (Standard Target Features): Add RISC-V Features
	sub-section.
2018-11-21 13:09:50 +00:00
Pedro Alves 38139a9681 valops.c: Overload resolution code: Rename parameters/locals
While looking over this code, I thought the names of the parameters to
find_oload_champ and related functions and locals were a bit too
cryptic.  For example, FN_LIST holds methods, not free functions.
Free-functions are in OLOAD_SYMS.

This patch renames parameters/variables to the more obvious
methods/xmethods/functions instead.

gdb/ChangeLog:
2018-11-21  Pedro Alves  <palves@redhat.com>

	* valops.c (find_method_list, value_find_oload_method_list)
	(find_overload_match, find_oload_champ): Rename parameters and
	locals.
2018-11-21 12:27:29 +00:00
Pedro Alves 85cca2bcbc valops.c: Some more gdb::array_view
This commit replaces some more use of pointer+length pairs in the
overload resolution code with gdb::array_view.

find_oload_champ's interface is simplified/normalized: the xmethods
parameter is converted from std::vector to array pointer, and then the
num_fns parameter is always passed in, no matter the array which is
non-NULL.  I tweaked the formatting of callers a little bit here and
there so that the 3 optional parameters are all in the same line.  (I
tried making the 3 optional array parameters be array_views, but the
resulting code didn't look as nice.)

gdb/ChangeLog:
2018-11-21  Pedro Alves  <palves@redhat.com>

	* valops.c (find_method_list): Replace pointer and length
	parameters with an gdb::array_view.  Adjust.
	(value_find_oload_method_list): Likewise.
	(find_overload_match): Use gdb::array_view for methods list.
	Adjust to find_oload_champ interface change.
	(find_oload_champ): 'xm_worker_vec' parameter now a pointer/array.
	'num_fns' parameter now a size_t.  Eliminate 'fn_count' local.
2018-11-21 12:11:45 +00:00
Pedro Alves 82ceee5014 C++ify badness_vector, fix leaks
badness_vector is currently an open coded vector.  This reimplements
it as a std::vector.

This fixes a few leaks as well:

 - find_oload_champ is leaking every badness vector calculated bar the
   one returned.

 - bv->rank is always leaked, since callers of rank_function only
   xfree the badness_vector pointer, not bv->rank.

gdb/ChangeLog:
2018-11-21  Pedro Alves  <palves@redhat.com>

	* gdbtypes.c (compare_badness): Change type of parameters to const
	reference.  Adjust to badness_vector being a std::vector now.
	(rank_function): Adjust to badness_vector being a std::vector now.
	* gdbtypes.h (badness_vector): Now a typedef to std::vector.
	(LENGTH_MATCH): Delete.
	(compare_badness): Change type of parameters to const reference.
	(rank_function): Return a badness_vector by value now.
	(find_overload_match): Adjust to badness_vector being a
	std::vector now.  Remove cleanups.
	(find_oload_champ_namespace): 'oload_champ_bv' parameter now a
	badness_vector pointer.
	(find_oload_champ_namespace_loop): 'oload_champ_bv' parameter now
	a badness_vector pointer.  Adjust to badness_vector being a
	std::vector now.  Remove cleanups.
	(find_oload_champ): 'oload_champ_bv' parameter now
	a badness_vector pointer.  Adjust to badness_vector being a
	std::vector now.  Remove cleanups.
2018-11-21 12:06:51 +00:00
Pedro Alves 0891c3cc13 Eliminate make_symbol_overload_list-related globals & cleanup
This gets rid of a few globals and a cleanup.

make_symbol_overload_list & friends currently maintain a global
open-coded vector.  Reimplement that with a std::vector, trickled down
through the functions.  Rename a few functions from "make_" to "add_"
for clarity.

gdb/ChangeLog:
2018-11-21  Pedro Alves  <palves@redhat.com>

	* cp-support.c (sym_return_val_size, sym_return_val_index)
	(sym_return_val): Delete.
	(overload_list_add_symbol): Add std::vector parameter.  Adjust to
	add to the vector.
	(make_symbol_overload_list): Adjust to return a std::vector
	instead of maintaining a global open coded vector.
	(make_symbol_overload_list_block): Add std::vector parameter.
	(make_symbol_overload_list_block): Rename to ...
	(add_symbol_overload_list_block): ... this and add std::vector
	parameter.
	(make_symbol_overload_list_namespace): Rename to ...
	(add_symbol_overload_list_namespace): ... this and add std::vector
	parameter.
	(make_symbol_overload_list_adl_namespace): Rename to ...
	(add_symbol_overload_list_adl_namespace): ... this and add
	std::vector parameter.
	(make_symbol_overload_list_adl): Delete.
	(add_symbol_overload_list_adl): New.
	(make_symbol_overload_list_using): Rename to ...
	(add_symbol_overload_list_using): ... this and add std::vector
	parameter.
	(make_symbol_overload_list_qualified): Rename to ...
	(add_symbol_overload_list_qualified): ... this and add std::vector
	parameter.
	* cp-support.h: Include "common/array-view.h" and <vector>.
	(make_symbol_overload_list): Change return type to std::vector.
	(make_symbol_overload_list_adl): Delete declaration.
	(add_symbol_overload_list_adl): New declaration.
	* valops.c (find_overload_match): Local 'oload_syms' now a
	std::vector.
	(find_oload_champ_namespace): 'oload_syms' parameter now a
	std::vector pointer.
	(find_oload_champ_namespace_loop): 'oload_syms' parameter now a
	std::vector pointer.  Adjust to new make_symbol_overload_list
	interface.
2018-11-21 12:06:36 +00:00
Pedro Alves 6b1747cd13 invoke_xmethod & array_view
This replaces more pointer+length with gdb::array_view.  This time,
around invoke_xmethod, and then propagating the fallout around, which
inevitably leaks to the overload resolution code.

There are several places in the code that want to grab a slice of an
array, by advancing the array pointer, and decreasing the length
pointer.  This patch introduces a pair of new
gdb::array_view::slice(...) methods to make that convenient and clear.
Unit test included.

gdb/ChangeLog:
2018-11-21  Pedro Alves  <palves@redhat.com>

	* common/array-view.h (array_view::splice(size_type, size_t)): New.
	(array_view::splice(size_type)): New.
	* eval.c (eval_call, evaluate_funcall): Adjust to use array_view.
	* extension.c (xmethod_worker::get_arg_types): Adjust to return an
	std::vector.
	(xmethod_worker::get_result_type): Adjust to use gdb::array_view.
	* extension.h: Include "common/array-view.h".
	(xmethod_worker::invoke): Adjust to use gdb::array_view.
	(xmethod_worker::get_arg_types): Adjust to return an std::vector.
	(xmethod_worker::get_result_type): Adjust to use gdb::array_view.
	(xmethod_worker::do_get_arg_types): Adjust to use std::vector.
	(xmethod_worker::do_get_result_type): Adjust to use
	gdb::array_view.
	* gdbtypes.c (rank_function): Adjust to use gdb::array_view.
	* gdbtypes.h: Include "common/array-view.h".
	(rank_function): Adjust to use gdb::array_view.
	* python/py-xmethods.c (python_xmethod_worker::invoke)
	(python_xmethod_worker::do_get_arg_types)
	(python_xmethod_worker::do_get_result_type)
	(python_xmethod_worker::invoke): Adjust to new interfaces.
	* valarith.c (value_user_defined_cpp_op, value_user_defined_op)
	(value_x_binop, value_x_unop): Adjust to use gdb::array_view.
	* valops.c (find_overload_match, find_oload_champ_namespace)
	(find_oload_champ_namespace_loop, find_oload_champ): Adjust to use
	gdb:array_view and the new xmethod_worker interfaces.
	* value.c (result_type_of_xmethod, call_xmethod): Adjust to use
	gdb::array_view.
	* value.h (find_overload_match, result_type_of_xmethod)
	(call_xmethod): Adjust to use gdb::array_view.
	* unittests/array-view-selftests.c: Add slicing tests.
2018-11-21 12:06:20 +00:00
Pedro Alves e71585ffe2 Use gdb:array_view in call_function_by_hand & friends
This replaces a few uses of pointer+length with gdb::array_view, in
call_function_by_hand and related code.

Unfortunately, due to -Wnarrowing, there are places where we can't
brace-initialize an gdb::array_view without an ugly-ish cast.  To
avoid the cast, this patch introduces a gdb::make_array_view function.
Unit tests included.

This patch in isolation may not look so interesting, due to
gdb::make_array_view uses, but I think it's still worth it.  Some of
the gdb::make_array_view calls disappear down the series, and others
could be eliminated with more (non-trivial) gdb::array_view
detangling/conversion (e.g. code around eval_call).  See this as a "we
have to start somewhere" patch.

gdb/ChangeLog:
2018-11-21  Pedro Alves  <palves@redhat.com>

	* ada-lang.c (ada_evaluate_subexp): Adjust to pass an array_view.
	* common/array-view.h (make_array_view): New.
	* compile/compile-object-run.c (compile_object_run): Adjust to
	pass an array_view.
	* elfread.c (elf_gnu_ifunc_resolve_addr): Adjust.
	* eval.c (eval_call): Adjust to pass an array_view.
	(evaluate_subexp_standard): Adjust to pass an array_view.
	* gcore.c (call_target_sbrk): Adjust to pass an array_view.
	* guile/scm-value.c (gdbscm_value_call): Likewise.
	* infcall.c (push_dummy_code): Replace pointer + size parameters
	with an array_view parameter.
	(call_function_by_hand, call_function_by_hand_dummy): Likewise and
	adjust.
	* infcall.h: Include "common/array-view.h".
	(call_function_by_hand, call_function_by_hand_dummy): Replace
	pointer + size parameters with an array_view parameter.
	* linux-fork.c (inferior_call_waitpid): Adjust to use array_view.
	* linux-tdep.c (linux_infcall_mmap): Likewise.
	* objc-lang.c (lookup_objc_class, lookup_child_selector)
	(value_nsstring, print_object_command): Likewise.
	* python/py-value.c (valpy_call): Likewise.
	* rust-lang.c (rust_evaluate_funcall): Likewise.
	* spu-tdep.c (flush_ea_cache): Likewise.
	* valarith.c (value_x_binop, value_x_unop): Likewise.
	* valops.c (value_allocate_space_in_inferior): Likewise.
	* unittests/array-view-selftests.c (run_tests): Add
	gdb::make_array_view test.
2018-11-21 11:55:11 +00:00
Andrew Burgess d63095c426 gdb: Use string_printf to format int fields instead of a fixed size buffer
This patch removes a FIXME comment from cli-out.c, now instead of
formatting integers into a fixed size buffer we build a std::string
and extract the formatted integer from that.

The old code using a fixed size buffer was probably fine (the integer
was not going to overflow it) and probably slightly more efficient
(avoids building a std::string) however, given we already have utility
code in GDB that will allow the 'FIXME' comment to be removed, it
seems like an easy improvement.

gdb/ChangeLog:

	* cli-out.c (cli_ui_out::do_field_int): Use string_printf rather
	than a fixed size buffer.
2018-11-20 23:01:42 +00:00
Andrew Burgess 1871a62daf gdb: Respect field width and alignment for 'fmt' fields in CLI output
Currently the method 'cli_ui_out::do_field_fmt' has this comment:

  /* This is the only field function that does not align.  */

The reality is even slightly worse, the 'fmt' field type doesn't
respect either the field alignment or the field width.  In at least
one place in GDB we attempt to work around this lack of respect for
field width by adding additional padding manually.  But, as is often
the case, this is leading to knock on problems.

Conside the output for 'info breakpoints' when a breakpoint has
multiple locations.  This example is taken from the testsuite, from
test gdb.opt/inline-break.exp:

  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  1       breakpoint     keep y   <MULTIPLE>
  1.1                     y     0x00000000004004ae in func4b at /src/gdb/testsuite/gdb.opt/inline-break.c:64
  1.2                     y     0x0000000000400682 in func4b at /src/gdb/testsuite/gdb.opt/inline-break.c:64

The miss-alignment of the fields shown here is exactly as GDB
currently produces.

With this patch 'fmt' style fields are now first written into a
temporary buffer, and then written out as a 'string' field.  The
result is that the field width, and alignment should now be respected.
With this patch in place the output from GDB now looks like this:

  (gdb) info breakpoints
  Num     Type           Disp Enb Address            What
  1       breakpoint     keep y   <MULTIPLE>
  1.1                         y   0x00000000004004ae in func4b at /src/gdb/testsuite/gdb.opt/inline-break.c:64
  1.2                         y   0x0000000000400682 in func4b at /src/gdb/testsuite/gdb.opt/inline-break.c:64

This patch has been tested on x86-64/Linux with no regressions,
however, the testsuite doesn't always spot broken output formatting or
alignment.  I have also audited all uses of 'fmt' fields that I could
find, and I don't think there are any other places that specifically
try to work around the lack of width/alignment, however, I could have
missed something.

gdb/ChangeLog:

	* breakpoint.c (print_one_breakpoint_location): Reduce whitespace,
	and remove insertion of extra spaces in GDB's output.
	* cli-out.c (cli_ui_out::do_field_fmt): Update header comment.
	Layout field into a temporary buffer, and then output it as a
	string field.

gdb/testsuite/ChangeLog:

	* gdb.opt/inline-break.exp: Add test that info breakpoint output
	is correctly aligned.
2018-11-20 23:01:42 +00:00
Philippe Waroquiers 604c4ca9f3 NEWS: Document the language choice by 'info [types|functions|variables]|rbreak'.
gdb/ChangeLog
2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* NEWS: Document the language choice done by
	'info [types|functions|variables]|rbreak'.
2018-11-20 22:44:50 +01:00
Philippe Waroquiers 20813a0b7b Document language choice in 'info [functions|variables|types]|rbreak' commands
doc/ChangeLog
2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.texinfo (Examining the Symbol Table): Document language choice
	for 'info types|functions|variables' commands.
	(Setting Breakpoints): Document language choice to print
	the functions in which a breakpoint is set.
2018-11-20 22:44:02 +01:00
Philippe Waroquiers fb5e1ed910 Add a test to verify info [functions|variables|types]|rbreak respect language_mode.
2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.ada/info_auto_lang.exp: New testcase.
	* gdb.ada/info_auto_lang/global_pack.ads: New file.
	* gdb.ada/info_auto_lang/proc_in_ada.adb: New file.
	* gdb.ada/info_auto_lang/some_c.c: New file.
2018-11-20 22:42:31 +01:00
Philippe Waroquiers 43d397ca8f Use scoped_switch_to_sym_language_if_auto in symtab.c to switch language.
Use scoped_switch_to_sym_language_if_auto in treg_matches_sym_type_name to
replace the local logic that was doing the same as the new class
scoped_switch_to_sym_language_if_auto.

Use scoped_switch_to_sym_language_if_auto inside print_symbol_info, so
that symbol information is printed in the symbol language when
language mode is auto.
This modifies the behaviour of the test dw2-case-insensitive.exp,
as the function FUNC_lang is now printed with the Fortran syntax
(as declared in the .S file).

gdb/ChangeLog
2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* symtab.c (treg_matches_sym_type_name): Use
	scoped_switch_to_sym_language_if_auto instead of local logic.
	(print_symbol_info): Use scoped_switch_to_sym_language_if_auto
	to switch to SYM language when language mode is auto.

gdb/testsuite/ChangeLog
2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.dwarf2/dw2-case-insensitive.exp: Update due to auto switch to
	FUNC_lang language syntax.
2018-11-20 22:41:08 +01:00
Philippe Waroquiers 9e6a1ab665 Add class scoped_switch_to_sym_language_if_auto.
The class scoped_switch_to_sym_language_if_auto allows to switch in a scope
the current language to the language of a symbol when language mode is
set to auto.

2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* language.h (scoped_switch_to_sym_language_if_auto): New class.
2018-11-20 22:39:08 +01:00
Philippe Waroquiers beddd67132 Test case for 'info variables|functions' with minimal symbols.
2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* gdb.base/info_minsym.c: New file.
	* gdb.base/info_minsym.exp: New file.
2018-11-20 21:56:06 +01:00
Philippe Waroquiers a8462bbf0b Fix regression 'info variables' does not show minimal symbols.
12615cba84 Add [-q] [-t TYPEREGEXP] [NAMEREGEXP] args to info [args|functions|locals|variables]
introduced a regression that minimal symbols were not listed anymore, due to a wrong
condition checking the absence of a type regexp in the loop scanning the minimal symbols.

Instead, before entering the loop scanning the minimal symbols, check that we
do not have a type regexp, as we will never match a minimal symbol with
this type regexp.

With the fix in this patch, for this part of the code, we basically go back
to the GDB 8.2 logic, with just the addition of
  && !treg.has_value ())
to 'enter' in the minsym case.
This should ensure that at least there is no regression compared to 8.2,
when not using the new type matching argument, as there was no treg in 8.2.

2018-11-20  Philippe Waroquiers  <philippe.waroquiers@skynet.be>

	* symtab.c (search_symbols): Properly check absence of type regexp
	before entering the loop scanning the minimal symbols.
2018-11-20 21:54:39 +01:00
Pedro Alves 4399bce99b Fix gdb/ChangeLog formatting and date 2018-11-20 19:04:14 +00:00
John Darrington c3247a98cd GDB: S12Z: new function s12z_extract_return_value
Make gdb aware of the return values of functions which
return in registers.

gdb/ChangeLog:
* s12z-tdep.c (s12z_extract_return_value): New function.
  (inv_reg_perm) New array.
  (s12z_return_value): Populate readbuf if non-null.
2018-11-20 18:55:02 +01:00
Eli Zaretskii 2fa1b3191e Fix previous change in filestuff.c
gdb/ChangeLog:

	* common/filestuff.c (O_NOINHERIT): Define if not defined.
2018-11-20 19:23:51 +02:00
Eli Zaretskii 970d89d8fd Avoid "Invalid parameter passed to C runtime function" warning
This warning was displayed by OutputDebugString on MinGW when
GDB was being debugged natively.

gdb/ChangeLog:

	* common/filestuff.c (gdb_fopen_cloexec): Disable use of "e" mode
	with 'fopen' also if O_CLOEXEC is equal to O_NOINHERIT, to cater
	to MinGW fixed by Gnulib.
2018-11-20 18:49:43 +02:00