Commit graph

52118 commits

Author SHA1 Message Date
Tom Tromey
69f6730df3 Remove gdb_static_assert
C++17 makes the second parameter to static_assert optional, so we can
remove gdb_static_assert now.
2023-11-29 14:29:44 -07:00
Tom Tromey
b096524827 Use try_emplace in index-write.c
index-write.c has a comment indicating that C++17's try_emplace could
be used.  This patch makes the change.

Approved-By: Pedro Alves <pedro@palves.net>
2023-11-29 14:29:44 -07:00
Tom Tromey
d57f38ec74 Switch to -Wimplicit-fallthrough=5
This changes the various gdb-related directories to use
-Wimplicit-fallthrough=5, meaning that only the fallthrough attribute
can be used in switches -- special 'fallthrough' comments will no
longer be usable.

Approved-By: Pedro Alves <pedro@palves.net>
2023-11-29 14:29:43 -07:00
Tom Tromey
d182e39881 Use C++17 [[fallthrough]] attribute
This changes gdb to use the C++17 [[fallthrough]] attribute rather
than special comments.

This was mostly done by script, but I neglected a few spellings and so
also fixed it up by hand.

I suspect this fixes the bug mentioned below, by switching to a
standard approach that, presumably, clang supports.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=23159
Approved-By: John Baldwin <jhb@FreeBSD.org>
Approved-By: Luis Machado <luis.machado@arm.com>
Approved-By: Pedro Alves <pedro@palves.net>
2023-11-29 14:29:43 -07:00
Andrew Burgess
a393b15517 gdb/python: display errors from command completion
This commit makes the gdb.Command.complete methods more verbose when
it comes to error handling.

Previous to this commit if any commands implemented in Python
implemented the complete method, and if there were any errors
encountered when calling that complete method, then GDB would silently
hide the error and continue as if there were no completions.

This makes is difficult to debug any errors encountered when writing
completion methods, and encourages the idea that Python extensions can
be broken, and GDB will just silently work around them.

I don't think this is a good idea.  GDB should encourage extensions to
be written correctly, and robustly, and one way in which GDB can (I
think) support this, is by pointing out when an extension goes wrong.

In this commit I've gone through the Python command completion code,
and added calls to gdbpy_print_stack() or gdbpy_print_stack_or_quit()
in places where we were either clearing the Python error, or, in some
cases, just not handling the error at all.

One thing I have not changed is in cmdpy_completer (py-cmd.c) where we
process the list of completions returned from the Command.complete
method; this routine includes a call to gdbpy_is_string to check a
possible completion is a string, if not the completion is ignored.

I was tempted to remove this check, attempt to complete each result to
a string, and display an error if the conversion fails.  After all,
returning anything but a string is surely a mistake by the extension
author.

However, the docs clearly say that only strings within the returned
list will be considered as completions.  Anything else is ignored.  As
such, and to avoid (what I think is pretty unlikely) breakage of
existing code, I've retained the gdbpy_is_string check.

After the gdbpy_is_string check we call python_string_to_host_string,
if this call fails then I do now print the error, where before we
ignored the error.  I think this is OK; if GDB thinks something is a
string, but still can't convert it to a string, then I think it's OK
to display the error in that case.

Another case which I was a little unsure about was in
cmdpy_completer_helper, and the call to PyObject_CallMethodObjArgs,
which is when we actually call Command.complete.  Previously, if this
call resulted in an exception then we would ignore this and just
pretend there were no completions.

Of all the changes, this is possibly the one with the biggest
potential for breaking existing scripts, but also, is, I think, the
most useful change.  If the user code is wrong in some way, such that
an exception is raised, then previously the user would have no obvious
feedback about this breakage.  Now GDB will print the exception for
them, making it, I think, much easier to debug their extension.  But,
if there is user code in the wild that relies on raising an exception
as a means to indicate there are no completions .... well, that code
is going to break after this commit.  I think we can live with this
though, the exceptions means no completions thing was never documented
behaviour.

I also added a new error() call if the PyObject_CallMethodObjArgs call
raises an exception.  This causes the completion mechanism within GDB
to stop.  Within GDB the completion code is called twice, the first
time to compute the work break characters, and then a second time to
compute the actual completions.

If PyObject_CallMethodObjArgs raises an exception when computing the
word break character, and we print it by calling
gdbpy_print_stack_or_quit(), but then carry on as if
PyObject_CallMethodObjArgs had returns no completions, GDB will
call the Python completion code again, which results in another call
to PyObject_CallMethodObjArgs, which might raise the same exception
again.  This results in the Python exception being printed twice.

By throwing a C++ exception after the failed
PyObject_CallMethodObjArgs call, the completion mechanism is aborted,
and no completions are offered.  But importantly, the Python exception
is only printed once.  I think this gives a much better user
experience.

