Commit Graph

364 Commits

Author SHA1 Message Date
Simon Marchi
8341132038 gdbsupport: fix gdb::optional compilation with C++11 && _GLIBCXX_DEBUG
Similar to 911438f9f4 ("gdbsupport: fix array-view compilation with
c++11 && _GLIBCXX_DEBUG"), but for gdb::optional.

I get this error when building with Clang 14 and -std=c++11:

      CXX      agent.o
    In file included from /home/simark/src/binutils-gdb/gdbsupport/agent.cc:20:
    In file included from /home/simark/src/binutils-gdb/gdbsupport/common-defs.h:210:
    In file included from /home/simark/src/binutils-gdb/gdbsupport/common-debug.h:23:
    /home/simark/src/binutils-gdb/gdbsupport/../gdbsupport/gdb_optional.h:213:5: error: use of this statement in a constexpr function is a C++14 extension [-Werror,-Wc++14-extensions]
        gdb_assert (this->has_value ());
        ^
    /home/simark/src/binutils-gdb/gdbsupport/gdb_assert.h:35:3: note: expanded from macro 'gdb_assert'
      ((void) ((expr) ? 0 :                                                       \
      ^

Change-Id: If0cf55607fc9dbd1925ccb97cd9abbf8993ff264
2022-08-26 11:47:23 -04:00
Simon Marchi
4fd404c298 gdb, gdbsupport: configure: factor out yes/no/auto value checking
Factor out the code that checks that a value is yes/no or yes/no/auto.
Add two macros to gdbsupport/common.m4 and use them in gdb/configure.ac

I inspected the changes to configure.  Other than whitespace changes, we
have some benign changes to the error messages (one of them had an error
actually).  There are changes to the --enable-source-highlight and
--enable-libbacktrace handling, but setting enable_source_highlight /
enable_libbacktrace was not really useful anyway, they already had the
right value.

Change-Id: I92587aec36874309e1605e2d60244649f09a757a
2022-08-26 10:29:51 -04:00
Patrick Monnerat
08b00371b5 gdb_do_one_event: use integer test syntax
Timeout is an int, not a bool.
2022-08-19 16:37:57 +02:00
Patrick Monnerat
bac814af17 gdbsupport/event-loop: add a timeout parameter to gdb_do_one_event
Since commit b2d8657, having a per-interpreter event/command loop is not
possible anymore.

As Insight uses a GUI that has its own event loop, gdb and GUI event
loops have then to be "merged" (i.e.: work together). But this is
problematic as gdb_do_one_event is not aware of this alternate event
loop and thus may wait forever.

A solution is to delegate GUI events handling to the gdb events handler.
Insight uses Tck/Tk as GUI and the latter offers a "notifier" feature to
implement such a delegation. The Tcl notifier spec requires the event wait
function to support a timeout parameter. Unfortunately gdb_do_one_event
does not feature such a parameter.
This timeout cannot be implemented externally with a gdb timer, because
it would become an event by itself and thus can cause a legitimate event to
be missed if the timeout is 0.
Tcl implements "idle events" that are (internally) triggered only when no
other event is pending. For this reason, it can call the event wait function
with a 0 timeout quite often.

This patch implements a wait timeout to gdb_do_one_event. The initial
pending events monitoring is performed as before without the possibility
to enter a wait state. If no pending event has been found during this
phase, a timer is then created for the given timeout in order to re-use
the implemented timeout logic and the event wait is then performed.
This "internal" timer only limits the wait time and should never be triggered.
It is deleted upon gdb_do_one_event exit.

The new parameter defaults to "no timeout" (-1): as it is used by Insight
only, there is no need to update calls from the gdb source tree.
2022-08-18 11:56:38 +02:00
Tom Tromey
02d04eac24 Use strwinerror in gdb/windows-nat.c
When working on windows-nat.c, it's useful to see an error message in
addition to the error number given by GetLastError.  This patch moves
strwinerror from gdbserver to gdbsupport, and then updates
windows-nat.c to use it.  A couple of minor changes to strwinerror
(constify the return type and use the ARRAY_SIZE macro) are also
included.
2022-08-16 08:04:37 -06:00
Tom de Vries
b859a3ef48 [gdbsupport] Add task size parameter in parallel_for_each
Add a task_size parameter to parallel_for_each, defaulting to nullptr, and use
the task size to distribute similarly-sized chunks to the threads.

Tested on x86_64-linux.
2022-08-05 16:12:56 +02:00
Pedro Alves
377c3a9c91 Introduce gdb::make_function_view
This adds gdb::make_function_view, which lets you create a function
view from a callable without specifying the function_view's template
parameter.  For example, this:

    auto lambda = [&] (int) { ... };
    auto fv = gdb::make_function_view (lambda);

instead of:

    auto lambda = [&] (int) { ... };
    gdb::function_view<void (int)> fv = lambda;

It is particularly useful if you have a template function with an
optional function_view parameter, whose type depends on the function's
template parameters.  Like:

    template<typename T>
    void my_function (T v, gdb::function_view<void(T)> callback = nullptr);

For such a function, the type of the callback argument you pass must
already be a function_view.  I.e., this wouldn't compile:

    auto lambda = [&] (int) { ... };
    my_function (1, lambda);

With gdb::make_function_view, you can write the call like so:

    auto lambda = [&] (int) { ... };
    my_function (1, gdb::make_function_view (lambda));

Unit tests included.

Tested by building with GCC 9.4, Clang 10, and GCC 4.8.5, on x86_64
GNU/Linux, and running the unit tests.

Change-Id: I5c4b3b4455ed6f0d8878cf1be189bea3ee63f626
2022-08-05 16:12:56 +02:00
Tom de Vries
731d2cc1d5 [gdb] Add debug_{exp,val}
When debugging cc1 I heavily rely on simple one-parameter debug functions
that allow me to inspect a variable of a common type, like:
- debug_generic_expr
- debug_gimple_stmt
- debug_rtx
and I miss similar functions in gdb.

Add functions to dump variables of types 'value' and 'expression':
- debug_exp, and
- debug_val.

Tested on x86_64-linux, by breaking on varobj_create, and doing:
...
(gdb) call debug_exp (var->root->exp.get ())
&"Operation: OP_VAR_VALUE\n"
&" Block symbol:\n"
&"  Symbol: aaa\n"
&"  Block: 0x2d064f0\n"
(gdb)
...
and:
...
(gdb) call debug_val (value)
&"5"
(gdb)
...
2022-08-05 08:09:57 +02:00
Pedro Alves
b669667d07 struct packed: Add fallback byte array implementation
Attribute gcc_struct is not implemented in Clang targeting Windows, so
add a fallback standard-conforming implementation based on arrays.

I ran the testsuite on x86_64 GNU/Linux with this implementation
forced, and saw no regressions.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29373

Change-Id: I023315ee03622c59c397bf4affc0b68179c32374
2022-07-25 16:04:05 +01:00
Pedro Alves
e249e6b801 struct packed: Unit tests and more operators
For PR gdb/29373, I wrote an alternative implementation of struct
packed that uses a gdb_byte array for internal representation, needed
for mingw+clang.  While adding that, I wrote some unit tests to make
sure both implementations behave the same.  While at it, I implemented
all relational operators.  This commit adds said unit tests and
relational operators.  The alternative gdb_byte array implementation
will come next.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29373

Change-Id: I023315ee03622c59c397bf4affc0b68179c32374
2022-07-25 16:04:05 +01:00
Pedro Alves
4ca26ad7de struct packed: Use gcc_struct on Windows
Building GDB on mingw/gcc hosts is currently broken, due to a static
assertion failure in gdbsupport/packed.h:

  In file included from ../../../../../binutils-gdb/gdb/../gdbsupport/common-defs.h:201,
		   from ../../../../../binutils-gdb/gdb/defs.h:28,
		   from ../../../../../binutils-gdb/gdb/dwarf2/read.c:31:
  ../../../../../binutils-gdb/gdb/../gdbsupport/packed.h: In instantiation of 'packed<T, Bytes>::packed(T) [with T = dwarf_unit_type; long long unsigned int Bytes = 1]':
  ../../../../../binutils-gdb/gdb/dwarf2/read.h:181:74:   required from here
  ../../../../../binutils-gdb/gdb/../gdbsupport/packed.h:41:40: error: static assertion failed
     41 |     gdb_static_assert (sizeof (packed) == Bytes);
	|                        ~~~~~~~~~~~~~~~~^~~~~~~~
  ../../../../../binutils-gdb/gdb/../gdbsupport/gdb_assert.h:27:48: note: in definition of macro 'gdb_static_assert'
     27 | #define gdb_static_assert(expr) static_assert (expr, "")
	|                                                ^~~~
  ../../../../../binutils-gdb/gdb/../gdbsupport/packed.h:41:40: note: the comparison reduces to '(4 == 1)'
     41 |     gdb_static_assert (sizeof (packed) == Bytes);
	|                        ~~~~~~~~~~~~~~~~^~~~~~~~


The issue is that mingw gcc defaults to "-mms-bitfields", which
affects how bitfields are laid out.  We can however tell GCC that we
want the regular GCC layout instead using attribute gcc_struct.

Attribute gcc_struct is not implemented in "clang -target
x86_64-pc-windows-gnu", so that will need a different fix.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29373

Change-Id: I023315ee03622c59c397bf4affc0b68179c32374
2022-07-25 16:04:05 +01:00
Andrew Burgess
11da1b13b3 gdbsupport: add checked_static_cast
This commit was inspired by these mailing list posts:

  https://sourceware.org/pipermail/gdb-patches/2022-June/190323.html
  https://sourceware.org/pipermail/gdb-patches/2022-April/188098.html

The idea is to add a new function gdb::checked_static_cast, which can,
in some cases, be used as a drop-in replacement for static_cast.  And
so, if I previously wrote this:

  BaseClass *base = get_base_class_pointer ();
  DerivedClass *derived = static_cast<DerivedClass *> (base);

I can now write:

  BaseClass *base = get_base_class_pointer ();
  DerivedClass *derived = gdb::checked_static_cast<DerivedClass *> (base);

The requirement is that BaseClass and DerivedClass must be
polymorphic.

The benefit of making this change is that, when GDB is built in
developer mode, a run-time check will be made to ensure that `base`
really is of type DerivedClass before the cast is performed.  If
`base` is not of type DerivedClass then GDB will assert.

In a non-developer build gdb::checked_static_cast is equivalent to a
static_cast, and there should be no performance difference.

This commit adds the support function, but does not make use of this
function, a use will be added in the next commit.

Co-Authored-By: Pedro Alves <pedro@palves.net>
Co-Authored-By: Tom Tromey <tom@tromey.com>
2022-07-21 15:19:43 +01:00
Tom de Vries
9b89bf16c3 [gdbsupport] Fix type of parallel_for_each_debug
When I changed the initialization of parallel_for_each_debug from 0 to false,
I forgot to change the type from int to bool.  Fix this.

Tested by rebuilding on x86_64-linux.
2022-07-21 13:34:14 +02:00
Tom de Vries
4319180c81 [gdbsupport] Improve thread scheduling in parallel_for_each
When running a task using parallel_for_each, we get the following
distribution:
...
Parallel for: n_elements: 7271
Parallel for: minimum elements per thread: 10
Parallel for: elts_per_thread: 1817
Parallel for: elements on worker thread 0       : 1817
Parallel for: elements on worker thread 1       : 1817
Parallel for: elements on worker thread 2       : 1817
Parallel for: elements on worker thread 3       : 0
Parallel for: elements on main thread           : 1820
...

Note that there are 4 active threads, and scheduling elts_per_thread on each
of those handles 4 * 1817 == 7268, leaving 3 "left over" elements.

These leftovers are currently handled in the main thread.

That doesn't seem to matter much for this example, but for say 10 threads and
99 elements, you'd have 9 threads handling 9 elements and 1 thread handling 18
elements.

Instead, distribute the left over elements over the worker threads, such that
we have:
...
Parallel for: elements on worker thread 0       : 1818
Parallel for: elements on worker thread 1       : 1818
Parallel for: elements on worker thread 2       : 1818
Parallel for: elements on worker thread 3       : 0
Parallel for: elements on main thread           : 1817
...

Tested on x86_64-linux.
2022-07-18 08:34:06 +02:00
Tom de Vries
53944a3bf5 [gdbsupport] Add parallel_for_each_debug
Add a parallel_for_each_debug variable, set to false by default.

With an a.out compiled from hello world, we get with
parallel_for_each_debug == true:
...
$ gdb -q -batch a.out -ex start
  ...
Parallel for: n_elements: 7271
Parallel for: minimum elements per thread: 10
Parallel for: elts_per_thread: 1817
Parallel for: elements on worker thread 0       : 1817
Parallel for: elements on worker thread 1       : 1817
Parallel for: elements on worker thread 2       : 1817
Parallel for: elements on worker thread 3       : 0
Parallel for: elements on main thread           : 1820

Temporary breakpoint 1, main () at /home/vries/hello.c:6
6         printf ("hello\n");
...

Tested on x86_64-linux.
2022-07-18 05:34:01 +02:00
Tom de Vries
18a5766d09 [gdbsupport] Add sequential_for_each
Add a sequential_for_each alongside the parallel_for_each, which can be used
as a drop-in replacement.

This can be useful when debugging multi-threading behaviour, and you want to
limit multi-threading in a fine-grained way.

Tested on x86_64-linux, by using it instead of the parallel_for_each in
dwarf2_build_psymtabs_hard.
2022-07-14 17:01:52 +02:00
Tom de Vries
2df41bda2f [gdb/build] Fix gdb build with gcc 4.8.5
When building gdb with gcc 4.8.5, we run into:
...
In file included from /usr/include/c++/4.8/future:43:0,
                 from gdbsupport/thread-pool.h:30,
                 from gdb/dwarf2/cooked-index.h:33,
                 from gdb/dwarf2/read.h:26,
                 from gdb/dwarf2/abbrev-cache.c:21:
/usr/include/c++/4.8/atomic: In instantiation of \
  ‘_Tp std::atomic<_Tp>::load(std::memory_order) const [with _Tp = \
  packed<dwarf_unit_type, 1ul>; std::memory_order = std::memory_order]’:
gdb/dwarf2/read.h:332:44:   required from here
/usr/include/c++/4.8/atomic:208:13: error: no matching function for call to \
  ‘packed<dwarf_unit_type, 1ul>::packed()’
         _Tp tmp;
             ^
...

Fix this by adding the default constructor for packed.

Tested on x86_64-linux, with gdb build with gcc 4.8.5.
2022-07-14 10:20:16 +02:00
Tom de Vries
02f0597c46 [gdb/build] Fix build with gcc 4.8.5
When building gdb with gcc 4.8.5, we run into problems due to unconditionally
using:
...
     gdb_static_assert (std::is_trivially_copyable<packed>::value);
...
in gdbsupport/packed.h.

Fix this by guarding the usage with HAVE_IS_TRIVIALLY_COPYABLE.

Tested by doing a full gdb build with gcc 4.8.5.
2022-07-12 13:36:57 +02:00
Pedro Alves
68c0faca76 Introduce struct packed template
When building gdb with -fsanitize=thread and gcc 12, and running test-case
gdb.dwarf2/dwz.exp, we run into a few data races.  For example, between:

 ...
   Write of size 1 at 0x7b200000300e by thread T4:
     #0 process_psymtab_comp_unit gdb/dwarf2/read.c:6789 (gdb+0x830720)
 ...

and:

 ...
   Previous read of size 1 at 0x7b200000300e by main thread:
     #0 cutu_reader::cutu_reader(dwarf2_per_cu_data*, dwarf2_per_objfile*, \
     abbrev_table*, dwarf2_cu*, bool, abbrev_cache*) gdb/dwarf2/read.c:6164 \
     (gdb+0x82edab)
 ...

In other words, between:

 ...
       this_cu->unit_type = DW_UT_partial;
 ...

and:

 ...
   if (this_cu->reading_dwo_directly)
 ...

The problem is that the written fields are part of the same memory
location as the read fields, so executing a read and write in
different threads is undefined behavour.

Making the written fields separate memory locations, like this:

...
  struct {
    ENUM_BITFIELD (dwarf_unit_type) unit_type : 8;
  };
...

fixes it, however that also increases the size of struct
dwarf2_per_cu_data, because it introduces padding due to alignment of
these new structs, which align on the natural alignment of the
specified type of their fields.  We can fix that with
__attribute__((packed)), like so:

  struct {
    ENUM_BITFIELD (dwarf_unit_type) unit_type : 8 __attribute__((packed));
  };

but to avoid having to write that in several places and add suitable
comments explaining how that concoction works, introduce a new struct
packed template that wraps/hides this.  Instead of the above, we'll be
able to write:

    packed<dwarf_unit_type, 1> unit_type;

Note that we can't change the type of dwarf_unit_type, as that is
defined in include/, and shared with other projects, some of those
written in C.

This patch just adds the struct packed type.  Following patches will
make use of it.  One of those patches will want to wrap a struct
packed in an std::atomic, like:

  std::atomic<std::packed<language, 1>> m_lang;

so the new gdbsupport/packed.h header adds some operators to make
comparisions between that std::atomic and the type that the wrapped
struct packed wraps work, like in:

   if (m_lang == language_c)

It would be possible to implement struct packed without using
__attribute__((packed)), by having it store an array of bytes of the
appropriate size instead, however that would make it less convenient
to debug GDB.  The way it's implemented, printing a struct packed
variable just prints its field using its natural type, which is
particularly useful if the type is an enum.  I believe that
__attribute__((packed)) is supported by all compilers that are able to
build GDB.  Even a few BFD headers use on ATTRIBUTE_PACKED on external
types:

 include/coff/external.h:  } ATTRIBUTE_PACKED
 include/coff/external.h:} ATTRIBUTE_PACKED ;
 include/coff/external.h:} ATTRIBUTE_PACKED ;
 include/coff/pe.h:} ATTRIBUTE_PACKED ;
 include/coff/pe.h:} ATTRIBUTE_PACKED;
 include/elf/external.h:} ATTRIBUTE_PACKED  Elf_External_Versym;

It is not possible to build GDB with MSVC today, but if it could, that
would be one compiler that doesn't support this attribute.  However,
it supports packing via pragmas, so there's a way to cross that bridge
if we ever get to it.  I believe any compiler worth its salt supports
some way of packing.

In any case, the worse that happens without the attribute is that some
types become larger than ideal.  Regardless, I've added a couple
static assertions to catch such compilers in action:

    /* Ensure size and aligment are what we expect.  */
    gdb_static_assert (sizeof (packed) == Bytes);
    gdb_static_assert (alignof (packed) == 1);

Change-Id: Ifa94f0a2cebfae5e8f6ddc73265f05e7fd9e1532
2022-07-12 12:20:13 +02:00
Tom de Vries
6418644b0d [gdb] Block SIGTERM in worker threads
With gdb build with gcc-12 and -fsanitize=thread, and test-case
gdb.base/gdb-sigterm.exp, I run into:
...
WARNING: ThreadSanitizer: data race (pid=9722)^M
  Write of size 4 at 0x00000325bc68 by thread T1:^M
  #0 handle_sigterm(int) src/gdb/event-top.c:1211 (gdb+0x8ec01f)^M
  ...
  Previous read of size 4 at 0x00000325bc68 by main thread:^M
    [failed to restore the stack]^M
^M
  Location is global 'sync_quit_force_run' of size 4 at \
  0x00000325bc68 (gdb+0x325bc68)^M
  ...
SUMMARY: ThreadSanitizer: data race gdb/event-top.c:1211 in \
  handle_sigterm(int)^M
...
and 3 more data races involving handle_sigterm and locations:
- active_ext_lang
- quit_flag
- heap block of size 40
  (XNEW (async_signal_handler) in create_async_signal_handler)

This was reported in PR29297.

The testcase executes a "kill -TERM $gdb_pid", which generates a
process-directed signal.

A process-directed signal can be delivered to any thread, and what we see
here is the fallout of the signal being delivered to a worker thread rather
than the main thread.

Fix this by blocking SIGTERM in the worker threads.

[ I have not been able to reproduce this after it occurred for the first time,
so unfortunately I cannot confirm that the patch fixes the problem. ]

Tested on x86_64-linux, with and without -fsanitize=thread.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29297
2022-06-30 13:31:06 +02:00
Pedro Alves
171fba11ab Make GDBserver abort on internal error in development mode
Currently, if GDBserver hits some internal assertion, it exits with
error status, instead of aborting.  This makes it harder to debug
GDBserver, as you can't just debug a core file if GDBserver fails an
assertion.  I've had to hack the code to make GDBserver abort to debug
something several times before.

I believe the reason it exits instead of aborting, is to prevent
potentially littering the filesystem of smaller embedded targets with
core files.  I think I recall Daniel Jacobowitz once saying that many
years ago, but I can't be sure.  Anyhow, that seems reasonable to me.

Since we nowadays have a distinction between development and release
modes, I propose to make GDBserver abort on internal error if in
development mode, while keeping the status quo when in release mode.

Thus, after this patch, in development mode, you get:

 $ ../gdbserver/gdbserver
 ../../src/gdbserver/server.cc:3711: A problem internal to GDBserver has been detected.
 captured_main: Assertion `0' failed.
 Aborted (core dumped)
 $

while in release mode, you'll continue to get:

 $ ../gdbserver/gdbserver
 ../../src/gdbserver/server.cc:3711: A problem internal to GDBserver has been detected.
 captured_main: Assertion `0' failed.
 $ echo $?
 1

I do not think that this requires a separate configure switch.

A "--target_board=native-extended-gdbserver" run on Ubuntu 20.04 ends
up with:

		 === gdb Summary ===

 # of unexpected core files      29
 ...

for me, of which 8 are GDBserver core dumps, 7 more than without this
patch.

Change-Id: I6861e08ad71f65a0332c91ec95ca001d130b0e9d
2022-06-27 13:55:36 +01:00
Tom Tromey
20a26f4e01 Finalize each cooked index separately
After DWARF has been scanned, the cooked index code does a
"finalization" step in a worker thread.  This step combines all the
index entries into a single master list, canonicalizes C++ names, and
splits Ada names to synthesize package names.

While this step is run in the background, gdb will wait for the
results in some situations, and it turns out that this step can be
slow.  This is PR symtab/29105.

This can be sped up by parallelizing, at a small memory cost.  Now
each index is finalized on its own, in a worker thread.  The cost
comes from name canonicalization: if a given non-canonical name is
referred to by multiple indices, there will be N canonical copies (one
per index) rather than just one.

This requires changing the users of the index to iterate over multiple
results.  However, this is easily done by introducing a new "chained
range" class.

When run on gdb itself, the memory cost seems rather low -- on my
current machine, "maint space 1" reports no change due to the patch.

For performance testing, using "maint time 1" and "file" will not show
correct results.  That approach measures "time to next prompt", but
because the patch only affects background work, this shouldn't (and
doesn't) change.  Instead, a simple way to make gdb wait for the
results is to set a breakpoint.

Before:

    $ /bin/time -f%e ~/gdb/install/bin/gdb -nx -q -batch \
        -ex 'break main' /tmp/gdb
    Breakpoint 1 at 0x43ec30: file ../../binutils-gdb/gdb/gdb.c, line 28.
    2.00

After:

    $ /bin/time -f%e ./gdb/gdb -nx -q -batch \
        -ex 'break main' /tmp/gdb
    Breakpoint 1 at 0x43ec30: file ../../binutils-gdb/gdb/gdb.c, line 28.
    0.65

Regression tested on x86-64 Fedora 34.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29105
2022-05-26 07:35:30 -06:00
Tom de Vries
735dfe028c [gdbsupport] Fix UB in print-utils.cc:int_string
When building gdb with -fsanitize=undefined, I run into:
...
(gdb) PASS: gdb.ada/access_to_packed_array.exp: set logging enabled on
maint print symbols^M
print-utils.cc:281:29:runtime error: negation of -9223372036854775808 cannot \
  be represented in type 'long int'; cast to an unsigned type to negate this \
  value to itself
(gdb) FAIL: gdb.ada/access_to_packed_array.exp: maint print symbols
...

By running in a debug session, we find that this happens during printing of:
...
   typedef system.storage_elements.storage_offset: \
     range -9223372036854775808 .. 9223372036854775807;
...
Possibly, an ada test-case could be created that exercises this in isolation.

The problem is here in int_string, where we negate a val with type LONGEST:
...
         return decimal2str ("-", -val, width);
...

Fix this by, as recommend, using "-(ULONGEST)val" instead.

Tested on x86_64-linux.
2022-05-23 14:50:02 +02:00
Simon Marchi
02646f1960 gdbsupport: fix path_join crash with -std=c++17 and -D_GLIBCXX_DEBUG
When building GDB with -std=c++17 and -D_GLIBCXX_DEBUG=1, I get:

  $ ./gdb -nx --data-directory=data-directory -q -ex "maint selftest path_join"
  /usr/include/c++/11.2.0/string_view:233: constexpr const value_type& std::basic_string_view<_CharT, _Traits>::operator[](std::basic_string_view<_CharT, _Traits>::size_type) const [with _CharT = char; _Traits = std::char_traits<char>; std::basic_string_view<_CharT, _Traits>::const_reference = const char&; std::basic_string_view<_CharT, _Traits>::size_type = long unsigned int]: Assertion  '__pos < this->_M_len' failed.

The problem is that we're passing an empty string_view to
IS_ABSOLUTE_PATH.  IS_ABSOLUTE_PATH accesses [0] on that string_view,
which is out-of-bounds.

The reason this is not seen with -std less than c++17 is that our local
copy of string_view (used with C++ < 17) does not have the assert in
operator[], as that wouldn't work in a constexpr method:

  5890af36e5/gdbsupport/gdb_string_view.h (L180)

IS_ABSOLUTE_PATH is normally used with null-terminated string.  It's
fine to pass an empty null-terminated string to IS_ABSOLUTE_PATH,
because index 0 in such a string is valid.  But not with an empty
string_view.

Fix that by avoiding the "call" to IS_ABSOLUTE_PATH if the string_view
is empty.

Change-Id: Idf4df961b63f513b3389235e93814c02b89ea32e
2022-05-19 08:04:13 -04:00
Pedro Alves
187075ebbc Reindent gdbsupport/event-loop.cc:handle_file_event
The handle_file_event function has a few unnecessary {} lexical
blocks, presumably because they were originally if blocks, and the
conditions were removed, or something along those lines.

Remove the unnecessary blocks, and reindent.

Change-Id: Iaecbe5c9f4940a80b81dbbc42e51ce506f6aafb2
2022-05-16 19:58:08 +01:00
Pedro Alves
36a5b37053 gdbsupport/event-loop.cc: simplify !HAVE_POLL paths
gdbsupport/event-loop.cc throughout handles the case of use_poll being
true on a system where HAVE_POLL is not defined, by calling
internal_error if that situation ever happens.

Simplify this by moving the "use_poll" global itself under HAVE_POLL,
so that it's way more unlikely to ever end up in such a situation.
Then, move the code that checks the value of use_poll under HAVE_POLL
too, and remove the internal_error calls.  Like, from:

    if (use_poll)
      {
  #ifdef HAVE_POLL
        // poll code
  #else
      internal_error (....);
  #endif /* HAVE_POLL */
      }
    else
      {
	// select code
      }

to

  #ifdef HAVE_POLL
    if (use_poll)
      {
        // poll code
      }
    else
  #endif /* HAVE_POLL */
      {
	// select code
      }

While at it, make use_poll be a bool.  The current code is using
unsigned char most probably to save space, but I don't think it really
matters here.

Co-Authored-By: Youling Tang <tangyouling@loongson.cn>
Change-Id: I0dd74fdd4d393ccd057906df4cd75e8e83c1cdb4
2022-05-16 19:54:20 +01:00
Tom Tromey
20c4eb4226 Fix --disable-threading build
PR build/29110 points out that GDB fails to build on mingw when the
"win32" thread model is in use.  It turns out that the Fedora cross
tools using the "posix" thread model, which somehow manages to support
std::future, whereas the win32 model does not.

While looking into this, I found that the configuring with
--disable-threading will also cause a build failure.

This patch fixes this build by introducing a compatibility wrapper for
std::future.

I am not able to test the win32 thread model build, but I'm going to
ask the reporter to try this patch.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29110
2022-05-10 08:15:40 -06:00
Pedro Alves
62b33fde9c Move non-dependent gdb::observers::observable::visit_state outside template
The other day, while looking at the symbols that end up in a GDB
index, I noticed that the gdb::observers::observable::visit_state enum
class appears a number of times:

 $ grep VISIT gdb-index-symbol-names.txt
 gdb::observers::observable<bpstat*, int>::visit_state::NOT_VISITED
 gdb::observers::observable<bpstat*, int>::visit_state::VISITED
 gdb::observers::observable<bpstat*, int>::visit_state::VISITING
 gdb::observers::observable<breakpoint*>::visit_state::NOT_VISITED
 gdb::observers::observable<breakpoint*>::visit_state::VISITED
 gdb::observers::observable<breakpoint*>::visit_state::VISITING
 gdb::observers::observable<char const*, char const*>::visit_state::NOT_VISITED
 gdb::observers::observable<char const*, char const*>::visit_state::VISITED
 gdb::observers::observable<char const*, char const*>::visit_state::VISITING
 gdb::observers::observable<char const*>::visit_state::NOT_VISITED
 gdb::observers::observable<char const*>::visit_state::VISITED
 gdb::observers::observable<char const*>::visit_state::VISITING
 gdb::observers::observable<enum_flags<user_selected_what_flag> >::visit_state::NOT_VISITED
 gdb::observers::observable<enum_flags<user_selected_what_flag> >::visit_state::VISITED
 gdb::observers::observable<enum_flags<user_selected_what_flag> >::visit_state::VISITING
 gdb::observers::observable<frame_info*, int>::visit_state::NOT_VISITED
 gdb::observers::observable<frame_info*, int>::visit_state::VISITED
 gdb::observers::observable<frame_info*, int>::visit_state::VISITING
 gdb::observers::observable<gdbarch*>::visit_state::NOT_VISITED
 gdb::observers::observable<gdbarch*>::visit_state::VISITED
 gdb::observers::observable<gdbarch*>::visit_state::VISITING
 gdb::observers::observable<gdb_signal>::visit_state::NOT_VISITED
 gdb::observers::observable<gdb_signal>::visit_state::VISITED
 gdb::observers::observable<gdb_signal>::visit_state::VISITING
 [... snip ...]

 $ grep VISIT gdb-index-symbol-names.txt | wc -l
 72