I've added some tests to cover this case, as I think this is the most
likely case that a user will run into.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 18:23:19 +00:00
Andrew Burgess
b489eb9088 gdb/testsuite: improve test regexp in gdb_get_worker_threads
I spotted I made a small mistake in this commit:

  commit aff250145a
  Date:   Fri Nov 24 12:04:36 2023 +0000

      gdb: generate gdb-index identically regardless of work thread count

In this commit I added a new proc in testsuite/lib/gdb.exp called
gdb_get_worker_threads.  This proc uses gdb_test_multiple with two
possible patterns.  One pattern is anchored with '^', while the other
is missing the '^' which it could use.

This commit adds the missing '^'.
2023-11-28 18:20:25 +00:00
Simon Marchi
0a3249820f gdb: fix call to breakpoint_inserted_here_p in darwin-nat.c
Fixes this issue, introduced by f9582a22db ("[gdb] Fix segfault in
for_each_block, part 1"):

       CXX    darwin-nat.o
     /Users/smarchi/src/binutils-gdb/gdb/darwin-nat.c:1169:7: error: no matching function for call to 'breakpoint_inserted_here_p'
       if (breakpoint_inserted_here_p (inf->aspace, pc))
           ^~~~~~~~~~~~~~~~~~~~~~~~~~

Change-Id: I3bb6be75b650319f0fa1dbdceb379b18531da96c
2023-11-28 12:25:56 -05:00
Tom Tromey
14e461bed4 Emit DAP "process" event
DAP specifies a "process" event that is sent when a process is started
or attached to.  gdb was not emitting this (several DAP clients appear
to ignore it entirely), but it looked easy and harmless to implement.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30473
2023-11-28 08:47:24 -07:00
Tom de Vries
1f6ce80388 [gdb/tui] Use const std::string for string literals in tui-stack.c
I noticed in gdb/tui/tui-stack.c a source-level micro-optimization where
strlen with a string literal argument:
...
strlen ("bla")
...
is replaced with sizeof:
...
sizeof ("bla") - 1
...

The benefit of this is that the optimization is also done at O0, but the
drawback is that it makes the expression harder to read.

Use const std::string to encapsulate the string literals, and use
std::string::size () instead.

I tried making the string names (PROC_PREFIX, LINE_PREFIX, PC_PREFIX and
SINGLE_KEY) lower-case, but that clashed with a pre-existing pc_prefix, so
I've left them upper-case.

Tested on x86_64-linux.

Tested-By: Alexandra Petlanova Hajkova <ahajkova@redhat.com>
2023-11-28 16:31:07 +01:00
Andrew Burgess
e5f1ee1832 gdb/testsuite: add a new check-all-boards target
The make-check-all.sh script (gdb/testsuite/make-check-all.sh) is
great, it makes it super easy to run some test(s) using all the
available board files.

This commit aims to make this script even easier to access by adding a
check-all-boards target to the GDB Makefile.  This new target checks
for (and requires) a number of environment variables, so the target
should be used like this:

  make check-all-boards GDB_TARGET_USERNAME=remote-target \
                        GDB_HOST_USERNAME=remote-host \
			TESTS="gdb.base/break.exp"

Where GDB_TARGET_USERNAME and GDB_HOST_USERNAME are the user names
that should be passed to the make-check-all.sh --target-user and
--host-user command line options respectively.

My personal intention is to set these variables in my environment, so
all I'll need to do is:

  make check-all-boards TESTS="gdb.base/break.exp"

The make rule always passes --keep-results to the make-check-all.sh
script, as I find that the most useful.  It's super frustrating to run
the tests and realise you forgot that option and the results have been
discarded.
2023-11-28 10:36:43 +00:00
Andrew Burgess
bcf90a927e gdb/testsuite: log 'make check' command in make-check-all.sh
I have been making more use of the make-check-all.sh script to run
tests against all boards.

But one thing is pretty annoying.  When a test fails on some random
board, I have to run make-check-all.sh with --verbose and --dry-run in
order to see what RUNTESTFLAGS I should be using.

I always run with --keep-results on, so, in this commit, I propose
that, when --keep-results is on the 'make check' command will be
written out to a file within the stored results directory, like:

  check-all/BOARD_NAME/make-check.sh

then, if I want to rerun a test, I can just:

  sh check-all/BOARD_NAME/make-check.sh

and the test will be re-run for me.
2023-11-28 10:33:44 +00:00
Andrew Burgess
3644f41dc8 gdb: generate dwarf-5 index identically as worker-thread count changes
Similar to the previous commit, this commit ensures that the dwarf-5
index files are generated identically as the number of worker-threads
changes.

Building the dwarf-5 index makes use of a closed hash table, the
bucket_hash local within debug_names::build().  Entries are added to
bucket_hash from m_name_to_value_set, which, in turn, is populated
by calls to debug_names::insert() in write_debug_names.  The insert
calls are ordered based on the entries within the cooked_index, and
the ordering within cooked_index depends on the number of worker
threads that GDB is using.

My proposal is to sort each chain within the bucket_hash closed hash
table prior to using this to build the dwarf-5 index.

The buckets within bucket_hash will always have the same ordering (for
a given GDB build with a given executable), and by sorting the chains
within each bucket, we can be sure that GDB will see each entry in a
deterministic order.

I've extended the index creation test to cover this case.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:19 +00:00
Andrew Burgess
aff250145a gdb: generate gdb-index identically regardless of work thread count
It was observed that changing the number of worker threads that GDB
uses (maintenance set worker-threads NUM) would have an impact on the
layout of the generated gdb-index.

The cause seems to be how the CU are distributed between threads, and
then symbols that appear in multiple CU can be encountered earlier or
later depending on whether a particular CU moves between threads.

I certainly found this behaviour was reproducible when generating an
index for GDB itself, like:

  gdb -q -nx -nh -batch \
      -eiex 'maint set worker-threads NUM' \
      -ex 'save gdb-index /tmp/'

And then setting different values for NUM will change the generated
index.

Now, the question is: does this matter?

I would like to suggest that yes, this does matter.  At Red Hat we
generate a gdb-index as part of the build process, and we would
ideally like to have reproducible builds: for the same source,
compiled with the same tool-chain, we should get the exact same output
binary.  And we do .... except for the index.

Now we could simply force GDB to only use a single worker thread when
we build the index, but, I don't think the idea of reproducible builds
is that strange, so I think we should ensure that our generated
indexes are always reproducible.

To achieve this, I propose that we add an extra step when building the
gdb-index file.  After constructing the initial symbol hash table
contents, we will pull all the symbols out of the hash, sort them,
then re-insert them in sorted order.  This will ensure that the
structure of the generated hash will remain consistent (given the same
set of symbols).

I've extended the existing index-file test to check that the generated
index doesn't change if we adjust the number of worker threads used.
Given that this test is already rather slow, I've only made one change
to the worker-thread count.  Maybe this test should be changed to use
a smaller binary, which is quicker to load, and for which we could
then try many different worker thread counts.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:19 +00:00
Andrew Burgess
acc117b57f gdb: C++-ify mapped_symtab from dwarf2/index-write.c
Make static the functions add_index_entry, find_slot, and hash_expand,
member functions of the mapped_symtab class.

Fold an additional snippet of code from write_gdbindex into
mapped_symtab::minimize, this code relates to minimisation, so this
seems like a good home for it.

Make the n_elements, data, and m_string_obstack member variables of
mapped_symtab private.  Provide a new obstack() member function to
provide access to the obstack when needed, and also add member
functions begin(), end(), cbegin(), and cend() so that the
mapped_symtab class can be treated like a contained and iterated
over.

I've also taken this opportunity to split out the logic for whether
the hash table (m_data) needs expanding, this is the new function
hash_needs_expanding.  This will be useful in a later commit.

There should be no user visible changes after this commit.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:19 +00:00
Andrew Burgess
aa19bc1d25 gdb: reduce size of generated gdb-index file
I noticed in passing that out algorithm for generating the gdb-index
file is incorrect.  When building the hash table in add_index_entry we
count every incoming entry rehash when the number of entries gets too
large.  However, some of the incoming entries will be duplicates,
which don't actually result in new items being added to the hash
table.

As a result, we grow the gdb-index hash table far too often.

With an unmodified GDB, generating a gdb-index for GDB, I see a file
size of 90M, with a hash usage (in the generated index file) of just
2.6%.

With a patched GDB, generating a gdb-index for the _same_ GDB binary,
I now see a gdb-index file size of 30M, with a hash usage of 41.9%.

This is a 67% reduction in gdb-index file size.

Obviously, not every gdb-index file is going to see such big savings,
however, the larger a program, and the more symbols that are
duplicated between compilation units, the more GDB would over count,
and so, over-grow the index.

The gdb-index hash table we create has a minimum size of 1024, and
then we grow the hash when it is 75% full, doubling the hash table at
that time.  Given this, then we expect that either:

  a. The hash table is size 1024, and less than 75% full, or
  b. The hash table is between 37.5% and 75% full.

I've include a test that checks some of these constraints -- I've not
bothered to check the upper limit, and over full hash table isn't
really a problem here, but if the fill percentage is less than 37.5%
then this indicates that we've done something wrong (obviously, I also
check for the 1024 minimum size).

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:19 +00:00
Andrew Burgess
1f0fab7ff8 gdb/testsuite: small refactor in selftest-support.exp
Split out the code that makes a copy of the GDB executable ready for
self testing into a new proc.  A later commit in this series wants to
load the GDB executable into GDB (for creating an on-disk debug
index), but doesn't need to make use of the full do_self_tests proc.