enum class visit_state is defined inside the class template
observable, but it doesn't have to be, as it does not depend on the
template parameters.  This commit moves it out, so that only one such
type exists.  This reduces the size of a -O0 -g3 build for me by
around 0.6%, like so:

 $ du -b gdb.before gdb.after
 164685280       gdb.before
 163707424       gdb.fixed

and codesize by some 0.5%.

Change-Id: I405f4ef27b8358fdd22158245b145d849b45658e
2022-05-10 13:40:57 +01:00
John Baldwin
3f0423f913 gdbsupport/pathstuff.h: #include <array> explicitly for std::array<>
This fixes build breakage using clang with libc++ on FreeBSD where
std::array<> is not yet declared when used by the path_join variadic
function template.
2022-04-25 17:06:09 -07:00
Simon Marchi
ffaebc199e gdbsupport: add path_join function
In this review [1], Eli pointed out that we should be careful when
concatenating file names to avoid duplicated slashes.  On Windows, a
double slash at the beginning of a file path has a special meaning.  So
naively concatenating "/"  and "foo/bar" would give "//foo/bar", which
would not give the desired results.  We already have a few spots doing:

  if (first_path ends with a slash)
    path = first_path + second_path
  else
    path = first_path + slash + second_path

In general, I think it's nice to avoid superfluous slashes in file
paths, since they might end up visible to the user and look a bit
unprofessional.

Introduce the path_join function that can be used to join multiple path
components together (along with unit tests).

I initially wanted to make it possible to join two absolute paths, to
support the use case of prepending a sysroot path to a target file path,
or the prepending the debug-file-directory to a target file path.  But
the code in solib_find_1 shows that it is more complex than this anyway
(for example, when the right hand side is a Windows path with a drive
letter).  So I don't think we need to support that case in path_join.
That also keeps the implementation simpler.

Change a few spots to use path_join to show how it can be used.  I
believe that all the spots I changed are guarded by some checks that
ensure the right hand side operand is not an absolute path.

Regression-tested on Ubuntu 18.04.  Built-tested on Windows, and I also
ran the new unit-test there.

[1] https://sourceware.org/pipermail/gdb-patches/2022-April/187559.html

Change-Id: I0df889f7e3f644e045f42ff429277b732eb6c752
2022-04-21 11:11:21 -04:00
Lancelot SIX
9a0f7f634e gdbsupport/selftest: Allow lazy registration
This patch adds a way to delay the registration of tests until the
latest possible moment.  This is intended for situations where GDB needs
to be fully initialized in order to decide if a particular selftest can
be executed or not.

This mechanism will be used in the next patch.

Change-Id: I7f6b061f4c0a6832226c7080ab4e3a2523e1b0b0
2022-04-19 09:12:42 +01:00
Lancelot SIX
c57207c15c gdbsupport/selftest: Replace for_each_selftest with an iterator_range
Remove the callback-based selftests::for_each_selftest function and use
an iterator_range instead.

Also use this iterator range in run_tests so all iterations over the
selftests are done in a consistent way.  This will become useful in a
later commit.

Change-Id: I0b3a5349a7987fbcb0071f11c394e353df986583
2022-04-19 09:12:42 +01:00
Simon Marchi
56325e2ba6 gdb: use gdb_tilde_expand instead of gdb_tilde_expand_up in source_script_with_search
Since this is the latest use of gdb_tilde_expand_up, remove it.

Change-Id: I964c812ce55fe087876abf91e7a3577ad79c0425
2022-04-18 15:48:03 -04:00
Simon Marchi
5f2491c300 gdbsupport: make gdb_realpath_keepfile return an std::string
I'm trying to switch these functions to use std::string instead of char
arrays, as much as possible.  Some callers benefit from it (can avoid
doing a copy of the result), while others suffer (have to make one more
copy).

Change-Id: I793aab17baaef8345488f4c40b9094e2695425bc
2022-04-18 15:48:03 -04:00
Simon Marchi
7ab2607f97 gdbsupport: make gdb_abspath return an std::string
I'm trying to switch these functions to use std::string instead of char
arrays, as much as possible.  Some callers benefit from it (can avoid
doing a copy of the result), while others suffer (have to make one more
copy).

Change-Id: Iced49b8ee2f189744c5072a3b217aab5af17a993
2022-04-18 15:48:03 -04:00
Tom Tromey
1ea519ec19 Set the worker thread name on Windows
This patch is a bit different from the rest of the series, in that it
is a change to gdb's behavior on the host.  It changes gdb's thread
pool to try to set the thread name on Windows, if SetThreadDescription
is available.

This is part of PR win32/29050.

This patch isn't likely to be useful to many people in the short term,
because the Windows port of the libstdc++ thread code is not upstream.
(AdaCore uses it, and sent it upstream, but it did not land, I don't
know why.)  However, if that patch does ever go in, or presumably if
you build using some other C++ runtime library, then this will be
useful.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=29050
2022-04-14 12:12:34 -06:00
Tom Tromey
c560a5fbae Let std::thread check pass even without pthreads
Currently, the configure check for std::thread relies on pthreads
existing.  However, this means that if std::thread is implemented for
a non-pthreads host, then the check will yield the wrong answer.  This
happened in AdaCore internal builds.  Here, we have this GCC patch:

    https://gcc.gnu.org/legacy-ml/gcc-patches/2019-06/msg01840.html

... which adds mingw support to GCC's gthreads implementation, and
also to std::thread.

This configure change fixes this problem and enables threading for
gdb.
2022-04-14 09:28:56 -06:00
Tiezhu Yang
11d7dd3357 gdb: fix build errors in gdbsupport/thread-pool.h used with old gcc
When I build gdb with gcc 8.3, there exist the following build errors,
rename the typedef to task_t to fix them.

  CXX      thread-pool.o
In file included from /home/loongson/gdb.git/gdbsupport/thread-pool.cc:21:
/home/loongson/gdb.git/gdbsupport/../gdbsupport/thread-pool.h: In member function ‘std::future<void> gdb::thread_pool::post_task(std::function<void()>&&)’:
/home/loongson/gdb.git/gdbsupport/../gdbsupport/thread-pool.h:69:44: error: declaration of ‘task’ shadows a previous local [-Werror=shadow=local]
     std::packaged_task<void ()> task (std::move (func));
                                            ^~~~
/home/loongson/gdb.git/gdbsupport/../gdbsupport/thread-pool.h:102:39: note: shadowed declaration is here
   typedef std::packaged_task<void ()> task;
                                       ^~~~
/home/loongson/gdb.git/gdbsupport/../gdbsupport/thread-pool.h: In member function ‘std::future<_Res> gdb::thread_pool::post_task(std::function<T()>&&)’:
/home/loongson/gdb.git/gdbsupport/../gdbsupport/thread-pool.h:80:41: error: declaration of ‘task’ shadows a previous local [-Werror=shadow=local]
     std::packaged_task<T ()> task (std::move (func));
                                         ^~~~
/home/loongson/gdb.git/gdbsupport/../gdbsupport/thread-pool.h:102:39: note: shadowed declaration is here
   typedef std::packaged_task<void ()> task;
                                       ^~~~

Signed-off-by: Tiezhu Yang <yangtiezhu@loongson.cn>
2022-04-14 23:05:00 +08:00
Pedro Alves
50b032ebc0 Make intrusive_list_node's next/prev private
Tromey noticed that intrusive_list_node leaves its data members
public, which seems sub-optimal.

This commit makes intrusive_list_node's data fields private.
intrusive_list_iterator, intrusive_list_reverse_iterator, and
intrusive_list do need to access the fields, so they are made friends.

Change-Id: Ia8b306b40344cc218d423c8dfb8355207a612ac5
2022-04-13 10:24:38 +01:00
Simon Marchi
a09520cdd9 gdbsupport: use result_of_t instead of result_of in parallel-for.h
When building with -std=c++11, I get:

In file included from /home/smarchi/src/binutils-gdb/gdb/unittests/parallel-for-selftests.c:22:                                                                             /home/smarchi/src/binutils-gdb/gdb/../gdbsupport/parallel-for.h:134:10: error: ‘result_of_t’ is not a member of ‘std’; did you mean ‘result_of’?
  134 |     std::result_of_t<RangeFunction (RandomIt, RandomIt)>
      |          ^~~~~~~~~~~
      |          result_of

This is because result_of_t has been introduced in C++14.  Use the
equivalent result_of<...>::type instead.

result_of and result_of_t have been removed in C++20 though, so I think
we'll need some patches eventually to make the code use invoke_result
instead, depending on the C++ version.

Change-Id: I4817f361c0ebcdd4b32976898fc368bb302b61b9
2022-04-12 14:09:49 -04:00
Tom Tromey
85098eeb4c Specialize std::hash for gdb_exception
This adds a std::hash specialization for gdb_exception.  This lets us
store these objects in a hash table, which is used later in this
series to de-duplicate the exception output from multiple threads.
2022-04-12 09:31:16 -06:00
Tom Tromey
f4565e4c99 Return vector of results from parallel_for_each
This changes gdb::parallel_for_each to return a vector of the results.
However, if the passed-in function returns void, the return type
remains 'void'.  This functionality is used later, to parallelize the
new indexer.
2022-04-12 09:31:16 -06:00
Tom Tromey
82d734f7a3 Add batching parameter to parallel_for_each
parallel_for_each currently requires each thread to process at least
10 elements.  However, when indexing, it's fine for a thread to handle
just a single CU.  This patch parameterizes this, and updates the one
user.
2022-04-12 09:31:16 -06:00
Tom Tromey
0981fe1017 Allow thread-pool.h to work without threads
thread-pool.h requires CXX_STD_THREAD in order to even be included.
However, there's no deep reason for this, and during review we found
that one patch in the new DWARF indexer series unconditionally
requires the thread pool.

Because the thread pool already allows a task to be run in the calling
thread (for example if it is configured to have no threads in the
pool), it seemed straightforward to make this code ok to use when host
threads aren't available at all.

This patch implements this idea.  I built it on a thread-less host
(mingw, before my recent configure patch) and verified that the result
builds.

After the thread-pool change, parallel-for.h no longer needs any
CXX_STD_THREAD checks at all, so this patch removes these as well.
2022-04-12 09:31:15 -06:00
Tom Tromey
c50e54825b Consolidate definition of current_directory
I noticed that both gdbserver and gdb define current_directory.
However, as it is referenced by gdbsupport, it seemed better to define
it there as well.  This patch also moves the declaration to
pathstuff.h.  Tested by rebuilding.
2022-03-30 09:08:48 -06:00
Tom Tromey
c8b76e1ec3 Let phex and phex_nz handle sizeof_l==1
Currently, neither phex nor phex_nz handle sizeof_l==1 -- they let
this case fall through to the default case.  However, a subsequent
patch in this series needs this case to work correctly.

I looked at all calls to these functions that pass a 1 for the
sizeof_l parameter.  The only such case seems to be correct with this
change.
2022-03-07 07:52:59 -07:00
Roland McGrath
26caf9aca8 Fix typo in last change. 2022-03-03 13:06:50 -08:00
Roland McGrath
8674f082e3 Avoid conflict with gnulib open/close macros.
On some systems, the gnulib configuration will decide to define open
and/or close as macros to replace the POSIX C functions.  This
interferes with using those names in C++ class or namespace scopes.

gdbsupport/
	* event-pipe.cc (event_pipe::open): Renamed to ...
	(event_pipe::open_pipe): ... this.
	(event_pipe::close): Renamed to ...
	(event_pipe::close_pipe): ... this.
	* event-pipe.h (class event_pipe): Updated.
gdb/
	* inf-ptrace.h (async_file_open, async_file_close): Updated.
gdbserver/
	* gdbserver/linux-low.cc (linux_process_target::async): Likewise.
2022-03-03 11:21:36 -08:00
Andrew Burgess
820ed8af6a gdb: add operator+= and operator+ overload for std::string
This commit adds operator+= and operator+ overloads for adding
gdb::unique_xmalloc_ptr<char> to a std::string.  I could only find 3
places in GDB where this was useful right now, and these all make use
of operator+=.

I've also added a self test for gdb::unique_xmalloc_ptr<char>, which
makes use of both operator+= and operator+, so they are both getting
used/tested.

There should be no user visible changes after this commit, except when
running 'maint selftest', where the new self test is visible.
2022-02-25 17:50:22 +00:00
John Baldwin
ea3e7446dc gdbsupport: Add an event-pipe class.
This pulls out the implementation of an event pipe used to implement
target async support in both linux-low.cc (gdbserver) and linux-nat.c
(gdb).

This will be used to replace the existing event pipe in linux-low.cc
and linux-nat.c in future commits.

Co-Authored-By: Lancelot SIX <lsix@lancelotsix.com>
2022-02-22 11:22:14 -08:00
Simon Marchi
7bf5587873 gdbsupport/gdb_regex.cc: replace defs.h include with common-defs.h
This was forgotten when gdb_regex was moved from gdb to gdbsupport.

Change-Id: I73b446f71861cabbf7afdb7408ef9d59fa64b804
2022-01-20 22:58:21 -05:00
Tom Tromey
d322d6d69d Move gdb_regex to gdbsupport
This moves the gdb_regex convenience class to gdbsupport.
2022-01-18 10:14:43 -07:00
Tom Tromey
0589ca4e7b Introduce gdb-hashtab module in gdbsupport
gdb has some extensions and helpers for working with the libiberty
hash table.  This patch consolidates these and moves them to
gdbsupport.
2022-01-18 10:14:43 -07:00
Tom Tromey
bf31fd38f0 Move gdb obstack code to gdbsupport
This moves the gdb-specific obstack code -- both extensions like
obconcat and obstack_strdup, and things like auto_obstack -- to
gdbsupport.
2022-01-18 10:14:42 -07:00
Tom Tromey
7904e9613e Move gdb_argv to gdbsupport
This moves the gdb_argv class to a new header in gdbsupport.
2022-01-18 10:14:42 -07:00
Andrew Burgess
4b74833d1a gdb: don't use -Wmissing-prototypes with g++
This commit aims to not make use of -Wmissing-prototypes when
compiling with g++.

Use of -Wmissing-prototypes was added with this commit:

  commit a0761e34f0
  Date:   Wed Mar 11 15:15:12 2020 -0400

      gdb: enable -Wmissing-prototypes warning

Because clang can provide helpful warnings with this flag.
Unfortunately, g++ doesn't accept this flag, and will give this
warning:

  cc1plus: warning: command line option ‘-Wmissing-prototypes’ is valid for C/ObjC but not for C++

In theory the fact that this flag is not supported should be detected
by the configure check in gdbsupport/warning.m4, but for users of
ccache, this check doesn't work due to a long standing ccache issue:

  https://github.com/ccache/ccache/issues/738

The ccache problem is that -W... options are reordered on the command
line, and so -Wmissing-prototypes is seen before -Werror.  Usually
this doesn't matter, but the above warning (about the flag not being
valid) is issued before the -Werror flag is processed, and so is not
fatal.

There have been two previous attempts to fix this that I'm aware of.
The first is:

  https://sourceware.org/pipermail/gdb-patches/2021-September/182148.html

In this attempt, instead of just relying on a compile to check if a
flag is valid, the proposal was to both compile and link.  As linking
doesn't go through ccache, we don't suffer from the argument
reordering problem, and the link phase will correctly fail when using
-Wmissing-prototypes with g++.  The configure script will then disable
the use of this flag.

This approach was rejected, and the suggestion was to only add the
-Wmissing-prototypes flag if we are compiling with gcc.

The second attempt, attempts this approach, and can be found here:

  https://sourceware.org/pipermail/gdb-patches/2021-November/183076.html

This attempt only adds the -Wmissing-prototypes flag is the value of
GCC is not 'yes'.  This feels like it is doing the right thing,
unfortunately, the GCC flag is really a 'is gcc like' flag, not a
strict, is gcc check.  As such, GCC is set to 'yes' for clang, which
would mean the flag was not included for clang or gcc.  The entire
point of the original commit was to add this flag for clang, so
clearly the second attempt is not sufficient either.

In this new attempt I have added gdbsupport/compiler-type.m4, this
file defines AM_GDB_COMPILER_TYPE.  This macro sets the variable
GDB_COMPILER_TYPE to either 'gcc', 'clang', or 'unknown'.  In future
the list of values might be extended to cover other compilers, if this
is ever useful.

I've then modified gdbsupport/warning.m4 to only add the problematic
-Wmissing-prototypes flag if GDB_COMPILER_TYPE is not 'gcc'.

I've tested this with both gcc and clang and see the expected results,
gcc no longer attempts to use the -Wmissing-prototypes flag, while
clang continues to use it.

When compiling using ccache, I am no longer seeing the warning.
2022-01-13 10:25:45 +00:00
Andrew Burgess
9ed5be5650 gdbsupport: regenerate Makefile.in
I had cause to regenerate gdbsupport/Makefile.in, and noticed some
unexpected changes in the copyright header dates.

I suspect that this was caused by the end of year date range update
process.

The Makefile.in contains two date ranges.  The first range appears to
be the date range for the version of automake being used, that is the
range runs up to 2017 only, when automake 1.15.1 was released.

The second date range in Makefile.in represents the date range for the
generated file, and so, now runs up to 2022.

Anyway, this is the result of running autoreconf (using automake
1.15.1) in the gdbsupport directory.
2022-01-11 10:10:51 +00:00
Andrew Burgess
926ac872e9 gdb: don't pass nullptr to sigwait
I tried building GDB on GNU/Hurd, and ran into this warning:

  gdbsupport/scoped_ignore_signal.h:78:16: error: null argument where non-null required (argument 2) [-Werror=nonnull]

This is because in this commit:

  commit 99624310dd
  Date:   Sun Jun 27 15:13:14 2021 -0400

      gdb: fall back on sigpending + sigwait if sigtimedwait is not available

A call to sigwait was introduced that passes nullptr as the second
argument, this call is only reached if sigtimedwait is not supported.

The original patch was written for macOS, I assume on that target
passing nullptr as the second argument is fine.

On my GNU/Linux box, the man-page for sigwait doesn't mention that
nullptr is allowed for the second argument, so my assumption would be
that nullptr is not OK, and, if I change the '#ifdef
HAVE_SIGTIMEDWAIT' introduced by the above patch to '#if 0', and
rebuild on GNU/Linux, I see the same warning that I see on GNU/Hurd.

I propose that we stop passing nullptr as the second argument to
sigwait, and instead pass a valid int pointer.  The value returned in
the int can then be used in an assert.

For testing, I (locally) made the change to the #ifdef I mentioned
above, compiled GDB, and ran the usual tests, this meant I was using
sigwait instead on sigtimedwait on GNU/Linux, I saw no regressions.
2022-01-04 10:28:19 +00:00
Joel Brobecker
4a94e36819 Automatic Copyright Year update after running gdb/copyright.py
This commit brings all the changes made by running gdb/copyright.py
as per GDB's Start of New Year Procedure.

For the avoidance of doubt, all changes in this commits were
performed by the script.
2022-01-01 19:13:23 +04:00
Luis Machado
261b07488b New --enable-threading configure option to control use of threads in GDB/GDBserver
Add the --enable-threading configure option so multithreading can be disabled
at configure time. This is useful for statically-linked builds of
GDB/GDBserver, since the thread library doesn't play well with that setup.

If you try to run a statically-linked GDB built with threading, it will crash
when setting up the number of worker threads.

This new option is also convenient when debugging GDB in a system with lots of
threads, where the thread discovery code in GDB will emit too many messages,
like so:

[New Thread 0xfffff74d3a50 (LWP 2625599)]

If you have X threads, that message will be repeated X times.

The default for --enable-threading is "yes".
2021-12-15 17:00:00 -03:00
Simon Marchi
b80a346e3d Revert "gdbsupport: remove unnecessary #ifndef IN_PROCESS_AGENT"
This reverts commit fe72c32765.

It turns out it was wrong, libinproctrace.so does build its own
gdbsupport/tdesc.cc.  This broke the build:

    make[1]: Entering directory '/home/simark/build/binutils-gdb-one-target/gdbserver'
      CXXLD  libinproctrace.so
    /usr/bin/ld: gdbsupport/tdesc-ipa.o: in function `print_xml_feature::visit_pre(target_desc const*)':
    /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/tdesc.cc:407: undefined reference to `tdesc_architecture_name(target_desc const*)'
    /usr/bin/ld: /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/tdesc.cc:408: undefined reference to `tdesc_architecture_name(target_desc const*)'
    /usr/bin/ld: /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/tdesc.cc:411: undefined reference to `tdesc_osabi_name(target_desc const*)'
    /usr/bin/ld: /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/tdesc.cc:416: undefined reference to `tdesc_compatible_info_list(target_desc const*)'
    /usr/bin/ld: /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/tdesc.cc:418: undefined reference to `tdesc_compatible_info_arch_name(std::unique_ptr<tdesc_compatible_info, std::default_delete<tdesc_compatible_info> > const&)'
2021-12-09 19:03:55 -05:00
Simon Marchi
fe72c32765 gdbsupport: remove unnecessary #ifndef IN_PROCESS_AGENT
I suppose this code was copied from GDBserver and this ifndef was left
there.  As far as I know, IN_PROCESS_AGENT will never be defined when
building this file, so we can remove this.

Change-Id: I84fc408e330b3a29106df830a09342861cadbaf6
2021-12-09 14:40:55 -05:00
Simon Marchi
671fac7c45 gdbsupport: fix memory leak in create_file_handler when re-using file handler
ASan made me notice a memory leak, where the memory tied to the file
handle name string wasn't freed.  When register a file handler with an
fd that is already registered, we re-use the file_handler object, so we
ended up creating a new std::string object and overwriting the
file_handler::name pointer, without free-ing the old std::string.

Fix this by allocating file_handler with new, deleting it with
delete, and making file_handler::name not a pointer.

Change-Id: Ie304cc78ab5ae5dfad9a1366e9890c09de651f43
2021-12-04 21:42:43 -05:00
Simon Marchi
4bce7cdaf4 gdbsupport: add array_view copy function
An assertion was recently added to array_view::operator[] to ensure we
don't do out of bounds accesses.  However, when the array_view is copied
to or from using memcpy, it bypasses that safety.

To address this, add a `copy` free function that copies data from an
array view to another, ensuring that the destination and source array
views have the same size.  When copying to or from parts of an
array_view, we are expected to use gdb::array_view::slice, which does
its own bounds check.  With all that, any copy operation that goes out
of bounds should be caught by an assertion at runtime.

copy is implemented using std::copy and std::copy_backward, which, at
least on libstdc++, appears to pick memmove when copying trivial data.
So in the end there shouldn't be much difference vs using a bare memcpy,
as we do right now.  When copying non-trivial data, std::copy and
std::copy_backward assigns each element in a loop.

To properly support overlapping ranges, we must use std::copy or
std::copy_backward, depending on whether the destination is before the
source or vice-versa.  std::copy and std::copy_backward don't support
copying exactly overlapping ranges (where the source range is equal to
the destination range).  But in this case, no copy is needed anyway, so
we do nothing.

The order of parameters of the new copy function is based on std::copy
and std::copy_backward, where the source comes before the destination.

Change a few randomly selected spots to use the new function, to show
how it can be used.

Add a test for the new function, testing both with arrays of a trivial
type (int) and of a non-trivial type (foo).  Test non-overlapping
ranges as well as three kinds of overlapping ranges: source before dest,
dest before source, and dest == source.

Change-Id: Ibeaca04e0028410fd44ce82f72e60058d6230a03
2021-12-03 16:37:36 -05:00
Simon Marchi
06de25b7af gdb: introduce target_waitkind_str, use it in target_waitstatus::to_string
I would like to print target_waitkind values in debug messages, so I
think that a target_waitkind-to-string function would be useful.  While
at it, use it in target_waitstatus::to_string.  This changes the output
of target_waitstatus::to_string a bit, but I think it is for the better.
The debug messages will show a string matching exactly the
target_waitkind enumerator (minus the TARGET_WAITKIND prefix).

As a convenience, make string_appendf return the same reference to
string it got as a parameter.  This allows doing this:

  return string_appendf (str, "foo");

... keeping the code concise.

Change-Id: I383dffc9c78614e7d0668b1516073905e798eef7
2021-11-22 13:57:49 -05:00
Simon Marchi
911438f9f4 gdbsupport: fix array-view compilation with c++11 && _GLIBCXX_DEBUG
When building with -std=c++11 and -D_GLIBCXX_DEBUG=1, we get some errors
like:

      CXX    unittests/array-view-selftests.o
    In file included from /home/smarchi/src/binutils-gdb/gdb/utils.h:25,
                     from /home/smarchi/src/binutils-gdb/gdb/defs.h:630,
                     from /home/smarchi/src/binutils-gdb/gdb/unittests/array-view-selftests.c:20:
    /home/smarchi/src/binutils-gdb/gdb/../gdbsupport/array-view.h: In instantiation of constexpr gdb::array_view<T> gdb::array_view<T>::slice(gdb::array_view<T>::size_type, gdb::array_view<T>::size_type) const [with T = unsigned char; gdb::array_view<T>::size_type = long unsigned int:
    /home/smarchi/src/binutils-gdb/gdb/unittests/array-view-selftests.c:532:29:   required from here
    /home/smarchi/src/binutils-gdb/gdb/../gdbsupport/array-view.h:192:3: error: body of constexpr function constexpr gdb::array_view<T> gdb::array_view<T>::slice(gdb::array_view<T>::size_type, gdb::array_view<T>::size_type) const [with T = unsigned char; gdb::array_view<T>::size_type = long unsigned int not a return-statement
      192 |   }
          |   ^

This is because constexpr functions in c++11 can only consist of a
single return statement, so we can't have the gdb_assert in there.  Make
the gdb_assert presence conditional to the __cplusplus version, to
enable it only for c++14 and later.

Change-Id: I2ac33f7b4bd1765ddc3ac8d07445b16ac1f340f0
2021-11-20 07:36:47 -05:00
Simon Marchi
557b4d7650 gdbsupport: make gdb_assert_not_reached accept a format string
Change gdb_assert_not_reached to accept a format string plus
corresponding arguments.  This allows giving more precise messages.

Because the format string passed by the caller is prepended with a "%s:"
to add the function name, the callers can no longer pass a translated
string (`_(...)`).  Make the gdb_assert_not_reached include the _(),
just like the gdb_assert_fail macro just above.

Change-Id: Id0cfda5a57979df6cdaacaba0d55dd91ae9efee7
2021-11-18 11:29:19 -05:00
Simon Marchi
830070c66d gdbsupport: remove FUNCTION_NAME
__func__ is standard C++11:

    https://en.cppreference.com/w/cpp/language/function

Also, in C++11, __func__ expands to the demangled function name, so the
mention in the comment above FUNCTION_NAME doesn't apply anymore.
Finally, in places where FUNCTION_NAME is used, I think it's enough to
print the function name, no need to print the whole signature.
Therefore, I propose to just remove FUNCTION_NAME and update users to
use the standard __func__.

Change-Id: I778f28155422b044402442dc18d42d0cded1017d
2021-11-16 15:37:00 -05:00
Andrew Burgess
8579fd136a gdb/gdbsupport: make xstrprintf and xstrvprintf return a unique_ptr
The motivation is to reduce the number of places where unmanaged
pointers are returned from allocation type routines.  All of the
callers are updated.

There should be no user visible changes after this commit.
2021-11-16 17:45:45 +00:00
Andrew Burgess
2bb7589ddf gdbsupport: move xfree into its own file
In the next commit I'd like to reference gdb_unique_ptr within the
common-utils.h file.  However, this requires that I include
gdb_unique_ptr.h, which requires that xfree be defined.

Interestingly, gdb_unique_ptr.h doesn't actually include anything that
defines xfree, but I was finding that when I added a gdb_unique_ptr.h
include to common-utils.h I was getting a dependency cycle; before my
change xfree was defined when gdb_unique_ptr.h was processed, while
after my change it was not, and this made g++ unhappy.

To break this cycle, I propose to move xfree into its own header file,
gdb-xfree.h, which I'll then include into gdb_unique_ptr.h and
common-utils.cc.
2021-11-16 17:45:44 +00:00
Tom de Vries
fdf95218bc [gdb/build] Fix Wimplicit-exception-spec-mismatch in clang build
When building with clang 13 (and -std=gnu++17 to work around an issue in
string_view-selftests.c), we run into a few Wimplicit-exception-spec-mismatch
warnings:
...
src/gdbsupport/new-op.cc:102:1: error: function previously declared with an \
  explicit exception specification redeclared with an implicit exception \
  specification [-Werror,-Wimplicit-exception-spec-mismatch]
operator delete (void *p)
^
/usr/include/c++/11/new:130:6: note: previous declaration is here
void operator delete(void*) _GLIBCXX_USE_NOEXCEPT
     ^
...

These are due to recent commit 5fff6115fe "Fix
LD_PRELOAD=/usr/lib64/libasan.so.6 gdb".

Fix this by adding the missing noexcept.

Build on x86_64-linux, using gcc 7.5.0 and clang 13.0.0.
2021-11-11 11:22:39 +01:00
Tom de Vries
b038b53f1f [gdb/build] Fix build with -std=c++11
When building with -std=c++11, we run into two Werror=missing-declarations:
...
new-op.cc: In function 'void operator delete(void*, std::size_t)':
new-op.cc:114:1: error: no previous declaration for \
  'void operator delete(void*, std::size_t)' [-Werror=missing-declarations]
 operator delete (void *p, std::size_t) noexcept
 ^~~~~~~~
new-op.cc: In function 'void operator delete [](void*, std::size_t)':
new-op.cc:132:1: error: no previous declaration for \
  'void operator delete [](void*, std::size_t)' [-Werror=missing-declarations]
 operator delete[] (void *p, std::size_t) noexcept
 ^~~~~~~~
...

These are due to recent commit 5fff6115fe "Fix
LD_PRELOAD=/usr/lib64/libasan.so.6 gdb".

The declarations are provided by <new> (which is included) for c++14 onwards,
but they are missing for c++11.

Fix this by adding the missing declarations.

Tested on x86_64-linux, with gcc 7.5.0, both without (implying -std=gnu++14) and
with -std=c++11.
2021-11-11 11:22:39 +01:00
Tom Tromey
0b03c6f03d Fix build on rhES5
The rhES5 build failed due to an upstream import a while back.  The
bug here is that, while the 'personality' function exists,
ADDR_NO_RANDOMIZE is only defined in <linux/personality.h>, not
<sys/personality.h>.

However, <linux/personality.h> does not declare the 'personality'
function, and <sys/personality.h> and <linux/personality.h> cannot
both be included.

This patch restores one of the removed configure checks and updates
the code to check it.

We had this as a local patch at AdaCore, because it seemed like there
was no interest upstream.  However, now it turns out that this fixes
PR build/28555, so I'm sending it now.
2021-11-09 08:21:18 -07:00
Lancelot SIX
e92f2b5eef Improve gdb::array_view ctor from contiguous containers
While reading the interface of gdb::array_view, I realized that the
constructor that builds an array_view on top of a contiguous container
(such as std::vector, std::array or even gdb::array_view) can be
missused.

Lets consider the following code sample:

	struct Parent
	{
	  Parent (int a): a { a } {}
	  int a;
	};

	std::ostream &operator<< (std::ostream& os, const Parent & p)
	{ os << "Parent {a=" << p.a << "}"; return os; }

	struct Child : public Parent
	{
	  Child (int a, int b): Parent { a }, b { b } {}
	  int b;
	};

	std::ostream &operator<< (std::ostream& os, const Child & p)
	{ os << "Child {a=" << p.a << ", b=" << p.b << "}"; return os; }

	template <typename T>
	void print (const gdb::array_view<const T> &p)
	{
	  std::for_each (p.begin (), p.end (), [](const T &p) { std::cout << p << '\n'; });
	}

Then with the current interface nothinng prevents this usage of
array_view to be done:

	const std::array<Child, 3> elts = {
	  Child {1, 2},
	  Child {3, 4},
	  Child {5, 6}
	};
	print_all<Parent> (elts);

This compiles fine and produces the following output:

	Parent {a=1}
	Parent {a=2}
	Parent {a=3}

which is obviously wrong.  There is nowhere in memory a Parent-like
object for which the A member is 2 and this call to print_all<Parent>
shold not compile at all (calling print_all<Child> is however fine).

This comes down to the fact that a Child* is convertible into a Parent*,
and that an array view is constructed to a pointer to the first element
and a size.  The valid type pointed to that can be used with this
constructor are restricted using SFINAE, which requires that a
pointer to a member into the underlying container can be converted into a
pointer the array_view's data type.

This patch proposes to change the constraints on the gdb::array_view
ctor which accepts a container now requires that the (decayed) type of
the elements in the container match the (decayed) type of the array_view
being constructed.

Applying this change required minimum adjustment in GDB codebase, which
are also included in this patch.

Tested by rebuilding.
2021-11-08 21:55:36 +00:00
Tom Tromey
be77dd73c7 Introduce make_unique_xstrndup
This adds a new make_unique_xstrndup function, which is the "n"
analogue of make_unique_xstrdup.  It also updates a couple existing
places to use this function.
2021-11-05 13:58:48 -06:00
Jan Kratochvil
5fff6115fe Fix LD_PRELOAD=/usr/lib64/libasan.so.6 gdb
Currently for a binary compiled normally (without -fsanitize=address) but with
LD_PRELOAD of ASAN one gets:

$ ASAN_OPTIONS=detect_leaks=0:alloc_dealloc_mismatch=1:abort_on_error=1:fast_unwind_on_malloc=0 LD_PRELOAD=/usr/lib64/libasan.so.6 gdb
=================================================================
==1909567==ERROR: AddressSanitizer: alloc-dealloc-mismatch (malloc vs operator delete []) on 0x602000001570
    #0 0x7f1c98e5efa7 in operator delete[](void*) (/usr/lib64/libasan.so.6+0xb0fa7)
...
0x602000001570 is located 0 bytes inside of 2-byte region [0x602000001570,0x602000001572)
allocated by thread T0 here:
    #0 0x7f1c98e5cd1f in __interceptor_malloc (/usr/lib64/libasan.so.6+0xaed1f)
    #1 0x557ee4a42e81 in operator new(unsigned long) (/usr/libexec/gdb+0x74ce81)
SUMMARY: AddressSanitizer: alloc-dealloc-mismatch (/usr/lib64/libasan.so.6+0xb0fa7) in operator delete[](void*)
==1909567==HINT: if you don't care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0
==1909567==ABORTING

Despite the code called properly operator new[] and operator delete[].
But GDB's new-op.cc provides its own operator new[] which gets translated into
malloc() (which gets recogized as operatore new(size_t)) but as it does not
translate also operators delete[] Address Sanitizer gets confused.

The question is how many variants of the delete operator need to be provided.
There could be 14 operators new but there are only 4, GDB uses 3 of them.
There could be 16 operators delete but there are only 6, GDB uses 2 of them.
It depends on libraries and compiler which of the operators will get used.
Currently being used:
                 U operator new[](unsigned long)
                 U operator new(unsigned long)
                 U operator new(unsigned long, std::nothrow_t const&)
                 U operator delete[](void*)
                 U operator delete(void*, unsigned long)

Tested on x86_64-linux.
2021-11-03 11:29:18 +01:00
Simon Marchi
c0492bea7c gdb: add selftest name completion
After the previous commit, it is easy to add completion for selftest
names.  Again, this is not particularly high value, but I rarely touched
completion, so it served as a simple example to get some practice.

Change the for_each_selftest_ftype parameter to gdb::function_view, so
that we can pass a lambda that captures things.

Change-Id: I87cac299ddca9ca7eb0ffab78342e850a98d954c
2021-10-28 11:17:45 -04:00
Simon Marchi
d9f82e9313 gdbsupport: add assertions in array_view
Add assertions to ensure we don't access an array_view out of bounds.
Enable these assertions only when _GLIBCXX_DEBUG is set, as we did for
gdb::optional.

Change-Id: Iffaee38252405073735ed123c8e57fde6b2c6be3
2021-10-25 14:51:44 -04:00
Tom Tromey
5dfe4bfcb9 Fix format_pieces selftest on Windows
The format_pieces selftest currently fails on Windows hosts.

The selftest doesn't handle the "%ll" -> "%I64" rewrite that the
formatter may perform, but also gdbsupport was missing a configure
check for PRINTF_HAS_LONG_LONG.  This patch fixes both issues.
2021-10-19 13:14:48 -06:00
Tom Tromey
d7c68312bd Always use std::function for self-tests
Now that there is a register_test variant that accepts std::function,
it seems to me that the 'selftest' struct and accompanying code is
obsolete -- simply always using std::function is simpler.  This patch
implements this idea.
2021-10-19 12:58:50 -06:00
Tom de Vries
77252bf26e [gdb/build] Add CXX_DIALECT to CXX
Say we use a gcc version that (while supporting c++11) does not support c++11
by default, and needs an -std setting to enable it.

If gdb would use the default AX_CXX_COMPILE_STDCXX from autoconf-archive, then
we'd have:
...
CXX="g++ -std=gnu++11"
...

That mechanism however has the following problem (quoting from commit
0bcda68539):
...
the top level Makefile passes CXX down to subdirs, and that overrides whatever
gdb/Makefile may set CXX to.  The result would be that a make invocation from
the build/gdb/ directory would use "g++ -std=gnu++11" as expected, while a
make invocation at the top level would not.
...

Commit 0bcda68539 fixes this by using a custom AX_CXX_COMPILE_STDCXX which
does:
...
CXX=g++
CXX_DIALECT=-std=gnu++11
...

The problem reported in PR28318 is that using the custom instead of the
default AX_CXX_COMPILE_STDCXX makes the configure test for std::thread
support fail.

We could simply add $CXX_DIALECT to the test for std::thread support, but
that would have to be repeated for each added c++ support test.

Instead, fix this by doing:
...
CXX="g++ -std=gnu++11"
CXX_DIALECT=-std=gnu++11
...

This is somewhat awkward, since it results in -std=gnu++11 occuring twice in
some situations:
...
$ touch src/gdb/dwarf2/read.c
$ ( cd build/gdb; make V=1 dwarf2/read.o )
g++-4.8 -std=gnu++11 -x c++ -std=gnu++11 ...
...

However, both settings are needed:
 - the switch in CXX for the std::thread tests (and other tests)
 - the switch in CXX_DIALECT so it can be appended in Makefiles, to
   counteract the fact that the top-level Makefile overrides CXX

The code added in gdb/ax_cxx_compile_stdcxx.m4 is copied from the default
AX_CXX_COMPILE_STDCXX from autoconf-archive.

Tested on x86_64-linux.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28318
2021-10-04 18:51:09 +02:00
Andrew Burgess
86c1ed137a gdbsupport: remove attempt to define TARGET_WORD_SIZE
In the gdbsupport configure.ac file, there is an attempt to define
TARGET_WORD_SIZE.  This is done by running grep on the file
../bfd/bfd-in3.h.

The problem with this is, the file bfd-in3.h is generated into the bfd
build directory when bfd is configured, and there is no dependency
between the gdbsupport module and the bfd module, so, for example, if
I do:

  $ ../src/configure
  $ make all-gdbsupport

Then bfd will neither be configured, or built.  In this case
TARGET_WORD_SIZE ends up being defined, but with no value because the
grep on bfd-in3.h fails.

However, it turns out that this doesn't matter; we don't actually use
TARGET_WORD_SIZE anywhere.

My proposal in this commit is to just remove the definition of
TARGET_WORD_SIZE, the alternative would be to add a dependency between
configure-gdbsupport and configure-bfd into Makefile.def, but adding a
dependency for something we don't need seems pretty pointless.
2021-10-04 10:52:35 +01:00
Simon Marchi
2fed9db40b gdbsupport: make gdb_mkostemp_cloexec return a scoped_fd
This encourages the callers to use automatic file descriptor management.

Change-Id: I137a81df6f3607b457e28c35aafde8ed6f3a3344
2021-09-30 15:21:48 -04:00
Simon Marchi
13084383e8 gdbsupport: make gdb_open_cloexec return scoped_fd
Make gdb_open_cloexec return a scoped_fd, to encourage using automatic
management of the file descriptor closing.  Except in the most trivial
cases, I changed the callers to just release the fd, which retains their
existing behavior.  That will allow the transition to using scoped_fd
more to go gradually, one caller at a time.

Change-Id: Ife022b403f96e71d5ebb4f1056ef6251b30fe554
2021-09-30 15:21:48 -04:00
Simon Marchi
e6e51c9c4b gdbsupport: move gdb_file_up to its own file
The following patches wants to change gdb_fopen_cloexec and
gdb_mkostemp_cloexec to return a scoped_fd.  Doing this causes a cyclic
include between scoped_fd.h and filestuff.h, that both want to include
each other.  scoped_fd.h includes filestuff.h because of the
scoped_fd::to_file method's return value.  filestuff.h would then
include scoped_fd.h for gdb_fopen_cloexec's and gdb_mkostemp_cloexec's
return values.

To fix that, move gdb_file_up to its own file, gdb_file.h.

Change-Id: Ic82a48914b2aacee8f14af535b7469245f88b93d
2021-09-30 15:21:48 -04:00
Tom Tromey
96bbe3ef96 Change ptid_t::tid to ULONGEST
The ptid_t 'tid' member is normally used as an address in gdb -- both
bsd-uthread and ravenscar-thread use it this way.  However, because
the type is 'long', this can cause problems with sign extension.

This patch changes the type to ULONGEST to ensure that sign extension
does not occur.
2021-09-23 09:30:54 -06:00
Tom Tromey
184ea2f731 Remove defaulted 'tid' parameter to ptid_t constructor
I wanted to find, and potentially modify, all the spots where the
'tid' parameter to the ptid_t constructor was used.  So, I temporarily
removed this parameter and then rebuilt.

In order to make it simpler to search through the "real" (nonzero)
uses of this parameter, something I knew I'd have to do multiple
times, I removed any ", 0" from constructor calls.

Co-Authored-By: John Baldwin <jhb@FreeBSD.org>
2021-09-23 09:30:54 -06:00
Tom de Vries
479209dd4f [gdb] Add maint selftest -verbose option
The print_one_insn selftest in gdb/disasm-selftests.c contains:
...
  /* If you want to see the disassembled instruction printed to gdb_stdout,
     set verbose to true.  */
  static const bool verbose = false;
...

Make this parameter available in the maint selftest command using a new option
-verbose, such that we can do:
...
(gdb) maint selftest -verbose print_one_insn
...

Tested on x86_64-linux.
2021-09-22 11:47:50 +02:00
Tom de Vries
c45a683f8f [gdb] Change register_test to use std::function arg
Change register_test to use std::function arg, such that we can do:
...
  register_test (test_name, [=] () { SELF_CHECK (...); });
...

Tested on x86_64-linux.
2021-09-21 00:41:26 +02:00
Simon Marchi
56d9e3c562 gdbsupport/gdb_proc_service.h: use decltype instead of typeof
Bug 28341 shows that GDB fails to compile when built with -std=c++11.
I don't know much about the use case, but according to the author of the
bug:

    I encountered the scenario where CXX is set to "g++ -std=c++11" when
    I try to compile binutils under GCC as part of the GCC 3-stage
    compilation, which is common for building a cross-compiler.

The author of the bug suggests using __typeof__ instead of typeof.  But
since we're using C++, we might as well use decltype, which is standard.
This is what this patch does.

The failure (and fix) can be observed by configuring GDB with CXX="g++
-std=c++11":

      CXX    linux-low.o
    In file included from /home/simark/src/binutils-gdb/gdbserver/gdb_proc_service.h:22,
		     from /home/simark/src/binutils-gdb/gdbserver/linux-low.h:27,
		     from /home/simark/src/binutils-gdb/gdbserver/linux-low.cc:20:
    /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/gdb_proc_service.h:177:50: error: expected constructor, destructor, or type conversion before (token
      177 |   __attribute__((visibility ("default"))) typeof (SYM) SYM
	  |                                                  ^
    /home/simark/src/binutils-gdb/gdbserver/../gdbsupport/gdb_proc_service.h:179:1: note: in expansion of macro PS_EXPORT
      179 | PS_EXPORT (ps_get_thread_area);
	  | ^~~~~~~~~

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28341
Change-Id: I84fbaae938209d8d935ca08dec9b7e6a0dd1bda0
2021-09-20 07:59:53 -04:00
Simon Marchi
4d7188abfd gdbsupport: add debug assertions in gdb::optional::get
The libstdc++ version of optional contains some runtime checks enabled
when _GLIBCXX_DEBUG is defined.  I think it would be useful if our
version contained similar checks.

Add checks in the two `get` methods, also conditional on _GLIBCXX_DEBUG.
I think it's simpler to use that macro rather than introducing a new
GDB-specific one, as I think that if somebody is interested in enabling
these runtime checks, they'll also be interested in enabling the
libstdc++ runtime checks (and vice-versa).

I implemented these checks using gdb_assert.  Note that gdb_assert
throws (after querying the user), and we are in noexcept methods.  That
means that std::terminate / abort will immediately be called.  I think
this is ok, since if those were "real" _GLIBCXX_DEBUG checks, abort
would be called straight away.

If I add a dummy failure, it looks like so:

    $ ./gdb -q -nx --data-directory=data-directory
    /home/simark/src/binutils-gdb/gdb/../gdbsupport/gdb_optional.h:206: internal-error: T& gdb::optional<T>::get() [with T = int]: Assertion `this->has_value ()' failed.
    A problem internal to GDB has been detected,
    further debugging may prove unreliable.
    Quit this debugging session? (y or n) n
    [1]    658767 abort (core dumped)  ./gdb -q -nx --data-directory=data-directory

Change-Id: Iadfdcd131425bd2ca6a2de30d7b22e9b3cc67793
2021-08-03 08:50:56 -04:00
Tom Tromey
785e5700ce Replace exception_print_same with operator!=
I noticed that exception_print_same is only used in a single spot, and
it seemed to be better as an operator!= method attached to
gdb_exception.

Regression tested on x86-64 Fedora 34.
2021-07-30 08:42:39 -06:00
Tom de Vries
fb6262e853 [gdb/build] Disable attribute nonnull
With trunk gcc (12.0) we're running into a -Werror=nonnull-compare build
breaker in gdb, which caused a broader review of the usage of the nonnull
attribute.

The current conclusion is that it's best to disable this.  This is explained
at length in the gdbsupport/common-defs.h comment.

Tested by building with trunk gcc.

gdb/ChangeLog:

2021-07-29  Tom de Vries  <tdevries@suse.de>

	* gdbsupport/common-defs.h (ATTRIBUTE_NONNULL): Disable.
2021-07-30 14:07:40 +02:00
Andrew Burgess
730afdd139 gdb: move remaining ChangeLogs to legacy files
In commit:

  commit f069ea46a0
  Date:   Sat Jul 3 16:29:08 2021 -0700

      Rename gdb/ChangeLog to gdb/ChangeLog-2021

The gdb/ChangeLog file was renamed, but all of the other ChangeLog
files relating to gdb were left in place.

As I understand things, the no ChangeLogs policy applies to all the
GDB related directories, so this commit renames all of the remaining
GDB related ChangeLog files.

As with the original commit, the intention behind this commit is to
hopefully stop people merging ChangeLog entries by mistake.

The renames carried out in this commit are:

    gdb/doc/ChangeLog -> gdb/doc/ChangeLog-1991-2021
    gdb/stubs/ChangeLog -> gdb/stubs/ChangeLog-2012-2020
    gdb/testsuite/ChangeLog -> gdb/testsuite/ChangeLog-2014-2021
    gdbserver/ChangeLog -> gdbserver/ChangeLog-2002-2021
    gdbsupport/ChangeLog -> gdbsupport/ChangeLog-2020-2021
2021-07-26 12:20:33 +01:00
Simon Marchi
11bd012ed2 gdb: make inferior::m_cwd an std::string
Same idea as the previous patch, but for m_cwd.

To keep things consistent across the board, change get_inferior_cwd as
well, which is shared with GDBserver.  So update the related GDBserver
code too.

Change-Id: Ia2c047fda738d45f3d18bc999eb67ceb8400ce4e
2021-07-23 15:38:54 -04:00
Simon Marchi
5b8bf2e75e gdb: un-share set_inferior_cwd declaration
The declaration of set_inferior_cwd is currently shared between gdb and
gdbserver, in gdbsupport/common-inferior.h.  It doesn't need to be, as
set_inferior_cwd is not called from common code.  Only get_inferior_cwd
needs to.

The motivation for this is that a future patch will change the prototype
of set_inferior_cwd in gdb, and I don't want to change it for gdbserver
unnecessarily.  I see this as a good cleanup in any case, to reduce to
just the essential what is shared between GDB and GDBserver.

Change-Id: I3127d27d078f0503ebf5ccc6fddf14f212426a73
2021-07-23 15:38:54 -04:00
Simon Marchi
12be796ca8 gdb: make all_inferiors_safe actually work
The test gdb.threads/fork-plus-threads.exp fails since 08bdefb58b
("gdb: make inferior_list use intrusive_list"):

    FAIL: gdb.threads/fork-plus-threads.exp: detach-on-fork=off: only inferior 1 left

Looking at the log, we see that we are left with a bunch of inferiors in
the detach-on-fork=off case:

    info inferiors^M
      Num  Description       Connection           Executable        ^M
    * 1    <null>                                 <snip>/fork-plus-threads ^M
      2    <null>                                 <snip>/fork-plus-threads ^M
      3    <null>                                 <snip>/fork-plus-threads ^M
      4    <null>                                 <snip>/fork-plus-threads ^M
      5    <null>                                 <snip>/fork-plus-threads ^M
      6    <null>                                 <snip>/fork-plus-threads ^M
      7    <null>                                 <snip>/fork-plus-threads ^M
      8    <null>                                 <snip>/fork-plus-threads ^M
      9    <null>                                 <snip>/fork-plus-threads ^M
      10   <null>                                 <snip>/fork-plus-threads ^M
      11   <null>                                 <snip>/fork-plus-threads ^M
    (gdb) FAIL: gdb.threads/fork-plus-threads.exp: detach-on-fork=off: only inferior 1 left

when we expect to have just one.  The problem is prune_inferiors not
pruning inferiors.  And this is caused by all_inferiors_safe not
actually iterating on inferiors.  The current implementation:

  inline all_inferiors_safe_range
  all_inferiors_safe ()
  {
    return {};
  }

default-constructs an all_inferiors_safe_range, which default-constructs
an all_inferiors_safe_iterator as its m_begin field, which
default-constructs a all_inferiors_iterator.  A default-constructed
all_inferiors_iterator is an end iterator, which means we have
constructed an (end,end) all_inferiors_safe_range.

We actually need to pass down the list on which we want to iterator
(that is the inferior_list global), so that all_inferiors_iterator's
first constructor is chosen.  We also pass nullptr as the proc_target
filter.  In this case, we don't do any filtering, but if in the future
all_inferiors_safe needed to allow filtering on process target (like
all_inferiors does), we could pass down a process target pointer.

basic_safe_iterator's constructor needs to be changed to allow
constructing the wrapped iterator with multiple arguments, not just one.

With this, gdb.threads/fork-plus-threads.exp is passing once again for
me.

Change-Id: I650552ede596e3590c4b7606ce403690a0278a01
2021-07-17 08:54:40 -04:00
Simon Marchi
a66f729819 gdb: maintain per-process-target list of resumed threads with pending wait status
Looking up threads that are both resumed and have a pending wait
status to report is something that we do quite often in the fast path
and is expensive if there are many threads, since it currently requires
walking whole thread lists.

The first instance is in maybe_set_commit_resumed_all_targets.  This is
called after handling each event in fetch_inferior_event, to see if we
should ask targets to commit their resumed threads or not.  If at least
one thread is resumed but has a pending wait status, we don't ask the
targets to commit their resumed threads, because we want to consume and
handle the pending wait status first.

The second instance is in random_pending_event_thread, where we want to
select a random thread among all those that are resumed and have a
pending wait status.  This is called every time we try to consume
events, to see if there are any pending events that we we want to
consume, before asking the targets for more events.

To allow optimizing these cases, maintain a per-process-target list of
threads that are resumed and have a pending wait status.

In maybe_set_commit_resumed_all_targets, we'll be able to check in O(1)
if there are any such threads simply by checking whether the list is
empty.

In random_pending_event_thread, we'll be able to use that list, which
will be quicker than iterating the list of threads, especially when
there are no resumed with pending wait status threads.

About implementation details: using the new setters on class
thread_info, it's relatively easy to maintain that list.  Any time the
"resumed" or "pending wait status" property is changed, we check whether
that should cause the thread to be added or removed from the list.

In set_thread_exited, we try to remove the thread from the list, because
keeping an exited thread in that list would make no sense (especially if
the thread is freed).  My first implementation assumed that a process
stratum target was always present when set_thread_exited is called.
That's however, not the case: in some cases, targets unpush themselves
from an inferior and then call "exit_inferior", which exits all the
threads.  If the target is unpushed before set_thread_exited is called
on the threads, it means we could mistakenly leave some threads in the
list.  I tried to see how hard it would be to make it such that targets
have to exit all threads before unpushing themselves from the inferior
(that would seem logical to me, we don't want threads belonging to an
inferior that has no process target).  That seemed quite difficult and
not worth the time at the moment.  Instead, I changed
inferior::unpush_target to remove all threads of that inferior from the
list.

As of this patch, the list is not used, this is done in the subsequent
patches.

The debug messages in process-stratum-target.c need to print some ptids.
However, they can't use target_pid_to_str to print them without
introducing a dependency on the current inferior (the current inferior
is used to get the current target stack).  For debug messages, I find it
clearer to print the spelled out ptid anyway (the pid, lwp and tid
values).  Add a ptid_t::to_string method that returns a string
representation of the ptid that is meant for debug messages, a bit like
we already have frame_id::to_string.

Change-Id: Iad8f93db2d13984dd5aa5867db940ed1169dbb67
2021-07-12 20:46:53 -04:00
Simon Marchi
8b6a69b2f3 gdb: use intrusive list for step-over chain
The threads that need a step-over are currently linked using an
hand-written intrusive doubly-linked list, so that seems a very good
candidate for intrusive_list, convert it.

For this, we have a use case of appending a list to another one (in
start_step_over).  Based on the std::list and Boost APIs, add a splice
method.  However, only support splicing the other list at the end of the
`this` list, since that's all we need.

Add explicit default assignment operators to
reference_to_pointer_iterator, which are otherwise implicitly deleted.
This is needed because to define thread_step_over_list_safe_iterator, we
wrap reference_to_pointer_iterator inside a basic_safe_iterator, and
basic_safe_iterator needs to be able to copy-assign the wrapped
iterator.  The move-assignment operator is therefore not needed, only
the copy-assignment operator is.  But for completeness, add both.

Change-Id: I31b2ff67c7b78251314646b31887ef1dfebe510c
2021-07-12 20:46:52 -04:00
Pedro Alves
bf80931081 gdb: introduce intrusive_list, make thread_info use it
GDB currently has several objects that are put in a singly linked list,
by having the object's type have a "next" pointer directly.  For
example, struct thread_info and struct inferior.  Because these are
simply-linked lists, and we don't keep track of a "tail" pointer, when
we want to append a new element on the list, we need to walk the whole
list to find the current tail.  It would be nice to get rid of that
walk.  Removing elements from such lists also requires a walk, to find
the "previous" position relative to the element being removed.  To
eliminate the need for that walk, we could make those lists
doubly-linked, by adding a "prev" pointer alongside "next".  It would be
nice to avoid the boilerplate associated with maintaining such a list
manually, though.  That is what the new intrusive_list type addresses.

With an intrusive list, it's also possible to move items out of the
list without destroying them, which is interesting in our case for
example for threads, when we exit them, but can't destroy them
immediately.  We currently keep exited threads on the thread list, but
we could change that which would simplify some things.

Note that with std::list, element removal is O(N).  I.e., with
std::list, we need to walk the list to find the iterator pointing to
the position to remove.  However, we could store a list iterator
inside the object as soon as we put the object in the list, to address
it, because std::list iterators are not invalidated when other
elements are added/removed.  However, if you need to put the same
object in more than one list, then std::list<object> doesn't work.
You need to instead use std::list<object *>, which is less efficient
for requiring extra memory allocations.  For an example of an object
in multiple lists, see the step_over_next/step_over_prev fields in
thread_info:

  /* Step-over chain.  A thread is in the step-over queue if these are
     non-NULL.  If only a single thread is in the chain, then these
     fields point to self.  */
  struct thread_info *step_over_prev = NULL;
  struct thread_info *step_over_next = NULL;

The new intrusive_list type gives us the advantages of an intrusive
linked list, while avoiding the boilerplate associated with manually
maintaining it.

intrusive_list's API follows the standard container interface, and thus
std::list's interface.  It is based the API of Boost's intrusive list,
here:

 https://www.boost.org/doc/libs/1_73_0/doc/html/boost/intrusive/list.html

Our implementation is relatively simple, while Boost's is complicated
and intertwined due to a lot of customization options, which our version
doesn't have.

The easiest way to use an intrusive_list is to make the list's element
type inherit from intrusive_node.  This adds a prev/next pointers to
the element type.  However, to support putting the same object in more
than one list, intrusive_list supports putting the "node" info as a
field member, so you can have more than one such nodes, one per list.

As a first guinea pig, this patch makes the per-inferior thread list use
intrusive_list using the base class method.

Unlike Boost's implementation, ours is not a circular list.  An earlier
version of the patch was circular: the intrusive_list type included an
intrusive_list_node "head".  In this design, a node contained pointers
to the previous and next nodes, not the previous and next elements.
This wasn't great for when debugging GDB with GDB, as it was difficult
to get from a pointer to the node to a pointer to the element.  With the
design proposed in this patch, nodes contain pointers to the previous
and next elements, making it easy to traverse the list by hand and
inspect each element.

The intrusive_list object contains pointers to the first and last
elements of the list.  They are nullptr if the list is empty.
Each element's node contains a pointer to the previous and next
elements.  The first element's previous pointer is nullptr and the last
element's next pointer is nullptr.  Therefore, if there's a single
element in the list, both its previous and next pointers are nullptr.
To differentiate such an element from an element that is not linked into
a list, the previous and next pointers contain a special value (-1) when
the node is not linked.  This is necessary to be able to reliably tell
if a given node is currently linked or not.

A begin() iterator points to the first item in the list.  An end()
iterator contains nullptr.  This makes iteration until end naturally
work, as advancing past the last element will make the iterator contain
nullptr, making it equal to the end iterator.  If the list is empty,
a begin() iterator will contain nullptr from the start, and therefore be
immediately equal to the end.

Iterating on an intrusive_list yields references to objects (e.g.
`thread_info&`).  The rest of GDB currently expects iterators and ranges
to yield pointers (e.g. `thread_info*`).  To bridge the gap, add the
reference_to_pointer_iterator type.  It is used to define
inf_threads_iterator.

Add a Python pretty-printer, to help inspecting intrusive lists when
debugging GDB with GDB.  Here's an example of the output:

    (top-gdb) p current_inferior_.m_obj.thread_list
    $1 = intrusive list of thread_info = {0x61700002c000, 0x617000069080, 0x617000069400, 0x61700006d680, 0x61700006eb80}

It's not possible with current master, but with this patch [1] that I
hope will be merged eventually, it's possible to index the list and
access the pretty-printed value's children:

    (top-gdb) p current_inferior_.m_obj.thread_list[1]
    $2 = (thread_info *) 0x617000069080
    (top-gdb) p current_inferior_.m_obj.thread_list[1].ptid
    $3 = {
      m_pid = 406499,
      m_lwp = 406503,
      m_tid = 0
    }

Even though iterating the list in C++ yields references, the Python
pretty-printer yields pointers.  The reason for this is that the output
of printing the thread list above would be unreadable, IMO, if each
thread_info object was printed in-line, since they contain so much
information.  I think it's more useful to print pointers, and let the
user drill down as needed.

[1] https://sourceware.org/pipermail/gdb-patches/2021-April/178050.html

Co-Authored-By: Simon Marchi <simon.marchi@efficios.com>
Change-Id: I3412a14dc77f25876d742dab8f44e0ba7c7586c0
2021-07-12 20:46:52 -04:00
Simon Marchi
9be259865c gdb: introduce iterator_range, remove next_adapter
I was always a bit confused by next_adapter, because it kind of mixes
the element type and the iterator type.  In reality, it is not much more
than a class that wraps two iterators (begin and end).  However, it
assumes that:

 - you can construct the begin iterator by passing a pointer to the
   first element of the iterable
 - you can default-construct iterator to make the end iterator

I think that by generalizing it a little bit, we can re-use it at more
places.

Rename it to "iterator_range".  I think it describes a bit better: it's
a range made by wrapping a begin and end iterator.  Move it to its own
file, since it's not related to next_iterator anymore.

iterator_range has two constructors.  The variadic one, where arguments
are forwarded to construct the underlying begin iterator.  The end
iterator is constructed through default construction.  This is a
generalization of what we have today.

There is another constructor which receives already constructed begin
and end iterators, useful if the end iterator can't be obtained by
default-construction.  Or, if you wanted to make a range that does not
end at the end of the container, you could pass any iterator as the
"end".

This generalization allows removing some "range" classes, like
all_inferiors_range.  These classes existed only to pass some arguments
when constructing the begin iterator.  With iterator_range, those same
arguments are passed to the iterator_range constructed and then
forwarded to the constructed begin iterator.

There is a small functional difference in how iterator_range works
compared to next_adapter.  next_adapter stored the pointer it received
as argument and constructeur an iterator in the `begin` method.
iterator_range constructs the begin iterator and stores it as a member.
Its `begin` method returns a copy of that iterator.

With just iterator_range, uses of next_adapter<foo> would be replaced
with:

  using foo_iterator = next_iterator<foo>;
  using foo_range = iterator_range<foo_iterator>;

However, I added a `next_range` wrapper as a direct replacement for
next_adapter<foo>.  IMO, next_range is a slightly better name than
next_adapter.

The rest of the changes are applications of this new class.

gdbsupport/ChangeLog:

	* next-iterator.h (class next_adapter): Remove.
	* iterator-range.h: New.

gdb/ChangeLog:

	* breakpoint.h (bp_locations_range): Remove.
	(bp_location_range): New.
	(struct breakpoint) <locations>: Adjust type.
	(breakpoint_range): Use iterator_range.
	(tracepoint_range): Use iterator_range.
	* breakpoint.c (breakpoint::locations): Adjust return type.
	* gdb_bfd.h (gdb_bfd_section_range): Use iterator_range.
	* gdbthread.h (all_threads_safe): Pass argument to
	all_threads_safe_range.
	* inferior-iter.h (all_inferiors_range): Use iterator_range.
	(all_inferiors_safe_range): Use iterator_range.
	(all_non_exited_inferiors_range): Use iterator_range.
	* inferior.h (all_inferiors, all_non_exited_inferiors): Pass
	inferior_list as argument.
	* objfiles.h (struct objfile) <compunits_range>: Remove.
	<compunits>: Return compunit_symtab_range.
	* progspace.h (unwrapping_objfile_iterator)
	<unwrapping_objfile_iterator>: Take parameter by value.
	(unwrapping_objfile_range): Use iterator_range.
	(struct program_space) <objfiles_range>: Define with "using".
	<objfiles>: Adjust.
	<objfiles_safe_range>: Define with "using".
	<objfiles_safe>: Adjust.
	<solibs>: Return so_list_range, define here.
	* progspace.c (program_space::solibs): Remove.
	* psymtab.h (class psymtab_storage) <partial_symtab_iterator>:
	New.
	<partial_symtab_range>: Use iterator_range.
	* solist.h (so_list_range): New.
	* symtab.h (compunit_symtab_range):
	New.
	(symtab_range): New.
	(compunit_filetabs): Change to a function.
	* thread-iter.h (inf_threads_range,
	inf_non_exited_threads_range, safe_inf_threads_range,
	all_threads_safe_range): Use iterator_range.
	* top.h (ui_range): New.
	(all_uis): Use ui_range.

Change-Id: Ib7a9d2a3547f45f01aa1c6b24536ba159db9b854
2021-07-06 15:02:05 -04:00
Simon Marchi
99624310dd gdb: fall back on sigpending + sigwait if sigtimedwait is not available
The macOS platform does not provide sigtimedwait, so we get:

      CXX    compile/compile.o
    In file included from /Users/smarchi/src/binutils-gdb/gdb/compile/compile.c:46:
    /Users/smarchi/src/binutils-gdb/gdb/../gdbsupport/scoped_ignore_signal.h:69:4: error: use of undeclared identifier 'sigtimedwait'
              sigtimedwait (&set, nullptr, &zero_timeout);
              ^

An alternative to sigtimedwait with a timeout of 0 is to use sigpending,
to first check which signals are pending, and then sigwait, to consume
them.  Since that's slightly more expensive (2 syscalls instead of 1),
keep using sigtimedwait for the platforms that provide it, and fall back
to sigpending + sigwait for the others.

gdbsupport/ChangeLog:

	* scoped_ignore_signal.h (struct scoped_ignore_signal)
	<~scoped_ignore_signal>: Use sigtimedwait if HAVE_SIGTIMEDWAIT
	is defined, else use sigpending + sigwait.

Change-Id: I2a72798337e81dd1bbd21214736a139dd350af87
Co-Authored-By: John Baldwin <jhb@FreeBSD.org>
2021-07-05 09:54:58 -04:00
Simon Marchi
f4931779e4 gdbsupport/common.m4: check for sigtimedwait
The next patch will make the use of sigtimedwait conditional to whether
the platform provides it.  Start by adding a configure check for it.

gdbsupport/ChangeLog:

	* common.m4 (GDB_AC_COMMON): Check for sigtimedwait.
	* config.in, configure: Re-generate.

gdb/ChangeLog:

	* config.in, configure: Re-generate.

gdbserver/ChangeLog:

	* config.in, configure: Re-generate.

Change-Id: Ic7613fe14521b966b4d991bbcd0933ab14629c05
2021-07-05 09:54:35 -04:00
Pedro Alves
336b30e58a Don't call sigtimedwait for scoped_ignore_sigttou
Because SIGTTOU is sent to the whole process instead of to a specific
thread, consuming a pending SIGTTOU in the destructor of
scoped_ignore_sigttou could consume a SIGTTOU signal raised due to
actions done by some other thread.  Simply avoid sigtimedwait in
scoped_ignore_sigttou, thus plugging the race.  This works because we
know that when the thread writes to the terminal and the signal is
blocked, the kernel does not raise the signal at all.

Tested on GNU/Linux, Solaris 11 and FreeBSD.

gdb/ChangeLog:
yyyy-mm-dd  Pedro Alves  <pedro@palves.net>

	* scoped_ignore_signal.h (scoped_ignore_signal): Add
	ConsumePending template parameter.
	(scoped_ignore_signal::~scoped_ignore_signal): Skip calling
	sigtimedwait if ConsumePending is false.
	(scoped_ignore_sigpipe): Initialize with ConsumePending=true.
	* scoped_ignore_sigttou.h (scoped_ignore_sigttou)
	<m_ignore_signal>: Initialize with ConsumePending=false.

Change-Id: I92f754dbc45c45819dce2ce68b8c067d8d5c61b1
2021-06-17 19:39:08 +01:00
Pedro Alves
606a431366 scoped_ignore_signal: Use sigprocmask+sigtimedwait instead of signal
The problem with using signal(...) to temporarily ignore a signal, is
that that changes the the signal disposition for the whole process.
If multiple threads do it at the same time, you have a race.

Fix this by using sigprocmask + sigtimedwait to implement the ignoring
instead, if available, which I think probably means everywhere except
Windows nowadays.  This way, we only change the signal mask for the
current thread, so there's no race.

Change-Id: Idfe3fb08327ef8cae926f3de9ee81c56a83b1738

gdbsupport/ChangeLog:
yyyy-mm-dd  Pedro Alves  <pedro@palves.net>

	* scoped_ignore_signal.h
	(scoped_ignore_signal::scoped_ignore_signal)
	[HAVE_SIGPROCMASK]: Use sigprocmask to block the signal instead of
	changing the signal disposition for the whole process.
	(scoped_ignore_signal::~scoped_ignore_signal) [HAVE_SIGPROCMASK]:
	Use sigtimedwait and sigprocmask to flush and unblock the signal.
2021-06-17 16:22:12 +01:00
Pedro Alves
6a7f1c20e8 Introduce scoped_restore_signal
We currently have scoped_restore_sigttou and scoped_restore_sigpipe
doing basically the same thing -- temporarily ignoring a specific
signal.

This patch introduce a scoped_restore_signal type that can be used for
both.  This will become more important for the next patch which
changes how the signal-ignoring is implemented.

scoped_restore_sigpipe is a straight alias to
scoped_restore_signal<SIGPIPE> on systems that define SIGPIPE, and an
alias to scoped_restore_signal_nop (a no-op version of
scoped_restore_signal) otherwise.

scoped_restore_sigttou is not a straight alias because it wants to
check the job_control global.

gdb/ChangeLog:
yyyy-mm-dd  Pedro Alves  <pedro@palves.net>

	* gdbsupport/scoped_ignore_signal.h: New.
	* compile/compile.c: Include gdbsupport/scoped_ignore_signal.h
	instead of <signal.h>.  Don't include <unistd.h>.
	(scoped_ignore_sigpipe): Remove.
	* gdbsupport/scoped_ignore_sigttou.h: Include gdbsupport/scoped_ignore_signal.h
	instead of <signal.h>.  Don't include <unistd.h>.
	(lazy_init): New.
	(scoped_ignore_sigttou): Reimplement using scoped_ignore_signal
	and lazy_init.

Change-Id: Ibb44d0bd705e96df03ef0787c77358a4a7b7086c
2021-06-17 16:22:11 +01:00
Pedro Alves
965febe599 Move scoped_ignore_sigttou to gdbsupport/
A following patch will want to use scoped_ignore_sigttou in code
shared between GDB and GDBserver.  Move it under gdbsupport/.

Note that despite what inflow.h/inflow.c's first line says, inflow.c
is no longer about ptrace, it is about terminal management.  Some
other files were unnecessarily including inflow.h, I guess a leftover
from the days when inflow.c really was about ptrace.  Those inclusions
are simply dropped.

gdb/ChangeLog:
yyyy-mm-dd  Pedro Alves  <pedro@palves.net>

	* Makefile.in (HFILES_NO_SRCDIR): Remove inflow.h.
	* inf-ptrace.c, inflow.c, procfs.c: Don't include "inflow.h".
	* inflow.h: Delete, moved to gdbsupport/ under a different name.
	* ser-unix.c: Don't include "inflow.h".  Include
	"gdbsupport/scoped_ignore_sigttou.h".

gdbsupport/ChangeLog:
yyyy-mm-dd  Pedro Alves  <pedro@palves.net>

	* scoped_ignore_sigttou.h: New file, moved from gdb/ and renamed.

Change-Id: Ie390abf42c3a78bec6d282ad2a63edd3e623559a
2021-06-17 16:22:11 +01:00
Andrew Burgess
c1c0a7e1f3 gdb: additional settings for emacs in .dir-locals.el
Two additional settings for developers who use emacs:

  1. Set brace-list-open to 0 for C and C++ modes, this ensures we
  format things like:

  enum blah
  {
    ....
  };

  Instead of the default for the emacs GNU style:

  enum blah
    {
      ...
    };

  The former seems to be the GDB style.

  2. Set sentence-end-double-space to t.  This is actually the default
  value for this setting, but if anyone has customised this to nil in
  general, then forcing this back to t for GDB files will give a
  better behaviour for the paragraph filling.

gdb/ChangeLog:

	* .dir-locals.el: Set sentence-end-double-space for all modes, and
	set brace-list-open to 0 for C and C++ modes.

gdbserver/ChangeLog:

	* .dir-locals.el: Set sentence-end-double-space for all modes, and
	set brace-list-open to 0 for C and C++ modes.

gdbsupport/ChangeLog:

	* .dir-locals.el: Set sentence-end-double-space for all modes, and
	set brace-list-open to 0 for C and C++ modes.
2021-05-17 20:47:46 +01:00
Simon Marchi
b6703327bb gdbsupport: re-generate configure & friends
I get these changes when re-generating the autoconf stuff in gdbsupport,
fallouts from 4655f8509f ("Don't run personality syscall at configure
time; don't check it at all").

gdbsupport/ChangeLog:

	* Makefile.in: Re-generate.
	* config.in: Re-generate.
	* configure: Re-generate.

Change-Id: Ie1876ee58d6f4f1cf25fa14900eecf4c85a744c1
2021-05-08 21:27:49 -04:00
Pedro Alves
4655f8509f Don't run personality syscall at configure time; don't check it at all
Currently, in order to tell whether support for disabling address
space randomization on Linux is available, GDB checks if the
personality syscall works, at configure time.  I.e., it does a run
test, instead of a compile/link test:

  AC_RUN_IFELSE([PERSONALITY_TEST],
		[have_personality=true],
		[have_personality=false],

This is a bit bogus, because the machine the build is done on may not
(and is when you consider distro gdbs) be the machine that eventually
runs gdb.  It would be better if this were a compile/link test
instead, and then at runtime, GDB coped with the personality syscall
failing.  Actually, GDB already copes.

One environment where this is problematic is building GDB in a Docker
container -- by default, Docker runs the container with seccomp, with
a profile that disables the personality syscall.  You can tell Docker
to use a less restricted seccomp profile, but I think we should just
fix it in GDB.

"man 2 personality" says:

       This system call first appeared in Linux 1.1.20 (and thus first
       in a stable kernel release with Linux 1.2.0); library support
       was added in glibc 2.3.

...

       ADDR_NO_RANDOMIZE (since Linux 2.6.12)
              With this flag set, disable address-space-layout randomization.

glibc 2.3 was released in 2002.
Linux 2.6.12 was released in 2005.

The original patch that added the configure checks was submitted in
2008.  The first version of the patch that was submitted to the list
called personality from common code:

 https://sourceware.org/pipermail/gdb-patches/2008-June/058204.html

and then was moved to Linux-specific code:

 https://sourceware.org/pipermail/gdb-patches/2008-June/058209.html

Since HAVE_PERSONALITY is only checked in Linux code, and
ADDR_NO_RANDOMIZE exists for over 15 years, I propose just completely
removing the configure checks.

If for some odd reason, some remotely modern system still needs a
configure check, then we can revert this commit but drop the
AC_RUN_IFELSE in favor of always doing the AC_LINK_IFELSE
cross-compile fallback.

gdb/ChangeLog:

	* linux-nat.c (linux_nat_target::supports_disable_randomization):
	Remove references to HAVE_PERSONALITY.
	* nat/linux-personality.c: Remove references to HAVE_PERSONALITY.
	(maybe_disable_address_space_randomization)
	(~maybe_disable_address_space_randomizatio): Remove references to
	HAVE_PERSONALITY.
	* config.in, configure: Regenerate.

gdbserver/ChangeLog:

	* linux-low.cc:
	(linux_process_target::supports_disable_randomization): Remove
	reference to HAVE_PERSONALITY.
	* config.in, configure: Regenerate.

gdbsupport/ChangeLog:

	* common.m4 (personality test): Remove.
2021-05-08 13:45:36 +01:00
Tom Tromey
698facb837 Use rvalue reference in thread_pool::post_task
Tankut's recent patches made me realize that thread_pool::post_task
should have used an rvalue reference for its parameter.  This patch
makes this change.

gdbsupport/ChangeLog
2021-04-30  Tom Tromey  <tromey@adacore.com>

	* thread-pool.cc (thread_pool::post_task): Update.
	* thread-pool.h (class thread_pool) <post_task>: Take rvalue
	reference to function.
2021-04-30 10:04:56 -06:00
Michael Weghorn
9a6e099f43 gdbsupport: allow to specify dependencies between observers
Previously, the observers attached to an observable were always notified
in the order in which they had been attached.  That order is not easily
controlled, because observers are typically attached in _initialize_*
functions, which are called in an undefined order.

However, an observer may require that another observer attached only
later is called before itself is.

Therefore, extend the 'observable' class to allow explicitly specifying
dependencies when attaching observers, by adding the possibility to
specify tokens for observers that it depends on.

To make sure dependencies are notified before observers depending on
them, the vector holding the observers is sorted in a way that
dependencies come before observers depending on them.  The current
implementation for sorting uses the depth-first search algorithm for
topological sorting as described at [1].

Extend the observable unit tests to cover this case as well.  Check that
this works for a few different orders in which the observers are
attached.

This newly introduced mechanism to explicitly specify dependencies will
be used in a follow-up commit.

[1] https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search

Tested on x86_64-linux (Debian testing).

gdb/ChangeLog:

	* unittests/observable-selftests.c (dependency_test_counters):
	New.
	(observer_token0, observer_token1, observer_token2,
	observer_token3, observer_token4, observer_token5): New.
	(struct dependency_observer_data): New struct.
	(observer_dependency_test_callback): New function.
	(test_observers): New.
	(run_dependency_test): New function.
	(test_dependency): New.
	(_initialize_observer_selftest): Register dependency test.

gdbsupport/ChangeLog:

	* observable.h (class observable): Extend to allow specifying
	dependencies between observers, keep vector holding observers
	sorted so that dependencies are notified before observers
	depending on them.

Change-Id: I5399def1eeb69ca99e28c9f1fdf321d78b530bdb
2021-04-27 11:22:32 -04:00
Simon Marchi
a8536c466a gdbsupport: add observer_debug_printf, OBSERVER_SCOPED_DEBUG_ENTER_EXIT
Switch observer to use the "new" debug printf mechanism and sprinkle a
few debug prints.  Here's a small example of the output with "infrun"
and "observer" debug output enabled:

    [infrun] proceed: enter
      [observer] notify: start: observable target_resumed notify() called
        [observer] notify: start: calling observer mi-interp of observable target_resumed
        [observer] notify: end: calling observer mi-interp of observable target_resumed
        [observer] notify: start: calling observer py-inferior of observable target_resumed
        [observer] notify: end: calling observer py-inferior of observable target_resumed
      [observer] notify: end: observable target_resumed notify() called
      ...

gdbsupport/ChangeLog:

	* observable.h (observer_debug_printf,
	OBSERVER_SCOPED_DEBUG_START_END): New.
	(class observable) <notify, attach>: Use them.

Change-Id: If3ae4b6b65450ca3b7cae56698a87fc526688b86
2021-04-24 19:26:41 -04:00
Simon Marchi
0df0cce7c6 gdbsupport: allow passing format string to scoped_debug_start_end
A little thing that bothers me with scoped_debug_start_end is that it's
not possible to pass a format string to add context to the messages: the
start and end messages are fixed.

It was done like this at the time because there's the risk that debug
output is not enabled on entry (when the constructor runs) but is
enabled on exit (when the destructor runs).  For example, a user
debugging from a top-gdb may manually enable a debug_foo variable.  If
debug output is disabled while the constructor runs, we won't render the
format string (to minimize overhead) so it won't be available in the
destructor.

I think it would be nice to be able to use a format string along with
scoped_debug_start_end, and I think it's unfortunate that such a narrow
use case prevents it.  So with this patch, I propose that we allow
passing a format string to scoped_debug_start_end, and if the rare
situation described above happens, then we just show a "sorry, message
not available" kind of message.

The following patch makes use of this.

gdbsupport/ChangeLog:

	* common-debug.h (struct scoped_debug_start_end)
	<scoped_debug_start_end>: Change start_msg/end_msg for
	start_prefix/end_prefix.  Add format string parameter and make
	variadic.
	<~scoped_debug_start_end>: Adjust.
	<m_end_msg>: Rename to...
	<m_end_prefix>: ... this.
	<m_with_format>: New.
	<m_msg>: New.
	(scoped_debug_start_end): Make variadic.
	(scoped_debug_enter_exit): Adjust.

Change-Id: I9427ce8877a246a46694b3a1fec3837dc6954d6e
2021-04-24 19:26:41 -04:00
Simon Marchi
c90e7d6352 gdbsupport, gdb: give names to observers
Give a name to each observer, this will help produce more meaningful
debug message.

gdbsupport/ChangeLog:

	* observable.h (class observable) <struct observer> <observer>:
	Add name parameter.
	<name>: New field.
	<attach>: Add name parameter, update all callers.

Change-Id: Ie0cc4664925215b8d2b09e026011b7803549fba0
2021-04-24 19:26:41 -04:00
Simon Marchi
ec098003e2 gdbsupport: introduce struct observer
Instead of using a pair.  This allows keeping more data per observer in
a structured way, and using field names is clearer than first/second.

gdbsupport/ChangeLog:

	* observable.h (class observable) <struct observer>: New.
	<detach, notify>: Update.
	<m_observers>: Change type to vector of observers.

Change-Id: Iadf7d1fa25049cfb089e6b1b429ddebc548825ab
2021-04-24 19:26:41 -04:00
Simon Marchi
98c897e37a gdbsupport, gdb: change observer_debug to bool
gdb/ChangeLog:

	* observable.c (observer_debug): Change to bool.

gdbsupport/ChangeLog:

	* observable.h (observer_debug): Change to bool.

Change-Id: I58634235a20740a66eacb1c83bae3cf3304ae1fd
2021-04-23 16:28:26 -04:00
Simon Marchi
4d6840c335 gdbsupport: include preprocessor.h in common-debug.h
While doing some changes, some code failed to compile because it used
the scoped_debug_start_end macro, but couldn't find the CONCAT macro.
Fix that by making common-debug.h include preprocessor.h, the header
file that provides CONCAT.

gdbsupport/ChangeLog:

	* common-debug.h: Include preprocessor.h.

Change-Id: Ibf863a932a18cba9a57b4bd72df538ef52d39127
2021-04-23 14:03:39 -04:00
Luis Machado
48136e006e New memory-tag commands
Add new commands under the "memory-tag" prefix to allow users to inspect,
modify and check memory tags in different ways.

The available subcommands are the following:

- memory-tag print-logical-tag <expression>: Prints the logical tag for a
  particular address.

- memory-tag withltag <expression> <tag>: Prints the address tagged with the
  logical tag <tag>.

- memory-tag print-allocation-tag <expression>: Prints the allocation tag for
  a particular address.

- memory-tag setatag <expression> <length> <tags>: Sets one or more allocation
  tags to the specified tags.

- memory-tag check <expression>: Checks if the logical tag in <address>
  matches its allocation tag.

These commands make use of the memory tagging gdbarch methods, and are still
available, but disabled, when memory tagging is not supported by the
architecture.

I've pondered about a way to make these commands invisible when memory tagging
is not available, but given the check is at runtime (and support may come and go
based on a process' configuration), that is a bit too late in the process to
either not include the commands or get rid of them.

Ideas are welcome.

gdb/ChangeLog:

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

	* printcmd.c: Include gdbsupport/rsp-low.h.
	(memory_tag_list): New static global.
	(process_print_command_args): Factored out of
	print_command_1.
	(print_command_1): Use process_print_command_args.
	(show_addr_not_tagged, show_memory_tagging_unsupported)
	(memory_tag_command, memory_tag_print_tag_command)
	(memory_tag_print_logical_tag_command)
	(memory_tag_print_allocation_tag_command, parse_with_logical_tag_input)
	(memory_tag_with_logical_tag_command, parse_set_allocation_tag_input)
	(memory_tag_set_allocation_tag_command, memory_tag_check_command): New
	functions.
	(_initialize_printcmd): Add "memory-tag" prefix and subcommands.

gdbsupport/ChangeLog:

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

	* rsp-low.cc (fromhex, hex2bin): Move to ...
	* common-utils.cc: ... here.
	(fromhex) Change error message text to not be RSP-specific.
	* rsp-low.h (fromhex, hex2bin): Move to ...
	* common-utils.h: ... here.
2021-03-24 14:57:53 -03:00
Alan Modra
e93388417c Provide an inline startswith function in bfd.h
bfd/
	* bfd-in.h (startswith): New inline.
	(CONST_STRNEQ): Use startswith.
	* bfd-in2.h: Regenerate.
gdbsupport/
	* common-utils.h (startswith): Delete version now supplied by bfd.h.
libctf/
	* ctf-impl.h: Include string.h.
2021-03-21 23:00:32 +10:30
Paul E. Murphy
9c9d63b15a gnulib: update to 776af40e0
This fixes PR27184, a failure to compile gdb due to
cdefs.h being out of sync with glibc on ppc64le targets
which are compiled with -mabi=ieeelongdouble and glibc
2.32.

Likewise, update usage of _GL_ATTRIBUTE_FORMAT_PRINTF to
_GL_ATTRIBUTE_FORMAT_PRINTF_STANDARD.

Likewise, disable newly added rpl_free gnulib api in
gdbserver support libraries.

Likewise, undefine read/write macros before redefining them
on mingw targets.

Likewise, wrap C++ usage of free with GNULIB_NAMESPACE namespace
as needed.

Change-Id: I86517613c0d8ac8f5ea45bbc4ebe2b54a3aef29f
2021-02-05 13:35:20 -05:00
Lancelot SIX
d3ee35dbf7 Improve gdb_tilde_expand logic.
Before this patch, gdb_tilde_expand would use glob(3) in order to expand
tilde at the begining of a path. This implementation has limitation when
expanding a tilde leading path to a non existing file since glob fails to
expand.

This patch proposes to use glob only to expand the tilde component of the
path and leaves the rest of the path unchanged.

This patch is a followup to the following discution:
https://sourceware.org/pipermail/gdb-patches/2021-January/174776.html

Before the patch:

	gdb_tilde_expand("~") -> "/home/lsix"
	gdb_tilde_expand("~/a/c/b") -> error() is called

After the patch:

	gdb_tilde_expand("~") -> "/home/lsix"
	gdb_tilde_expand("~/a/c/b") -> "/home/lsix/a/c/b"

Tested on x84_64 linux.

gdb/ChangeLog:

	* Makefile.in (SELFTESTS_SRCS): Add
	unittests/gdb_tilde_expand-selftests.c.
	* unittests/gdb_tilde_expand-selftests.c: New file.

gdbsupport/ChangeLog:

	* gdb_tilde_expand.cc (gdb_tilde_expand): Improve
	implementation.
	(gdb_tilde_expand_up): Delegate logic to gdb_tilde_expand.
	* gdb_tilde_expand.h (gdb_tilde_expand): Update description.
2021-01-23 17:17:38 +00:00
Simon Marchi
2189c31265 gdb: add remote_debug_printf
This is the next in the new-style debug macro series.

For this one, I decided to omit the function name from the "Sending packet" /
"Packet received" kind of prints, just because it's not very useful in that
context and hinders readability more than anything else.  This is completely
arbitrary.

This is with:

  [remote] putpkt_binary: Sending packet: $qTStatus#49...
  [remote] getpkt_or_notif_sane_1: Packet received: T0;tnotrun:0;tframes:0;tcreated:0;tfree:500000;tsize:500000;circular:0;disconn:0;starttime:0;stoptime:0;username:;notes::

and without:

  [remote] Sending packet: $qTStatus#49...
  [remote] Packet received: T0;tnotrun:0;tframes:0;tcreated:0;tfree:500000;tsize:500000;circular:0;disconn:0;starttime:0;stoptime:0;username:;notes::

A difference is that previously, the query packet and its reply would be
printed on the same line, like this:

  Sending packet: $qTStatus#49...Packet received: T0;tnotrun:0;tframes:0;tcreated:0;tfree:500000;tsize:500000;circular:0;disconn:0;starttime:0;stoptime:0;username:;notes::

Now, they are printed on two lines, since each remote_debug_printf{,_nofunc}
prints its own complete message including an end of line.  It's probably
a matter of taste, but I prefer the two-line version, it's easier to
follow, especially when the query packet is long.

As a result, lib/range-stepping-support.exp needs to be updated, as it
currently expects the vCont packet and the reply to be on the same line.
I think it's sufficient in that context to just expect the vCont packet
and not the reply, since the goal is just to count how many vCont;r GDB
sends.

gdb/ChangeLog:

	* remote.h (remote_debug_printf): New.
	(remote_debug_printf_nofunc): New.
	(REMOTE_SCOPED_DEBUG_ENTER_EXIT): New.
	* remote.c: Use above macros throughout file.

gdbsupport/ChangeLog:

	* common-debug.h (debug_prefixed_printf_cond_nofunc): New.
	* common-debug.c (debug_prefixed_vprintf): Handle a nullptr
	func.

gdb/testsuite/ChangeLog:

	* lib/range-stepping-support.exp (exec_cmd_expect_vCont_count):
	Adjust to "set debug remote" changes.

Change-Id: Ica6dead50d3f82e855c7d763f707cef74bed9fee
2021-01-22 12:43:27 -05:00
Simon Marchi
6abd4cf281 gdb: check for empty strings in get_standard_cache_dir/get_standard_config_dir
As reported in PR 27157, if some environment variables read at startup
by GDB are defined but empty, we hit the assert in gdb_abspath:

    $ XDG_CACHE_HOME= ./gdb -nx --data-directory=data-directory -q
    AddressSanitizer:DEADLYSIGNAL
    =================================================================
    ==2007040==ERROR: AddressSanitizer: SEGV on unknown address 0x0000000001b0 (pc 0x5639d4aa4127 bp 0x7ffdac232c00 sp 0x7ffdac232bf0 T0)
    ==2007040==The signal is caused by a READ memory access.
    ==2007040==Hint: address points to the zero page.
        #0 0x5639d4aa4126 in target_stack::top() const /home/smarchi/src/binutils-gdb/gdb/target.h:1334
        #1 0x5639d4aa41f1 in inferior::top_target() /home/smarchi/src/binutils-gdb/gdb/inferior.h:369
        #2 0x5639d4a70b1f in current_top_target() /home/smarchi/src/binutils-gdb/gdb/target.c:120
        #3 0x5639d4b00591 in gdb_readline_wrapper_cleanup::gdb_readline_wrapper_cleanup() /home/smarchi/src/binutils-gdb/gdb/top.c:1046
        #4 0x5639d4afab31 in gdb_readline_wrapper(char const*) /home/smarchi/src/binutils-gdb/gdb/top.c:1104
        #5 0x5639d4ccce2c in defaulted_query /home/smarchi/src/binutils-gdb/gdb/utils.c:893
        #6 0x5639d4ccd6af in query(char const*, ...) /home/smarchi/src/binutils-gdb/gdb/utils.c:985
        #7 0x5639d4ccaec1 in internal_vproblem /home/smarchi/src/binutils-gdb/gdb/utils.c:373
        #8 0x5639d4ccb3d1 in internal_verror(char const*, int, char const*, __va_list_tag*) /home/smarchi/src/binutils-gdb/gdb/utils.c:439
        #9 0x5639d5151a92 in internal_error(char const*, int, char const*, ...) /home/smarchi/src/binutils-gdb/gdbsupport/errors.cc:55
        #10 0x5639d5162ab4 in gdb_abspath(char const*) /home/smarchi/src/binutils-gdb/gdbsupport/pathstuff.cc:132
        #11 0x5639d5162fac in get_standard_cache_dir[abi:cxx11]() /home/smarchi/src/binutils-gdb/gdbsupport/pathstuff.cc:228
        #12 0x5639d3e76a81 in _initialize_index_cache() /home/smarchi/src/binutils-gdb/gdb/dwarf2/index-cache.c:325
        #13 0x5639d4dbbe92 in initialize_all_files() /home/smarchi/build/binutils-gdb/gdb/init.c:321
        #14 0x5639d4b00259 in gdb_init(char*) /home/smarchi/src/binutils-gdb/gdb/top.c:2344
        #15 0x5639d4440715 in captured_main_1 /home/smarchi/src/binutils-gdb/gdb/main.c:950
        #16 0x5639d444252e in captured_main /home/smarchi/src/binutils-gdb/gdb/main.c:1229
        #17 0x5639d44425cf in gdb_main(captured_main_args*) /home/smarchi/src/binutils-gdb/gdb/main.c:1254
        #18 0x5639d3923371 in main /home/smarchi/src/binutils-gdb/gdb/gdb.c:32
        #19 0x7fa002d3f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
        #20 0x5639d392314d in _start (/home/smarchi/build/binutils-gdb/gdb/gdb+0x4d414d)

gdb_abspath doesn't handle empty strings, so handle this case in the
callers.  If a variable is defined but empty, I think it's reasonable in
this case to just ignore it, as if it was not defined.

Note that this sometimes also lead to a segfault, because the failed
assertion happens very early during startup, before things are fully
initialized.

gdbsupport/ChangeLog:

	PR gdb/27157
	* pathstuff.cc (get_standard_cache_dir, get_standard_config_dir,
	find_gdb_home_config_file): Add empty string check.

gdb/testsuite/ChangeLog:

	PR gdb/27157
	* gdb.base/empty-host-env-vars.exp: New test.

Change-Id: I8654d8e97e74e1dff6d308c111ae4b1bbf07bef9
2021-01-08 13:46:56 -05:00
Mike Frysinger
4b186f88b8 gdbsupport: common-utils.h: fix typo in header 2021-01-06 05:52:06 -05:00
Simon Marchi
3ec3145c5d gdb: introduce scoped debug prints
I spent a lot of time reading infrun debug logs recently, and I think
they could be made much more readable by being indented, to clearly see
what operation is done as part of what other operation.  In the current
format, there are no visual cues to tell where things start and end,
it's just a big flat list.  It's also difficult to understand what
caused a given operation (e.g. a call to resume_1) to be done.

To help with this, I propose to add the new scoped_debug_start_end
structure, along with a bunch of macros to make it convenient to use.

The idea of scoped_debug_start_end is simply to print a start and end
message at construction and destruction.  It also increments/decrements
a depth counter in order to make debug statements printed during this
range use some indentation.  Some care is taken to handle the fact that
debug can be turned on or off in the middle of such a range.  For
example, a "set debug foo 1" command in a breakpoint command, or a
superior GDB manually changing the debug_foo variable.

Two macros are added in gdbsupport/common-debug.h, which are helpers to
define module-specific macros:

  - scoped_debug_start_end: takes a message that is printed both at
    construction / destruction, with "start: " and "end: " prefixes.
  - scoped_debug_enter_exit: prints hard-coded "enter" and "exit"
    messages, to denote the entry and exit of a function.

I added some examples in the infrun module to give an idea of how it can
be used and what the result looks like.  The macros are in capital
letters (INFRUN_SCOPED_DEBUG_START_END and
INFRUN_SCOPED_DEBUG_ENTER_EXIT) to mimic the existing SCOPE_EXIT, but
that can be changed if you prefer something else.

Here's an excerpt of the debug
statements printed when doing "continue", where a displaced step is
started:

    [infrun] proceed: enter
      [infrun] proceed: addr=0xffffffffffffffff, signal=GDB_SIGNAL_DEFAULT
      [infrun] global_thread_step_over_chain_enqueue: enqueueing thread Thread 0x7ffff75a5640 (LWP 2289301) in global step over chain
      [infrun] start_step_over: enter
        [infrun] start_step_over: stealing global queue of threads to step, length = 1
        [infrun] start_step_over: resuming [Thread 0x7ffff75a5640 (LWP 2289301)] for step-over
        [infrun] resume_1: step=1, signal=GDB_SIGNAL_0, trap_expected=1, current thread [Thread 0x7ffff75a5640 (LWP 2289301)] at 0x5555555551bd
        [displaced] displaced_step_prepare_throw: displaced-stepping Thread 0x7ffff75a5640 (LWP 2289301) now
        [displaced] prepare: selected buffer at 0x5555555550c2
        [displaced] prepare: saved 0x5555555550c2: 1e fa 31 ed 49 89 d1 5e 48 89 e2 48 83 e4 f0 50
        [displaced] amd64_displaced_step_copy_insn: copy 0x5555555551bd->0x5555555550c2: c7 45 fc 00 00 00 00 eb 13 8b 05 d4 2e 00 00 83
        [displaced] displaced_step_prepare_throw: prepared successfully thread=Thread 0x7ffff75a5640 (LWP 2289301), original_pc=0x5555555551bd, displaced_pc=0x5555555550c2
        [displaced] resume_1: run 0x5555555550c2: c7 45 fc 00
        [infrun] infrun_async: enable=1
        [infrun] prepare_to_wait: prepare_to_wait
        [infrun] start_step_over: [Thread 0x7ffff75a5640 (LWP 2289301)] was resumed.
        [infrun] operator(): step-over queue now empty
      [infrun] start_step_over: exit
      [infrun] proceed: start: resuming threads, all-stop-on-top-of-non-stop
        [infrun] proceed: resuming Thread 0x7ffff7da7740 (LWP 2289296)
        [infrun] resume_1: step=0, signal=GDB_SIGNAL_0, trap_expected=0, current thread [Thread 0x7ffff7da7740 (LWP 2289296)] at 0x7ffff7f7d9b7
        [infrun] prepare_to_wait: prepare_to_wait
        [infrun] proceed: resuming Thread 0x7ffff7da6640 (LWP 2289300)
        [infrun] resume_1: thread Thread 0x7ffff7da6640 (LWP 2289300) has pending wait status status->kind = stopped, signal = GDB_SIGNAL_TRAP (currently_stepping=0).
        [infrun] prepare_to_wait: prepare_to_wait
        [infrun] proceed: [Thread 0x7ffff75a5640 (LWP 2289301)] resumed
        [infrun] proceed: resuming Thread 0x7ffff6da4640 (LWP 2289302)
        [infrun] resume_1: thread Thread 0x7ffff6da4640 (LWP 2289302) has pending wait status status->kind = stopped, signal = GDB_SIGNAL_TRAP (currently_stepping=0).
        [infrun] prepare_to_wait: prepare_to_wait
      [infrun] proceed: end: resuming threads, all-stop-on-top-of-non-stop
    [infrun] proceed: exit

We can easily see where the call to `proceed` starts and end.  We can
also see why there are a bunch of resume_1 calls, it's because we are
resuming threads, emulating all-stop on top of a non-stop target.

We also see that debug statements nest well with other modules that have
been migrated to use the "new" debug statement helpers (because they all
use debug_prefixed_vprintf in the end.  I think this is desirable, for
example we could see the debug statements about reading the DWARF info
of a library nested under the debug statements about loading that
library.

Of course, modules that haven't been migrated to use the "new" helpers
will still print without indentations.  This will be one good reason to
migrate them.

I think the runtime cost (when debug statements are disabled) of this is
reasonable, given the improvement in readability.  There is the cost of
the conditionals (like standard debug statements), one more condition
(if (m_must_decrement_print_depth)) and the cost of constructing a stack
object, which means copying a fews pointers.

Adding the print in fetch_inferior_event breaks some tests that use "set
debug infrun", because it prints a debug statement after the prompt.  I
adapted these tests to cope with it, by using the "-prompt" switch of
gdb_test_multiple to as if this debug statement is part of the expected
prompt.  It's unfortunate that we have to do this, but I think the debug
print is useful, and I don't want a few tests to get in the way of
adding good debug output.

gdbsupport/ChangeLog:

	* common-debug.h (debug_print_depth): New.
	(struct scoped_debug_start_end): New.
	(scoped_debug_start_end): New.
	(scoped_debug_enter_exit): New.
	* common-debug.cc (debug_prefixed_vprintf): Print indentation.

gdb/ChangeLog:

	* debug.c (debug_print_depth): New.
	* infrun.h (INFRUN_SCOPED_DEBUG_START_END): New.
	(INFRUN_SCOPED_DEBUG_ENTER_EXIT): New.
	* infrun.c (start_step_over): Use
	INFRUN_SCOPED_DEBUG_ENTER_EXIT.
	(proceed): Use INFRUN_SCOPED_DEBUG_ENTER_EXIT and
	INFRUN_SCOPED_DEBUG_START_END.
	(fetch_inferior_event): Use INFRUN_SCOPED_DEBUG_ENTER_EXIT.

gdbserver/ChangeLog:

	* debug.cc (debug_print_depth): New.

gdb/testsuite/ChangeLog:

        * gdb.base/ui-redirect.exp: Expect infrun debug print after
	prompt.
        * gdb.threads/ia64-sigill.exp: Likewise.
        * gdb.threads/watchthreads-reorder.exp: Likewise.

Change-Id: I7c3805e6487807aa63a1bae318876a0c69dce949
2021-01-04 12:00:54 -05:00
Joel Brobecker
3666a04883 Update copyright year range in all GDB files
This commits the result of running gdb/copyright.py as per our Start
of New Year procedure...

gdb/ChangeLog

        Update copyright year range in copyright header of all GDB files.
2021-01-01 12:12:21 +04:00
Andrew Burgess
9664849417 gdbsupport: make use of safe-ctype functions from libiberty
Make use of the safe-ctype replacements for the standard ctype
character checking functions in gdbsupport/common-utils.cc.  The
gdbsupport library is included into both gdb and gdbserver, and on the
gdbserver side there are two targets, gdbserver itself, and also
libinproctrace.so.

libiberty was already being included in the gdbserver link command,
but was missing from the libinproctrace.so link.  As a result, after
changing gdbsupport/common-utils.cc to depend on libiberty,
libinproctrace.so would no longer link until I modified its link line.

gdbserver/ChangeLog:

	* Makefile.in (IPA_LIB): Include libiberty library.

gdbsupport/ChangeLog:

	* gdbsupport/common-utils.cc: Change 'ctype.h' include to
	'safe-ctype.h'.
	(extract_string_maybe_quoted): Use safe-ctype function versions.
	(is_digit_in_base): Likewise.
	(digit_to_int): Likewise.
	(strtoulst): Likewise.
	(skip_spaces): Likewise.
	(skip_to_space): Likewise.
2020-12-11 22:04:28 +00:00
Simon Marchi
74b773fcd6 gdb: factor out debug_prefixed_printf_cond
The same pattern happens often to define a "debug_printf" macro:

    #define displaced_debug_printf(fmt, ...) \
      do \
        { \
          if (debug_displaced) \
    	debug_prefixed_printf ("displaced", __func__, fmt, ##__VA_ARGS__); \
        } \
      while (0)

Move this pattern behind a helper macro, debug_prefixed_printf_cond and
update the existing macros to use it.

gdb/ChangeLog:

	* displaced-stepping.h (displaced_debug_printf): Use
	debug_prefixed_printf_cond.
	* dwarf2/read.c (dwarf_read_debug_printf): Likewise.
	(dwarf_read_debug_printf_v): Likewise.
	* infrun.h (infrun_debug_printf): Likewise.
	* linux-nat.c (linux_nat_debug_printf): Likewise.

gdbsupport/ChangeLog:

	* common-debug.h (debug_prefixed_printf_cond): New.
	* event-loop.h (event_loop_debug_printf): Use
	debug_prefixed_printf_cond.

Change-Id: I1ff48b98b8d1cc405d1c7e8da8ceadf4e3a17f99
2020-12-11 14:01:12 -05:00
Alexander Fedotov
60a7223fdd gdbsupport: Use LOCALAPPDATA to determine cache dir
Use the LOCALAPPDATA environment variable to determine the cache dir
when running on Windows with native command line, otherwise nasty
warning "Couldn't determine a path for index cached directory" appears.

Change-Id: I77903f9f0cb4743555866b8aea892cef55132589
2020-12-08 09:50:12 -05:00
Andrew Burgess
54e75f291e gdbsupport/tdesc: print enum fields using 'evalue' syntax
Currently when printing an XML description GDB prints enum values like
this:

  <enum id="levels_type" size="4">
    <field name="low" start="0"/>
    <field name="high" start="1"/>
  </enum>

This is incorrect, and is most likely a copy and paste error with the
struct and flags printing code.  The correct syntax is:

  <enum id="levels_type" size="4">
    <evalue name="low" value="0"/>
    <evalue name="high" value="1"/>
  </enum>

A test is included to cover this functionality.

gdb/testsuite/ChangeLog:

	* gdb.xml/maint-xml-dump-03.xml: New file.

gdbsupport/ChangeLog:

	* tdesc.cc (print_xml_feature::visit): Print enum fields using
	'evalue' syntax.
2020-12-01 11:22:24 +00:00
Chungyi Chi
4f36e61b2d gdbsupport/tdesc: print enum size attribute
According to gdb online docs[1], XML target description enum types
have both name and size attributes.  Currently GDB does not print the
size attribute.  This commit fixes this.  This change will be visible
in the output of the command `maint print xml-tdesc`.

There are other bugs with the print of enum types in XML target
descriptions, the next commit will fix these and include a test that
covers this patch.

[1] https://sourceware.org/gdb/current/onlinedocs/gdb/Enum-Target-Types.html#Enum-Target-Types

gdbsupport/ChangeLog:

	* tdesc.cc (print_xml_feature::visit): Print enum size attribute.
2020-12-01 11:22:24 +00:00
Tom Tromey
14f62a099a Ignore system_error in thread startup
libstdc++ might change so that it always implements std::thread, but
then have thread startup simply fail.  This is being discussed here:

https://gcc.gnu.org/pipermail/gcc-patches/2020-November/558736.html

This patch pre-emptively changes gdb to handle this scenario.  It
seemed fine to me to ignore all system errors at thread startup, so
that is what this does.

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

	* thread-pool.cc (thread_pool::set_thread_count): Ignore system
	errors.
2020-11-20 08:22:46 -07:00
Tom Tromey
6c51cf513d Move include block to pathstuff.h
A recent commit caused pathstuff.cc to fail to compile on mingw, like:

../../binutils-gdb/gdbsupport/pathstuff.cc:324:1: error: no previous declaration for 'std::string find_gdb_home_config_file(const char*, _stati64*)' [-Werror=missing-declarations]

Some newly-added #includes were changing which "stat" was being seen
by the compiler.  This patch moves the includes to the header, so that
the declaration and definition now agree.

2020-11-10  Tom Tromey  <tromey@adacore.com>

	PR build/26848:
	* pathstuff.h: Move include block here...
	* pathstuff.cc: ... from here.
2020-11-10 13:12:59 -07:00
Andrew Burgess
64aaad6349 gdb: use get_standard_config_dir when looking for .gdbinit
This commit effectively changes the default location of the .gdbinit
file, while maintaining backward compatibility.

For non Apple hosts the .gdbinit file will now be looked for in the
following locations:

  $XDG_CONFIG_HOME/gdb/gdbinit
  $HOME/.config/gdb/gdbinit
  $HOME/.gdbinit

On Apple hosts the search order is instead:

  $HOME/Library/Preferences/gdb/gdbinit
  $HOME/.gdbinit

I've performed an extensive rewrite of the documentation, moving all
information about initialization files and where to find them into a
new @node, text from other areas has been moved into this one
location, and other areas cross-reference to this new @node as much as
possible.

gdb/ChangeLog:

	* NEWS: Mention changes to config file search path.
	* main.c

gdb/doc/ChangeLog:

	* gdb.texinfo (Mode Options): Descriptions of initialization files
	has been moved to 'Initialization Files'.
	(Startup): Likewise.
	(Initialization Files): New node.
	(gdb man): Update to mention alternative file paths.
	(gdbinit man): Likewise.
2020-11-02 17:42:11 +00:00
Tom Tromey
8768c3e362 Add get_standard_config_dir function
This adds a new get_standard_config_dir, which returns the name of the
configuration directory.  In XDG, this is ~/.config/gdb/.  Future
patches will make use of this.

2020-07-05  Tom Tromey  <tom@tromey.com>

	* pathstuff.h (get_standard_config_dir): Declare.
	* pathstuff.cc (get_standard_config_dir): New function.
2020-11-02 17:42:10 +00:00
Simon Marchi
dda83cd783 gdb, gdbserver, gdbsupport: fix leading space vs tabs issues
Many spots incorrectly use only spaces for indentation (for example,
there are a lot of spots in ada-lang.c).  I've always found it awkward
when I needed to edit one of these spots: do I keep the original wrong
indentation, or do I fix it?  What if the lines around it are also
wrong, do I fix them too?  I probably don't want to fix them in the same
patch, to avoid adding noise to my patch.

So I propose to fix as much as possible once and for all (hopefully).

One typical counter argument for this is that it makes code archeology
more difficult, because git-blame will show this commit as the last
change for these lines.  My counter counter argument is: when
git-blaming, you often need to do "blame the file at the parent commit"
anyway, to go past some other refactor that touched the line you are
interested in, but is not the change you are looking for.  So you
already need a somewhat efficient way to do this.

Using some interactive tool, rather than plain git-blame, makes this
trivial.  For example, I use "tig blame <file>", where going back past
the commit that changed the currently selected line is one keystroke.
It looks like Magit in Emacs does it too (though I've never used it).
Web viewers of Github and Gitlab do it too.  My point is that it won't
really make archeology more difficult.

The other typical counter argument is that it will cause conflicts with
existing patches.  That's true... but it's a one time cost, and those
are not conflicts that are difficult to resolve.  I have also tried "git
rebase --ignore-whitespace", it seems to work well.  Although that will
re-introduce the faulty indentation, so one needs to take care of fixing
the indentation in the patch after that (which is easy).

gdb/ChangeLog:

	* aarch64-linux-tdep.c: Fix indentation.
	* aarch64-ravenscar-thread.c: Fix indentation.
	* aarch64-tdep.c: Fix indentation.
	* aarch64-tdep.h: Fix indentation.
	* ada-lang.c: Fix indentation.
	* ada-lang.h: Fix indentation.
	* ada-tasks.c: Fix indentation.
	* ada-typeprint.c: Fix indentation.
	* ada-valprint.c: Fix indentation.
	* ada-varobj.c: Fix indentation.
	* addrmap.c: Fix indentation.
	* addrmap.h: Fix indentation.
	* agent.c: Fix indentation.
	* aix-thread.c: Fix indentation.
	* alpha-bsd-nat.c: Fix indentation.
	* alpha-linux-tdep.c: Fix indentation.
	* alpha-mdebug-tdep.c: Fix indentation.
	* alpha-nbsd-tdep.c: Fix indentation.
	* alpha-obsd-tdep.c: Fix indentation.
	* alpha-tdep.c: Fix indentation.
	* amd64-bsd-nat.c: Fix indentation.
	* amd64-darwin-tdep.c: Fix indentation.
	* amd64-linux-nat.c: Fix indentation.
	* amd64-linux-tdep.c: Fix indentation.
	* amd64-nat.c: Fix indentation.
	* amd64-obsd-tdep.c: Fix indentation.
	* amd64-tdep.c: Fix indentation.
	* amd64-windows-tdep.c: Fix indentation.
	* annotate.c: Fix indentation.
	* arc-tdep.c: Fix indentation.
	* arch-utils.c: Fix indentation.
	* arch/arm-get-next-pcs.c: Fix indentation.
	* arch/arm.c: Fix indentation.
	* arm-linux-nat.c: Fix indentation.
	* arm-linux-tdep.c: Fix indentation.
	* arm-nbsd-tdep.c: Fix indentation.
	* arm-pikeos-tdep.c: Fix indentation.
	* arm-tdep.c: Fix indentation.
	* arm-tdep.h: Fix indentation.
	* arm-wince-tdep.c: Fix indentation.
	* auto-load.c: Fix indentation.
	* auxv.c: Fix indentation.
	* avr-tdep.c: Fix indentation.
	* ax-gdb.c: Fix indentation.
	* ax-general.c: Fix indentation.
	* bfin-linux-tdep.c: Fix indentation.
	* block.c: Fix indentation.
	* block.h: Fix indentation.
	* blockframe.c: Fix indentation.
	* bpf-tdep.c: Fix indentation.
	* break-catch-sig.c: Fix indentation.
	* break-catch-syscall.c: Fix indentation.
	* break-catch-throw.c: Fix indentation.
	* breakpoint.c: Fix indentation.
	* breakpoint.h: Fix indentation.
	* bsd-uthread.c: Fix indentation.
	* btrace.c: Fix indentation.
	* build-id.c: Fix indentation.
	* buildsym-legacy.h: Fix indentation.
	* buildsym.c: Fix indentation.
	* c-typeprint.c: Fix indentation.
	* c-valprint.c: Fix indentation.
	* c-varobj.c: Fix indentation.
	* charset.c: Fix indentation.
	* cli/cli-cmds.c: Fix indentation.
	* cli/cli-decode.c: Fix indentation.
	* cli/cli-decode.h: Fix indentation.
	* cli/cli-script.c: Fix indentation.
	* cli/cli-setshow.c: Fix indentation.
	* coff-pe-read.c: Fix indentation.
	* coffread.c: Fix indentation.
	* compile/compile-cplus-types.c: Fix indentation.
	* compile/compile-object-load.c: Fix indentation.
	* compile/compile-object-run.c: Fix indentation.
	* completer.c: Fix indentation.
	* corefile.c: Fix indentation.
	* corelow.c: Fix indentation.
	* cp-abi.h: Fix indentation.
	* cp-namespace.c: Fix indentation.
	* cp-support.c: Fix indentation.
	* cp-valprint.c: Fix indentation.
	* cris-linux-tdep.c: Fix indentation.
	* cris-tdep.c: Fix indentation.
	* darwin-nat-info.c: Fix indentation.
	* darwin-nat.c: Fix indentation.
	* darwin-nat.h: Fix indentation.
	* dbxread.c: Fix indentation.
	* dcache.c: Fix indentation.
	* disasm.c: Fix indentation.
	* dtrace-probe.c: Fix indentation.
	* dwarf2/abbrev.c: Fix indentation.
	* dwarf2/attribute.c: Fix indentation.
	* dwarf2/expr.c: Fix indentation.
	* dwarf2/frame.c: Fix indentation.
	* dwarf2/index-cache.c: Fix indentation.
	* dwarf2/index-write.c: Fix indentation.
	* dwarf2/line-header.c: Fix indentation.
	* dwarf2/loc.c: Fix indentation.
	* dwarf2/macro.c: Fix indentation.
	* dwarf2/read.c: Fix indentation.
	* dwarf2/read.h: Fix indentation.
	* elfread.c: Fix indentation.
	* eval.c: Fix indentation.
	* event-top.c: Fix indentation.
	* exec.c: Fix indentation.
	* exec.h: Fix indentation.
	* expprint.c: Fix indentation.
	* f-lang.c: Fix indentation.
	* f-typeprint.c: Fix indentation.
	* f-valprint.c: Fix indentation.
	* fbsd-nat.c: Fix indentation.
	* fbsd-tdep.c: Fix indentation.
	* findvar.c: Fix indentation.
	* fork-child.c: Fix indentation.
	* frame-unwind.c: Fix indentation.
	* frame-unwind.h: Fix indentation.
	* frame.c: Fix indentation.
	* frv-linux-tdep.c: Fix indentation.
	* frv-tdep.c: Fix indentation.
	* frv-tdep.h: Fix indentation.
	* ft32-tdep.c: Fix indentation.
	* gcore.c: Fix indentation.
	* gdb_bfd.c: Fix indentation.
	* gdbarch.sh: Fix indentation.
	* gdbarch.c: Re-generate
	* gdbarch.h: Re-generate.
	* gdbcore.h: Fix indentation.
	* gdbthread.h: Fix indentation.
	* gdbtypes.c: Fix indentation.
	* gdbtypes.h: Fix indentation.
	* glibc-tdep.c: Fix indentation.
	* gnu-nat.c: Fix indentation.
	* gnu-nat.h: Fix indentation.
	* gnu-v2-abi.c: Fix indentation.
	* gnu-v3-abi.c: Fix indentation.
	* go32-nat.c: Fix indentation.
	* guile/guile-internal.h: Fix indentation.
	* guile/scm-cmd.c: Fix indentation.
	* guile/scm-frame.c: Fix indentation.
	* guile/scm-iterator.c: Fix indentation.
	* guile/scm-math.c: Fix indentation.
	* guile/scm-ports.c: Fix indentation.
	* guile/scm-pretty-print.c: Fix indentation.
	* guile/scm-value.c: Fix indentation.
	* h8300-tdep.c: Fix indentation.
	* hppa-linux-nat.c: Fix indentation.
	* hppa-linux-tdep.c: Fix indentation.
	* hppa-nbsd-nat.c: Fix indentation.
	* hppa-nbsd-tdep.c: Fix indentation.
	* hppa-obsd-nat.c: Fix indentation.
	* hppa-tdep.c: Fix indentation.
	* hppa-tdep.h: Fix indentation.
	* i386-bsd-nat.c: Fix indentation.
	* i386-darwin-nat.c: Fix indentation.
	* i386-darwin-tdep.c: Fix indentation.
	* i386-dicos-tdep.c: Fix indentation.
	* i386-gnu-nat.c: Fix indentation.
	* i386-linux-nat.c: Fix indentation.
	* i386-linux-tdep.c: Fix indentation.
	* i386-nto-tdep.c: Fix indentation.
	* i386-obsd-tdep.c: Fix indentation.
	* i386-sol2-nat.c: Fix indentation.
	* i386-tdep.c: Fix indentation.
	* i386-tdep.h: Fix indentation.
	* i386-windows-tdep.c: Fix indentation.
	* i387-tdep.c: Fix indentation.
	* i387-tdep.h: Fix indentation.
	* ia64-libunwind-tdep.c: Fix indentation.
	* ia64-libunwind-tdep.h: Fix indentation.
	* ia64-linux-nat.c: Fix indentation.
	* ia64-linux-tdep.c: Fix indentation.
	* ia64-tdep.c: Fix indentation.
	* ia64-tdep.h: Fix indentation.
	* ia64-vms-tdep.c: Fix indentation.
	* infcall.c: Fix indentation.
	* infcmd.c: Fix indentation.
	* inferior.c: Fix indentation.
	* infrun.c: Fix indentation.
	* iq2000-tdep.c: Fix indentation.
	* language.c: Fix indentation.
	* linespec.c: Fix indentation.
	* linux-fork.c: Fix indentation.
	* linux-nat.c: Fix indentation.
	* linux-tdep.c: Fix indentation.
	* linux-thread-db.c: Fix indentation.
	* lm32-tdep.c: Fix indentation.
	* m2-lang.c: Fix indentation.
	* m2-typeprint.c: Fix indentation.
	* m2-valprint.c: Fix indentation.
	* m32c-tdep.c: Fix indentation.
	* m32r-linux-tdep.c: Fix indentation.
	* m32r-tdep.c: Fix indentation.
	* m68hc11-tdep.c: Fix indentation.
	* m68k-bsd-nat.c: Fix indentation.
	* m68k-linux-nat.c: Fix indentation.
	* m68k-linux-tdep.c: Fix indentation.
	* m68k-tdep.c: Fix indentation.
	* machoread.c: Fix indentation.
	* macrocmd.c: Fix indentation.
	* macroexp.c: Fix indentation.
	* macroscope.c: Fix indentation.
	* macrotab.c: Fix indentation.
	* macrotab.h: Fix indentation.
	* main.c: Fix indentation.
	* mdebugread.c: Fix indentation.
	* mep-tdep.c: Fix indentation.
	* mi/mi-cmd-catch.c: Fix indentation.
	* mi/mi-cmd-disas.c: Fix indentation.
	* mi/mi-cmd-env.c: Fix indentation.
	* mi/mi-cmd-stack.c: Fix indentation.
	* mi/mi-cmd-var.c: Fix indentation.
	* mi/mi-cmds.c: Fix indentation.
	* mi/mi-main.c: Fix indentation.
	* mi/mi-parse.c: Fix indentation.
	* microblaze-tdep.c: Fix indentation.
	* minidebug.c: Fix indentation.
	* minsyms.c: Fix indentation.
	* mips-linux-nat.c: Fix indentation.
	* mips-linux-tdep.c: Fix indentation.
	* mips-nbsd-tdep.c: Fix indentation.
	* mips-tdep.c: Fix indentation.
	* mn10300-linux-tdep.c: Fix indentation.
	* mn10300-tdep.c: Fix indentation.
	* moxie-tdep.c: Fix indentation.
	* msp430-tdep.c: Fix indentation.
	* namespace.h: Fix indentation.
	* nat/fork-inferior.c: Fix indentation.
	* nat/gdb_ptrace.h: Fix indentation.
	* nat/linux-namespaces.c: Fix indentation.
	* nat/linux-osdata.c: Fix indentation.
	* nat/netbsd-nat.c: Fix indentation.
	* nat/x86-dregs.c: Fix indentation.
	* nbsd-nat.c: Fix indentation.
	* nbsd-tdep.c: Fix indentation.
	* nios2-linux-tdep.c: Fix indentation.
	* nios2-tdep.c: Fix indentation.
	* nto-procfs.c: Fix indentation.
	* nto-tdep.c: Fix indentation.
	* objfiles.c: Fix indentation.
	* objfiles.h: Fix indentation.
	* opencl-lang.c: Fix indentation.
	* or1k-tdep.c: Fix indentation.
	* osabi.c: Fix indentation.
	* osabi.h: Fix indentation.
	* osdata.c: Fix indentation.
	* p-lang.c: Fix indentation.
	* p-typeprint.c: Fix indentation.
	* p-valprint.c: Fix indentation.
	* parse.c: Fix indentation.
	* ppc-linux-nat.c: Fix indentation.
	* ppc-linux-tdep.c: Fix indentation.
	* ppc-nbsd-nat.c: Fix indentation.
	* ppc-nbsd-tdep.c: Fix indentation.
	* ppc-obsd-nat.c: Fix indentation.
	* ppc-ravenscar-thread.c: Fix indentation.
	* ppc-sysv-tdep.c: Fix indentation.
	* ppc64-tdep.c: Fix indentation.
	* printcmd.c: Fix indentation.
	* proc-api.c: Fix indentation.
	* producer.c: Fix indentation.
	* producer.h: Fix indentation.
	* prologue-value.c: Fix indentation.
	* prologue-value.h: Fix indentation.
	* psymtab.c: Fix indentation.
	* python/py-arch.c: Fix indentation.
	* python/py-bpevent.c: Fix indentation.
	* python/py-event.c: Fix indentation.
	* python/py-event.h: Fix indentation.
	* python/py-finishbreakpoint.c: Fix indentation.
	* python/py-frame.c: Fix indentation.
	* python/py-framefilter.c: Fix indentation.
	* python/py-inferior.c: Fix indentation.
	* python/py-infthread.c: Fix indentation.
	* python/py-objfile.c: Fix indentation.
	* python/py-prettyprint.c: Fix indentation.
	* python/py-registers.c: Fix indentation.
	* python/py-signalevent.c: Fix indentation.
	* python/py-stopevent.c: Fix indentation.
	* python/py-stopevent.h: Fix indentation.
	* python/py-threadevent.c: Fix indentation.
	* python/py-tui.c: Fix indentation.
	* python/py-unwind.c: Fix indentation.
	* python/py-value.c: Fix indentation.
	* python/py-xmethods.c: Fix indentation.
	* python/python-internal.h: Fix indentation.
	* python/python.c: Fix indentation.
	* ravenscar-thread.c: Fix indentation.
	* record-btrace.c: Fix indentation.
	* record-full.c: Fix indentation.
	* record.c: Fix indentation.
	* reggroups.c: Fix indentation.
	* regset.h: Fix indentation.
	* remote-fileio.c: Fix indentation.
	* remote.c: Fix indentation.
	* reverse.c: Fix indentation.
	* riscv-linux-tdep.c: Fix indentation.
	* riscv-ravenscar-thread.c: Fix indentation.
	* riscv-tdep.c: Fix indentation.
	* rl78-tdep.c: Fix indentation.
	* rs6000-aix-tdep.c: Fix indentation.
	* rs6000-lynx178-tdep.c: Fix indentation.
	* rs6000-nat.c: Fix indentation.
	* rs6000-tdep.c: Fix indentation.
	* rust-lang.c: Fix indentation.
	* rx-tdep.c: Fix indentation.
	* s12z-tdep.c: Fix indentation.
	* s390-linux-tdep.c: Fix indentation.
	* score-tdep.c: Fix indentation.
	* ser-base.c: Fix indentation.
	* ser-mingw.c: Fix indentation.
	* ser-uds.c: Fix indentation.
	* ser-unix.c: Fix indentation.
	* serial.c: Fix indentation.
	* sh-linux-tdep.c: Fix indentation.
	* sh-nbsd-tdep.c: Fix indentation.
	* sh-tdep.c: Fix indentation.
	* skip.c: Fix indentation.
	* sol-thread.c: Fix indentation.
	* solib-aix.c: Fix indentation.
	* solib-darwin.c: Fix indentation.
	* solib-frv.c: Fix indentation.
	* solib-svr4.c: Fix indentation.
	* solib.c: Fix indentation.
	* source.c: Fix indentation.
	* sparc-linux-tdep.c: Fix indentation.
	* sparc-nbsd-tdep.c: Fix indentation.
	* sparc-obsd-tdep.c: Fix indentation.
	* sparc-ravenscar-thread.c: Fix indentation.
	* sparc-tdep.c: Fix indentation.
	* sparc64-linux-tdep.c: Fix indentation.
	* sparc64-nbsd-tdep.c: Fix indentation.
	* sparc64-obsd-tdep.c: Fix indentation.
	* sparc64-tdep.c: Fix indentation.
	* stabsread.c: Fix indentation.
	* stack.c: Fix indentation.
	* stap-probe.c: Fix indentation.
	* stubs/ia64vms-stub.c: Fix indentation.
	* stubs/m32r-stub.c: Fix indentation.
	* stubs/m68k-stub.c: Fix indentation.
	* stubs/sh-stub.c: Fix indentation.
	* stubs/sparc-stub.c: Fix indentation.
	* symfile-mem.c: Fix indentation.
	* symfile.c: Fix indentation.
	* symfile.h: Fix indentation.
	* symmisc.c: Fix indentation.
	* symtab.c: Fix indentation.
	* symtab.h: Fix indentation.
	* target-float.c: Fix indentation.
	* target.c: Fix indentation.
	* target.h: Fix indentation.
	* tic6x-tdep.c: Fix indentation.
	* tilegx-linux-tdep.c: Fix indentation.
	* tilegx-tdep.c: Fix indentation.
	* top.c: Fix indentation.
	* tracefile-tfile.c: Fix indentation.
	* tracepoint.c: Fix indentation.
	* tui/tui-disasm.c: Fix indentation.
	* tui/tui-io.c: Fix indentation.
	* tui/tui-regs.c: Fix indentation.
	* tui/tui-stack.c: Fix indentation.
	* tui/tui-win.c: Fix indentation.
	* tui/tui-winsource.c: Fix indentation.
	* tui/tui.c: Fix indentation.
	* typeprint.c: Fix indentation.
	* ui-out.h: Fix indentation.
	* unittests/copy_bitwise-selftests.c: Fix indentation.
	* unittests/memory-map-selftests.c: Fix indentation.
	* utils.c: Fix indentation.
	* v850-tdep.c: Fix indentation.
	* valarith.c: Fix indentation.
	* valops.c: Fix indentation.
	* valprint.c: Fix indentation.
	* valprint.h: Fix indentation.
	* value.c: Fix indentation.
	* value.h: Fix indentation.
	* varobj.c: Fix indentation.
	* vax-tdep.c: Fix indentation.
	* windows-nat.c: Fix indentation.
	* windows-tdep.c: Fix indentation.
	* xcoffread.c: Fix indentation.
	* xml-syscall.c: Fix indentation.
	* xml-tdesc.c: Fix indentation.
	* xstormy16-tdep.c: Fix indentation.
	* xtensa-config.c: Fix indentation.
	* xtensa-linux-nat.c: Fix indentation.
	* xtensa-linux-tdep.c: Fix indentation.
	* xtensa-tdep.c: Fix indentation.

gdbserver/ChangeLog:

	* ax.cc: Fix indentation.
	* dll.cc: Fix indentation.
	* inferiors.h: Fix indentation.
	* linux-low.cc: Fix indentation.
	* linux-nios2-low.cc: Fix indentation.
	* linux-ppc-ipa.cc: Fix indentation.
	* linux-ppc-low.cc: Fix indentation.
	* linux-x86-low.cc: Fix indentation.
	* linux-xtensa-low.cc: Fix indentation.
	* regcache.cc: Fix indentation.
	* server.cc: Fix indentation.
	* tracepoint.cc: Fix indentation.

gdbsupport/ChangeLog:

	* common-exceptions.h: Fix indentation.
	* event-loop.cc: Fix indentation.
	* fileio.cc: Fix indentation.
	* filestuff.cc: Fix indentation.
	* gdb-dlfcn.cc: Fix indentation.
	* gdb_string_view.h: Fix indentation.
	* job-control.cc: Fix indentation.
	* signals.cc: Fix indentation.

Change-Id: I4bad7ae6be0fbe14168b8ebafb98ffe14964a695
2020-11-02 10:28:45 -05:00
Simon Marchi
17417fb0ec gdb, gdbsupport: add debug_prefixed_printf, remove boilerplate functions
The *_debug_print_1 functions are all very similar, the only difference
being the subsystem name.  Remove them all and make the logging macros
use a new debug_prefixed_printf function directly.

gdb/ChangeLog:

	* infrun.c (infrun_debug_printf_1): Remove.
	(displaced_debug_printf_1): Remove.
	(stop_all_threads): Use debug_prefixed_printf.
	* infrun.h (infrun_debug_printf_1): Remove.
	(infrun_debug_printf): Use debug_prefixed_printf.
	(displaced_debug_printf_1): Remove.
	(displaced_debug_printf): Use debug_prefixed_printf.
	* linux-nat.c (linux_nat_debug_printf_1): Remove.
	(linux_nat_debug_printf): Use debug_prefixed_printf.

gdbsupport/ChangeLog:

	* common-debug.cc (debug_prefixed_printf): New.
	* common-debug.h (debug_prefixed_printf): New declaration.
	* event-loop.cc (event_loop_debug_printf_1): Remove.
	* event-loop.h (event_loop_debug_printf_1): Remove.
	(event_loop_debug_printf): Use debug_prefixed_printf.
	(event_loop_ui_debug_printf): Use debug_prefixed_printf.

Change-Id: Ib323087c7257f0060121d302055c41eb64aa60c6
2020-10-31 09:15:13 -04:00
Simon Marchi
b9442ec18b gdbsupport: replace AC_TRY_COMPILE in common.m4
... with AC_COMPILE_IFELSE + AC_LANG_PROGRAM.  All the changes in the
generated configure files are insignificant whitespace changes.

gdb/ChangeLog:

	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure: Re-generate.

gdbsupport/ChangeLog:

	* common.m4: Replace AC_TRY_COMPILE with AC_COMPILE_IFELSE +
	AC_LANG_PROGRAM.
	* configure: Re-generate.

Change-Id: Id58e6e887f6be817d52b189921845838031dbd2a
2020-10-31 08:31:00 -04:00
Simon Marchi
15dabc52a1 gdbsupport: use AC_FUNC_FORK instead of AC_FUNC_VFORK
autoupdate does this change, it fixes this warning:

    configure.ac:50: warning: The macro `AC_FUNC_VFORK' is obsolete.
    configure.ac:50: You should run autoupdate.
    ../../lib/autoconf/functions.m4:1944: AC_FUNC_VFORK is expanded from...
    common.m4:20: GDB_AC_COMMON is expanded from...
    configure.ac:50: the top level

There are not changes in the generated configure files.

gdbsupport/ChangeLog:

	* common.m4: Replace AC_FUNC_VFORK with AC_FUNC_FORK.

Change-Id: I9de9f718c57e6d51c9734161f36c36ce39170325
2020-10-31 08:31:00 -04:00
Simon Marchi
864ca43565 gdbsupport: replace AC_TRY_COMPILE in warning.m4
Replace AC_TRY_COMPILE with AC_COMPILE_IFELSE + AC_LANG_PROGRAM.

All changes in generated configure files are insignificant whitespace
changes.

gdb/ChangeLog:

	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure: Re-generate.
	* warning.m4: Replace AC_TRY_COMPILE with AC_COMPILE_IFELSE +
	AC_LANG_PROGRAM.

Change-Id: I517bd20ec3af960ad999a586761df0ac8959a3fc
2020-10-31 08:30:59 -04:00
Simon Marchi
5164c11714 gdbsupport: replace AC_TRY_COMPILE in ptrace.m4
Replace AC_TRY_COMPILE with AC_COMPILE_IFELSE + AC_LANG_PROGRAM.

All the changes in the generated configure files are insignificant
whitespace changes.

gdb/ChangeLog:

	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure: Re-generate.
	* ptrace.m4: Replace AC_TRY_COMPILE with AC_COMPILE_IFELSE +
	AC_LANG_PROGRAM.

Change-Id: Ia782b5477fe49dad04e68c0f41c6d8ab3fde5bf0
2020-10-31 08:30:59 -04:00
Simon Marchi
b6fb30eda7 gdbsupport: re-indent ptrace.m4
For some reason, autoupdate isn't able to grok ptrace.m4:

    $ autoupdate ptrace.m4
    /usr/bin/m4:/tmp/auYjuodw/input.m4:171: ERROR: end of file in string
    autoupdate: /usr/bin/m4 failed with exit status: 1

Honestly, I'm unable to grok it either.  This patch re-indents it in a
way that I think is easier to read.  With this patch applied, autoupdate
becomes able to parse ptrace.m4, but I chose to keep this re-indent in a
patch of its own.

All the changes in generated configure files consist of insignificant
whitespace changes.

gdb/ChangeLog:

	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure: Re-generate.
	* ptrace.m4: Re-indent.

Change-Id: Ie2afab09fecc8b6d0cccccb47ac9756f3843881e
2020-10-31 08:30:59 -04:00
Simon Marchi
e41fda1d5f gdb: use AC_PROG_CC_STDC instead of AM_PROG_CC_STDC
`autoconf -Wall` notes that AM_PROG_CC_STDC is obsolete:
Fixes this autoconf warning:

    configure.ac:40: warning: 'AM_PROG_CC_STDC': this macro is obsolete.
    configure.ac:40: You should simply use the 'AC_PROG_CC' macro instead.
    configure.ac:40: Also, your code should no longer depend upon 'am_cv_prog_cc_stdc',
    configure.ac:40: but upon 'ac_cv_prog_cc_stdc'.
    aclocal.m4:770: AM_PROG_CC_STDC is expanded from...
    configure.ac:40: the top level

Since we build with a C++ compiler now, I don't think this is relevant.
If you look at the messages removed from gdbsupport/aclocal.m4, it says
that this functionality is now integrated in AC_PROG_CC, which we
already call.  So it might not even make a difference.

We had a local version of AM_PROG_CC_STDC, in gdb/acinclude.m4 (only
used by gdb/configure.ac), remove it.

gdb/ChangeLog:

	* acinclude.m4 (AM_PROG_CC_STDC): Remove.
	* configure: Re-generate.
	* configure.ac: Remove AM_PROG_CC_STDC.

gdbsupport/ChangeLog:

	* aclocal.m4: Re-generate.
	* configure: Re-generate.
	* configure.ac: Remove AM_PROG_CC_STDC.

Change-Id: Ic824393598805d4f78cda9d119f8af46096e9c73
2020-10-31 08:30:57 -04:00
Simon Marchi
91e1a0ed09 gdb, gdbserver, gdbsupport: use AC_CANONICAL_{BUILD,HOST,TARGET} instead of AC_CANONICAL_SYSTEM
`autoreconf -Wall` notes that AC_CANONICAL_SYSTEM is obsolete:

    configure.ac:36: warning: The macro `AC_CANONICAL_SYSTEM' is obsolete.

Replace it by AC_CANONICAL_BUILD, AC_CANONICAL_HOST and
AC_CANONICAL_TARGET in configure.ac files in gdb, gdbserver and
gdbsupport.  All three macros may not be needed everywhere, but it is
hard to completely audit the configure files to see which are required,
so I think it's better (and that there's no downside) to just call all
three.

gdb/ChangeLog:

	* configure.ac: Use AC_CANONICAL_{BUILD,HOST,TARGET} instead of
	AC_CANONICAL_SYSTEM.
	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure.ac: Use AC_CANONICAL_{BUILD,HOST,TARGET} instead of
	AC_CANONICAL_SYSTEM.
	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure.ac: Use AC_CANONICAL_{BUILD,HOST,TARGET} instead of
	AC_CANONICAL_SYSTEM.
	* configure: Re-generate.

Change-Id: Ifd0e21f1e478634e768b5de1b8ee06a7f690d863
2020-10-31 08:30:57 -04:00
Pedro Alves
d744f0f965 gdb::handle_eintr, remove need to specify return type
This eliminates the need to specify the return type when using
handle_eintr.  We let the compiler deduce it for us.

Also, use lowercase for function parameter names.  Uppercase should
only be used on template parameters.

gdb/ChangeLog:

	* nat/linux-waitpid.c: Include "gdbsupport/eintr.h".
	(my_waitpid): Use gdb::handle_eintr.

gdbserver/ChangeLog:

	* netbsd-low.cc (netbsd_waitpid, netbsd_process_target::kill)
	(netbsd_qxfer_libraries_svr4): Use gdb::handle_eintr without
	explicit type.

gdbsupport/ChangeLog:

	* eintr.h (handle_eintr): Replace Ret template parameter with
	ErrorValType.  Use it as type of the failure value.  Deduce the
	function's return type using decltype.  Use lowercase for function
	parameter names.
2020-10-26 18:57:40 +00:00
Simon Marchi
006811bc02 gdb: move ptrace.m4 to gdbsupport
ptrace.m4, providing the GDB_AC_PTRACE autoconf macro, is used by gdb,
gdbserver and gdbsupport.  I think it would make sense to move it to
gdbsupport.

gdb/ChangeLog:

	* acinclude.m4: Update ptrace.m4 path.
	* ptrace.m4: Moved to gdbsupport.

gdbserver/ChangeLog:

	* acinclude.m4: Update ptrace.m4 path.

gdbsupport/ChangeLog:

	* Makefile.in: Re-generate.
	* acinclude.m4: Update ptrace.m4 path.
	* ptrace.m4: Move here.

Change-Id: I849c149fd5dd8c3b2b0af38654fb353e3727871b
2020-10-25 21:08:49 -04:00
Andrew Burgess
51a948fdf0 gdb: Have allocate_target_description return a unique_ptr
Update allocate_target_description to return a target_desc_up, a
specialisation of unique_ptr.

This commit does not attempt to make use of the unique_ptr in the
best possible way, in almost all cases we immediately release the
pointer from within the unique_ptr and then continue as before.

There are a few places where it was easy to handle the unique_ptr, and
in these cases I've done that.

Everything under gdb/features/* is auto-regenerated.

There should be no user visible changes after this commit.

gdb/ChangeLog:

	* arch/aarch32.c (aarch32_create_target_description): Release
	unique_ptr returned from allocate_target_description.
	* arch/aarch64.c (aarch64_create_target_description): Likewise.
	* arch/amd64.c (amd64_create_target_description): Likewise.
	* arch/arc.c (arc_create_target_description): Likewise.
	* arch/arm.c (arm_create_target_description): Likewise.
	* arch/i386.c (i386_create_target_description): Likewise.
	* arch/riscv.c (riscv_create_target_description): Update return
	type.  Handle allocate_target_description returning a unique_ptr.
	(riscv_lookup_target_description): Update to handle unique_ptr.
	* arch/tic6x.c (tic6x_create_target_description): Release
	unique_ptr returned from allocate_target_description.
	* features/microblaze-with-stack-protect.c: Regenerate.
	* features/microblaze.c: Regenerate.
	* features/mips-dsp-linux.c: Regenerate.
	* features/mips-linux.c: Regenerate.
	* features/mips64-dsp-linux.c: Regenerate.
	* features/mips64-linux.c: Regenerate.
	* features/nds32.c: Regenerate.
	* features/nios2.c: Regenerate.
	* features/or1k.c: Regenerate.
	* features/rs6000/powerpc-32.c: Regenerate.
	* features/rs6000/powerpc-32l.c: Regenerate.
	* features/rs6000/powerpc-403.c: Regenerate.
	* features/rs6000/powerpc-403gc.c: Regenerate.
	* features/rs6000/powerpc-405.c: Regenerate.
	* features/rs6000/powerpc-505.c: Regenerate.
	* features/rs6000/powerpc-601.c: Regenerate.
	* features/rs6000/powerpc-602.c: Regenerate.
	* features/rs6000/powerpc-603.c: Regenerate.
	* features/rs6000/powerpc-604.c: Regenerate.
	* features/rs6000/powerpc-64.c: Regenerate.
	* features/rs6000/powerpc-64l.c: Regenerate.
	* features/rs6000/powerpc-7400.c: Regenerate.
	* features/rs6000/powerpc-750.c: Regenerate.
	* features/rs6000/powerpc-860.c: Regenerate.
	* features/rs6000/powerpc-altivec32.c: Regenerate.
	* features/rs6000/powerpc-altivec32l.c: Regenerate.
	* features/rs6000/powerpc-altivec64.c: Regenerate.
	* features/rs6000/powerpc-altivec64l.c: Regenerate.
	* features/rs6000/powerpc-e500.c: Regenerate.
	* features/rs6000/powerpc-e500l.c: Regenerate.
	* features/rs6000/powerpc-isa205-32l.c: Regenerate.
	* features/rs6000/powerpc-isa205-64l.c: Regenerate.
	* features/rs6000/powerpc-isa205-altivec32l.c: Regenerate.
	* features/rs6000/powerpc-isa205-altivec64l.c: Regenerate.
	* features/rs6000/powerpc-isa205-ppr-dscr-vsx32l.c: Regenerate.
	* features/rs6000/powerpc-isa205-ppr-dscr-vsx64l.c: Regenerate.
	* features/rs6000/powerpc-isa205-vsx32l.c: Regenerate.
	* features/rs6000/powerpc-isa205-vsx64l.c: Regenerate.
	* features/rs6000/powerpc-isa207-htm-vsx32l.c: Regenerate.
	* features/rs6000/powerpc-isa207-htm-vsx64l.c: Regenerate.
	* features/rs6000/powerpc-isa207-vsx32l.c: Regenerate.
	* features/rs6000/powerpc-isa207-vsx64l.c: Regenerate.
	* features/rs6000/powerpc-vsx32.c: Regenerate.
	* features/rs6000/powerpc-vsx32l.c: Regenerate.
	* features/rs6000/powerpc-vsx64.c: Regenerate.
	* features/rs6000/powerpc-vsx64l.c: Regenerate.
	* features/rs6000/rs6000.c: Regenerate.
	* features/rx.c: Regenerate.
	* features/s390-gs-linux64.c: Regenerate.
	* features/s390-linux32.c: Regenerate.
	* features/s390-linux32v1.c: Regenerate.
	* features/s390-linux32v2.c: Regenerate.
	* features/s390-linux64.c: Regenerate.
	* features/s390-linux64v1.c: Regenerate.
	* features/s390-linux64v2.c: Regenerate.
	* features/s390-te-linux64.c: Regenerate.
	* features/s390-tevx-linux64.c: Regenerate.
	* features/s390-vx-linux64.c: Regenerate.
	* features/s390x-gs-linux64.c: Regenerate.
	* features/s390x-linux64.c: Regenerate.
	* features/s390x-linux64v1.c: Regenerate.
	* features/s390x-linux64v2.c: Regenerate.
	* features/s390x-te-linux64.c: Regenerate.
	* features/s390x-tevx-linux64.c: Regenerate.
	* features/s390x-vx-linux64.c: Regenerate.
	* mips-tdep.c (_initialize_mips_tdep): Release unique_ptr returned
	from allocate_target_description.
	* target-descriptions.c (allocate_target_description): Update
	return type.
	(print_c_tdesc::visit_pre): Release unique_ptr returned from
	allocate_target_description.

gdbserver/ChangeLog:

	* linux-low.cc (linux_process_target::handle_extended_wait):
	Release the unique_ptr returned from allocate_target_description.
	* linux-riscv-low.cc (riscv_target::low_arch_setup): Likewise.
	* linux-x86-low.cc (tdesc_amd64_linux_no_xml): Change type.
	(tdesc_i386_linux_no_xml): Change type.
	(x86_linux_read_description): Borrow pointer from unique_ptr
	object.
	(x86_target::get_ipa_tdesc_idx): Likewise.
	(initialize_low_arch): Likewise.
	* tdesc.cc (allocate_target_description): Update return type.

gdbsupport/ChangeLog:

	* tdesc.h (allocate_target_description): Update return type.
2020-10-08 10:14:14 +01:00
Tom Tromey
4a72de7366 Move simple_search_memory to gdbsupport/search.cc
This moves the simple_search_memory function to a new file,
gdbsupport/search.cc.  The API is slightly changed to make it more
general.  This generality is useful for wiring it to gdbserver, and
also for unit testing.

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

	* target.h (simple_search_memory): Don't declare.
	* target.c (simple_search_memory): Move to gdbsupport.
	(default_search_memory): Update.
	* remote.c (remote_target::search_memory): Update.

gdbsupport/ChangeLog
2020-10-07  Tom Tromey  <tromey@adacore.com>

	* Makefile.in: Rebuild.
	* Makefile.am (libgdbsupport_a_SOURCES): Add search.cc.
	* search.h: New file.
	* search.cc: New file.
2020-10-07 12:07:55 -06:00
Simon Marchi
6b01403b25 gdb: add debug prints in event loop
Add debug printouts about event loop-related events:

 - When a file descriptor handler gets invoked
 - When an async event/signal handler gets invoked

gdb/ChangeLog:

	* async-event.c (invoke_async_signal_handlers): Add debug
	print.
	(check_async_event_handlers): Likewise.
	* event-top.c (show_debug_event_loop): New function.
	(_initialize_event_top): Register "set debug event-loop"
	setting.

gdbserver/ChangeLog:

	* server.cc (handle_monitor_command): Handle "set
	debug-event-loop".
	(captured_main): Handle "--debug-event-loop".
	(monitor_show_help): Mention new setting.
	(gdbserver_usage): Mention new flag.

gdbsupport/ChangeLog:

	* event-loop.h (debug_event_loop): New variable declaration.
	(event_loop_debug_printf_1): New function declaration.
	(event_loop_debug_printf): New macro.
	* event-loop.cc (debug_event_loop): New variable.
	(handle_file_event): Add debug print.
	(event_loop_debug_printf_1): New function.

Change-Id: If78ed3a69179881368e7895b42940ce13b6a1a05
2020-10-02 14:47:42 -04:00
Simon Marchi
ba98841943 gdb: move debug_prefixed_vprintf here
The following patch needs to output debug prints from gdbsupport code.
Move debug_prefixed_vprintf so that it is possible to use it from
gdbsupport.

gdb/ChangeLog:

	* debug.c (debug_prefixed_vprintf): Move to gdbsupport.
	* debug.h: Remove.
	* infrun.c: Include gdbsupport/common-debug.h.
	* linux-nat.c: Likewise.

gdbsupport/ChangeLog:

	* common-debug.cc (debug_prefixed_vprintf): Move here.
	* common-debug.h (debug_prefixed_vprintf): Move here.

Change-Id: I5170065fc10a7a49c0f1bba67c691decb2cf3bcb
2020-10-02 14:47:26 -04:00
Simon Marchi
2554f6f564 gdb: give names to event loop file handlers
Assign names to event loop file handlers.  They will be used in debug
messages when file handlers are invoked.

In GDB, each UI used to get its own unique number, until commit
cbe256847e ("Remove ui::num").  Re-introduce this field, and use it to
make a unique name for the handler.

I'm not too sure what goes on in ser-base.c, all I know is that it's
what is used when debugging remotely.  I've just named the main handler
"serial".  It would be good to have unique names there too.  For instance
when debugging with two different remote connections, we'd ideally want
the handlers to have unique names.  I didn't do it in this patch though.

gdb/ChangeLog:

	* async-event.c (initialize_async_signal_handlers): Pass name to
	add_file_handler
	* event-top.c (ui_register_input_event_handler): Likewise.
	* linux-nat.c (linux_nat_target::async): Likewise.
	* run-on-main-thread.c (_initialize_run_on_main_thread):
	Likewise
	* ser-base.c (reschedule): Likewise.
	(ser_base_async): Likewise.
	* tui/tui-io.c: Likewise.
	* top.h (struct ui) <num>: New field.
	* top.c (highest_ui_num): New variable.
	(ui::ui): Initialize num.

gdbserver/ChangeLog:

	* linux-low.cc (linux_process_target::async): Pass name to
	add_file_handler.
	* remote-utils.cc (handle_accept_event): Likewise.
	(remote_open): Likewise.

gdbsupport/ChangeLog:

	* event-loop.h (add_file_handler): Add "name" parameter.
	* event-loop.cc (struct file_handler) <name>: New field.
	(create_file_handler): Add "name" parameter, assign it to file
	handler.
	(add_file_handler): Add "name" parameter.

Change-Id: I9f1545f73888ebb6778eb653a618ca44d105f92c
2020-10-02 14:46:56 -04:00
Kamil Rytarowski
e2a2a24a8e Preinitialize the sockaddr_un variable to zero
Don't pass random sun_len for the BSD's,
zero the whole structure as recommended for portability.

Reported by Coverity.

gdbsupport/ChangeLog:

	* agent.cc (gdb_connect_sync_socket): Preinitialize addr with zeros.
2020-10-02 00:38:12 +02:00
Pedro Alves
de38d64ad2 Tweak gdbsupport/valid-expr.h for GCC 6, fix build
With GCC 6.4 and 6.5 (at least), unit tests that use
gdbsupport/valid-expr.h's CHECK_VALID fail to compile, with:

 In file included from src/gdb/unittests/offset-type-selftests.c:24:0:
 src/gdb/unittests/offset-type-selftests.c: In substitution of 'template<class Expected, template<class ...> class Op, class ... Args> using is_detected_exact = std::is_same<Expected, typename gdb::detection_detail::detector<gdb::nonesuch, void, Op, Args ...>::type> [with Expected = selftests::offset_type::off_A&; Op = selftests::offset_type::check_valid_expr75::archetype; Args = {selftests::offset_type::off_A, selftests::offset_type::off_B}]':
 src/gdb/unittests/offset-type-selftests.c:75:1:   required from here
 src/gdb/../gdbsupport/valid-expr.h:65:20: error: type/value mismatch at argument 2 in template parameter list for 'template<class Expected, template<class ...> class Op, class ... Args> using is_detected_exact = std::is_same<Expected, typename gdb::detection_detail::detector<gdb::nonesuch, void, Op, Args ...>::type>'
     archetype, TYPES>::value == VALID,   \
		     ^

The important part is the "error: type/value mismatch" error.  Seems
like that GCC doesn't understand that archetype is an alias template,
and is being strict in requiring a template class.

The fix here is then to make archetype a template class, to pacify
GCC.  The resulting code looks like this:

  template <TYPENAMES, typename = decltype (EXPR)>
  struct archetype
  {
  };

  static_assert (gdb::is_detected_exact<archetype<TYPES, EXPR_TYPE>,
 		 archetype, TYPES>::value == VALID, "");

is_detected_exact<Expected, Op, Args> checks whether Op<Args> is type
Expected:

 - For Expected, we pass the explicit EXPR_TYPE, overriding the
   default parameter type of archetype.

 - For Args we don't pass the last template parameter, so archtype
   defaults to the EXPR's decltype.

So in essence, we're really checking whether EXPR_TYPE is the same as
decltype(EXPR).

We need to do the decltype in a template context in order to trigger
SFINAE instead of failing to compile.


The hunk in unittests/enum-flags-selftests.c becomes necessary,
because unlike with the current alias template version, this new
version makes GCC trigger -Wenum-compare warnings as well:

 src/gdb/unittests/enum-flags-selftests.c:328:33: error: comparison between 'enum selftests::enum_flags_tests::RE' and 'enum selftests::enum_flags_tests::RE2' [-Werror=enum-compare]
  CHECK_VALID (true,  bool, RE () != RE2 ())
				  ^
 src/gdb/../gdbsupport/valid-expr.h:61:45: note: in definition of macro 'CHECK_VALID_EXPR_INT'
    template <TYPENAMES, typename = decltype (EXPR)>   \
					      ^

Build-tested with:

 - GCC {4.8.5, 6.4, 6.5, 7.3.1, 9.3.0, 11.0.0-20200910}
 - Clang 10.0.0

gdbsupport/ChangeLog:

	* valid-expr.h (CHECK_VALID_EXPR_INT): Make archetype a template
	class instead of an alias template and adjust static_assert.

gdb/ChangeLog:

	* unittests/enum-flags-selftests.c: Check whether __GNUC__ is
	defined before using '#pragma GCC diagnostic' instead of checking
	__clang__.
2020-09-29 23:48:04 +01:00
Simon Marchi
29363cfa40 gdb: remove file_handler typedef
Remove the typedef (unneeded with C++).  Re-format the comments to
follow the more common style.

gdbsupport/ChangeLog:

	* event-loop.c (struct file_handler): Remove typedef, re-format.

Change-Id: I3aea21fba1eb2584c507de3412da4e4c98283b2d
2020-09-24 15:19:46 -04:00
John Baldwin
e911c6663b Require kinfo_get_file and kinfo_get_vmmap for FreeBSD hosts.
FreeBSD systems have provided these functions in libutil since 7.1
release.  The most recent release without support is 6.4 released in
November of 2008.

This also requires libutil-freebsd on GNU/kFreeBSD systems.  I assume
that those systems have supported kinfo_get_file and kinfo_get_vmmap
over a similar timeframe.

gdb/ChangeLog:

	* configure.ac: Remove check for kinfo_getvmmap().
	* configure, config.in: Regenerate.
	* fbsd-nat.c (fbsd_read_mapping): Remove
	(fbsd_nat_target::find_memory_regions): Remove the procfs version.
	(fbsd_nat_target::info_proc): Assume kinfo_getfile() and
	kinfo_get_vmmap() are always present.

gdbsupport/ChangeLog:

	* common.m4 (GDB_AC_COMMON): Refactor checks for kinfo_getfile().
	* configure, config.in: Regenerate.
2020-09-16 11:40:05 -07:00
Pedro Alves
04902b0995 Rewrite enum_flags, add unit tests, fix problems
This patch started by adding comprehensive unit tests for enum_flags.

For the testing part, it adds:

 - tests of normal expected uses of the API.

 - checks that _invalid_ uses of the API would fail to compile.  I.e.,
   it validates that enum_flags really is a strong type, and that
   incorrect mixing of enum types would be caught at compile time.  It
   pulls that off making use of SFINEA and C++11's decltype/constexpr.

This revealed many holes in the enum_flags API.  For example, the f1
assignment below currently incorrectly fails to compile:

 enum_flags<flags> f1 = FLAG1;
 enum_flags<flags> f2 = FLAG2 | f1;

The unit tests also revealed that this useful use case doesn't work:

    enum flag { FLAG1 = 1, FLAG2 = 2 };
    enum_flags<flag> src = FLAG1;
    enum_flags<flag> f1 = condition ? src : FLAG2;

It fails to compile because enum_flags<flag> and flag are convertible
to each other.

Turns out that making enum_flags be implicitly convertible to the
backing raw enum type was not a good idea.

If we make it convertible to the underlying type instead, we fix that
ternary operator use case, and, we find cases throughout the codebase
that should be using the enum_flags but were using the raw backing
enum instead.  So it's a good change overall.

Also, several operators were missing.

These holes and more are plugged by this patch, by reworking how the
enum_flags operators are implemented, and making use of C++11's
feature of being able to delete methods/functions.

There are cases in gdb/compile/ where we need to call a function in a
C plugin API that expects the raw enum.  To address cases like that,
this adds a "raw()" method to enum_flags.  This way we can keep using
the safer enum_flags to construct the value, and then be explicit when
we need to get at the raw enum.

This makes most of the enum_flags operators constexpr.  Beyond
enabling more compiler optimizations and enabling the new unit tests,
this has other advantages, like making it possible to use operator|
with enum_flags values in switch cases, where only compile-time
constants are allowed:

    enum_flags<flags> f = FLAG1 | FLAG2;
    switch (f)
      {
      case FLAG1 | FLAG2:
	break;
      }

Currently that fails to compile.

It also switches to a different mechanism of enabling the global
operators.  The current mechanism isn't namespace friendly, the new
one is.

It also switches to C++11-style SFINAE -- instead of wrapping the
return type in a SFINAE-friently structure, we use an unnamed template
parameter.  I.e., this:

  template <typename enum_type,
	    typename = is_enum_flags_enum_type_t<enum_type>>
  enum_type
  operator& (enum_type e1, enum_type e2)

instead of:

  template <typename enum_type>
  typename enum_flags_type<enum_type>::type
  operator& (enum_type e1, enum_type e2)

Note that the static_assert inside operator~() was converted to a
couple overloads (signed vs unsigned), because static_assert is too
late for SFINAE-based tests, which is important for the CHECK_VALID
unit tests.

Tested with gcc {4.8, 7.1, 9.3} and clang {5.0.2, 10.0.0}.

gdb/ChangeLog:

	* Makefile.in (SELFTESTS_SRCS): Add
	unittests/enum-flags-selftests.c.
	* btrace.c (ftrace_update_caller, ftrace_fixup_calle): Use
	btrace_function_flags instead of enum btrace_function_flag.
	* compile/compile-c-types.c (convert_qualified): Use
	enum_flags::raw.
	* compile/compile-cplus-symbols.c (convert_one_symbol)
	(convert_symbol_bmsym):
	* compile/compile-cplus-types.c (compile_cplus_convert_method)
	(compile_cplus_convert_struct_or_union_methods)
	(compile_cplus_instance::convert_qualified_base):
	* go-exp.y (parse_string_or_char): Add cast to int.
	* unittests/enum-flags-selftests.c: New file.
	* record-btrace.c (btrace_thread_flag_to_str): Change parameter's
	type to btrace_thread_flags from btrace_thread_flag.
	(record_btrace_cancel_resume, record_btrace_step_thread): Change
	local's type to btrace_thread_flags from btrace_thread_flag.  Add
	cast in DEBUG call.

gdbsupport/ChangeLog:

	* enum-flags.h: Include "traits.h".
	(DEF_ENUM_FLAGS_TYPE): Declare a function instead of defining a
	structure.
	(enum_underlying_type): Update comment.
	(namespace enum_flags_detail): New.  Move struct zero_type here.
	(EnumIsUnsigned, EnumIsSigned): New.
	(class enum_flags): Make most methods constexpr.
	(operator&=, operator|=, operator^=): Take an enum_flags instead
	of an enum_type.  Make rvalue ref versions deleted.
	(operator enum_type()): Delete.
	(operator&, operator|, operator^, operator~): Delete, moved out of
	class.
	(raw()): New method.
	(is_enum_flags_enum_type_t): Declare.
	(ENUM_FLAGS_GEN_BINOP, ENUM_FLAGS_GEN_COMPOUND_ASSIGN)
	(ENUM_FLAGS_GEN_COMP): New.  Use them to reimplement global
	operators.
	(operator~): Now constexpr and reimplemented.
	(operator<<, operator>>): New deleted functions.
	* valid-expr.h (CHECK_VALID_EXPR_5, CHECK_VALID_EXPR_6): New.
2020-09-14 22:21:07 +01:00
Pedro Alves
1945192cb9 Rewrite valid-expr.h's internals in terms of the detection idiom (C++17/N4502)
An earlier attempt at doing this had failed (wouldn't work in GCCs
around 4.8, IIRC), but now that I try again, it works.  I suspect that
my previous attempt did not use the pre C++14-safe void_t (in
traits.h).

I want to switch to this model because:

 - It's the standard detection idiom that folks will learn starting
   with C++17.

 - In the enum_flags unit tests, I have a static_assert that triggers
   a warning (resulting in build error), which GCC does not suppress
   because the warning is not being triggered in the SFINAE context.
   Switching to the detection idiom fixes that.  Alternatively,
   switching to the C++03-style expression-validity checking with a
   varargs overload would allow addressing that, but I think that
   would be going backwards idiomatically speaking.

 - While this patch shows a net increase of lines of code, the magic
   being added to traits.h can be removed in a few years when we start
   requiring C++17.

gdbsupport/ChangeLog:

	* traits.h (struct nonesuch, struct detector, detected_or)
	(detected_or_t, is_detected, detected_t, detected_or)
	(detected_or_t, is_detected_exact, is_detected_convertible): New.
	* valid-expr.h (CHECK_VALID_EXPR_INT): Use gdb::is_detected_exact.
2020-09-14 22:19:31 +01:00
Felix Willgerodt
2a67f09db1 Add bfloat16 support for AVX512 register view.
This adds support for the bfloat16 datatype, which can be seen as a short
version of FP32, skipping the least significant 16 bits of the mantissa.
Since the datatype is currently only supported by the AVX512 registers,
the printing of bfloat16 values is only supported for xmm, ymm and zmm
registers.

gdb/ChangeLog:
2020-09-11  Moritz Riesterer  <moritz.riesterer@intel.com>
	    Felix Willgerodt  <Felix.Willgerodt@intel.com>

	* gdbarch.sh: Added bfloat16 type.
	* gdbarch.c: Regenerated.
	* gdbarch.h: Regenerated.
	* gdbtypes.c (floatformats_bfloat16): New struct.
	(gdbtypes_post_init): Add builtin_bfloat16.
	* gdbtypes.h (struct builtin_type) <builtin_bfloat16>: New member.
	(floatformats_bfloat16): New struct.
	* i386-tdep.c (i386_zmm_type): Add field "v32_bfloat16"
	(i386_ymm_type): Add field "v16_bfloat16"
	(i386_gdbarch_init): Add set_gdbarch_bfloat16_format.
	* target-descriptions.c (make_gdb_type): Add case TDESC_TYPE_BFLOAT16.
	* gdbsupport/tdesc.cc (tdesc_predefined_types): New member bfloat16.
	* gdbsupport/tdesc.h (tdesc_type_kind): New member TDESC_TYPE_BFLOAT16.
	* features/i386/64bit-avx512.xml: Add bfloat16 type.
	* features/i386/64bit-avx512.c: Regenerated.
	* features/i386/64bit-sse.xml: Add bfloat16 type.
	* features/i386/64bit-sse.c: Regenerated.

gdb/testsuite/ChangeLog:
2020-09-11  Moritz Riesterer  <moritz.riesterer@intel.com>
	    Felix Willgerodt  <Felix.Willgerodt@intel.com>

	* x86-avx512bf16.c: New file.
	* x86-avx512bf16.exp: Likewise.
	* lib/gdb.exp (skip_avx512bf16_tests): New function.
2020-09-11 11:42:47 -07:00
Kamil Rytarowski
48c9b43332 Add handle_eintr to wrap EINTR handling in syscalls
gdbsupport/ChangeLog:

	* eintr.h: New file.
2020-09-10 15:35:12 +02:00
Simon Marchi
ece5bc8ac3 gdb: allow specifying multiple filters when running selftests
I found myself wanting to run a few specific selftests while developing.
I thought it would be nice to be able to provide multiple test names
when running `maintenant selftests`.  The arguments to that command is
currently interpreted as a single filter (not split by spaces), it now
becomes a list a filters, split by spaces.  A test is executed when it
matches at least one filter.

Here's an example of the result in GDB:

    (gdb) maintenance selftest xml
    Running selftest xml_escape_text.
    Running selftest xml_escape_text_append.
    Ran 2 unit tests, 0 failed
    (gdb) maintenance selftest xml unord
    Running selftest unordered_remove.
    Running selftest xml_escape_text.
    Running selftest xml_escape_text_append.
    Ran 3 unit tests, 0 failed
    (gdb) maintenance selftest xml unord foobar
    Running selftest unordered_remove.
    Running selftest xml_escape_text.
    Running selftest xml_escape_text_append.
    Ran 3 unit tests, 0 failed

Since the selftest machinery is also shared with gdbserver, I also
adapted gdbserver.  It accepts a `--selftest` switch, which accepts an
optional filter argument.  I made it so you can now pass `--selftest`
multiple time to add filters.

It's not so useful right now though: there's only a single selftest
right now in GDB and it's for an architecture I can't compile.  So I
tested by adding dummy tests, here's an example of the result:

    $ ./gdbserver --selftest=foo
    Running selftest foo.
    foo
    Running selftest foobar.
    foobar
    Ran 2 unit tests, 0 failed
    $ ./gdbserver --selftest=foo --selftest=bar
    Running selftest bar.
    bar
    Running selftest foo.
    foo
    Running selftest foobar.
    foobar
    Ran 3 unit tests, 0 failed

gdbsupport/ChangeLog:

	* selftest.h (run_tests): Change parameter to array_view.
	* selftest.c (run_tests): Change parameter to array_view and use
	it.

gdb/ChangeLog:

	* maint.c (maintenance_selftest): Split args and pass array_view
	to run_tests.

gdbserver/ChangeLog:

	* server.cc (captured_main): Accept multiple `--selftest=`
	options.  Pass all `--selftest=` arguments to run_tests.

Change-Id: I422bd49f08ea8095ae174c5d66a2dd502a59613a
2020-08-13 07:55:48 -04:00
Simon Marchi
888bdb2b74 gdb: change regcache list to be a map
One regcache object is created for each stopped thread and is stored in
the regcache::regcaches linked list.  Looking up a regcache for a given
thread is therefore in O(number of threads).  Stopping all threads then
becomes O((number of threads) ^ 2).  Same goes for resuming a thread
(need to delete the regcache of a given ptid) and resuming all threads.
It becomes noticeable when debugging thousands of threads, which is
typical with GPU targets.  This patch replaces the linked list with some
maps to reduce that complexity.

The first design was using an std::unordered_map with (target, ptid,
arch) as the key, because that's how lookups are done (in
get_thread_arch_aspace_regcache).  However, the registers_changed_ptid
function, also somewhat on the hot path (it is used when resuming
threads), needs to delete all regcaches associated to a given (target,
ptid) tuple.  If the key of the map is (target, ptid, arch), we have to
walk all items of the map, not good.

The second design was therefore using an std::unordered_multimap with
(target, ptid) as the key.  One key could be associated to multiple
regcaches, all with different gdbarches.  When looking up, we would have
to walk all these regcaches.  This would be ok, because there will
usually be actually one matching regcache.  In the exceptional
multi-arch thread cases, there will be maybe two.  However, in
registers_changed_ptid, we sometimes need to remove all regcaches
matching a given target.  We would then have to talk all items of the
map again, not good.

The design as implemented in this patch therefore uses two levels of
map.  One std::unordered_map uses the target as the key.  The value type
is an std::unordered_multimap that itself uses the ptid as the key.  The
values of the multimap are the regcaches themselves.  Again, we expect
to have one or very few regcaches per (target, ptid).

So, in summary:

* The lookups (in get_thread_arch_aspace_regcache), become faster when
  the number of threads grows, compared to the linked list.  With a
  small number of threads, it will probably be a bit slower to do map
  lookups than to walk a few linked list nodes, but I don't think it
  will be noticeable in practice.

* The function registers_changed_ptid deletes all regcaches related to a
  given (target, ptid).  It must now handle the different cases separately:

    - NULL target and minus_one_ptid: we delete all the entries
    - NULL target and non-minus_one_ptid: invalid (checked by assert)
    - non-NULL target and non-minus_one_ptid: we delete all the entries
      associated to that tuple
    - a non-NULL target and minus_one_ptid: we delete all the entries
      associated to that target

* The function regcache_thread_ptid_changed is called when a thread
  changes ptid.  It is implemented efficiently using the map, although
  that's not very important: it is not called often, mostly when
  creating an inferior, on some specific platforms.

This patch is a tiny bit from ROCm GDB [1] we would like to merge
upstream.  Laurent Morichetti gave be these performance numbers:

The benchmark used is:

  time ./gdb --data-directory=data-directory /extra/lmoriche/hip/samples/0_Intro/bit_extract/bit_extract -ex "set pagination off" -ex "set breakpoint pending on" -ex "b bit_extract_kernel if \$_thread == 5" -ex run -ex c -batch

It measures the time it takes to continue from a conditional breakpoint with
2048 threads at that breakpoint, one of them reporting the breakpoint.

baseline:
real    0m10.227s
real    0m10.177s
real    0m10.362s

with patch:
real    0m8.356s
real    0m8.424s
real    0m8.494s

[1] https://github.com/ROCm-Developer-Tools/ROCgdb

gdb/ChangeLog:

	* regcache.c (ptid_regcache_map): New type.
	(target_ptid_regcache_map): New type.
	(regcaches): Change type to target_ptid_regcache_map.
	(get_thread_arch_aspace_regcache): Update to regcaches' new
	type.
	(regcache_thread_ptid_changed): Likewise.
	(registers_changed_ptid): Likewise.
	(regcaches_size): Likewise.
	(regcaches_test): Update.
	(regcache_thread_ptid_changed): Update.
	* regcache.h (regcache_up): New type.
	* gdbsupport/ptid.h (hash_ptid): New struct.

Change-Id: Iabb0a1111707936ca111ddb13f3b09efa83d3402
2020-08-07 11:29:00 -04:00
Rainer Orth
c8693053f8 Unify Solaris procfs and largefile handling
GDB currently doesn't build on 32-bit Solaris:

* On Solaris 11.4/x86:

In file included from /usr/include/sys/procfs.h:26,
                 from /vol/src/gnu/gdb/hg/master/dist/gdb/i386-sol2-nat.c:24:
/usr/include/sys/old_procfs.h:31:2: error: #error "Cannot use procfs in the large file compilation environment"
 #error "Cannot use procfs in the large file compilation environment"
  ^~~~~

* On Solaris 11.3/x86 there are several more instances of this.

The interaction between procfs and large-file support historically has
been a royal mess on Solaris:

* There are two versions of the procfs interface:

** The old ioctl-based /proc, deprecated and not used any longer in
   either gdb or binutils.

** The `new' (introduced in Solaris 2.6, 1997) structured /proc.

* There are two headers one can possibly include:

** <procfs.h> which only provides the structured /proc, definining
   _STRUCTURED_PROC=1 and then including ...

** <sys/procfs.h> which defaults to _STRUCTURED_PROC=0, the ioctl-based
   /proc, but provides structured /proc if _STRUCTURED_PROC == 1.

* procfs and the large-file environment didn't go well together:

** Until Solaris 11.3, <sys/procfs.h> would always #error in 32-bit
   compilations when the large-file environment was active
   (_FILE_OFFSET_BITS == 64).

** In both Solaris 11.4 and Illumos, this restriction was lifted for
   structured /proc.

So one has to be careful always to define _STRUCTURED_PROC=1 when
testing for or using <sys/procfs.h> on Solaris.  As the errors above
show, this isn't always the case in binutils-gdb right now.

Also one may need to disable large-file support for 32-bit compilations
on Solaris.  config/largefile.m4 meant to do this by wrapping the
AC_SYS_LARGEFILE autoconf macro with appropriate checks, yielding
ACX_LARGEFILE.  Unfortunately the macro doesn't always succeed because
it neglects the _STRUCTURED_PROC part.

To make things even worse, since GCC 9 g++ predefines
_FILE_OFFSET_BITS=64 on Solaris.  So even if largefile.m4 deciced not to
enable large-file support, this has no effect, breaking the gdb build.

This patch addresses all this as follows:

* All tests for the <sys/procfs.h> header are made with
  _STRUCTURED_PROC=1, the definition going into the various config.h
  files instead of having to make them (and sometimes failing) in the
  affected sources.

* To cope with the g++ predefine of _FILE_OFFSET_BITS=64,
  -U_FILE_OFFSET_BITS is added to various *_CPPFLAGS variables.  It had
  been far easier to have just

  #undef _FILE_OFFSET_BITS

  in config.h, but unfortunately such a construct in config.in is
  commented by config.status irrespective of indentation and whitespace
  if large-file support is disabled.  I found no way around this and
  putting the #undef in several global headers for bfd, binutils, ld,
  and gdb seemed way more invasive.

* Last, the applicability check in largefile.m4 was modified only to
  disable largefile support if really needed.  To do so, it checks if
  <sys/procfs.h> compiles with _FILE_OFFSET_BITS=64 defined.  If it
  doesn't, the disabling only happens if gdb exists in-tree and isn't
  disabled, otherwise (building binutils from a tarball), there's no
  conflict.

  What initially confused me was the check for $plugins here, which
  originally caused the disabling not to take place.  Since AC_PLUGINGS
  does enable plugin support if <dlfcn.h> exists (which it does on
  Solaris), the disabling never happened.

  I could find no explanation why the linker plugin needs large-file
  support but thought it would be enough if gld and GCC's lto-plugin
  agreed on the _FILE_OFFSET_BITS value.  Unfortunately, that's not
  enough: lto-plugin uses the simple-object interface from libiberty,
  which includes off_t arguments.  So to fully disable large-file
  support would mean also disabling it in libiberty and its users: gcc
  and libstdc++-v3.  This seems highly undesirable, so I decided to
  disable the linker plugin instead if large-file support won't work.

The patch allows binutils+gdb to build on i386-pc-solaris2.11 (both
Solaris 11.3 and 11.4, using GCC 9.3.0 which is the worst case due to
predefined _FILE_OFFSET_BITS=64).  Also regtested on
amd64-pc-solaris2.11 (again on Solaris 11.3 and 11.4),
x86_64-pc-linux-gnu and i686-pc-linux-gnu.

	config:
	* largefile.m4 (ACX_LARGEFILE) <sparc-*-solaris*|i?86-*-solaris*>:
	Check for <sys/procfs.h> incompatilibity with large-file support
	on Solaris.
	Only disable large-file support and perhaps plugins if needed.
	Set, substitute LARGEFILE_CPPFLAGS if so.

	bfd:
	* bfd.m4 (BFD_SYS_PROCFS_H): New macro.
	(BFD_HAVE_SYS_PROCFS_TYPE): Require BFD_SYS_PROCFS_H.
	Don't define _STRUCTURED_PROC.
	(BFD_HAVE_SYS_PROCFS_TYPE_MEMBER): Likewise.
	* elf.c [HAVE_SYS_PROCFS_H] (_STRUCTURED_PROC): Don't define.
	* configure.ac: Use BFD_SYS_PROCFS_H to check for <sys/procfs.h>.
	* configure, config.in: Regenerate.
	* Makefile.am (AM_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* Makefile.in, doc/Makefile.in: Regenerate.

	binutils:
	* Makefile.am (AM_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* Makefile.in, doc/Makefile.in: Regenerate.
	* configure: Regenerate.

	gas:
	* Makefile.am (AM_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* Makefile.in, doc/Makefile.in: Regenerate.
	* configure: Regenerate.

	gdb:
	* proc-api.c (_STRUCTURED_PROC): Don't define.
	* proc-events.c: Likewise.
	* proc-flags.c: Likewise.
	* proc-why.c: Likewise.
	* procfs.c: Likewise.

	* Makefile.in (INTERNAL_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* configure, config.in: Regenerate.

	gdbserver:
	* configure, config.in: Regenerate.

	gdbsupport:
	* Makefile.am (AM_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* common.m4 (GDB_AC_COMMON): Use BFD_SYS_PROCFS_H to check for
	<sys/procfs.h>.
	* Makefile.in: Regenerate.
	* configure, config.in: Regenerate.

	gnulib:
	* configure.ac: Run ACX_LARGEFILE before gl_EARLY.
	* configure: Regenerate.

	gprof:
	* Makefile.am (AM_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* Makefile.in: Regenerate.
	* configure: Regenerate.

	ld:
	* Makefile.am (AM_CPPFLAGS): Add LARGEFILE_CPPFLAGS.
	* Makefile.in: Regenerate.
	* configure: Regenerate.
2020-07-30 15:41:50 +02:00
Tom de Vries
866b34a12d [gdb/build] Fix Wmaybe-uninitialized in gdb_optional.h
When building with CFLAGS/CXXFLAGS="-O2 -g -Wall", we run into:
...
In file included from src/gdb/exceptions.h:23,
                 from src/gdb/utils.h:24,
                 from src/gdb/defs.h:630,
                 from src/gdb/record-btrace.c:22:
src/gdb/ui-out.h: In function 'void btrace_insn_history(ui_out*, \
  const btrace_thread_info*, const btrace_insn_iterator*, \
  const btrace_insn_iterator*, gdb_disassembly_flags)':
src/gdb/ui-out.h:352:18: warning: \
  'asm_list.ui_out_emit_type<ui_out_type_list>::m_uiout' may be used \
  uninitialized in this function [-Wmaybe-uninitialized]
  352 |     m_uiout->end (Type);
      |     ~~~~~~~~~~~~~^~~~~~
src/gdb/record-btrace.c:795:35: note: \
  'asm_list.ui_out_emit_type<ui_out_type_list>::m_uiout' was declared here
  795 |   gdb::optional<ui_out_emit_list> asm_list;
      |                                   ^~~~~~~~
...

This is reported as PR gcc/80635 - "[8/9/10/11 regression] std::optional and
bogus -Wmaybe-uninitialized warning".

Silence the warning by using the workaround suggested here (
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80635#c53 ):
...
   union
   {
     struct { } m_dummy;
     T m_item;
+    volatile char dont_use; // Silences -Wmaybe-uninitialized warning.
   };
...

Build on x86_64-linux.

gdbsupport/ChangeLog:

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

	PR build/26281
	* gdb_optional.h (class optional): Add volatile member to union
	contaning m_dummy and m_item.
2020-07-28 15:07:44 +02:00
Andrew Burgess
0e26741636 gdb/riscv: delete target descriptions when gdb exits
It was pointed out on IRC that the RISC-V target allocates target
descriptions and stores them in a global map, and doesn't delete these
target descriptions when GDB shuts down.

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

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

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

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

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

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

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

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

I start getting this error from GCC:

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

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

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

gdb/ChangeLog:

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

gdbserver/ChangeLog:

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

gdbsupport/ChangeLog:

	* tdesc.h (struct target_desc_deleter): Moved here
	from gdb/target-descriptions.h, extend comment.
	(target_desc_up): Likewise.
2020-07-17 21:15:32 +01:00
Tom Tromey
5ac588997c Do not define basic_string_view::to_string
gdb's copy of basic_string_view includes a to_string method.  However,
according to cppreference, this is not a method on the real
std::basic_string_view:

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

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

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

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

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

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

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

	PR build/26183:
	* gdb_string_view.h (basic_string_view::to_string): Remove.
	(gdb::to_string): New function.
2020-06-30 07:53:03 -06:00
Simon Marchi
6db3031e5c gdbsupport: add format attribute to print_xml_feature::add_line
Fixes this clang error:

      CXX      tdesc.o
    /home/smarchi/src/binutils-gdb/gdbsupport/tdesc.cc:444:25: error: format string is not a string literal [-Werror,-Wformat-nonliteral]
      string_vappendf (tmp, fmt, ap);
                            ^~~

There is already a but about GCC not emitting this warning:

    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82206

gdbsupport/ChangeLog:

	* tdesc.h (class print_xml_feature) <add_line>: Add
	ATTRIBUTE_PRINTF.

Change-Id: I7014075e83717f6d7e19d044a3675ff9981ebe17
2020-06-27 14:39:00 -04:00
Andrew Burgess
caa7fd04f6 gdb: New maintenance command to print XML target description
This commit adds a new maintenance command that dumps the current
target description as an XML document.  This is a maintenance command
as I currently only see this being useful for GDB developers, or for
people debugging a new remote target.

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

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

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

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

Will produce this output:

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

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

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

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

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

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

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

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

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

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

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

gdbsupport/ChangeLog:

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

gdb/ChangeLog:

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

gdb/testsuite/ChangeLog:

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

gdb/doc/ChangeLog:

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

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

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

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

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

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

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

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

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

gdb/ChangeLog:

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

gdbserver/ChangeLog:

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

gdbsupport/ChangeLog:

	* tdesc.cc (print_xml_feature::visit_pre): Print compatible
	information.
	* tdesc.h (struct tdesc_compatible_info): Declare new struct.
	(tdesc_compatible_info_up): New typedef.
	(tdesc_compatible_info_list): Declare new function.
	(tdesc_compatible_info_arch_name): Declare new function.
2020-06-23 22:17:19 +01:00
Michael Weghorn
7dbfcd6f79 gdbsupport: Drop now unused function 'stringify_argv'
The function did not properly escape special characters
and all uses have been replaced in previous commits, so
drop the now unused function.

gdbsupport/ChangeLog:

	* common-utils.cc, common-utils.h (stringify_argv): Drop
	now unused function stringify_argv

Change-Id: Id5f861f44eae1f0fbde3476a5eac23a842ed04fc
2020-05-25 11:40:35 -04:00
Michael Weghorn
8c4b5f3d98 gdbsupport: Let construct_inferior_arguments take gdb::array_view param
Adapt the construct_inferior_arguments function to
take a gdb::array_view<char * const> parameter instead
of a char * array and an int indicating the length
and adapt the only call site.

This will allow calling it more simply in a follow-up
patch introducing more uses of the function.

gdbsupport/ChangeLog:

	* common-inferior.cc, common-inferior.h (construct_inferior_arguments):
	Adapt to take a gdb::array_view<char * const> parameter.
	Adapt call site.

Change-Id: I1c6496c8c0b0eb3ef3fda96e9e3bd64c5e6cac3c
2020-05-25 11:38:45 -04:00
Michael Weghorn
c699004a29 gdbsupport: Adapt construct_inferior_arguments
Allow construct_inferior_arguments to handle zero args
and have it return a std::string, similar to how
stringify_argv in gdbsupport/common-utils does.

Also, add a const qualifier for the second parameter,
since it is only read, not written to.

The intention is to replace existing uses of
stringify_argv by construct_inferior_arguments
in a subsequent step, since construct_inferior_arguments
properly handles special characters, while stringify_argv
doesn't.

gdbsupport/ChangeLog:

	* common-inferior.cc, common-inferior.h (construct_inferior_arguments):
	Adapt to handle zero args and return a std::string.
	Adapt call site.

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

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

gdb/ChangeLog:

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

gdbsupport/ChangeLog:

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

Change-Id: Ib9290464ce8c0872f605d8829f88352d064c30d6
2020-05-25 11:38:02 -04:00
Pedro Alves
51e2cfa2dc Use safe-ctype.h (ISSPACE etc.) in symbol parsing & comparison
This patch avoids depending on the current locale when parsing &
comparing symbol names, by using libiberty's safe-ctype.h uppercase
TOLOWER, ISXDIGIT, etc. macros instead of the standard ctype.h
tolower, isxdigit, etc. macros/functions.

This commit:

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

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

did something similar, except in the expression parser.

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

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

I ran GDB 10 times like:

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

Then I computed the mean time.

The baseline mean time was

 gdb    2.515

This patch brings the number down to

 gdb    2.096

Which is an around 16% improvement.

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

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

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

	* gdb-safe-ctype.h: New.
2020-05-23 12:46:37 +01:00
Kevin Buettner
a51951c258 Disable record btrace bts support for AMD processors
Some Intel processors implement a Branch Trace Store (BTS) which GDB
uses for reverse execution support via the "record btrace bts"
command.

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

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

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

Therefore...

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

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

Intel machine - Desired behavior:

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

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

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

AMD machine - Wrong behavior:

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

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

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

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

gdbsupport/ChangeLog:

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

gdb/ChangeLog:

	* nat/linux-btrace.c (btrace_this_cpu): Add check for AMD
	processors.
	(cpu_supports_bts): Add CV_AMD case.
2020-05-14 17:56:33 -07:00
Tankut Baris Aktemur
fc75c28ba1 gdb: protect some 'regcache_read_pc' calls
It possible that a thread whose PC we attempt to read is already dead.
In this case, 'regcache_read_pc' errors out.  This impacts the
"proceed" execution flow, where GDB quits early before having a chance
to check if there exists a pending event.  To remedy, keep going with
a 0 value for the PC if 'regcache_read_pc' fails.  Because the value
of PC before resuming a thread is mostly used for storing and checking
the next time the thread stops, this tolerance is expected to be
harmless for a dead thread/process.

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

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

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

	* common-regcache.h (regcache_read_pc_protected): New function
	declaration.
2020-05-14 13:59:53 +02:00
Tankut Baris Aktemur
32d1f47a12 Fix typo (thead -> thread)
gdb/stubs/ChangeLog:
2020-04-28  Tankut Baris Aktemur  <tankut.baris.aktemur@intel.com>

	* ia64vms-stub.c: Fix typo in comment (thead -> thread).

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

	* gdb.threads/stop-with-handle.exp: Fix typo in comment
	(theads -> threads).

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

	* gdb-sigmask.h: Fix typo (pthead_sigmask -> pthread_sigmask).
2020-04-28 11:38:26 +02:00
Simon Marchi
ff8885c3be gdbsupport: include cstdlib in common-defs.h
In PR 25731 [1], the following build failure was reported:

    ../../binutils-gdb/gdb/gdbtypes.c:1254:10: error: no member named 'abs' in namespace 'std'; did you mean simply 'abs'?
                = ((std::abs (stride) * element_count) + 7) / 8;
                    ^~~~~~~~
                    abs
    /usr/include/stdlib.h:129:6: note: 'abs' declared here
    int      abs(int) __pure2;
             ^
The original report was using:

    $ gcc -v
    Apple LLVM version 8.0.0 (clang-800.0.42.1)
    Target: x86_64-apple-darwin15.6.0

Note that I was _not_ able to reproduce using:

    $ g++ --version
    Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
    Apple clang version 11.0.0 (clang-1100.0.33.17)
    Target: x86_64-apple-darwin19.3.0

The proposed fix is to include <cstdlib> in addition to <stdlib.h>.

Here's an excerpt of [2] relevant to this problem:

    These headers [speaking of the .h form] are allowed to also declare
    the same names in the std namespace, and the corresponding cxxx
    headers are allowed to also declare the same names in the global
    namespace: including <cstdlib> definitely provides std::malloc and
    may also provide ::malloc.  Including <stdlib.h> definitely provides
    ::malloc and may also provide std::malloc

Since we use std::abs, we should not assume that our include of stdlib.h
declares an `abs` function in the `std` namespace.

If we replace the include of stdlib.h with cstdlib, then we fall in the
opposite situation.  A standard C++ library may decide to only put the
declarations in the std namespace, requiring us to prefix all standard
functions with `std::`.  I'm not against that, but for the moment I think the
safest way forward is to just include both.

Note that I don't know what effect this patch can have on any stdlib.h fix
provided by gnulib.

[1] https://sourceware.org/bugzilla/show_bug.cgi?id=25731
[2] https://en.cppreference.com/w/cpp/header#C_compatibility_headers

gdbsupport/ChangeLog:

	* common-defs.h: Include cstdlib.h.
2020-04-27 09:28:03 -04:00
Tom Tromey
0fa7617d84 Mark move constructors as "noexcept"
I recently learned that move constructors generally should be marked
"noexcept".  This ensures that standard containers will move objects
when possible, rather than copy them.

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

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

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

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

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

	* scoped_mmap.h (scoped_mmap): Mark move constructor as noexcept.
	Use initialization style.  Don't call destroy.
	* scoped_fd.h (class scoped_fd): Mark move constructor as
	noexcept.
	* gdb_ref_ptr.h (class ref_ptr): Mark move constructor as
	noexcept.
2020-04-20 11:45:06 -06:00
Tom Tromey
7990abcc9b Move gdb_notifier comment
This moves the gdb_notifier comment a bit lower in event-loop.c, to
where it belongs; and removes an obsolete comment that Pedro pointed
out.

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

	* event-loop.c: Move comment.  Remove obsolete 	comment.
2020-04-13 14:10:04 -06:00
Tom Tromey
400b5eca00 Move event-loop.[ch] to gdbsupport/
This moves event-loop.[ch] to gdbsupport/ and updates the uses in gdb.

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

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

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

	* event-loop.h: Move from ../gdb/.
	* event-loop.cc: Move from ../gdb/.
2020-04-13 14:10:04 -06:00
Tom Tromey
c1cd3163d9 Introduce and use flush_streams
Code in gdbsupport can't call gdb_flush, so this introduces a new
"flush_streams" function that must be supplied by the client.

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

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

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

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

	* errors.h (flush_streams): Declare.
2020-04-13 14:10:04 -06:00
Tom Tromey
06cc9596e8 Move gdb_select.h to gdbsupport/
This moves gdb_select.h to gdbsupport/, so it can be used by other
code there.

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

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

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

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

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

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

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

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

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

	* config.in, configure: Rebuild.
	* common.m4 (GDB_AC_COMMON): Check for poll.h, sys/poll.h,
	sys/select.h, and poll.
2020-04-13 14:10:03 -06:00
Tom Tromey
af62665e13 Don't pass NULL to memcpy in gdb
I compiled gdb with -fsanitize=undefined and ran the test suite.

A couple of reports came from passing NULL to memcpy, e.g.:

[...]btrace-common.cc:176:13: runtime error: null pointer passed as argument 2, which is declared to never be null

While it would be better to fix this in the standard, in the meantime
it seems easy to avoid this error.

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

	* dwarf2/abbrev.c (abbrev_table::read): Conditionally call
	memcpy.

gdbsupport/ChangeLog
2020-03-31  Tom Tromey  <tromey@adacore.com>

	* btrace-common.cc (btrace_data_append): Conditionally call
	memcpy.
2020-03-31 07:29:53 -06:00
Andrew Burgess
8f2dae6a6a gdbsupport: Resolve shellcheck issues in create-version.sh script
Run shellcheck (version 0.4.7) on the create-version.sh script, and
resolve the issues it highlighter - they all seemed reasonable.

gdbsupport/ChangeLog:

	* create-version.sh: Resolve issues highlighted by shellcheck.
2020-03-27 13:52:00 +00:00
Simon Marchi
c884cc4619 gdb: remove HAVE_DECL_PTRACE
I stumbled on this snippet in nat/gdb_ptrace.h:

    /* Some systems, in particular DEC OSF/1, Digital Unix, Compaq Tru64
       or whatever it's called these days, don't provide a prototype for
       ptrace.  Provide one to silence compiler warnings.  */

    #ifndef HAVE_DECL_PTRACE
    extern PTRACE_TYPE_RET ptrace();
    #endif

I believe this is unnecessary today and should be removed.  First, the
comment only mentions OSes we don't support (and to be honest, I had
never even heard of).

But most importantly, in C++, a declaration with empty parenthesis
declares a function that accepts no arguments, unlike in C.  So if this
declaration was really used, GDB wouldn't build, since all ptrace call
sites pass some arguments.  Since we haven't heard anything about this
causing some build failures since we have transitioned to C++, I
conclude that it's not used.

This patch removes it as well as the corresponding configure check.

gdb/ChangeLog:

	* ptrace.m4: Don't check for ptrace declaration.
	* config.in: Re-generate.
	* configure: Re-generate.
	* nat/gdb_ptrace.h: Don't declare ptrace if HAVE_DECL_PTRACE is
	not defined.

gdbserver/ChangeLog:

	* config.in: Re-generate.
	* configure: Re-generate.

gdbsupport/ChangeLog:

	* config.in: Re-generate.
	* configure: Re-generate.
2020-03-20 11:57:49 -04:00
Kamil Rytarowski
d3e2a5e85d Include <alloca.h> conditionally
Fixes build on NetBSD, where alloca() is defined in <stdlib.h>.

gdbsupport:

	* common-defs.h: Include alloca.h if HAVE_ALLOCA_H is defined.
2020-03-18 02:29:21 +01:00
Tom Tromey
213291361b Change gdbsupport not to rely on BFD
This changes gdbsupport so that it no longer relies on BFD.  This is a
precursor to making gdbserver use the already-built gdbsupport,
because building gdbserver should not require BFD to be built.

The most notable change here is that CORE_ADDR is always a 64-bit
type.  This makes it so that gdb acts as if it were always built in
64-bit mode.

ChangeLog
2020-03-12  Tom Tromey  <tom@tromey.com>

	* Makefile.in: Rebuild.
	* Makefile.def (gdbsupport): Don't depend on bfd.

gdbsupport/ChangeLog
2020-03-12  Tom Tromey  <tom@tromey.com>

	* common-types.h: Remove GDBSERVER code.
	(gdb_byte, CORE_ADDR, LONGEST, ULONGEST): Redefine.
	* common-defs.h: Remove GDBSERVER code.
2020-03-12 13:32:16 -06:00
Simon Marchi
272cd5a31e Move gdb/selftest.m4 to gdbsupport/selftest.m4
The selftest.m4 file is used by gdb, gdbserver and gdbsupport, I think
it belongs in gdbsupport.

gdb/ChangeLog:

	* selftest.m4: Move to gdbsupport/.
	* acinclude.m4: Update path to selftest.m4.

gdbserver/ChangeLog:

	* acinclude.m4: Update path to selftest.m4.

gdbsupport/ChangeLog:

	* selftest.m4: Moved from gdb/.
	* acinclude.m4: Update path to selftest.m4.
2020-03-12 14:19:38 -04:00
Simon Marchi
db6878ac55 Move sourcing of development.sh to GDB_AC_COMMON
The same is done for gdb, gdbserver and gdbsupport.  I therefore think
it makes sense to move that to GDB_AC_COMMON.

It is required to move the call to GDB_AC_COMMON so it is before
GDB_AC_SELFTEST in gdbserver/configure.ac, otherwise the $development
variable isn't set when the code behind GDB_AC_SELFTEST executes.

gdb/ChangeLog:

	* configure.ac: Don't source bfd/development.sh.
	* selftest.m4: Modify comment.
	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure.ac: Don't source bfd/development.sh, move
	GDB_AC_COMMON higher.
	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure.ac: Don't source bfd/development.sh.
	* common.m4: Source bfd/development.sh.
	* configure: Re-generate.
2020-03-12 14:18:00 -04:00
Simon Marchi
4d696a5c68 gdb/selftest.m4: ensure $development is set
Before commit 3d1e5a43cb ("gdbsupport/configure.ac: source
development.sh"), the GDB build in non-development mode (turn
development to false in bfd/development.sh if you want to try) was
broken because the gdbsupport configure script didn't source
bfd/development.sh to set the development variable.

Since the GDB_AC_SELFTEST macro relies on the `development` variable, I
propose to modify it such that it errors out if $development does not
have an expected value of "true" or "false".  This could prevent a
future similar problem from happening while refactoring the configure
scripts.  It would have caught the problem fixed by the patch mentioned
earlier.

gdb/ChangeLog:

	* selftest.m4 (GDB_AC_SELFTEST): Error out if $development is
	not "true" or "false".
	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure: Re-generate.
2020-03-12 14:17:57 -04:00
Simon Marchi
a0761e34f0 gdb: enable -Wmissing-prototypes warning
While compiling with clang, I noticed it didn't catch cases where my
function declaration didn't match my function definition.  This is
normally caught by gcc with -Wmissing-declarations.

On clang, this is caught by -Wmissing-prototypes instead.

Note that on gcc, -Wmissing-prototypes also exists, but is only valid
for C and Objective-C.  It gets correctly rejected by the configure
script since gcc rejects it with:

    cc1plus: error: command line option '-Wmissing-prototypes' is valid for C/ObjC but not for C++ -Werror

So this warning flag ends up not used for gcc (which is what we want).

gdb/ChangeLog:

	* configure: Re-generate.

gdbserver/ChangeLog:

	* configure: Re-generate.

gdbsupport/ChangeLog:

	* configure: Re-generate.
	* warning.m4: Enable -Wmissing-prototypes.
2020-03-11 15:15:12 -04:00
Tom Tromey
e63ee24f98 Fix two typos in gdb_binary_search.h
I noticed a couple of typos in gdb_binary_search.h.  This fixes them.

gdbsupport/ChangeLog
2020-03-08  Tom Tromey  <tom@tromey.com>

	* gdb_binary_search.h: Fix two typos.
2020-03-08 11:05:43 -06:00
Andrew Burgess
20ea4a609c gdbserver/gdbsupport: Add .dir-locals.el file
Copy the .dir-locls.el file from gdb/ to gdbserver/ and gdbsupport/ so
that we get the GNU/GDB style when editing these files in Emacs.

I initially wanted to remove the (c-mode . ((mode . c++))) that
switches c-mode files into c++-mode as we store C++ code in *.cc files
in the gdbserver/ directory, unlike gdb/ where we use *.c, however, I
was forgetting about the header files - we still use *.h for our C++
header files, so for now I left the settings in place to open all C
files in c++-mode.

We now have three copies of this file, which are all identical.  It
would be nice if we could remove this duplication, however, for now we
haven't found a good way to do this.

Some options considered were:

  1. Use symlinks to only have one copy of the file.  This was
  rejected as not all targets support symlinks in the way.

  2. Have two of the .dir-locals.el files contain some mechanism by
  which the third copy of the file is sourced.  Though this would, in
  theory, be possible, it would involve some advanced Emacs scripting,
  would be fragile, and a maintenance burdon.

  3. Move the .dir-locals up into top level src/ directory, then use
  Emacs dir-locals directory pattern matching to only apply the rules
  for the three directories we care about.  The problem is that each
  directory has to be listed separately, so we still end up having to
  duplicate all the rules.

In the end, it was decided that having three copies of the file,
though not ideal, is probably easiest for now.  This was all discussed
in this mailing list thread:

  https://sourceware.org/ml/gdb-patches/2020-03/msg00024.html

The copyright date in the new files is left as for gdb/.dir-locals.el,
as the new files are a copy of the old, this is inline with this rule:

  https://sourceware.org/gdb/wiki/ContributionChecklist#Copyright_Header

gdb/ChangeLog:

	* .dir-locals.el: Add a comment referencing the other copies of
	this file.

gdbserver/ChangeLog:

	* .dir-locals.el: New file.

gdbsupport/ChangeLog:

	* .dir-locals.el: New file.
2020-03-06 11:29:46 +00:00
Vyacheslav Petrishchev
3d1e5a43cb gdbsupport/configure.ac: source development.sh
[Commit message by Simon Marchi]

The GDB build in non-development mode (turn development to false in
bfd/development.sh if you want to try) is currently broken:

      CXXLD  gdb
    /home/smarchi/src/binutils-gdb/gdb/disasm-selftests.c:218: error: undefined reference to 'selftests::register_test_foreach_arch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, void (*)(gdbarch*))'
    /home/smarchi/src/binutils-gdb/gdb/disasm-selftests.c:220: error: undefined reference to 'selftests::register_test_foreach_arch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, void (*)(gdbarch*))'
    /home/smarchi/src/binutils-gdb/gdb/dwarf2/frame.c:2310: error: undefined reference to 'selftests::register_test_foreach_arch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, void (*)(gdbarch*))'
    /home/smarchi/src/binutils-gdb/gdb/gdbarch-selftests.c:168: error: undefined reference to 'selftests::register_test_foreach_arch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, void (*)(gdbarch*))'
    /home/smarchi/src/binutils-gdb/gdbsupport/selftest.cc:96: error: undefined reference to 'selftests::reset()'

This is because the gdbsupport configure script doesn't source
bfd/development.sh to set the development variable.  When $development
is unset, GDB_AC_SELFTEST defaults to enabling selftests.  I don't think
the macro was written with this intention in mind, it just happens to be
that way.

So gdbsupport thinks selftests are enabled, while gdb thinks they are
disabled.  gdbsupport compiles in code that calls selftests:: functions,
which are normally provided by gdb, but gdb doesn't provide them, hence
the undefined references.

Fix this by sourcing bfd/development.sh in gdbsupport/configure.ac, so
that the development variable is set.

gdbsupport/ChangeLog:

        * configure.ac: Added call development.sh.
        * configure: Regenerate.
2020-03-05 14:33:17 -05:00
Tankut Baris Aktemur
842806cb6f gdb, gdbserver, gdbsupport: add .gitattributes files
Create .gitattributes files in gdb/, gdbserver/, and gdbsupport/.

The files specify cpp-style diffs for .h and .c files.  This is
particularly helpful if a class in a header file is modified.
For instance, if the `stop_requested` field of `thread_info` in
gdb/gdbthread.h is modified, we get the following diff with
'git diff' (using git version 2.17.1):

   @@ -379,7 +379,7 @@ public:
      struct target_waitstatus pending_follow;

      /* True if this thread has been explicitly requested to stop.  */
   -  int stop_requested = 0;
   +  bool stop_requested = 0;

      /* The initiating frame of a nexting operation, used for deciding
         which exceptions to intercept.  If it is null_frame_id no

Note that the context of the change shows up as 'public:'; not so
useful.  With the .gitattributes file, we get:

   @@ -379,7 +379,7 @@ class thread_info : public refcounted_object
      struct target_waitstatus pending_follow;

      /* True if this thread has been explicitly requested to stop.  */
   -  int stop_requested = 0;
   +  bool stop_requested = 0;

      /* The initiating frame of a nexting operation, used for deciding
         which exceptions to intercept.  If it is null_frame_id no

The context is successfully shown as 'class thread_info'.

This patch creates a .gitattributes file per each of gdb, gdbserver,
and gdbsupport folders.  An alternative would be to define the
attributes in the root folder -- this would impact all the top-level
folders, though.  I opted for the more conservative approach.

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

	* .gitattributes: New file.

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

	* .gitattributes: New file.

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

	* .gitattributes: New file.
2020-03-05 15:59:22 +01:00
Simon Marchi
89725b0d53 gdbsupport: re-generate Makefile.in
It looks like after doing last minute changes to Makefile.am in commit
06b3c5bdb ("gdbsupport: rename source files to .cc"), I forgot to
re-generate Makefile.in.  This patch fixes it.

gdbsupport/ChangeLog:

	* Makefile.in: Re-generate.
2020-03-03 17:11:12 -05:00
Sergio Durigan Junior
d7592e9747 Fix comment for 'gdb_dlopen'
The 'gdb_dlopen' function doesn't return NULL if the shlib load
fails; it actually throws an error.  This patch updates the comment
to reflect this.

gdbsupport/ChangeLog:
2020-02-28  Sergio Durigan Junior  <sergiodj@redhat.com>

	* gdb-dlfcn.h (gdb_dlopen): Update comment.
2020-02-28 11:04:28 -05:00
Andrew Burgess
9f1528a1bd Merge changes from GCC for the config/ directory
GCC's config/ChangeLog since the last time this merge was done
(in the binutils-gdb commit 0b4d000cc4) is included at the
end of this commit message.

It is worth noting that the binutils-gdb commit 301a9420d9
added the file config/debuginfod.m4 which is not present in GCC's
config/ directory.  This file is preserved, unmodified, after this
commit.

In order to regenerate all of the configure files, I configured with
--enable-maintainer-mode, and built the 'all' target.  I then did the
same thing on a source tree without this patch, and only committed
those files that changed when this patch was added.

GCC's config/ChangeLog entries:

  2020-02-12  Sandra Loosemore  <sandra@codesourcery.com>

  	PR libstdc++/79193
  	PR libstdc++/88999

  	* no-executables.m4: Use a non-empty program to test for linker
  	support.

  2020-02-01  Andrew Burgess  <andrew.burgess@embecosm.com>

  	* lib-link.m4 (AC_LIB_LINKFLAGS_BODY): Update shell syntax.

  2020-01-27  Andrew Burgess  <andrew.burgess@embecosm.com>

  	* lib-link.m4 (AC_LIB_LINKFLAGS_BODY): Add new
  	--with-libXXX-type=... option.  Use this to guide the selection of
  	either a shared library or a static library.

  2020-01-24  Maciej W. Rozycki  <macro@wdc.com>

  	* toolexeclibdir.m4: New file.

  2019-09-10  Christophe Lyon  <christophe.lyon@st.com>

  	* futex.m4: Handle *-uclinux*.
  	* tls.m4 (GCC_CHECK_TLS): Likewise.

  2019-09-06  Florian Weimer  <fweimer@redhat.com>

  	* futex.m4 (GCC_LINUX_FUTEX): Include <unistd.h> for the syscall
  	function.

  2019-07-08  Richard Sandiford  <richard.sandiford@arm.com>

  	* bootstrap-Og.mk: New file.

  2019-06-25  Kwok Cheung Yeung  <kcy@codesourcery.com>
              Andrew Stubbs  <ams@codesourcery.com>

  	* gthr.m4 (GCC_AC_THREAD_HEADER): Add case for gcn.

  2019-05-30  Rainer Orth  <ro@CeBiTec.Uni-Bielefeld.DE>

  	* ax_count_cpus.m4: New file.

  2019-05-02  Richard Biener  <rguenther@suse.de>

  	PR bootstrap/85574
  	* bootstrap-lto.mk (extra-compare): Set to gcc/lto1$(exeext).

  2019-04-16  Martin Liska  <mliska@suse.cz>

  	* bootstrap-lto-lean.mk: Filter out -flto in STAGEtrain_CFLAGS.

  2019-04-09  Martin Liska  <mliska@suse.cz>

  	* bootstrap-lto-lean.mk: New file.

  2019-03-02  Johannes Pfau  <johannespfau@gmail.com>

  	* mh-mingw: Also set __USE_MINGW_ACCESS flag for C++ code.

  2018-10-31  Joseph Myers  <joseph@codesourcery.com>

  	PR bootstrap/82856
  	* math.m4, tls.m4: Use AC_LANG_SOURCE.

  	Merge from binutils-gdb:
  	2018-06-19  Simon Marchi  <simon.marchi@ericsson.com>

  	* override.m4 (_GCC_AUTOCONF_VERSION): Bump from 2.64 to 2.69.

config/ChangeLog:

	* ax_count_cpus.m4: New file, backported from GCC.
	* bootstrap-Og.mk: New file, backported from GCC.
	* bootstrap-lto-lean.mk: New file, backported from GCC.
	* bootstrap-lto.mk: Changes backported from GCC.
	* futex.m4: Changes backported from GCC.
	* gthr.m4: Changes backported from GCC.
	* lib-link.m4: Changes backported from GCC.
	* mh-mingw: Changes backported from GCC.
	* no-executables.m4: Changes backported from GCC.
	* tls.m4: Changes backported from GCC.
	* toolexeclibdir.m4: New file, backported from GCC.

binutils/ChangeLog:

	* configure: Regenerate.

gdb/ChangeLog:

	* configure: Regenerate.

gdbserver/ChangeLog:

	* configure: Regenerate.

gdbsupport/ChangeLog:

	* configure: Regenerate.

intl/ChangeLog:

	* configure: Regenerate.

libiberty/ChangeLog:

	* configure: Regenerate.

zlib/ChangeLog.bin-gdb:

	* configure: Regenerate.
2020-02-19 17:51:24 +00:00