There should be no changes in what is tested after this commit.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:19 +00:00
Andrew Burgess
640713c5a0 gdb: option completion for 'save gdb-index' command
Add proper support for option completion to the 'save gdb-index'
command.  Update save_gdb_index_command function to make use of the
new option_def data structures for parsing the '-dwarf-5' option.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:18 +00:00
Andrew Burgess
4793f551a5 gdb: allow use of ~ in 'save gdb-index' command
Add a call to gdb_tilde_expand in the save_gdb_index_command function,
this means that we can now do:

  (gdb) save gdb-index ~/blah/

Previous this wouldn't work.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-28 10:23:18 +00:00
Tom de Vries
14414227bf [gdb] Fix segfault in for_each_block, part 2
The previous commit describes PR gdb/30547, a segfault when running test-case
gdb.base/vfork-follow-parent.exp on powerpc64 (likewise on s390x).

The root cause for the segmentation fault is that linux_is_uclinux gives an
incorrect result: it returns true instead of false.

So, why does linux_is_uclinux:
...
int
linux_is_uclinux (void)
{
  CORE_ADDR dummy;

  return (target_auxv_search (AT_NULL, &dummy) > 0
	  && target_auxv_search (AT_PAGESZ, &dummy) == 0);
...
return true?

This is because ppc_linux_target_wordsize returns 4 instead of 8, causing
ppc_linux_nat_target::auxv_parse to misinterpret the auxv vector.

So, why does ppc_linux_target_wordsize:
...
int
ppc_linux_target_wordsize (int tid)
{
  int wordsize = 4;

  /* Check for 64-bit inferior process.	 This is the case when the host is
     64-bit, and in addition the top bit of the MSR register is set.  */
  long msr;

  errno = 0;
  msr = (long) ptrace (PTRACE_PEEKUSER, tid, PT_MSR * 8, 0);
  if (errno == 0 && ppc64_64bit_inferior_p (msr))
    wordsize = 8;

  return wordsize;
}
...
return 4?

Specifically, we get this result because because tid == 0, so we get
errno == ESRCH.

The tid == 0 is caused by the switch_to_no_thread in
handle_vfork_child_exec_or_exit:
...
	  /* Switch to no-thread while running clone_program_space, so
	     that clone_program_space doesn't want to read the
	     selected frame of a dead process.  */
	  scoped_restore_current_thread restore_thread;
	  switch_to_no_thread ();

	  inf->pspace = new program_space (maybe_new_address_space ());
...
but moving the maybe_new_address_space call to before that gives us the
same result.  The tid is no longer 0, but we still get ESRCH because the
thread has exited.

Fix this in handle_vfork_child_exec_or_exit by doing the
maybe_new_address_space call in the context of the vfork parent.

Tested on top of trunk on x86_64-linux and ppc64le-linux.
Tested on top of gdb-14-branch on ppc64-linux.

Co-Authored-By: Simon Marchi <simon.marchi@polymtl.ca>

PR gdb/30547
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30547
2023-11-28 10:31:25 +01:00
Tom de Vries
f9582a22db [gdb] Fix segfault in for_each_block, part 1
When running test-case gdb.base/vfork-follow-parent.exp on powerpc64 (likewise
on s390x), I run into:
...
(gdb) PASS: gdb.base/vfork-follow-parent.exp: \
  exec_file=vfork-follow-parent-exit: target-non-stop=on: non-stop=off: \
  resolution_method=schedule-multiple: print unblock_parent = 1
continue^M
Continuing.^M
Reading symbols from vfork-follow-parent-exit...^M
^M
^M
Fatal signal: Segmentation fault^M
----- Backtrace -----^M
0x1027d3e7 gdb_internal_backtrace_1^M
        src/gdb/bt-utils.c:122^M
0x1027d54f _Z22gdb_internal_backtracev^M
        src/gdb/bt-utils.c:168^M
0x1057643f handle_fatal_signal^M
        src/gdb/event-top.c:889^M
0x10576677 handle_sigsegv^M
        src/gdb/event-top.c:962^M
0x3fffa7610477 ???^M
0x103f2144 for_each_block^M
        src/gdb/dcache.c:199^M
0x103f235b _Z17dcache_invalidateP13dcache_struct^M
        src/gdb/dcache.c:251^M
0x10bde8c7 _Z24target_dcache_invalidatev^M
        src/gdb/target-dcache.c:50^M
...
or similar.

The root cause for the segmentation fault is that linux_is_uclinux gives an
incorrect result: it should always return false, given that we're running on a
regular linux system, but instead it returns first true, then false.

In more detail, the segmentation fault happens as follows:
- a program space with an address space is created
- a second program space is about to be created. maybe_new_address_space
  is called, and because linux_is_uclinux returns true, maybe_new_address_space
  returns false, and no new address space is created
- a second program space with the same address space is created
- a program space is deleted. Because linux_is_uclinux now returns false,
  gdbarch_has_shared_address_space (current_inferior ()->arch ()) returns
  false, and the address space is deleted
- when gdb uses the address space of the remaining program space, we run into
  the segfault, because the address space is deleted.

Hardcoding linux_is_uclinux to false makes the test-case pass.

We leave addressing the root cause for the following commit in this series.

For now, prevent the segmentation fault by making the address space a refcounted
object.

This was already suggested here [1]:
...
A better solution might be to have the address spaces be reference counted
...

Tested on top of trunk on x86_64-linux and ppc64le-linux.
Tested on top of gdb-14-branch on ppc64-linux.

Co-Authored-By: Simon Marchi <simon.marchi@polymtl.ca>

PR gdb/30547
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30547

[1] https://sourceware.org/pipermail/gdb-patches/2023-October/202928.html
2023-11-28 10:31:25 +01:00
John Baldwin
66637e209c i386: Use a fallback XSAVE layout for remote targets
If a target provides a target description including registers from the
XSAVE extended region, but does not provide an XSAVE layout, use a
fallback XSAVE layout based on the included registers.  This fallback
layout matches GDB's behavior in earlier releases which assumes the
layout from Intel CPUs.

This fallback layout is currently only used for remote targets since
native targets which support XSAVE provide an explicit layout derived
from CPUID.

PR gdb/30912
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30912
Approved-By: Simon Marchi <simon.marchi@efficios.com>
2023-11-27 13:53:22 -08:00
Tom de Vries
f1b8ee6f2b [gdb/testsuite] Add boards/cc-with-index-cache.exp
We have a target board cc-with-gdb-index that uses the gdb-add-index script to
add a .gdb_index index to an exec.

There is however an alternative way of adding a .gdb_index: the index-cache.

Add a new target board cc-with-index-cache.

This is not superfluous for two reasons:
- there is functionality that gdb-add-index doesn't support, but the
  index-cache does: the index-cache can add an index to an exec with a
  .gnu_debugaltlink (note that when using the cc-with-gdb-index board this
  case is quietly ignored), and
- using the index-cache is excercised in only a few test-cases, and having
  this target board extends the test coverage to the entire test suite.  This
  is for instance relevant because the index-cache is written by a worker
  thread in the background, so we can check more thoroughly for data races
  (see PR symtab/30837).

Tested on x86_64-linux.

Shell script changes checked with shellcheck.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-27 21:15:26 +01:00
Tom Tromey
0da23004a0 Change serial_readchar to throw
This changes serial_readchar to throw an exception rather than trying
to set and preserve errno.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30770
2023-11-27 12:55:14 -07:00
Tom Tromey
d69939bded Change serial_send_break and serial_write to throw
This changes serial_send_break and serial_write to throw exceptions
rather than attempt to set errno and return an error indicator.  This
lets us correctly report failures on Windows.

Both functions had to be converted in a single patch because one
implementation of send_break works via write.

This also introduces remote_serial_send_break to handle error checking
when attempting to send a break.  This was previously ignored.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30770
2023-11-27 12:55:14 -07:00
Tom Tromey
a2e0acea42 Change serial "open" functions to throw exception
remote.c assumes that a failure to open the serial connection will set
errno.  This is somewhat true, because the Windows code tries to set
errno appropriately -- but only somewhat, because it isn't clear that
the "pex" code sets it, and the tcp code seems to do the wrong thing.
It seems better to simply have the serial open functions throw on
error.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30770
2023-11-27 12:55:14 -07:00
Tom Tromey
ad3cf8c64e Change serial_setbaudrate to throw exception
remote.c has this code:

      if (serial_setbaudrate (rs->remote_desc, baud_rate))
	{
	  /* The requested speed could not be set.  Error out to
	     top level after closing remote_desc.  Take care to
	     set remote_desc to NULL to avoid closing remote_desc
	     more than once.  */
	  serial_close (rs->remote_desc);
	  rs->remote_desc = NULL;
	  perror_with_name (name);

The perror here cannot be correct, because if serial_setbaudrate did
set errno, it may be obscured by serial_close.

This patch changes serial_setbaudrate to throw an exception instead.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30770
2023-11-27 12:55:14 -07:00
Tom Tromey
602971b386 Introduce throw_winerror_with_name
This introduces throw_winerror_with_name, a Windows analog of
perror_with_name, and changes various places in gdb to call it.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30770
2023-11-27 12:55:14 -07:00
Tom Tromey
4dda9cc4b0 Fix latent bug in ser_windows_send_break
The ClearCommBreak documentation says:

    If the function fails, the return value is zero.

ser_windows_send_break inverts this check.  This has never been
noticed because the caller doesn't check the result.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=30770
2023-11-27 12:55:14 -07:00
Tom Tromey
c618a1c548 Fix bug in DAP handling of 'pause' requests
While working on cancellation, I noticed that a DAP 'pause' request
would set the "do not emit the continue" flag.  This meant that a
subsequent request that should provoke a 'continue' event would
instead suppress the event.

I then tried writing a more obvious test case for this, involving an
inferior call -- and discovered that gdb.events.cont does not fire for
an inferior call.

This patch installs a new event listener for gdb.events.inferior_call
and arranges for this to emit continue and stop events when
appropriate.  It also fixes the original bug, by adding a check to
exec_and_expect_stop.
2023-11-27 08:54:56 -07:00
Simon Marchi
f087eb2765 gdb: make catch_syscall_enabled return bool
Make it return a bool and adjust a few comparisons where it's used.

Change-Id: Ic77d23b0dcfcfc9195dfe65e4c7ff9cf3229f6fb
2023-11-27 10:48:20 -05:00
Andrew Burgess
935dc9ff65 gdb/python: handle completion returning a non-sequence
GDB's Python API documentation for gdb.Command.complete() says:

  The 'complete' method can return several values:
     * If the return value is a sequence, the contents of the
       sequence are used as the completions.  It is up to 'complete'
       to ensure that the contents actually do complete the word.  A
       zero-length sequence is allowed, it means that there were no
       completions available.  Only string elements of the sequence
       are used; other elements in the sequence are ignored.

     * If the return value is one of the 'COMPLETE_' constants
       defined below, then the corresponding GDB-internal completion
       function is invoked, and its result is used.

     * All other results are treated as though there were no
       available completions.

So, returning a non-sequence, and non-integer from a complete method
should be fine; it should just be treated as though there are no
completions.

However, if I write a complete method that returns None, I see this
behaviour:

  (gdb) complete completefilenone x
  Python Exception <class 'TypeError'>: 'NoneType' object is not iterable
  warning: internal error: Unhandled Python exception
  (gdb)

Which is caused because we currently assume that anything that is not
an integer must be iterable, and we call PyObject_GetIter on it.  When
this call fails a Python exception is set, but instead of
clearing (and therefore ignoring) this exception as we do everywhere
else in the Python completion code, we instead just return with the
exception set.

In this commit I add a PySequence_Check call.  If this call returns
false (and we've already checked the integer case) then we can assume
there are no completion results.

I've added a test which checks returning a non-sequence.

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-27 15:44:45 +00:00
Tom de Vries
a2ee3a8fff [gdb/testsuite] Use more %progbits for arm
On pinebook I ran into:
...
Running gdb.tui/tui-layout-asm-short-prog.exp ...
gdb compile failed, gdb.tui/tui-layout-asm-short-prog.S: Assembler messages:
gdb.tui/tui-layout-asm-short-prog.S:23: Error: \
  junk at end of line, first unrecognized character is `,'
...

Fix this by using %progbits instead of @progbits for arm.

Approved-by: Luis Machado <luis.machado@arm.com>

Tested on x86_64-linux and pinebook.
2023-11-24 15:41:22 +01:00
Tom de Vries
1571765654 [gdb/testsuite] Two fixes in gdb.python/tui-window-disabled.exp
I ran test-case gdb.python/tui-window-disabled.exp on a configuration without
python support, and ran into:
...
PASS: $exp: cleanup_properly=True: initial restart: set pagination off
UNSUPPORTED: $exp: cleanup_properly=True: couldn't restart GDB
PASS: $exp: cleanup_properly=False: initial restart: set pagination off
UNSUPPORTED: $exp: cleanup_properly=False: couldn't restart GDB
...

After looking into the test-case, I realized that this is a consequence of
!allow_python_tests.

Handle this instead by requiring allow_python_tests, such that we get the usual
and more clear:
...
UNSUPPORTED: $exp: require failed: allow_python_tests
...

Also fix a return without value in clean_restart_and_setup, which if triggered
would cause:
...
ERROR: expected boolean value but got ""
...

Tested on x86_64-linux.
2023-11-24 15:38:17 +01:00
Ilya Leoshkevich
fa1c74b22a gdb: Fix "target file /proc/.../cmdline contained unexpected null characters"
When using the gcore command, GDB prints the following warning:

    (gdb) gcore
    warning: target file /proc/.../cmdline contained unexpected null characters

The reason is that cmdline is read with target_fileio_read_stralloc(),
which warns on seeing null characters. However, it's perfectly valid
for cmdline to contain \0s, so switch to target_fileio_read_alloc().

Approved-By: Tom Tromey <tom@tromey.com>
2023-11-24 12:26:16 +01:00
Tom de Vries
dd5516bf98 [gdb/python] Reformat missing_debug.py using black
Reformat gdb/python/lib/gdb/missing_debug.py with black after commit
e8c3dafa5f ("[gdb/python] Don't import curses.ascii module unless necessary").
2023-11-23 07:37:19 +01:00
Tom Tromey
a54a99a6e5 Fix build with GCC 7.5
A recent change to 'struct field' caused a build failure with GCC
7.5.0, as reported by Tom de Vries:

/data/vries/gdb/src/gdb/gdbtypes.h:721:51: error:
‘field::m_accessibility’ is too small to hold all values of ‘enum
class accessibility’ [-Werror]
   ENUM_BITFIELD (accessibility) m_accessibility : 2;
                                                   ^

Mark Wielaard pointed out that this was a GCC bug:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51242

This patch works around the bug by changing several members not to be
bitfields.  It reduces the size of the enum's underlying type,
instead.

I also changed m_bitsize to no longer be a bitfield -- that was done
for packing reasons in ancient times, but with m_accessibility not
being a bitfield, this no longer matters.

I removed fn_field::dummy.  In earlier times it was somewhat normal in
gdb to have these dummy fields to keep track of any available padding.
However, since the advent of "ptype/o", there doesn't seem to be any
need for this.

This patch does not change the size of struct field, fn_field, or
decl_field on 64-bit hosts.
2023-11-22 21:20:37 -07:00
Aditya Vidyadhar Kamath
10a0a5e239 Fix AIX thr!= NULL assertion failure during fork.
In AIX, while we followed the child process and detach on fork was on we hit thr!= NULL assertion failure.

The reason for the same was GDB core trying to switch to a child thread with tid not set that does not
exist, since child's ptid was changed to ptid_t (pid, 0, tid) in sync_threadlists() as it was threaded.

The way this happened was when a new child process is born, its object file will be loaded, calling the new_objfile ()
in aix-thread.c file from clone_program_space, which is
called from within follow_fork_inferior. Therefore it end ups syncing threadlists via pd_update ().

This patch is a fix for the same where pd_update () is called in the wait () or in update_thread_list() hook only.
2023-11-22 19:29:21 +01:00
Tom de Vries
03893ce67b [gdb/tui] Fix resizing of terminal to 1 or 2 lines
When starting TUI in a terminal with 3 lines:
...
$ echo $LINES
3
$ gdb -q -tui
...
and resizing the terminal to 2 lines we run into a segfault.

The problem is that for the source window:
- the minimum height is 3 (the default), but
- the maximum height is only 2 because there are only 2 lines.

This discrepancy eventually leads to a call to newwin in make_window with:
...
(gdb) p height
$1 = 3
(gdb) p width
$2 = 56
(gdb) p y
$3 = -1
(gdb) p x
$4 = 0
...
which results in a nullptr.

This violates the assumption here in tui_apply_current_layout:
....
  /* Get the new list of currently visible windows.  */
  std::vector<tui_win_info *> new_tui_windows;
  applied_layout->get_windows (&new_tui_windows);
...
that get_windows only returns visible windows, which leads to tui_windows
holding a dangling pointer, which results in the segfault.

Fix this by:
- making sure get_windows only returns visible windows, and
- detecting the situation and dropping windows from the layout if
  there's no room for them.

Tested on x86_64-linux.

Approved-By: Tom Tromey <tom@tromey.com>

PR tui/31044
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=31044
2023-11-22 19:07:47 +01:00
Tom de Vries
6697fa28bb [gdb/tui] Allow command window of 1 or 2 lines
When starting TUI in a terminal with 2 lines (likewise with 1 line):
...
$ echo $LINES
2
$ gdb -q -tui
...
we run into this assert in tui_apply_current_layout:
...
  /* This should always be made visible by a layout.  */
  gdb_assert (TUI_CMD_WIN != nullptr);
...

The problem is that for the command window:
- the minimum height is 3 (the default), but
- the maximum height is only 2 because there are only 2 lines.

This discrepancy eventually leads to a call to newwin in make_window with:
...
(gdb) p height
$1 = 3
(gdb) p width
$2 = 66
(gdb) p y
$3 = -1
(gdb) p x
$4 = 0
(gdb)
...
which results in a nullptr, which eventually triggers the assert.

The easiest way to fix this is to change the minimum height of the command
window to 1.  However, that would also change behaviour for the case that the
screen size is 3 lines or more.  For instance, in gdb.tui/winheight.exp the
number of lines in the terminal is 24, and the test-case checks that the user
cannot increase the source window height to the point that the command window
height would be less than 3.

Fix this by calculating the minimum height of the command window as follows:
- the default (3) if max_height () allows it, and
- max_height () otherwise.

Tested on x86_64-linux.

Approved-By: Tom Tromey <tom@tromey.com>

PR tui/31044
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=31044
2023-11-22 19:07:47 +01:00
Tom de Vries
e8c3dafa5f [gdb/python] Don't import curses.ascii module unless necessary
I ran into a failure in test-case gdb.python/py-missing-debug.exp with python
3.6, which was fixed by commit 7db795bc67 ("gdb/python: remove use of
str.isascii()").

However, I subsequently ran into a failure with python 3.11:
...
(gdb) PASS: $exp: initial checks: debug info no longer found
source py-missing-debug.py^M
Traceback (most recent call last):^M
  File "py-missing-debug.py", line 17, in <module>^M
    from gdb.missing_debug import MissingDebugHandler^M
  File "missing_debug.py", line 21, in <module>^M
    from curses.ascii import isascii, isalnum^M
  File "/usr/lib64/python3.11/_import_failed/curses.py", line 16, in <module>^M
    raise ImportError(f"""Module '{failed_name}' is not installed.^M
ImportError: Module 'curses' is not installed.^M
Use:^M
  sudo zypper install python311-curses^M
to install it.^M
(gdb) FAIL: $exp: source python script
...

Apparently I have the curses module installed for 3.6, but not 3.11.

I could just install it, but the test-case worked fine with 3.11 before commit
7db795bc67.

Fix this by only using the curses module when necessary, for python <= 3.7.

Tested on x86_64-linux, with both python 3.6 and 3.11.
2023-11-22 19:02:34 +01:00
Tom Tromey
3eac77a500 Simplify C++ type-printing
The C++ type-printing code had its own variant of the accessibility
enum.  This patch removes this and changes the code to use the new one
from gdbtypes.h.

This patch also changes the C++ code to recognize the default
accessibility of a class.  This makes ptype a bit more C++-like, and
lets us remove a chunk of questionable code.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
5028c9e206 Use enum accessibility in types and member functions
This changes nested types and member functions to use the new
'accessibility' enum, rather than separate private/protected flags.
This is done for consistency, but it also lets us simplify some other
code in the next patch.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
e17fd6c28e Remove char-based bitfield macros
This removes the char-based bitfield macros from gdbtypes.h, as they
are no longer used.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
20aadb931d Remove some type field accessor macros
This removes TYPE_FIELD_PRIVATE, TYPE_FIELD_PROTECTED,
TYPE_FIELD_IGNORE, and TYPE_FIELD_VIRTUAL.

In c-varobj.c, match_accessibility can be removed entirely now.  Note
that the comment before this function was incorrect.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
a3e9fbf7e8 Remove some QUIT calls from need_access_label_p
I think these invocations of QUIT in need_access_label_p are overkill.
QUIT is already called from its caller.  This just removes them.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
c3842cbe44 Add field::is_public
This adds a field::is_public convenience method, and updates one spot
to use it.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
61461a5b41 Remove byte vectors from cplus_struct_type
This removes some byte vectors from cplus_struct_type, moving the
information into bitfields in holes in struct field.

A new 'enum accessibility' is added to hold some of this information.
A similar enum is removed from c-varobj.c.

Note that the stabs reader treats "ignored" as an accessibility.
However, the stabs texinfo documents this as a public field that is
optimized out -- unfortunately nobody has updated the stabs reader to
use the better value-based optimized-out machinery.  I looked and
apparently gcc never emitted this visibility value, so whatever
compiler generated this stab is unknown.  I left a comment in
gdbtypes.h to this effect.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:05 -07:00
Tom Tromey
5ffb4736f0 Print field accessibility inline
This changes recursive_dump_type to print field accessibility
information "inline".  This is clearer and preserves the information
when the byte vectors are removed.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:04 -07:00
Tom Tromey
e626733c05 Use .def file to stringify type codes
This changes recursive_dump_type to reuse the type-codes.def file when
stringifying type codes.

This version of the patch changes the "unknown" case to an assert.

Acked-By: Simon Marchi <simon.marchi@efficios.com>
Reviewed-by: Keith Seitz <keiths@redhat.com>
2023-11-21 14:52:04 -07:00
Simon Marchi
790ce1f70c gdb: fix build of darwin-nat.c
Patch 743877128 ("gdb: remove regcache's address space") changed the
signature of darwin_nat_target::cancel_breakpoint, but missing updating
the class declaration, resulting in:

      CXX    darwin-nat.o
    /Users/smarchi/src/binutils-gdb/gdb/darwin-nat.c:1154:20: error: out-of-line definition of 'cancel_breakpoint' does not match any declaration in 'darwin_nat_target'
    darwin_nat_target::cancel_breakpoint (inferior *inf, ptid_t ptid)
                       ^~~~~~~~~~~~~~~~~
    /Users/smarchi/src/binutils-gdb/gdb/darwin-nat.c:1290:9: error: too many arguments to function call, expected single argument 'ptid', have 2 arguments
                                        ptid_t (inf->pid, 0, thread->gdb_port)))
                                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/smarchi/src/binutils-gdb/gdb/darwin-nat.h:129:7: note: 'cancel_breakpoint' declared here
      int cancel_breakpoint (ptid_t ptid);
          ^

Fix that.

Change-Id: Iedd58b36777eb77bca9e23f94882b217c9c87059
2023-11-21 11:44:49 -05:00