[PATCH] Improve ptrace-error detection on Linux targets

classic Classic list List threaded Threaded
99 messages Options
12345
Reply | Threaded
Open this post in threaded view
|

Re: [PATCH 2/6] Don't reset errno/bfd_error on 'throw_perror_with_name'

Sergio Durigan Junior
On Friday, February 28 2020, Pedro Alves wrote:

> On 2/28/20 3:29 PM, Tom Tromey wrote:
>>>>>>> "Sergio" == Sergio Durigan Junior <[hidden email]> writes:
>>
>> Sergio> Since this hunk may be a bit controversial, I decided to split it into
>> Sergio> a separate patch.  This is going to be needed by the ptrace-error
>> Sergio> feature; GDB will need to be able to access the value of errno even
>> Sergio> after a call to our 'perror'-like functions.
>>
>> I'm in favor of this.  The existing code seems pretty ugly.
>
> I'm not sure in favor of relying on errno being preserved from
> throw site to catch site, with potentially multiple try/catch hops
> in between.  Sergio, can you point out exactly how you're
> intending to use that?

Yeah.  I caught this problem when I was testing to see if GDB would
print the ptrace fail reason when trying (unsuccessfully) to attach to a
process.

The call stack looks like:

  linux_nat_target::attach
    |
    |--> inf_ptrace_target::attach # where ptrace fails
         |
         |--> throw_perror_with_name # where errno is set to 0

When 'throw_perror_with_name' calls 'error', 'linux_nat_target::attach'
catches the exception and tries to print the reason:

  try
    {
      inf_ptrace_target::attach (args, from_tty);
    }
  catch (const gdb_exception_error &ex)
    {
      int saved_errno = errno;
      pid_t pid = parse_pid_to_attach (args);
      std::string reason = linux_ptrace_attach_fail_reason (pid, saved_errno);
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

      if (!reason.empty ())
        throw_error (ex.error, "warning: %s\n%s", reason.c_str (),
                     ex.what ());
      else
        throw_error (ex.error, "%s", ex.what ());
    }

However, at this point errno is already 0, so the function can't
determine the exact reason for the ptrace failure.  In fact, because
errno = 0, 'linux_ptrace_attach_fail_reason' doesn't print anything,
because it thinks everything is OK!

IMO, it doesn't make sense to have errno = 0 while you're handling an
exception (which, in this case, was caused exactly because a syscall
failed, and so we expect errno to be different than 0).

Thanks,

--
Sergio
GPG key ID: 237A 54B1 0287 28BF 00EF  31F4 D0EB 7628 65FC 5E36
Please send encrypted e-mail if possible
http://sergiodj.net/

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH 2/6] Don't reset errno/bfd_error on 'throw_perror_with_name'

Pedro Alves-7
On 2/28/20 8:35 PM, Sergio Durigan Junior wrote:

> On Friday, February 28 2020, Pedro Alves wrote:
>
>> On 2/28/20 3:29 PM, Tom Tromey wrote:
>>>>>>>> "Sergio" == Sergio Durigan Junior <[hidden email]> writes:
>>>
>>> Sergio> Since this hunk may be a bit controversial, I decided to split it into
>>> Sergio> a separate patch.  This is going to be needed by the ptrace-error
>>> Sergio> feature; GDB will need to be able to access the value of errno even
>>> Sergio> after a call to our 'perror'-like functions.
>>>
>>> I'm in favor of this.  The existing code seems pretty ugly.
>>
>> I'm not sure in favor of relying on errno being preserved from
>> throw site to catch site, with potentially multiple try/catch hops
>> in between.  Sergio, can you point out exactly how you're
>> intending to use that?
>
> Yeah.  I caught this problem when I was testing to see if GDB would
> print the ptrace fail reason when trying (unsuccessfully) to attach to a
> process.
>
> The call stack looks like:
>
>   linux_nat_target::attach
>     |
>     |--> inf_ptrace_target::attach # where ptrace fails
>          |
>          |--> throw_perror_with_name # where errno is set to 0
>
> When 'throw_perror_with_name' calls 'error', 'linux_nat_target::attach'
> catches the exception and tries to print the reason:
>
>   try
>     {
>       inf_ptrace_target::attach (args, from_tty);
>     }
>   catch (const gdb_exception_error &ex)
>     {
>       int saved_errno = errno;
>       pid_t pid = parse_pid_to_attach (args);
>       std::string reason = linux_ptrace_attach_fail_reason (pid, saved_errno);
>       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>
>       if (!reason.empty ())
> throw_error (ex.error, "warning: %s\n%s", reason.c_str (),
>     ex.what ());
>       else
> throw_error (ex.error, "%s", ex.what ());
>     }
>
> However, at this point errno is already 0, so the function can't
> determine the exact reason for the ptrace failure.  In fact, because
> errno = 0, 'linux_ptrace_attach_fail_reason' doesn't print anything,
> because it thinks everything is OK!
>
> IMO, it doesn't make sense to have errno = 0 while you're handling an
> exception (which, in this case, was caused exactly because a syscall
> failed, and so we expect errno to be different than 0).

This is bad design.  Exception objects should be self contained
and not rely on global state to transfer information.

E.g., it should be possible to do

void my_function ()
{
  try
    {
       function_that_throws ();
    }
  catch (const gdb_exception &ex)
    {
       // call some function that potentially changes errno.
       function_that_changes_errno ();
 
       throw; // rethrow.
    }
}

and then:

try
  {
     my_function ();
  }
catch (const gdb_exception &ex)
  {
     // errno here is really unreliable.
  }

It's not even guaranteed that the exception thrown from
within inf_ptrace_target::attach is thrown after setting
errno, or that errno is meaningful for the exception thrown.

For example, this error:

  if (pid == getpid ())
    error (_("I refuse to debug myself!"));


I think the simpler thing to do here is to change
inf_ptrace_target::attach to return the ptrace errno
as the function's return.  I.e., rename it and change it
from:

 void inf_ptrace_target::attach (const char *args, int from_tty);

to:

 int inf_ptrace_target::ptrace_attach (const char *args, int from_tty);

And change the body like this:

  errno = 0;
  ptrace (PT_ATTACH, pid, (PTRACE_TYPE_ARG3)0, 0);
  if (errno != 0)
-   perror_with_name (("ptrace"));
+   return errno;

with a return 0 added at the end.

All other errors still throw like before.

Then add a new "attach" method that wraps the old method, so that
targets that inherit inf_ptrace_target and don't override attach
continue working:

 void
 inf_ptrace_target::attach (const char *args, int from_tty)
 {
   errno = ptrace_attach (args, from_tty);
   if (errno != 0)
     perror_with_name (("ptrace"));
 }

This avoids having to think about storing the errno number in
the exception object.

Thanks,
Pedro Alves

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH 2/6] Don't reset errno/bfd_error on 'throw_perror_with_name'

Sergio Durigan Junior
On Friday, February 28 2020, Pedro Alves wrote:

> On 2/28/20 8:35 PM, Sergio Durigan Junior wrote:
>> On Friday, February 28 2020, Pedro Alves wrote:
>>
>>> On 2/28/20 3:29 PM, Tom Tromey wrote:
>>>>>>>>> "Sergio" == Sergio Durigan Junior <[hidden email]> writes:
>>>>
>>>> Sergio> Since this hunk may be a bit controversial, I decided to split it into
>>>> Sergio> a separate patch.  This is going to be needed by the ptrace-error
>>>> Sergio> feature; GDB will need to be able to access the value of errno even
>>>> Sergio> after a call to our 'perror'-like functions.
>>>>
>>>> I'm in favor of this.  The existing code seems pretty ugly.
>>>
>>> I'm not sure in favor of relying on errno being preserved from
>>> throw site to catch site, with potentially multiple try/catch hops
>>> in between.  Sergio, can you point out exactly how you're
>>> intending to use that?
>>
>> Yeah.  I caught this problem when I was testing to see if GDB would
>> print the ptrace fail reason when trying (unsuccessfully) to attach to a
>> process.
>>
>> The call stack looks like:
>>
>>   linux_nat_target::attach
>>     |
>>     |--> inf_ptrace_target::attach # where ptrace fails
>>          |
>>          |--> throw_perror_with_name # where errno is set to 0
>>
>> When 'throw_perror_with_name' calls 'error', 'linux_nat_target::attach'
>> catches the exception and tries to print the reason:
>>
>>   try
>>     {
>>       inf_ptrace_target::attach (args, from_tty);
>>     }
>>   catch (const gdb_exception_error &ex)
>>     {
>>       int saved_errno = errno;
>>       pid_t pid = parse_pid_to_attach (args);
>>       std::string reason = linux_ptrace_attach_fail_reason (pid, saved_errno);
>>       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>
>>       if (!reason.empty ())
>> throw_error (ex.error, "warning: %s\n%s", reason.c_str (),
>>     ex.what ());
>>       else
>> throw_error (ex.error, "%s", ex.what ());
>>     }
>>
>> However, at this point errno is already 0, so the function can't
>> determine the exact reason for the ptrace failure.  In fact, because
>> errno = 0, 'linux_ptrace_attach_fail_reason' doesn't print anything,
>> because it thinks everything is OK!
>>
>> IMO, it doesn't make sense to have errno = 0 while you're handling an
>> exception (which, in this case, was caused exactly because a syscall
>> failed, and so we expect errno to be different than 0).
>
> This is bad design.  Exception objects should be self contained
> and not rely on global state to transfer information.

OK.  I implemented your idea, but I will wait until the other patches
are reviewed so I can submit a v2 of the whole series.

Thanks.

--
Sergio
GPG key ID: 237A 54B1 0287 28BF 00EF  31F4 D0EB 7628 65FC 5E36
Please send encrypted e-mail if possible
http://sergiodj.net/

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH 0/6] Improve ptrace-error detection

Sergio Durigan Junior
In reply to this post by Sergio Durigan Junior
On Wednesday, February 26 2020, I wrote:

> This patch series is the continuation of:
>
>   [PATCH v5] Improve ptrace-error detection on Linux targets
>   https://sourceware.org/ml/gdb-patches/2019-09/msg00504.html

Ping.  Some of the patch have not been reviewed yet.  I can submit a v2
with an updated version of the series if needed.

Thanks.

> I decided to start a new series because this involved a rewrite of
> several parts of the patch.  I addressed all of the comments I
> received back in September (mostly from Pedro), but I also did some
> improvements, especially in the 'fork_inferior' code.
>
> After submitting this series to our Buildbot, no regressions were
> found.
>
> Sergio Durigan Junior (6):
>   Introduce scoped_pipe.h
>   Don't reset errno/bfd_error on 'throw_perror_with_name'
>   Expand 'fork_inferior' to check whether 'traceme_fun' succeeded
>   Extend GNU/Linux to check for ptrace error
>   Document Linux-specific possible ptrace restrictions
>   Fix comment for 'gdb_dlopen'
>
>  gdb/Makefile.in                       |   1 +
>  gdb/doc/gdb.texinfo                   | 143 ++++++++++++++++
>  gdb/inf-ptrace.c                      |  18 +-
>  gdb/linux-nat.c                       |  10 +-
>  gdb/nat/fork-inferior.c               | 231 ++++++++++++++++++++++++--
>  gdb/nat/fork-inferior.h               |  87 ++++++++--
>  gdb/nat/linux-ptrace.c                | 178 +++++++++++++++++++-
>  gdb/nat/linux-ptrace.h                |  27 ++-
>  gdb/remote.c                          |  40 ++++-
>  gdb/unittests/scoped_pipe-selftests.c |  96 +++++++++++
>  gdb/utils.c                           |   6 -
>  gdbserver/linux-low.cc                |  31 +++-
>  gdbserver/server.cc                   |  38 ++++-
>  gdbserver/thread-db.cc                |   2 +-
>  gdbserver/utils.cc                    |   2 +
>  gdbsupport/gdb-dlfcn.h                |   4 +-
>  gdbsupport/scoped_pipe.h              |  63 +++++++
>  17 files changed, 909 insertions(+), 68 deletions(-)
>  create mode 100644 gdb/unittests/scoped_pipe-selftests.c
>  create mode 100644 gdbsupport/scoped_pipe.h
>
> --
> 2.24.1

--
Sergio
GPG key ID: 237A 54B1 0287 28BF 00EF  31F4 D0EB 7628 65FC 5E36
Please send encrypted e-mail if possible
http://sergiodj.net/

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH 0/6] Improve ptrace-error detection

Sourceware - gdb-patches mailing list
On Friday, March 06 2020, I wrote:

> On Wednesday, February 26 2020, I wrote:
>
>> This patch series is the continuation of:
>>
>>   [PATCH v5] Improve ptrace-error detection on Linux targets
>>   https://sourceware.org/ml/gdb-patches/2019-09/msg00504.html
>
> Ping.  Some of the patch have not been reviewed yet.  I can submit a v2
> with an updated version of the series if needed.

Ping^2.

> Thanks.
>
>> I decided to start a new series because this involved a rewrite of
>> several parts of the patch.  I addressed all of the comments I
>> received back in September (mostly from Pedro), but I also did some
>> improvements, especially in the 'fork_inferior' code.
>>
>> After submitting this series to our Buildbot, no regressions were
>> found.
>>
>> Sergio Durigan Junior (6):
>>   Introduce scoped_pipe.h
>>   Don't reset errno/bfd_error on 'throw_perror_with_name'
>>   Expand 'fork_inferior' to check whether 'traceme_fun' succeeded
>>   Extend GNU/Linux to check for ptrace error
>>   Document Linux-specific possible ptrace restrictions
>>   Fix comment for 'gdb_dlopen'
>>
>>  gdb/Makefile.in                       |   1 +
>>  gdb/doc/gdb.texinfo                   | 143 ++++++++++++++++
>>  gdb/inf-ptrace.c                      |  18 +-
>>  gdb/linux-nat.c                       |  10 +-
>>  gdb/nat/fork-inferior.c               | 231 ++++++++++++++++++++++++--
>>  gdb/nat/fork-inferior.h               |  87 ++++++++--
>>  gdb/nat/linux-ptrace.c                | 178 +++++++++++++++++++-
>>  gdb/nat/linux-ptrace.h                |  27 ++-
>>  gdb/remote.c                          |  40 ++++-
>>  gdb/unittests/scoped_pipe-selftests.c |  96 +++++++++++
>>  gdb/utils.c                           |   6 -
>>  gdbserver/linux-low.cc                |  31 +++-
>>  gdbserver/server.cc                   |  38 ++++-
>>  gdbserver/thread-db.cc                |   2 +-
>>  gdbserver/utils.cc                    |   2 +
>>  gdbsupport/gdb-dlfcn.h                |   4 +-
>>  gdbsupport/scoped_pipe.h              |  63 +++++++
>>  17 files changed, 909 insertions(+), 68 deletions(-)
>>  create mode 100644 gdb/unittests/scoped_pipe-selftests.c
>>  create mode 100644 gdbsupport/scoped_pipe.h
>>
>> --
>> 2.24.1
>
> --
> Sergio
> GPG key ID: 237A 54B1 0287 28BF 00EF  31F4 D0EB 7628 65FC 5E36
> Please send encrypted e-mail if possible
> http://sergiodj.net/

--
Sergio
GPG key ID: 237A 54B1 0287 28BF 00EF  31F4 D0EB 7628 65FC 5E36
Please send encrypted e-mail if possible
http://sergiodj.net/

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH 0/6] Improve ptrace-error detection

Sourceware - gdb-patches mailing list
On Sun, 15 Mar 2020 00:21:50 -0400
Sergio Durigan Junior via Gdb-patches <[hidden email]> wrote:

> > Ping.  Some of the patch have not been reviewed yet.  I can submit a v2
> > with an updated version of the series if needed.  
>
> Ping^2.

After looking at it for a little while, I think it'd be useful (to me
anyway) to submit a v2 series with all of your local patches applied.

Kevin

Reply | Threaded
Open this post in threaded view
|

[PATCH v2 0/5] Improve ptrace-error detection

Sourceware - gdb-patches mailing list
In reply to this post by Sergio Durigan Junior
Changes from v1:

- Remove "config.h" include from scoped_pipe.h.

- Remove "explicit" keyword from scoped_pipe's constructor.

- Use "GDBSUPPORT" instead of "COMMON" as a prefix for #define on
  scoped_pipe.h.

- Remove errno save/restore dance from
  gdbserver/utils.cc:perror_with_name.

- Implement "ptrace_attach" vs. "attach" idea (from Pedro) on
  inf-ptrace.c in order to make sure we return ptrace errno when
  calling "attach".

Sergio Durigan Junior (5):
  Introduce scoped_pipe.h
  Don't reset errno/bfd_error on 'throw_perror_with_name'
  Expand 'fork_inferior' to check whether 'traceme_fun' succeeded
  Extend GNU/Linux to check for ptrace error
  Document Linux-specific possible ptrace restrictions

 gdb/Makefile.in                       |   1 +
 gdb/doc/gdb.texinfo                   | 136 +++++++++++++++
 gdb/inf-ptrace.c                      |  34 +++-
 gdb/inf-ptrace.h                      |   2 +
 gdb/linux-nat.c                       |  24 +--
 gdb/nat/fork-inferior.c               | 231 ++++++++++++++++++++++++--
 gdb/nat/fork-inferior.h               |  87 ++++++++--
 gdb/nat/linux-ptrace.c                | 178 +++++++++++++++++++-
 gdb/nat/linux-ptrace.h                |  27 ++-
 gdb/remote.c                          |  40 ++++-
 gdb/unittests/scoped_pipe-selftests.c |  95 +++++++++++
 gdb/utils.c                           |   6 -
 gdbserver/linux-low.cc                |  31 +++-
 gdbserver/server.cc                   |  38 ++++-
 gdbserver/thread-db.cc                |   2 +-
 gdbsupport/scoped_pipe.h              |  63 +++++++
 16 files changed, 918 insertions(+), 77 deletions(-)
 create mode 100644 gdb/unittests/scoped_pipe-selftests.c
 create mode 100644 gdbsupport/scoped_pipe.h

--
2.24.1

Reply | Threaded
Open this post in threaded view
|

[PATCH v2 1/5] Introduce scoped_pipe.h

Sourceware - gdb-patches mailing list
This simple patch introduces gdbsupport/scoped_pipe.h, which is based
on gdbsupport/scoped_fd.h.  When the object is instantiated, a pipe is
created using 'gdb_pipe_cloexec'.  There are two methods (get_read_end
and get_write_end) that allow the user to obtain the read/write ends
of the pipe (no more messing with [0] and [1]), and when the object is
destroyed, the pipe is closed (both ends).

gdb/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

        * unittests/scoped_pipe-selftests.c: New file.

gdbsupport/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

        * scoped_pipe.h: New file.
---
 gdb/Makefile.in                       |  1 +
 gdb/unittests/scoped_pipe-selftests.c | 95 +++++++++++++++++++++++++++
 gdbsupport/scoped_pipe.h              | 63 ++++++++++++++++++
 3 files changed, 159 insertions(+)
 create mode 100644 gdb/unittests/scoped_pipe-selftests.c
 create mode 100644 gdbsupport/scoped_pipe.h

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 0c331af4bf..458863b01c 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -447,6 +447,7 @@ SELFTESTS_SRCS = \
  unittests/rsp-low-selftests.c \
  unittests/scoped_fd-selftests.c \
  unittests/scoped_mmap-selftests.c \
+ unittests/scoped_pipe-selftests.c \
  unittests/scoped_restore-selftests.c \
  unittests/string_view-selftests.c \
  unittests/style-selftests.c \
diff --git a/gdb/unittests/scoped_pipe-selftests.c b/gdb/unittests/scoped_pipe-selftests.c
new file mode 100644
index 0000000000..14abbb1b7b
--- /dev/null
+++ b/gdb/unittests/scoped_pipe-selftests.c
@@ -0,0 +1,95 @@
+/* Self tests for scoped_pipe for GDB, the GNU debugger.
+
+   Copyright (C) 2020 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include "defs.h"
+
+#include "gdbsupport/scoped_pipe.h"
+#include "gdbsupport/selftest.h"
+
+namespace selftests {
+namespace scoped_pipe {
+
+/* Test that the pipe is correctly created.  */
+
+static void
+test_create ()
+{
+  ::scoped_pipe spipe;
+
+  SELF_CHECK (spipe.get_read_end () > 0);
+  SELF_CHECK (spipe.get_write_end () > 0);
+}
+
+/* Test that we can write and read from the pipe.  */
+
+static void
+test_transmission ()
+{
+  int foo = 123;
+  ::scoped_pipe spipe;
+
+  /* Write to the pipe.  */
+  {
+    ssize_t writeret;
+
+    do
+      {
+ writeret = write (spipe.get_write_end (), &foo, sizeof (foo));
+      }
+    while (writeret < 0 && (errno == EAGAIN || errno == EINTR));
+
+    SELF_CHECK (writeret > 0);
+  }
+
+  /* Read from the pipe, and check if the value read is the same as
+     the one that was written.  */
+  {
+    ssize_t readret;
+    int read_foo;
+
+    do
+      {
+ readret = read (spipe.get_read_end (), &read_foo, sizeof (read_foo));
+      }
+    while (readret < 0 && (errno == EAGAIN || errno == EINTR));
+
+    SELF_CHECK (readret > 0);
+
+    SELF_CHECK (read_foo == foo);
+  }
+}
+
+/* Run selftests.  */
+static void
+run_tests ()
+{
+  test_create ();
+  test_transmission ();
+}
+
+} /* namespace scoped_pipe */
+} /* namespace selftests */
+
+void _initialize_scoped_pipe_selftests ();
+void
+_initialize_scoped_pipe_selftests ()
+{
+  selftests::register_test ("scoped_pipe",
+    selftests::scoped_pipe::run_tests);
+}
diff --git a/gdbsupport/scoped_pipe.h b/gdbsupport/scoped_pipe.h
new file mode 100644
index 0000000000..5180df80ae
--- /dev/null
+++ b/gdbsupport/scoped_pipe.h
@@ -0,0 +1,63 @@
+/* scoped_pipe, automatically close a pipe.
+
+   Copyright (C) 2020 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#ifndef GDBSUPPORT_SCOPED_PIPE_H
+#define GDBSUPPORT_SCOPED_PIPE_H
+
+#include <unistd.h>
+#include "filestuff.h"
+
+/* A smart-pointer-like class to automatically close a pipe.  */
+
+class scoped_pipe
+{
+public:
+  scoped_pipe ()
+  {
+    if (gdb_pipe_cloexec (m_pipe) < 0)
+      error (_("gdb_pipe_cloexec: %s"), safe_strerror (errno));
+  }
+
+  ~scoped_pipe ()
+  {
+    if (m_pipe[0] >= 0)
+      close (m_pipe[0]);
+    if (m_pipe[1] >= 0)
+      close (m_pipe[1]);
+  }
+
+  DISABLE_COPY_AND_ASSIGN (scoped_pipe);
+
+  /* Get the read end of the pipe.  */
+  int get_read_end () const noexcept
+  {
+    return m_pipe[0];
+  }
+
+  /* Get the write end of the pipe.  */
+  int get_write_end () const noexcept
+  {
+    return m_pipe[1];
+  }
+
+private:
+  int m_pipe[2];
+};
+
+#endif /* ! GDBSUPPORT_SCOPED_PIPE_H */
--
2.24.1

Reply | Threaded
Open this post in threaded view
|

[PATCH v2 2/5] Don't reset errno/bfd_error on 'throw_perror_with_name'

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
Even though this patch is not necessarily needed by the main feature,
I think it's a good idea to have it.

We currently have this code on 'throw_perror_with_name':

  /* I understand setting these is a matter of taste.  Still, some people
     may clear errno but not know about bfd_error.  Doing this here is not
     unreasonable.  */
  bfd_set_error (bfd_error_no_error);
  errno = 0;

git blame tells me that this piece of code is pretty old; the commit
that "introduced" it is:

  commit c906108c21474dfb4ed285bcc0ac6fe02cd400cc
  Author: Stan Shebs <[hidden email]>
  Date:   Fri Apr 16 01:35:26 1999 +0000

      Initial creation of sourceware repository

so yeah...

If we go to the POSIX specification for 'perror', it doesn't really
say anything about whether errno should be preserved or not.  It does,
however, say that 'perror's messages should be the same as those
returned by 'strerror', and 'strerror' is not supposed to alter errno
if the call is successful.

Maybe when our wrapper was written it was OK to modify errno, I don't
know.  But I'd like to propose that we stick to POSIX in this case.

gdb/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

        * utils.c (throw_perror_with_name): Don't reset
        errno/bfd_error.
---
 gdb/utils.c | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/gdb/utils.c b/gdb/utils.c
index 0b470120a2..df8add1afa 100644
--- a/gdb/utils.c
+++ b/gdb/utils.c
@@ -595,12 +595,6 @@ throw_perror_with_name (enum errors errcode, const char *string)
 {
   std::string combined = perror_string (string);
 
-  /* I understand setting these is a matter of taste.  Still, some people
-     may clear errno but not know about bfd_error.  Doing this here is not
-     unreasonable.  */
-  bfd_set_error (bfd_error_no_error);
-  errno = 0;
-
   throw_error (errcode, _("%s."), combined.c_str ());
 }
 
--
2.24.1

Reply | Threaded
Open this post in threaded view
|

[PATCH v2 3/5] Expand 'fork_inferior' to check whether 'traceme_fun' succeeded

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
This patch is one important piece of the series.  It expands
'fork_inferior' in order to deal with new steps in the process of
initializing the inferior.  We now have to:

- Create a pipe that will be used to communicate with our
  fork (pre-exec), and which the fork will use to pass back to us the
  errno value of the 'traceme_fun' call.

- Close this pipe after it is used.

- Check the errno value passed back from the fork, and report any
  problems in the initialization to the user.

I thought about and implemented a few designs for all of this, but
ended up sticking with the function overload one.  'fork_inferior' is
now two functions: one that will take a traceme function like
'(*traceme_fun) ()' --- i.e., the original 'fork_inferior' behaviour,
and other that will take a function like '(*traceme_fun) (int
trace_pipe_write)'.  Depending on which function it takes, we know
whether the user does not want us to check whether the 'traceme_fun'
call was successful (former) or if she does (latter).

All in all, the patch is not complicated to understand and keeps the
interface clean enough so that we don't have to update every caller of
'fork_inferior' (which was a problem with previous designs I tried).

The subsequent patch will build on top of this one and implement the
errno-passing-via-pipe on the GNU/Linux target.

gdb/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

         * nat/fork-inferior.c: Include "gdbsupport/scoped_pipe.h".
         (default_trace_me_fail_reason): New function.
         (trace_me_fail_reason): New variable.
         (write_trace_errno_to_pipe): New function.
         (read_trace_errno_from_pipe): Likewise.
         (check_child_trace_me_errno): Likewise.
         (traceme_info): New struct.
         (fork_inferior_1): Renamed from 'fork_inferior'.
         (fork_inferior): New overloads.
         (trace_start_error_with_name): Add "append" parameter.
         * nat/fork-inferior.h (fork_inferior): Expand comment.
         Add overload declaration.
         (trace_start_error_with_name): Add "append" parameter.
         (trace_me_fail_reason): New variable.
         (check_child_trace_me_errno): New function.
         (write_trace_errno_to_pipe): Likewise.
---
 gdb/nat/fork-inferior.c | 231 ++++++++++++++++++++++++++++++++++++----
 gdb/nat/fork-inferior.h |  87 ++++++++++++---
 2 files changed, 288 insertions(+), 30 deletions(-)

diff --git a/gdb/nat/fork-inferior.c b/gdb/nat/fork-inferior.c
index 1185ef8998..223ff44195 100644
--- a/gdb/nat/fork-inferior.c
+++ b/gdb/nat/fork-inferior.c
@@ -27,6 +27,7 @@
 #include "gdbsupport/pathstuff.h"
 #include "gdbsupport/signals-state-save-restore.h"
 #include "gdbsupport/gdb_tilde_expand.h"
+#include "gdbsupport/scoped_pipe.h"
 #include <vector>
 
 extern char **environ;
@@ -262,16 +263,157 @@ execv_argv::init_for_shell (const char *exec_file,
   m_argv.push_back (NULL);
 }
 
-/* See nat/fork-inferior.h.  */
+/* Default implementation of 'trace_me_fail_reason'.  Always return
+   an empty string.  */
 
-pid_t
-fork_inferior (const char *exec_file_arg, const std::string &allargs,
-       char **env, void (*traceme_fun) (),
-       gdb::function_view<void (int)> init_trace_fun,
-       void (*pre_trace_fun) (),
-       const char *shell_file_arg,
-               void (*exec_fun)(const char *file, char * const *argv,
-                                char * const *env))
+static std::string
+default_trace_me_fail_reason (int err)
+{
+  return {};
+}
+
+/* See fork-inferior.h.  */
+
+std::string (*trace_me_fail_reason) (int err)
+  = default_trace_me_fail_reason;
+
+/* See fork-inferior.h.  */
+
+void
+write_trace_errno_to_pipe (int writepipe, int trace_errno)
+{
+  ssize_t writeret;
+
+  do
+    {
+      writeret = write (writepipe, &trace_errno, sizeof (trace_errno));
+    }
+  while (writeret < 0 && (errno == EAGAIN || errno == EINTR));
+
+  if (writeret < 0)
+    error (_("Could not write trace errno: %s"), safe_strerror (errno));
+}
+
+/* Helper function to read TRACE_ERRNO from READPIPE, which handles
+   EINTR/EAGAIN and throws and exception if there was an error.  */
+
+static int
+read_trace_errno_from_pipe (int readpipe)
+{
+  ssize_t readret;
+  int trace_errno;
+
+  do
+    {
+      readret = read (readpipe, &trace_errno, sizeof (trace_errno));
+    }
+  while (readret < 0 && (errno == EAGAIN || errno == EINTR));
+
+  if (readret < 0)
+    error (_("Could not read trace errno: %s"), safe_strerror (errno));
+
+  return trace_errno;
+}
+
+/* See fork-inferior.h.  */
+
+void
+check_child_trace_me_errno (int readpipe)
+{
+  fd_set rset;
+  struct timeval timeout;
+  int ret;
+
+  /* Make sure we have a valid 'trace_me_fail_reason' function
+     defined.  */
+  gdb_assert (trace_me_fail_reason != nullptr);
+
+  FD_ZERO (&rset);
+  FD_SET (readpipe, &rset);
+
+  /* Five seconds should be plenty of time to wait for the child's
+     reply.  */
+  timeout.tv_sec = 5;
+  timeout.tv_usec = 0;
+
+  do
+    {
+      ret = select (readpipe + 1, &rset, NULL, NULL, &timeout);
+    }
+  while (ret < 0 && (errno == EAGAIN || errno == EINTR));
+
+  if (ret < 0)
+    perror_with_name ("select");
+  else if (ret == 0)
+    error (_("Timeout while waiting for child's trace errno"));
+  else
+    {
+      int child_errno;
+
+      child_errno = read_trace_errno_from_pipe (readpipe);
+
+      if (child_errno != 0)
+ {
+  /* The child can't use TRACE_TRACEME.  We have to check whether
+     we know the reason for the failure, and then error out.  */
+  std::string reason = trace_me_fail_reason (child_errno);
+
+  if (reason.empty ())
+    reason = "Could not determine reason for trace failure.";
+
+  /* The child is supposed to display a warning containing the
+     safe_strerror message before us, so we just display the
+     possible reason for the failure.  */
+  error ("%s", reason.c_str ());
+ }
+    }
+}
+
+/* Helper struct for fork_inferior_1, containing information on
+   whether we should check if TRACEME_FUN was successfully called or
+   not.  */
+
+struct traceme_info
+{
+  /* True if we should check whether the call to 'traceme_fun
+     (TRACE_ME...)' succeeded or not. */
+  bool check_trace_me_fail_reason;
+
+  union
+  {
+    /* The non-check version of TRACEME_FUN.  It will be set if
+       CHECK_TRACEME_FAIL_REASON is false.
+
+       This function will usually just perform the call to whatever
+       trace function needed to start tracing the inferior (e.g.,
+       ptrace).  */
+    void (*traceme_fun_nocheck) ();
+
+    /* The check version of TRACEME_FUN.  It will be set if
+       CHECK_TRACEME_FAIL_REASON is true.
+
+       This function will usually perform the call to whatever trace
+       function needed to start tracing the inferior, but will also
+       write its errno value to TRACE_ERRNO_PIPE, so that
+       fork_inferior_1 can check whether it suceeded.  */
+    void (*traceme_fun_check) (int trace_errno_pipe);
+  } u;
+};
+
+/* Helper function.
+
+   Depending on the value of TRACEME_INFO.CHECK_TRACEME_FAIL_REASON,
+   this function will check whether the call to TRACEME_FUN succeeded
+   or not.  */
+
+static pid_t
+fork_inferior_1 (const char *exec_file_arg, const std::string &allargs,
+ char **env, const struct traceme_info traceme_info,
+ gdb::function_view<void (int)> init_trace_fun,
+ void (*pre_trace_fun) (),
+ const char *shell_file_arg,
+ void (*exec_fun)(const char *file, char * const *argv,
+  char * const *env))
 {
   pid_t pid;
   /* Set debug_fork then attach to the child while it sleeps, to debug.  */
@@ -283,6 +425,7 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
   int save_errno;
   const char *inferior_cwd;
   std::string expanded_inferior_cwd;
+  scoped_pipe trace_pipe;
 
   /* If no exec file handed to us, get it from the exec-file command
      -- with a good, common error message if none is specified.  */
@@ -365,12 +508,6 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
 
   if (pid == 0)
     {
-      /* Close all file descriptors except those that gdb inherited
- (usually 0/1/2), so they don't leak to the inferior.  Note
- that this closes the file descriptors of all secondary
- UIs.  */
-      close_most_fds ();
-
       /* Change to the requested working directory if the user
  requested it.  */
       if (inferior_cwd != NULL)
@@ -392,7 +529,10 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
          for the inferior.  */
 
       /* "Trace me, Dr. Memory!"  */
-      (*traceme_fun) ();
+      if (traceme_info.check_trace_me_fail_reason)
+ (*traceme_info.u.traceme_fun_check) (trace_pipe.get_write_end ());
+      else
+ (*traceme_info.u.traceme_fun_nocheck) ();
 
       /* The call above set this process (the "child") as debuggable
         by the original gdb process (the "parent").  Since processes
@@ -403,6 +543,12 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
         saying "not parent".  Sorry; you'll have to use print
         statements!  */
 
+      /* Close all file descriptors except those that gdb inherited
+ (usually 0/1/2), so they don't leak to the inferior.  Note
+ that this closes the file descriptors of all secondary
+ UIs, and the trace errno pipe (if it's open).  */
+      close_most_fds ();
+
       restore_original_signals_state ();
 
       /* There is no execlpe call, so we have to set the environment
@@ -431,6 +577,13 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
       _exit (0177);
     }
 
+  if (traceme_info.check_trace_me_fail_reason)
+    {
+      /* Check the trace errno, and inform the user about the reason
+ of the failure, if there was any.  */
+      check_child_trace_me_errno (trace_pipe.get_read_end ());
+    }
+
   /* Restore our environment in case a vforked child clob'd it.  */
   environ = save_our_env;
 
@@ -448,6 +601,48 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
   return pid;
 }
 
+/* See fork-inferior.h.  */
+
+pid_t
+fork_inferior (const char *exec_file_arg, const std::string &allargs,
+       char **env, void (*traceme_fun) (),
+       gdb::function_view<void (int)> init_trace_fun,
+       void (*pre_trace_fun) (),
+       const char *shell_file_arg,
+               void (*exec_fun)(const char *file, char * const *argv,
+                                char * const *env))
+{
+  struct traceme_info traceme_info;
+
+  traceme_info.check_trace_me_fail_reason = false;
+  traceme_info.u.traceme_fun_nocheck = traceme_fun;
+
+  return fork_inferior_1 (exec_file_arg, allargs, env, traceme_info,
+  init_trace_fun, pre_trace_fun, shell_file_arg,
+  exec_fun);
+}
+
+/* See fork-inferior.h.  */
+
+pid_t
+fork_inferior (const char *exec_file_arg, const std::string &allargs,
+       char **env, void (*traceme_fun) (int trace_errno_pipe),
+       gdb::function_view<void (int)> init_trace_fun,
+       void (*pre_trace_fun) (),
+       const char *shell_file_arg,
+               void (*exec_fun)(const char *file, char * const *argv,
+                                char * const *env))
+{
+  struct traceme_info traceme_info;
+
+  traceme_info.check_trace_me_fail_reason = true;
+  traceme_info.u.traceme_fun_check = traceme_fun;
+
+  return fork_inferior_1 (exec_file_arg, allargs, env, traceme_info,
+  init_trace_fun, pre_trace_fun, shell_file_arg,
+  exec_fun);
+}
+
 /* See nat/fork-inferior.h.  */
 
 ptid_t
@@ -592,7 +787,7 @@ trace_start_error (const char *fmt, ...)
 /* See nat/fork-inferior.h.  */
 
 void
-trace_start_error_with_name (const char *string)
+trace_start_error_with_name (const char *string, const char *append)
 {
-  trace_start_error ("%s: %s", string, safe_strerror (errno));
+  trace_start_error ("%s: %s%s", string, safe_strerror (errno), append);
 }
diff --git a/gdb/nat/fork-inferior.h b/gdb/nat/fork-inferior.h
index cf6f137edd..b67215353f 100644
--- a/gdb/nat/fork-inferior.h
+++ b/gdb/nat/fork-inferior.h
@@ -32,17 +32,41 @@ struct process_stratum_target;
 #define START_INFERIOR_TRAPS_EXPECTED 1
 
 /* Start an inferior Unix child process and sets inferior_ptid to its
-   pid.  EXEC_FILE is the file to run.  ALLARGS is a string containing
-   the arguments to the program.  ENV is the environment vector to
-   pass.  SHELL_FILE is the shell file, or NULL if we should pick
-   one.  EXEC_FUN is the exec(2) function to use, or NULL for the default
-   one.  */
-
-/* This function is NOT reentrant.  Some of the variables have been
-   made static to ensure that they survive the vfork call.  */
+   pid.
+
+   EXEC_FILE is the file to run.
+
+   ALLARGS is a string containing the arguments to the program.
+
+   ENV is the environment vector to pass.
+
+   SHELL_FILE is the shell file, or NULL if we should pick one.
+
+   EXEC_FUN is the exec(2) function to use, or NULL for the default
+   one.
+
+   This function is NOT reentrant.  Some of the variables have been
+   made static to ensure that they survive the vfork call.
+
+   This function does not check whether the call to TRACEME_FUN
+   succeeded or not.  */
 extern pid_t fork_inferior (const char *exec_file_arg,
     const std::string &allargs,
-    char **env, void (*traceme_fun) (),
+    char **env,
+    void (*traceme_fun) (),
+    gdb::function_view<void (int)> init_trace_fun,
+    void (*pre_trace_fun) (),
+    const char *shell_file_arg,
+    void (*exec_fun) (const char *file,
+      char * const *argv,
+      char * const *env));
+
+/* Like fork_inferior above, but check whether the call to TRACEME_FUN
+   succeeded or not.  */
+extern pid_t fork_inferior (const char *exec_file_arg,
+    const std::string &allargs,
+    char **env,
+    void (*traceme_fun) (int trace_errno_pipe),
     gdb::function_view<void (int)> init_trace_fun,
     void (*pre_trace_fun) (),
     const char *shell_file_arg,
@@ -82,9 +106,48 @@ extern void trace_start_error (const char *fmt, ...)
   ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (1, 2);
 
 /* Like "trace_start_error", but the error message is constructed by
-   combining STRING with the system error message for errno.  This
-   function does not return.  */
-extern void trace_start_error_with_name (const char *string)
+   combining STRING with the system error message for errno, and
+   (optionally) with APPEND.  This function does not return.  */
+extern void trace_start_error_with_name (const char *string,
+ const char *append = "")
   ATTRIBUTE_NORETURN;
 
+/* Pointer to function which can be called by
+   'check_child_trace_me_errno' when we need to determine the reason
+   of a e.g. 'ptrace (PTRACE_ME, ...)' failure.  ERR is the ERRNO
+   value set by the failing ptrace call.
+
+   By default, the function returns an empty string (see
+   fork-inferior.c).
+
+   This pointer can be overriden by targets that want to personalize
+   the error message printed when trace fails (see linux-nat.c or
+   gdbserver/linux-low.c, for example).  */
+extern std::string (*trace_me_fail_reason) (int err);
+
+/* Check the "trace me" errno (generated when executing e.g. 'ptrace
+   (PTRACE_ME, ...)') of the child process that was created by
+   GDB/GDBserver when creating an inferior.  The errno value will be
+   passed via a pipe (see 'fork_inferior'), and READPIPE is the read
+   end of the pipe.
+
+   If possible (i.e., if 'trace_me_fail_reason' is defined by the
+   target), then we also try to determine the possible reason for a
+   failure.
+
+   The idea is to wait a few seconds (via 'select') until something is
+   written on READPIPE.  When that happens, we check if the child's
+   trace errno is different than 0.  If it is, we call the function
+   'trace_me_fail_reason' and try to obtain the reason for the
+   failure, and then throw an exception (with the reason as the
+   exception's message).
+
+   If nothing is written on the pipe, or if 'select' fails, we also
+   throw exceptions.  */
+extern void check_child_trace_me_errno (int readpipe);
+
+/* Helper function to write TRACE_ERRNO to WRITEPIPE, which handles
+   EINTR/EAGAIN and throws an exception if there was an error.  */
+extern void write_trace_errno_to_pipe (int writepipe, int trace_errno);
+
 #endif /* NAT_FORK_INFERIOR_H */
--
2.24.1

Reply | Threaded
Open this post in threaded view
|

[PATCH v2 4/5] Extend GNU/Linux to check for ptrace error

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
This patch implements the ptrace-errno-checking on the GNU/Linux
target (both native and remote).  It builds on top of the previous
'fork_inferior' extension patch.

The idea is to provide a new 'traceme_fun' for each ptrace backend,
which will accept a new integer argument representing the write end of
the ptrace status pipe (that was created in 'fork_inferior').  This
function will invoke the actual tracing syscall (which is 'ptrace' in
this case), get its errno value and write it back via the pipe.  You
can see examples of this new approach by looking at
'inf_ptrace_me' (GDB) or 'linux_ptrace_fun' (gdbserver).

The rest of the patch implements the necessary machinery to do
something useful with the errno information that we received from
'ptrace'.

In Fedora GDB, we carry the following patch:

  https://src.fedoraproject.org/rpms/gdb/blob/8ac06474ff1e2aa4920d14e0666b083eeaca8952/f/gdb-attach-fail-reasons-5of5.patch

Its purpose is to try to detect a specific scenario where SELinux's
'deny_ptrace' option is enabled, which prevents GDB from ptrace'ing in
order to debug the inferior (PTRACE_ATTACH and PTRACE_TRACEME will
fail with EACCES in this case).

I like the idea of improving error detection and providing more
information to the user (a simple "Permission denied" can be really
frustrating), but I don't fully agree with the way the patch was
implemented: it makes GDB link against libselinux only for the sake of
consulting the 'deny_ptrace' setting, and then prints a warning if
ptrace failed and this setting is on.

There is now a new function, 'linux_ptrace_restricted_fail_reason',
which does a few things to check what's wrong with ptrace:

  - It dlopen's "libselinux.so.1" and checks if the "deny_ptrace"
    option is enabled.

  - It reads the contents of "/proc/sys/kernel/yama/ptrace_scope" and
    checks if it's different than 0.

For each of these checks, if it succeeds, the user will see a message
informing about the restriction in place, and how it can be disabled.
For example, if "deny_ptrace" is enabled, the user will see:

  # gdb /usr/bin/true
  ...
  (gdb) run
  Starting program: /usr/bin/true
  warning: Could not trace the inferior process.
  warning: ptrace: Permission denied

  The SELinux 'deny_ptrace' option is enabled and preventing GDB
  from using 'ptrace'.  You can disable it by executing (as root):

    setsebool deny_ptrace off

  If you are debugging the inferior remotely, the ptrace restriction(s) must
  be disabled in the target system (e.g., where GDBserver is running).

In case "/proc/sys/kernel/yama/ptrace_scope" is > 0:

  # gdb /usr/bin/true
  ...
  (gdb) run
  Starting program: /usr/bin/true
  warning: Could not trace the inferior process.
  warning: ptrace: Operation not permitted

  The Linux kernel's Yama ptrace scope is in effect, which can prevent
  GDB from using 'ptrace'.  You can disable it by executing (as root):

    echo 0 > /proc/sys/kernel/yama/ptrace_scope

  If you are debugging the inferior remotely, the ptrace restriction(s) must
  be disabled in the target system (e.g., where GDBserver is running).

If both restrictions are enabled, both messages will show up.

This works for gdbserver as well, and actually fixes a latent bug I
found: when ptrace is restricted, gdbserver would hang due to an
unchecked ptrace call:

  # gdbserver :9988 /usr/bin/true
  gdbserver: linux_ptrace_test_ret_to_nx: Cannot PTRACE_TRACEME: Operation not permitted
  gdbserver: linux_ptrace_test_ret_to_nx: status 256 is not WIFSTOPPED!
  gdbserver: linux_ptrace_test_ret_to_nx: failed to kill child pid 2668100 No such process
  [ Here you would have to issue a C-c ]

Now, you will see:

  # gdbserver :9988 /usr/bin/true
  gdbserver: linux_ptrace_test_ret_to_nx: Cannot PTRACE_TRACEME: Permission denied
  gdbserver: linux_ptrace_test_ret_to_nx: status 256 is not WIFSTOPPED!
  gdbserver: linux_ptrace_test_ret_to_nx: failed to kill child pid 2766868 No such process
  gdbserver: Could not trace the inferior process.
  gdbserver: ptrace: Permission denied

  The SELinux 'deny_ptrace' option is enabled and preventing GDB
  from using 'ptrace'.  You can disable it by executing (as root):

    setsebool deny_ptrace off

  If you are debugging the inferior remotely, the ptrace restriction(s) need
  to be disabled in the target system (e.g., where GDBserver is running).
  Exiting.
  #

(I decided to keep all the other messages, even though I find them a
bit distracting).

If GDB can't determine the cause for the failure, it will still print
the generic error message which tells the user to check our
documentation:

  There might be restrictions preventing ptrace from working.  Please see
  the appendix "Linux kernel ptrace restrictions" in the GDB documentation
  for more details.
  If you are debugging the inferior remotely, the ptrace restriction(s) need
  to be disabled in the target system (e.g., where GDBserver is running).

This means that the series expands our documentation (in the next
patch) and creates a new appendix section named "Linux kernel ptrace
restrictions", with sub-sections for each possible restriction that
might be in place.

Notice how, on every message, we instruct the user to "do the right
thing" if gdbserver is being used.  This is because if the user
started gdbserver *before* any ptrace restriction was in place, and
then, for some reason, one or more restrictions get enabled, then the
error message will be displayed both on gdbserver *and* on the
connected GDB.  Since the user will be piloting GDB, it's important to
explicitly say that the ptrace restrictions are enabled in the target,
where gdbserver is running.

The current list of possible restrictions is:

  - SELinux's 'deny_ptrace' option (detected).

  - YAMA's /proc/sys/kernel/yama/ptrace_scope setting (detected).

  - seccomp on Docker containers (I couldn't find how to detect).

It's important to mention that all of this is Linux-specific; as far
as I know, SELinux, YAMA and seccomp are Linux-only features.

gdb/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

        * inf-ptrace.c: Include "nat/fork-inferior.h".
        (inf_ptrace_me): New parameter "trace_errno_wpipe".  Check
        "ptrace" errno.
        (inf_ptrace_target::attach): Rewrite to use
        "inf_ptrace_target::ptrace_attach".
        (inf_ptrace_target::ptrace_attach): New function, almost
        identical to the previous "inf_ptrace_target::attach".
        * inf-ptrace.h (struct inf_ptrace_target) <int ptrace_attach>:
        New method.
        * linux-nat.c: Include "nat/fork-inferior.h".
        (attach_proc_task_lwp_callback): Call
        "linux_ptrace_attach_fail_reason_lwp" instead of
        "linux_ptrace_attach_fail_reason_string".
        (linux_nat_target::attach): Save "ERRNO".  Pass it to
        "linux_ptrace_attach_fail_reason".
        (_initialize_linux_nat): Set "trace_me_fail_reason".
        * nat/linux-ptrace.c: Include "gdbsupport/gdb-dlfcn.h",
        "nat/fork-inferior.h" and "gdbsupport/filestuff.h".
        (selinux_ftype): New type.
        (linux_ptrace_restricted_fail_reason): New function.
        (linux_ptrace_attach_fail_reason_1): New function, renamed
        from "linux_ptrace_attach_fail_reason".
        (linux_ptrace_attach_fail_reason): New function.
        (linux_ptrace_attach_fail_reason_lwp): Likewise.
        (linux_ptrace_me_fail_reason): Likewise.
        (errno_pipe): New variable.
        (linux_child_function): Check "ptrace" errno.  Send it through
        the pipe.
        (linux_check_ptrace_features): Initialize pipe.  Check
        "ptrace" errno sent through the pipe.
        * nat/linux-ptrace.h (linux_ptrace_attach_fail_reason): New
        function.
        (linux_ptrace_attach_fail_reason_lwp): Likewise.
        (linux_ptrace_me_fail_reason): Likewise.
        * remote.c (extended_remote_target::attach): Check error
        message on PACKET_ERROR.
        (remote_target::extended_remote_run): Likewise.

gdbserver/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

        * linux-low.cc (linux_ptrace_fun): New parameter
        "trace_errno_wpipe".  Check "ptrace" errno.
        (attach_proc_task_lwp_callback): Call
        "linux_ptrace_attach_fail_reason_lwp" instead of
        "linux_ptrace_attach_fail_reason_string".
        (linux_process_target::attach): Likewise.
        (initialize_low): Set "trace_me_fail_reason".
        * server.cc (handle_v_attach): Check if "attach_inferior"
        succeeded.
        (handle_v_run): Likewise.
        * thread-db.cc (attach_thread): Call
        "linux_ptrace_attach_fail_reason_lwp" instead of
        "linux_ptrace_attach_fail_reason_string".
---
 gdb/inf-ptrace.c        |  34 +++++++-
 gdb/inf-ptrace.h        |   2 +
 gdb/linux-nat.c         |  24 +++---
 gdb/nat/fork-inferior.c |   6 +-
 gdb/nat/fork-inferior.h |   2 +-
 gdb/nat/linux-ptrace.c  | 178 ++++++++++++++++++++++++++++++++++++++--
 gdb/nat/linux-ptrace.h  |  27 ++++--
 gdb/remote.c            |  40 ++++++++-
 gdbserver/linux-low.cc  |  31 +++++--
 gdbserver/server.cc     |  38 ++++++++-
 gdbserver/thread-db.cc  |   2 +-
 11 files changed, 339 insertions(+), 45 deletions(-)

diff --git a/gdb/inf-ptrace.c b/gdb/inf-ptrace.c
index db17a76d94..941f019709 100644
--- a/gdb/inf-ptrace.c
+++ b/gdb/inf-ptrace.c
@@ -34,6 +34,7 @@
 #include "nat/fork-inferior.h"
 #include "utils.h"
 #include "gdbarch.h"
+#include "nat/fork-inferior.h"
 
 
 
@@ -97,10 +98,23 @@ inf_ptrace_target::remove_fork_catchpoint (int pid)
 /* Prepare to be traced.  */
 
 static void
-inf_ptrace_me (void)
+inf_ptrace_me (int trace_errno_wpipe)
 {
   /* "Trace me, Dr. Memory!"  */
-  if (ptrace (PT_TRACE_ME, 0, (PTRACE_TYPE_ARG3) 0, 0) < 0)
+  int ret = ptrace (PT_TRACE_ME, 0, (PTRACE_TYPE_ARG3) 0, 0);
+  int ptrace_errno = ret < 0 ? errno : 0;
+
+  try
+    {
+      write_trace_errno_to_pipe (trace_errno_wpipe, ptrace_errno);
+    }
+  catch (const gdb_exception &e)
+    {
+      warning ("%s", e.what ());
+      _exit (0177);
+    }
+
+  if (ret < 0)
     trace_start_error_with_name ("ptrace");
 }
 
@@ -185,6 +199,18 @@ inf_ptrace_target::mourn_inferior ()
 
 void
 inf_ptrace_target::attach (const char *args, int from_tty)
+{
+   errno = ptrace_attach (args, from_tty);
+   if (errno != 0)
+     perror_with_name (("ptrace"));
+}
+
+/* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
+   be chatty about it.  Return ERRNO if the call to ptrace failed; 0
+   otherwise.  */
+
+int
+inf_ptrace_target::ptrace_attach (const char *args, int from_tty)
 {
   pid_t pid;
   struct inferior *inf;
@@ -223,7 +249,7 @@ inf_ptrace_target::attach (const char *args, int from_tty)
   errno = 0;
   ptrace (PT_ATTACH, pid, (PTRACE_TYPE_ARG3)0, 0);
   if (errno != 0)
-    perror_with_name (("ptrace"));
+    return errno;
 #else
   error (_("This system does not support attaching to a process"));
 #endif
@@ -241,6 +267,8 @@ inf_ptrace_target::attach (const char *args, int from_tty)
   set_executing (this, thr->ptid, true);
 
   unpusher.release ();
+
+  return 0;
 }
 
 #ifdef PT_GET_PROCESS_STATE
diff --git a/gdb/inf-ptrace.h b/gdb/inf-ptrace.h
index dd0733736f..ca36ca3af3 100644
--- a/gdb/inf-ptrace.h
+++ b/gdb/inf-ptrace.h
@@ -31,6 +31,8 @@ struct inf_ptrace_target : public inf_child_target
 
   void attach (const char *, int) override;
 
+  int ptrace_attach (const char *, int);
+
   void detach (inferior *inf, int) override;
 
   void resume (ptid_t, int, enum gdb_signal) override;
diff --git a/gdb/linux-nat.c b/gdb/linux-nat.c
index 81af83c4ac..cc044ee3ac 100644
--- a/gdb/linux-nat.c
+++ b/gdb/linux-nat.c
@@ -31,6 +31,7 @@
 #include "nat/linux-ptrace.h"
 #include "nat/linux-procfs.h"
 #include "nat/linux-personality.h"
+#include "nat/fork-inferior.h"
 #include "linux-fork.h"
 #include "gdbthread.h"
 #include "gdbcmd.h"
@@ -1136,7 +1137,7 @@ attach_proc_task_lwp_callback (ptid_t ptid)
   else
     {
       std::string reason
- = linux_ptrace_attach_fail_reason_string (ptid, err);
+ = linux_ptrace_attach_fail_reason_lwp (ptid, err);
 
       warning (_("Cannot attach to lwp %d: %s"),
        lwpid, reason.c_str ());
@@ -1185,20 +1186,15 @@ linux_nat_target::attach (const char *args, int from_tty)
   /* Make sure we report all signals during attach.  */
   pass_signals ({});
 
-  try
-    {
-      inf_ptrace_target::attach (args, from_tty);
-    }
-  catch (const gdb_exception_error &ex)
+  int err = inf_ptrace_target::ptrace_attach (args, from_tty);
+
+  if (err != 0)
     {
       pid_t pid = parse_pid_to_attach (args);
-      std::string reason = linux_ptrace_attach_fail_reason (pid);
+      std::string reason = linux_ptrace_attach_fail_reason (pid, err);
 
-      if (!reason.empty ())
- throw_error (ex.error, "warning: %s\n%s", reason.c_str (),
-     ex.what ());
-      else
- throw_error (ex.error, "%s", ex.what ());
+      error (_("warning: ptrace: %s\n%s"),
+       safe_strerror (err), reason.c_str ());
     }
 
   /* The ptrace base target adds the main thread with (pid,0,0)
@@ -4582,6 +4578,10 @@ Enables printf debugging output."),
   sigemptyset (&blocked_mask);
 
   lwp_lwpid_htab_create ();
+
+  /* Set the proper function to generate a message when ptrace
+     fails.  */
+  trace_me_fail_reason = linux_ptrace_me_fail_reason;
 }
 
 
diff --git a/gdb/nat/fork-inferior.c b/gdb/nat/fork-inferior.c
index 223ff44195..eb4c4625d7 100644
--- a/gdb/nat/fork-inferior.c
+++ b/gdb/nat/fork-inferior.c
@@ -394,9 +394,9 @@ struct traceme_info
 
        This function will usually perform the call to whatever trace
        function needed to start tracing the inferior, but will also
-       write its errno value to TRACE_ERRNO_PIPE, so that
+       write its errno value to TRACE_ERRNO_WPIPE, so that
        fork_inferior_1 can check whether it suceeded.  */
-    void (*traceme_fun_check) (int trace_errno_pipe);
+    void (*traceme_fun_check) (int trace_errno_wpipe);
   } u;
 };
 
@@ -626,7 +626,7 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
 
 pid_t
 fork_inferior (const char *exec_file_arg, const std::string &allargs,
-       char **env, void (*traceme_fun) (int trace_errno_pipe),
+       char **env, void (*traceme_fun) (int trace_errno_wpipe),
        gdb::function_view<void (int)> init_trace_fun,
        void (*pre_trace_fun) (),
        const char *shell_file_arg,
diff --git a/gdb/nat/fork-inferior.h b/gdb/nat/fork-inferior.h
index b67215353f..3fbead2e33 100644
--- a/gdb/nat/fork-inferior.h
+++ b/gdb/nat/fork-inferior.h
@@ -66,7 +66,7 @@ extern pid_t fork_inferior (const char *exec_file_arg,
 extern pid_t fork_inferior (const char *exec_file_arg,
     const std::string &allargs,
     char **env,
-    void (*traceme_fun) (int trace_errno_pipe),
+    void (*traceme_fun) (int trace_errno_wpipe),
     gdb::function_view<void (int)> init_trace_fun,
     void (*pre_trace_fun) (),
     const char *shell_file_arg,
diff --git a/gdb/nat/linux-ptrace.c b/gdb/nat/linux-ptrace.c
index 5335d69092..b3fcf8bc07 100644
--- a/gdb/nat/linux-ptrace.c
+++ b/gdb/nat/linux-ptrace.c
@@ -21,6 +21,9 @@
 #include "linux-procfs.h"
 #include "linux-waitpid.h"
 #include "gdbsupport/buffer.h"
+#include "gdbsupport/gdb-dlfcn.h"
+#include "nat/fork-inferior.h"
+#include "gdbsupport/filestuff.h"
 #ifdef HAVE_SYS_PROCFS_H
 #include <sys/procfs.h>
 #endif
@@ -30,11 +33,93 @@
    of 0 means there are no supported features.  */
 static int supported_ptrace_options = -1;
 
-/* Find all possible reasons we could fail to attach PID and return these
-   as a string.  An empty string is returned if we didn't find any reason.  */
+typedef int (*selinux_ftype) (const char *);
 
-std::string
-linux_ptrace_attach_fail_reason (pid_t pid)
+/* Helper function which checks if ptrace is probably restricted
+   (i.e., if ERR is either EACCES or EPERM), and returns a string with
+   possible workarounds.  */
+
+static std::string
+linux_ptrace_restricted_fail_reason (int err)
+{
+  if (err != EACCES && err != EPERM)
+    {
+      /* It just makes sense to perform the checks below if errno was
+ either EACCES or EPERM.  */
+      return {};
+    }
+
+  std::string ret;
+  gdb_dlhandle_up handle;
+
+  try
+    {
+      handle = gdb_dlopen ("libselinux.so.1");
+    }
+  catch (const gdb_exception_error &e)
+    {
+    }
+
+  if (handle != nullptr)
+    {
+      selinux_ftype selinux_get_bool
+ = (selinux_ftype) gdb_dlsym (handle, "security_get_boolean_active");
+
+      if (selinux_get_bool != NULL
+  && (*selinux_get_bool) ("deny_ptrace") == 1)
+ string_appendf (ret,
+ _("\n\
+The SELinux 'deny_ptrace' option is enabled and preventing GDB\n\
+from using 'ptrace'.  You can disable it by executing (as root):\n\
+\n\
+  setsebool deny_ptrace off\n"));
+    }
+
+  gdb_file_up yama_ptrace_scope
+    = gdb_fopen_cloexec ("/proc/sys/kernel/yama/ptrace_scope", "r");
+
+  if (yama_ptrace_scope != nullptr)
+    {
+      char yama_scope = fgetc (yama_ptrace_scope.get ());
+
+      if (yama_scope != '0')
+ string_appendf (ret,
+ _("\n\
+The Linux kernel's Yama ptrace scope is in effect, which can prevent\n\
+GDB from using 'ptrace'.  You can disable it by executing (as root):\n\
+\n\
+  echo 0 > /proc/sys/kernel/yama/ptrace_scope\n"));
+    }
+
+  if (ret.empty ())
+    {
+      /* It wasn't possible to determine the exact reason for the
+ ptrace error.  Let's just emit a generic error message
+ pointing the user to our documentation, where she can find
+ instructions on how to try to diagnose the problem.  */
+      ret = _("\n\
+There might be restrictions preventing ptrace from working.  Please see\n\
+the appendix \"Linux kernel ptrace restrictions\" in the GDB documentation\n\
+for more details.");
+    }
+
+  /* The user may be debugging remotely, so we have to warn that
+     the instructions above should be performed in the target.  */
+  string_appendf (ret,
+  _("\n\
+If you are debugging the inferior remotely, the ptrace restriction(s) must\n\
+be disabled in the target system (e.g., where GDBserver is running)."));
+
+  return ret;
+}
+
+/* Find all possible reasons we could fail to attach PID and return
+   these as a string.  An empty string is returned if we didn't find
+   any reason.  Helper for linux_ptrace_attach_fail_reason and
+   linux_ptrace_attach_fail_reason_lwp.  */
+
+static std::string
+linux_ptrace_attach_fail_reason_1 (pid_t pid)
 {
   pid_t tracerpid = linux_proc_get_tracerpid_nowarn (pid);
   std::string result;
@@ -56,10 +141,24 @@ linux_ptrace_attach_fail_reason (pid_t pid)
 /* See linux-ptrace.h.  */
 
 std::string
-linux_ptrace_attach_fail_reason_string (ptid_t ptid, int err)
+linux_ptrace_attach_fail_reason (pid_t pid, int err)
+{
+  std::string result = linux_ptrace_attach_fail_reason_1 (pid);
+  std::string ptrace_restrict = linux_ptrace_restricted_fail_reason (err);
+
+  if (!ptrace_restrict.empty ())
+    result += "\n" + ptrace_restrict;
+
+  return result;
+}
+
+/* See linux-ptrace.h.  */
+
+std::string
+linux_ptrace_attach_fail_reason_lwp (ptid_t ptid, int err)
 {
   long lwpid = ptid.lwp ();
-  std::string reason = linux_ptrace_attach_fail_reason (lwpid);
+  std::string reason = linux_ptrace_attach_fail_reason_1 (lwpid);
 
   if (!reason.empty ())
     return string_printf ("%s (%d), %s", safe_strerror (err), err,
@@ -68,6 +167,14 @@ linux_ptrace_attach_fail_reason_string (ptid_t ptid, int err)
     return string_printf ("%s (%d)", safe_strerror (err), err);
 }
 
+/* See linux-ptrace.h.  */
+
+std::string
+linux_ptrace_me_fail_reason (int err)
+{
+  return linux_ptrace_restricted_fail_reason (err);
+}
+
 #if defined __i386__ || defined __x86_64__
 
 /* Address of the 'ret' instruction in asm code block below.  */
@@ -257,6 +364,12 @@ linux_ptrace_test_ret_to_nx (void)
 #endif /* defined __i386__ || defined __x86_64__ */
 }
 
+/* If the PTRACE_TRACEME call on linux_child_function errors, we need
+   to be able to send ERRNO back to the parent so that it can check
+   whether there are restrictions in place preventing ptrace from
+   working.  We do that with a pipe.  */
+static int errno_pipe[2];
+
 /* Helper function to fork a process and make the child process call
    the function FUNCTION, passing CHILD_STACK as parameter.
 
@@ -321,7 +434,30 @@ linux_grandchild_function (void *child_stack)
 static int
 linux_child_function (void *child_stack)
 {
-  ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);
+  /* Close read end.  */
+  close (errno_pipe[0]);
+
+  int ret = ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
+    (PTRACE_TYPE_ARG4) 0);
+  int ptrace_errno = ret < 0 ? errno : 0;
+
+  /* Write ERRNO to the pipe, even if it's zero, and close the writing
+     end of the pipe.  */
+  try
+    {
+      write_trace_errno_to_pipe (errno_pipe[1], ptrace_errno);
+    }
+  catch (const gdb_exception &e)
+    {
+      warning ("%s", e.what ());
+      _exit (0177);
+    }
+
+  close (errno_pipe[1]);
+
+  if (ret != 0)
+    trace_start_error_with_name ("ptrace");
+
   kill (getpid (), SIGSTOP);
 
   /* Fork a grandchild.  */
@@ -346,12 +482,40 @@ linux_check_ptrace_features (void)
   /* Initialize the options.  */
   supported_ptrace_options = 0;
 
+  /* Initialize our pipe.  */
+  if (gdb_pipe_cloexec (errno_pipe) < 0)
+    perror_with_name ("gdb_pipe_cloexec");
+
   /* Fork a child so we can do some testing.  The child will call
      linux_child_function and will get traced.  The child will
      eventually fork a grandchild so we can test fork event
      reporting.  */
   child_pid = linux_fork_to_function (NULL, linux_child_function);
 
+  /* We don't need the write end of the pipe anymore.  */
+  close (errno_pipe[1]);
+
+  try
+    {
+      /* Check whether 'ptrace (PTRACE_ME, ...)' failed when being
+ invoked by the child.  If it did, we might get the
+ possible reason for it as the exception message.  */
+      check_child_trace_me_errno (errno_pipe[0]);
+    }
+  catch (const gdb_exception &e)
+    {
+      /* Close the pipe so we don't leak fd's.  */
+      close (errno_pipe[0]);
+
+      /* A failure here means that PTRACE_ME failed, which means that
+ GDB/gdbserver will most probably not work correctly.  If we
+ want to be pedantic, we could just call 'exit' here.
+ However, let's just re-throw the exception.  */
+      throw;
+    }
+
+  close (errno_pipe[0]);
+
   ret = my_waitpid (child_pid, &status, 0);
   if (ret == -1)
     perror_with_name (("waitpid"));
diff --git a/gdb/nat/linux-ptrace.h b/gdb/nat/linux-ptrace.h
index 65568301f2..7cb77114ca 100644
--- a/gdb/nat/linux-ptrace.h
+++ b/gdb/nat/linux-ptrace.h
@@ -176,12 +176,27 @@ struct buffer;
 # define TRAP_HWBKPT 4
 #endif
 
-extern std::string linux_ptrace_attach_fail_reason (pid_t pid);
-
-/* Find all possible reasons we could have failed to attach to PTID
-   and return them as a string.  ERR is the error PTRACE_ATTACH failed
-   with (an errno).  */
-extern std::string linux_ptrace_attach_fail_reason_string (ptid_t ptid, int err);
+/* Find all possible reasons we could fail to attach PID and return
+   these as a string.  An empty string is returned if we didn't find
+   any reason.  If ERR is EACCES or EPERM, we also add a warning about
+   possible restrictions to use ptrace.  */
+extern std::string linux_ptrace_attach_fail_reason (pid_t pid, int err);
+
+/* Find all possible reasons we could have failed to attach to PID's
+   LWPID and return them as a string.  ERR is the error PTRACE_ATTACH
+   failed with (an errno).  Unlike linux_ptrace_attach_fail_reason,
+   this function should be used when attaching to an LWP other than
+   the leader; it does not warn about ptrace restrictions.  */
+extern std::string linux_ptrace_attach_fail_reason_lwp (ptid_t pid, int err);
+
+/* When the call to 'ptrace (PTRACE_TRACEME...' fails, and we have
+   already forked, this function can be called in order to try to
+   obtain the reason why ptrace failed.  ERR should be the ERRNO value
+   returned by ptrace.
+
+   This function will return a 'std::string' containing the fail
+   reason, or an empty string otherwise.  */
+extern std::string linux_ptrace_me_fail_reason (int err);
 
 extern void linux_ptrace_init_warnings (void);
 extern void linux_check_ptrace_features (void);
diff --git a/gdb/remote.c b/gdb/remote.c
index 0f78b1be1b..aacbdf1984 100644
--- a/gdb/remote.c
+++ b/gdb/remote.c
@@ -5882,9 +5882,26 @@ extended_remote_target::attach (const char *args, int from_tty)
       break;
     case PACKET_UNKNOWN:
       error (_("This target does not support attaching to a process"));
+    case PACKET_ERROR:
+      {
+ std::string errmsg = rs->buf.data ();
+
+ /* Check if we have a specific error (i.e., not a generic
+   "E01") coming from the target.  If there is, we print it
+   here.  */
+ if (startswith (errmsg.c_str (), "E."))
+  {
+    /* Get rid of the "E." prefix.  */
+    errmsg.erase (0, 2);
+  }
+
+ error (_("Attaching to %s failed%s%s"),
+       target_pid_to_str (ptid_t (pid)).c_str (),
+       !errmsg.empty () ? "\n" : "",
+       errmsg.c_str ());
+      }
     default:
-      error (_("Attaching to %s failed"),
-     target_pid_to_str (ptid_t (pid)).c_str ());
+      gdb_assert_not_reached (_("bad switch"));
     }
 
   set_current_inferior (remote_add_inferior (false, pid, 1, 0));
@@ -10024,8 +10041,23 @@ remote_target::extended_remote_run (const std::string &args)
  error (_("Running the default executable on the remote target failed; "
  "try \"set remote exec-file\"?"));
       else
- error (_("Running \"%s\" on the remote target failed"),
-       remote_exec_file);
+ {
+  std::string errmsg = rs->buf.data ();
+
+  /* Check if we have a specific error (i.e., not a generic
+     "E01") coming from the target.  If there is, we print it
+     here.  */
+  if (startswith (errmsg.c_str (), "E."))
+    {
+      /* Get rid of the "E." prefix.  */
+      errmsg.erase (0, 2);
+    }
+
+  error (_("Running \"%s\" on the remote target failed%s%s"),
+ remote_exec_file,
+ !errmsg.empty () ? "\n" : "",
+ errmsg.c_str ());
+ }
     default:
       gdb_assert_not_reached (_("bad switch"));
     }
diff --git a/gdbserver/linux-low.cc b/gdbserver/linux-low.cc
index 2872bc78da..42283802dd 100644
--- a/gdbserver/linux-low.cc
+++ b/gdbserver/linux-low.cc
@@ -968,10 +968,24 @@ add_lwp (ptid_t ptid)
    actually initiating the tracing of the inferior.  */
 
 static void
-linux_ptrace_fun ()
+linux_ptrace_fun (int ptrace_errno_wpipe)
 {
-  if (ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
-      (PTRACE_TYPE_ARG4) 0) < 0)
+  int ret = ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
+    (PTRACE_TYPE_ARG4) 0);
+  int ptrace_errno = ret < 0 ? errno : 0;
+
+  try
+    {
+      write_trace_errno_to_pipe (ptrace_errno_wpipe, ptrace_errno);
+    }
+  catch (const gdb_exception &e)
+    {
+      warning ("%s", e.what ());
+      _exit (0177);
+    }
+
+  errno = ptrace_errno;
+  if (ret < 0)
     trace_start_error_with_name ("ptrace");
 
   if (setpgid (0, 0) < 0)
@@ -1170,7 +1184,7 @@ attach_proc_task_lwp_callback (ptid_t ptid)
       else if (err != 0)
  {
   std::string reason
-    = linux_ptrace_attach_fail_reason_string (ptid, err);
+    = linux_ptrace_attach_fail_reason_lwp (ptid, err);
 
   warning (_("Cannot attach to lwp %d: %s"), lwpid, reason.c_str ());
  }
@@ -1202,8 +1216,8 @@ linux_process_target::attach (unsigned long pid)
     {
       remove_process (proc);
 
-      std::string reason = linux_ptrace_attach_fail_reason_string (ptid, err);
-      error ("Cannot attach to process %ld: %s", pid, reason.c_str ());
+      std::string reason = linux_ptrace_attach_fail_reason (pid, err);
+      error (_("Cannot attach to process %ld: %s"), pid, reason.c_str ());
     }
 
   /* Don't ignore the initial SIGSTOP if we just attached to this
@@ -7552,5 +7566,10 @@ initialize_low (void)
 
   initialize_low_arch ();
 
+  /* Initialize the 'trace_me_fail_reason' function pointer.  We will
+     use this to determine the reason for possible failures when
+     invoking 'ptrace (PTRACE_ME, ...)'.  */
+  trace_me_fail_reason = linux_ptrace_me_fail_reason;
+
   linux_check_ptrace_features ();
 }
diff --git a/gdbserver/server.cc b/gdbserver/server.cc
index 43962adc86..003385f42a 100644
--- a/gdbserver/server.cc
+++ b/gdbserver/server.cc
@@ -2892,9 +2892,31 @@ handle_v_attach (char *own_buf)
 {
   client_state &cs = get_client_state ();
   int pid;
+  int ret;
 
   pid = strtol (own_buf + 8, NULL, 16);
-  if (pid != 0 && attach_inferior (pid) == 0)
+
+  if (pid <= 0)
+    {
+      write_enn (own_buf);
+      return 0;
+    }
+
+  try
+    {
+      /* Attach to the specified PID.  This function can throw, so we
+ make sure to catch the exception and send it (as an error
+ packet) back to GDB.  */
+      ret = attach_inferior (pid);
+    }
+  catch (const gdb_exception_error &e)
+    {
+      fprintf (stderr, "%s\n", e.what ());
+      snprintf (own_buf, PBUFSIZ, "E.%s", e.what ());
+      return 0;
+    }
+
+  if (ret == 0)
     {
       /* Don't report shared library events after attaching, even if
  some libraries are preloaded.  GDB will always poll the
@@ -3030,7 +3052,19 @@ handle_v_run (char *own_buf)
   free_vector_argv (program_args);
   program_args = new_argv;
 
-  target_create_inferior (program_path.get (), program_args);
+  try
+    {
+      /* Create the inferior.  This function can throw, so we make
+ sure to catch the exception and send it (as an error packet)
+ back to GDB.  */
+      target_create_inferior (program_path.get (), program_args);
+    }
+  catch (const gdb_exception_error &e)
+    {
+      fprintf (stderr, "%s\n", e.what ());
+      snprintf (own_buf, PBUFSIZ, "E.%s", e.what ());
+      return 0;
+    }
 
   if (cs.last_status.kind == TARGET_WAITKIND_STOPPED)
     {
diff --git a/gdbserver/thread-db.cc b/gdbserver/thread-db.cc
index 2bb6d28820..60ceb7b663 100644
--- a/gdbserver/thread-db.cc
+++ b/gdbserver/thread-db.cc
@@ -224,7 +224,7 @@ attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p)
   err = linux_attach_lwp (ptid);
   if (err != 0)
     {
-      std::string reason = linux_ptrace_attach_fail_reason_string (ptid, err);
+      std::string reason = linux_ptrace_attach_fail_reason_lwp (ptid, err);
 
       warning ("Could not attach to thread %ld (LWP %d): %s",
        (unsigned long) ti_p->ti_tid, ti_p->ti_lid, reason.c_str ());
--
2.24.1

Reply | Threaded
Open this post in threaded view
|

[PATCH v2 5/5] Document Linux-specific possible ptrace restrictions

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
This patch creates a new "Linux kernel ptrace restrictions" which
documents possible causes that can be prevent the inferior from being
correctly started/debugged.

This has been pre-approved by Eli.

gdb/doc/ChangeLog:
yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>

        * gdb.texinfo (Linux kernel ptrace restrictions): New appendix
        section.
---
 gdb/doc/gdb.texinfo | 136 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 136 insertions(+)

diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo
index 385c832f22..0a6c6f6df6 100644
--- a/gdb/doc/gdb.texinfo
+++ b/gdb/doc/gdb.texinfo
@@ -182,6 +182,9 @@ software in general.  We will miss him.
                                 @value{GDBN}
 * Operating System Information:: Getting additional information from
                                  the operating system
+* Linux kernel ptrace restrictions::        Restrictions sometimes
+                                            imposed by the Linux
+                                            kernel on @code{ptrace}
 * Trace File Format:: GDB trace file format
 * Index Section Format::        .gdb_index section format
 * Man Pages:: Manual pages
@@ -45656,6 +45659,139 @@ should contain a comma-separated list of cores that this process
 is running on.  Target may provide additional columns,
 which @value{GDBN} currently ignores.
 
+@node Linux kernel ptrace restrictions
+@appendix Linux kernel @code{ptrace} restrictions
+@cindex linux kernel ptrace restrictions, attach
+
+The @code{ptrace} system call is used by @value{GDBN} and
+@code{gdbserver} on GNU/Linux to, among other things, attach to a new
+or existing inferior in order to start debugging it.  Due to security
+concerns, some distributions and vendors disable or severely restrict
+the ability to perform these operations, which can make @value{GDBN}
+or @code{gdbserver} malfunction.  In this section, we will expand on
+how this malfunction can manifest itself, and how to modify the
+system's settings in order to be able to use @value{GDBN} and
+@code{gdbserver} properly.
+
+@menu
+* The error message::                   The error message displayed when the
+                                        system prevents @value{GDBN}
+                                        or @code{gdbserver} from using
+                                        @code{ptrace}
+* SELinux's deny_ptrace::               SELinux and the @code{deny_ptrace} option
+* Yama's ptrace_scope::                 Yama and the @code{ptrace_scope} setting
+* Docker and seccomp::                  Docker and the @code{seccomp}
+                                        infrastructure
+@end menu
+
+@node The error message
+@appendixsection The error message
+
+When the system prevents @value{GDBN} or @code{gdbserver} from using
+the @code{ptrace} system call, you will likely see a descriptive error
+message explaining what is wrong and how to attempt to fix the
+problem.  For example, when SELinux's @code{deny_ptrace} option is
+enabled, you can see:
+
+@smallexample
+$ gdb program
+...
+(@value{GDBP}) run
+Starting program: program
+warning: Could not trace the inferior process.
+Error:
+warning: ptrace: Permission denied
+The SELinux 'deny_ptrace' option is enabled and preventing @value{GDBN}
+from using 'ptrace'.  You can disable it by executing (as root):
+
+  setsebool deny_ptrace off
+
+If you are debugging the inferior remotely, the instruction(s) above must
+be performed in the target system (e.g., where GDBserver is running).
+During startup program exited with code 127.
+(@value{GDBP})
+@end smallexample
+
+Sometimes, it may not be possible to acquire the necessary data to
+determine the root cause of the failure.  In this case, you will see a
+generic error message pointing you to this section:
+
+@smallexample
+$ gdb program
+...
+Starting program: program
+warning: Could not trace the inferior process.
+Error:
+warning: ptrace: Permission denied
+There might be restrictions preventing ptrace from working.  Please see
+the appendix "Linux kernel ptrace restrictions" in the GDB documentation
+for more details.
+During startup program exited with code 127.
+(@value{GDBP})
+@end smallexample
+
+@node SELinux's deny_ptrace
+@appendixsection SELinux's @code{deny_ptrace}
+@cindex SELinux
+@cindex deny_ptrace
+
+If you are using SELinux, you might want to check whether the
+@code{deny_ptrace} option is enabled by doing:
+
+@smallexample
+$ getsebool deny_ptrace
+deny_ptrace --> on
+@end smallexample
+
+If the option is enabled, you can disable it by doing, as root:
+
+@smallexample
+# setsebool deny_ptrace off
+@end smallexample
+
+The option will be disabled until the next reboot.  If you would like
+to disable it permanently, you can do (as root):
+
+@smallexample
+# setsebool -P deny_ptrace off
+@end smallexample
+
+@node Yama's ptrace_scope
+@appendixsection Yama's @code{ptrace_scope}
+@cindex yama, ptrace_scope
+
+If your system has Yama enabled, you might want to check whether the
+@code{ptrace_scope} setting is enabled by checking the value of
+@file{/proc/sys/kernel/yama/ptrace_scope}:
+
+@smallexample
+$ cat /proc/sys/kernel/yama/ptrace_scope
+0
+@end smallexample
+
+If you see anything other than @code{0}, @value{GDBN} or
+@code{gdbserver} can be affected by it.  You can temporarily disable
+the feature by doing, as root:
+
+@smallexample
+# sysctl -w kernel.yama.ptrace_scope=0
+kernel.yama.ptrace_scope = 0
+@end smallexample
+
+@node Docker and seccomp
+@appendixsection Docker and @code{seccomp}
+@cindex docker, seccomp
+
+If you are using Docker (@uref{https://www.docker.com/}) containers,
+you will probably have to disable its @code{seccomp} protections in
+order to be able to use @value{GDBN} or @code{gdbserver}.  To do that,
+you can use the options @code{--cap-add=SYS_PTRACE --security-opt
+seccomp=unconfined} when invoking Docker:
+
+@smallexample
+$ docker run --cap-add=SYS_PTRACE --security-opt seccomp=unconfined
+@end smallexample
+
 @node Trace File Format
 @appendix Trace File Format
 @cindex trace file format
--
2.24.1

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 0/5] Improve ptrace-error detection

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
Hi Sergio,

I'm still reviewing this patch set, but noticed the following during testing:

< PASS: gdb.base/attach-twice.exp: attach
---
> XFAIL: gdb.base/attach-twice.exp: attach

and:

< PASS: gdb.base/attach.exp: do_attach_failure_tests: fail to attach again
---
> FAIL: gdb.base/attach.exp: do_attach_failure_tests: fail to attach again

For gdb.base/attach-twice.exp, the relevant sections of the log files look
like this:

(gdb) spawn /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice
attach 1113400
Attaching to program: /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice, process 1113400
warning: process 1113400 is already traced by process 1113405
ptrace: Operation not permitted.
(gdb) PASS: gdb.base/attach-twice.exp: attach

Versus:

(gdb) spawn /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice
attach 1113182
Attaching to program: /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice, process 1113182
warning: ptrace: Operation not permitted
process 1113182 is already traced by process 1113187

There might be restrictions preventing ptrace from working.  Please see
the appendix "Linux kernel ptrace restrictions" in the GDB documentation
for more details.
If you are debugging the inferior remotely, the ptrace restriction(s) must
be disabled in the target system (e.g., where GDBserver is running).
(gdb) XFAIL: gdb.base/attach-twice.exp: attach

It seems to me that this should still PASS; I think the regex for that
test simply needs to be updated.  (You could also add another case.)

I've also looked at the logs for gdb.base/attach.exp.  The output is
similar to that shown above.  Again, I think that the regex needs to
be updated.

If it's the case that the old output might still be produced by some
platforms, care must be taken to ensure that both cases (still) pass.

Kevin

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 0/5] Improve ptrace-error detection

Sourceware - gdb-patches mailing list
On Thursday, March 19 2020, Kevin Buettner wrote:

> Hi Sergio,

Hey Kevin,

Thanks for the review.

> I'm still reviewing this patch set, but noticed the following during testing:
>
> < PASS: gdb.base/attach-twice.exp: attach
> ---
>> XFAIL: gdb.base/attach-twice.exp: attach
>
> and:
>
> < PASS: gdb.base/attach.exp: do_attach_failure_tests: fail to attach again
> ---
>> FAIL: gdb.base/attach.exp: do_attach_failure_tests: fail to attach again
>
> For gdb.base/attach-twice.exp, the relevant sections of the log files look
> like this:
>
> (gdb) spawn /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice
> attach 1113400
> Attaching to program: /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice, process 1113400
> warning: process 1113400 is already traced by process 1113405
> ptrace: Operation not permitted.
> (gdb) PASS: gdb.base/attach-twice.exp: attach
>
> Versus:
>
> (gdb) spawn /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice
> attach 1113182
> Attaching to program: /mesquite2/sourceware-git/f31-ptrace-error-detection/bld/gdb/testsuite/outputs/gdb.base/attach-twice/attach-twice, process 1113182
> warning: ptrace: Operation not permitted
> process 1113182 is already traced by process 1113187

> There might be restrictions preventing ptrace from working.  Please see
> the appendix "Linux kernel ptrace restrictions" in the GDB documentation
> for more details.
> If you are debugging the inferior remotely, the ptrace restriction(s) must
> be disabled in the target system (e.g., where GDBserver is running).
> (gdb) XFAIL: gdb.base/attach-twice.exp: attach

Ah, good catch.  I can reproduce these here (obviously), which makes me
wonder why I missed them.  I think I may have looked at them and thought
they were racy.

> It seems to me that this should still PASS; I think the regex for that
> test simply needs to be updated.  (You could also add another case.)

Yeah.

> I've also looked at the logs for gdb.base/attach.exp.  The output is
> similar to that shown above.  Again, I think that the regex needs to
> be updated.

You know, I thought it was just going to be a matter of expanding the
regexp in order to match the extra text, but then I started thinking if
there was a better way to do this.  I mean, in these two specific cases
(attach.exp and attach-twice.exp) we *know* what is wrong: we're trying
to attach twice to the same process.  So GDB knows this is the problem,
and when we print the whole "There might be restrictions preventing
ptrace from working..." text, it can confuse the user.

Looking at nat/linux-ptrace.c:linux_ptrace_attach_fail_reason, I see
that my patch is currently doing:

  std::string
  linux_ptrace_attach_fail_reason (pid_t pid, int err)
  {
    std::string result = linux_ptrace_attach_fail_reason_1 (pid);
    std::string ptrace_restrict = linux_ptrace_restricted_fail_reason (err);

   if (!ptrace_restrict.empty ())
     result += "\n" + ptrace_restrict;

IOW, it's always appending the result of
"linux_ptrace_restricted_fail_reason" to the string that will be
printed.  Upon a closer inspection of
"linux_ptrace_attach_fail_reason_1"'s comment, we see:

  /* Find all possible reasons we could fail to attach PID and return
     these as a string.  An empty string is returned if we didn't find
     any reason.  Helper for linux_ptrace_attach_fail_reason and
     linux_ptrace_attach_fail_reason_lwp.  */

  static std::string
  linux_ptrace_attach_fail_reason_1 (pid_t pid)

IOW, if the string returned by it is not empty, it means that the
function was able to determine the reason for the ptrace failure.

After seeing this, I decided that the best approach is to call
"linux_ptrace_restricted_fail_reason" only if
"linux_ptrace_attach_fail_reason_1" returns an empty string.

With this, the output generated when the user tries to attach twice to
the same process is kept minimal and concise.

It was still necessary to make a small adjustment in both testcases
because the order of the warnings was reversed: we now first print the
message saying that the process is already attached to GDB, and then
print the ptrace strerror string.

> If it's the case that the old output might still be produced by some
> platforms, care must be taken to ensure that both cases (still) pass.

Right.  I believe that with the change I described above it won't be
necessary to worry about arch-specific cases.

Thanks,

--
Sergio
GPG key ID: 237A 54B1 0287 28BF 00EF  31F4 D0EB 7628 65FC 5E36
Please send encrypted e-mail if possible
http://sergiodj.net/

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 3/5] Expand 'fork_inferior' to check whether 'traceme_fun' succeeded

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
Hi Sergio,

See my comments below.

On Tue, 17 Mar 2020 11:47:17 -0400
Sergio Durigan Junior <[hidden email]> wrote:

> +      if (child_errno != 0)
> + {
> +  /* The child can't use TRACE_TRACEME.  We have to check whether
> +     we know the reason for the failure, and then error out.  */
> +  std::string reason = trace_me_fail_reason (child_errno);

I think you mean PTRACE_TRACEME in the comment, right?

[...]
> +/* Helper struct for fork_inferior_1, containing information on
> +   whether we should check if TRACEME_FUN was successfully called or
> +   not.  */
> +
> +struct traceme_info
> +{
> +  /* True if we should check whether the call to 'traceme_fun
> +     (TRACE_ME...)' succeeded or not. */
> +  bool check_trace_me_fail_reason;

While reading the patch, I noticed that some things have "traceme" or
"TRACEME" in the their names while others instead use "trace_me" or
"TRACE_ME".  While it's already the case that GDB is inconsistent in
this regard, I think it might be a good to not propogate that
inconsistency further.

It's likely that this came about due to the two differently named
constants used with ptrace(), i.e. PTRACE_TRACEME and PT_TRACE_ME.
Since these constants are used on different platforms, I don't think
there's any way we can reconcile these.  But for, for names that we
pick, I think we should choose either "traceme" or "trace_me" and stick
with it.

I prefer "traceme" / "TRACEME", but won't object though if you choose
the other option.

> +
> +  union
> +  {
> +    /* The non-check version of TRACEME_FUN.  It will be set if
> +       CHECK_TRACEME_FAIL_REASON is false.

"CHECK_TRACEME_FAIL_REASON" in this comment doesn't match the
declaration above in which check_trace_me_fail_reason (with the _
between "trace" and "me") is used instead.  There are several
instances; I'll only point out this one.

[...]

> +/* Pointer to function which can be called by
> +   'check_child_trace_me_errno' when we need to determine the reason
> +   of a e.g. 'ptrace (PTRACE_ME, ...)' failure.  ERR is the ERRNO
> +   value set by the failing ptrace call.
> +
> +   By default, the function returns an empty string (see
> +   fork-inferior.c).
> +
> +   This pointer can be overriden by targets that want to personalize
> +   the error message printed when trace fails (see linux-nat.c or
> +   gdbserver/linux-low.c, for example).  */
> +extern std::string (*trace_me_fail_reason) (int err);

On my first pass through this patch, I had concerns about the
introduction of this global variable.  (That's why I asked for a
new set of patches.)  I can't think of a better way to do it though.

Kevin

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 3/5] Expand 'fork_inferior' to check whether 'traceme_fun' succeeded

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
On 3/17/20 3:47 PM, Sergio Durigan Junior via Gdb-patches wrote:

> This patch is one important piece of the series.  It expands
> 'fork_inferior' in order to deal with new steps in the process of
> initializing the inferior.  We now have to:
>
> - Create a pipe that will be used to communicate with our
>   fork (pre-exec), and which the fork will use to pass back to us the
>   errno value of the 'traceme_fun' call.
>
> - Close this pipe after it is used.
>
> - Check the errno value passed back from the fork, and report any
>   problems in the initialization to the user.
>
> I thought about and implemented a few designs for all of this, but
> ended up sticking with the function overload one.  'fork_inferior' is
> now two functions: one that will take a traceme function like
> '(*traceme_fun) ()' --- i.e., the original 'fork_inferior' behaviour,
> and other that will take a function like '(*traceme_fun) (int
> trace_pipe_write)'.  Depending on which function it takes, we know
> whether the user does not want us to check whether the 'traceme_fun'
> call was successful (former) or if she does (latter).

Pedantically: user -> caller.  she -> it.  "user" normally refers to
a person who uses gdb.

> All in all, the patch is not complicated to understand and keeps the
> interface clean enough so that we don't have to update every caller of
> 'fork_inferior' (which was a problem with previous designs I tried).
>
> The subsequent patch will build on top of this one and implement the
> errno-passing-via-pipe on the GNU/Linux target.
>
> gdb/ChangeLog:
> yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>
>
> * nat/fork-inferior.c: Include "gdbsupport/scoped_pipe.h".
> (default_trace_me_fail_reason): New function.
> (trace_me_fail_reason): New variable.
> (write_trace_errno_to_pipe): New function.
> (read_trace_errno_from_pipe): Likewise.
> (check_child_trace_me_errno): Likewise.
> (traceme_info): New struct.
> (fork_inferior_1): Renamed from 'fork_inferior'.
> (fork_inferior): New overloads.
> (trace_start_error_with_name): Add "append" parameter.
> * nat/fork-inferior.h (fork_inferior): Expand comment.
> Add overload declaration.
> (trace_start_error_with_name): Add "append" parameter.
> (trace_me_fail_reason): New variable.
> (check_child_trace_me_errno): New function.
> (write_trace_errno_to_pipe): Likewise.
> ---
>  gdb/nat/fork-inferior.c | 231 ++++++++++++++++++++++++++++++++++++----
>  gdb/nat/fork-inferior.h |  87 ++++++++++++---
>  2 files changed, 288 insertions(+), 30 deletions(-)
>
> diff --git a/gdb/nat/fork-inferior.c b/gdb/nat/fork-inferior.c
> index 1185ef8998..223ff44195 100644
> --- a/gdb/nat/fork-inferior.c
> +++ b/gdb/nat/fork-inferior.c
> @@ -27,6 +27,7 @@
>  #include "gdbsupport/pathstuff.h"
>  #include "gdbsupport/signals-state-save-restore.h"
>  #include "gdbsupport/gdb_tilde_expand.h"
> +#include "gdbsupport/scoped_pipe.h"
>  #include <vector>
>  
>  extern char **environ;
> @@ -262,16 +263,157 @@ execv_argv::init_for_shell (const char *exec_file,
>    m_argv.push_back (NULL);
>  }
>  
> -/* See nat/fork-inferior.h.  */
> +/* Default implementation of 'trace_me_fail_reason'.  Always return
> +   an empty string.  */
>  
> -pid_t
> -fork_inferior (const char *exec_file_arg, const std::string &allargs,
> -       char **env, void (*traceme_fun) (),
> -       gdb::function_view<void (int)> init_trace_fun,
> -       void (*pre_trace_fun) (),
> -       const char *shell_file_arg,
> -               void (*exec_fun)(const char *file, char * const *argv,
> -                                char * const *env))
> +static std::string
> +default_trace_me_fail_reason (int err)
> +{
> +  return {};
> +}
> +
> +/* See fork-inferior.h.  */
> +
> +std::string (*trace_me_fail_reason) (int err)
> +  = default_trace_me_fail_reason;
> +
> +/* See fork-inferior.h.  */
> +
> +void
> +write_trace_errno_to_pipe (int writepipe, int trace_errno)
> +{
> +  ssize_t writeret;
> +
> +  do
> +    {
> +      writeret = write (writepipe, &trace_errno, sizeof (trace_errno));
> +    }
> +  while (writeret < 0 && (errno == EAGAIN || errno == EINTR));
> +
> +  if (writeret < 0)
> +    error (_("Could not write trace errno: %s"), safe_strerror (errno));

I'll have a comment about this error in a following patch.


> +}
> +
> +/* Helper function to read TRACE_ERRNO from READPIPE, which handles
> +   EINTR/EAGAIN and throws and exception if there was an error.  */
> +
> +static int
> +read_trace_errno_from_pipe (int readpipe)
> +{
> +  ssize_t readret;
> +  int trace_errno;
> +
> +  do
> +    {
> +      readret = read (readpipe, &trace_errno, sizeof (trace_errno));
> +    }
> +  while (readret < 0 && (errno == EAGAIN || errno == EINTR));
> +
> +  if (readret < 0)
> +    error (_("Could not read trace errno: %s"), safe_strerror (errno));
> +
> +  return trace_errno;
> +}
> +
> +/* See fork-inferior.h.  */
> +
> +void
> +check_child_trace_me_errno (int readpipe)
> +{
> +  fd_set rset;
> +  struct timeval timeout;
> +  int ret;
> +
> +  /* Make sure we have a valid 'trace_me_fail_reason' function
> +     defined.  */
> +  gdb_assert (trace_me_fail_reason != nullptr);
> +
> +  FD_ZERO (&rset);
> +  FD_SET (readpipe, &rset);
> +
> +  /* Five seconds should be plenty of time to wait for the child's
> +     reply.  */
> +  timeout.tv_sec = 5;
> +  timeout.tv_usec = 0;
> +
> +  do
> +    {
> +      ret = select (readpipe + 1, &rset, NULL, NULL, &timeout);
> +    }
> +  while (ret < 0 && (errno == EAGAIN || errno == EINTR));
> +
> +  if (ret < 0)
> +    perror_with_name ("select");
> +  else if (ret == 0)
> +    error (_("Timeout while waiting for child's trace errno"));
> +  else
> +    {
> +      int child_errno;
> +
> +      child_errno = read_trace_errno_from_pipe (readpipe);
> +
> +      if (child_errno != 0)
> + {
> +  /* The child can't use TRACE_TRACEME.  We have to check whether
> +     we know the reason for the failure, and then error out.  */
> +  std::string reason = trace_me_fail_reason (child_errno);
> +
> +  if (reason.empty ())
> +    reason = "Could not determine reason for trace failure.";

Missing i18n.

> +
> +  /* The child is supposed to display a warning containing the
> +     safe_strerror message before us, so we just display the
> +     possible reason for the failure.  */
> +  error ("%s", reason.c_str ());
> + }
> +    }
> +}
> +
> +/* Helper struct for fork_inferior_1, containing information on
> +   whether we should check if TRACEME_FUN was successfully called or
> +   not.  */

"was successfully called" seems ambiguous -- I first read it as,
"whether we managed to call TRACEME_FUN", which is not what you meant,
since we always call it.

It'd suggest:

 "should check whether TRACEME_FUN succeeded tracing the child"

> +
> +struct traceme_info
> +{
> +  /* True if we should check whether the call to 'traceme_fun
> +     (TRACE_ME...)' succeeded or not. */
> +  bool check_trace_me_fail_reason;
> +
> +  union
> +  {
> +    /* The non-check version of TRACEME_FUN.  It will be set if
> +       CHECK_TRACEME_FAIL_REASON is false.
> +
> +       This function will usually just perform the call to whatever
> +       trace function needed to start tracing the inferior (e.g.,
> +       ptrace).  */
> +    void (*traceme_fun_nocheck) ();
> +
> +    /* The check version of TRACEME_FUN.  It will be set if
> +       CHECK_TRACEME_FAIL_REASON is true.
> +
> +       This function will usually perform the call to whatever trace
> +       function needed to start tracing the inferior, but will also
> +       write its errno value to TRACE_ERRNO_PIPE, so that
> +       fork_inferior_1 can check whether it suceeded.  */

Typo: "suceeded" -> "succeeded".

I'd drop the "usually" both places.  It's not usually, it's always.

> +    void (*traceme_fun_check) (int trace_errno_pipe);
> +  } u;
> +};
> +
> +/* Helper function.
> +
> +   Depending on the value of TRACEME_INFO.CHECK_TRACEME_FAIL_REASON,
> +   this function will check whether the call to TRACEME_FUN succeeded
> +   or not.  */
> +
> +static pid_t
> +fork_inferior_1 (const char *exec_file_arg, const std::string &allargs,
> + char **env, const struct traceme_info traceme_info,
> + gdb::function_view<void (int)> init_trace_fun,
> + void (*pre_trace_fun) (),
> + const char *shell_file_arg,
> + void (*exec_fun)(const char *file, char * const *argv,
> +  char * const *env))
>  {
>    pid_t pid;
>    /* Set debug_fork then attach to the child while it sleeps, to debug.  */
> @@ -283,6 +425,7 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>    int save_errno;
>    const char *inferior_cwd;
>    std::string expanded_inferior_cwd;
> +  scoped_pipe trace_pipe;

You could wrap this in a gdb::optional to avoid creating the pipe
unless necessary.  Like:

  gdb::optional<scoped_pipe> trace_pipe;
  if (traceme_info.check_trace_me_fail_reason)
    trace_pipe.emplace ();

>  
>    /* If no exec file handed to us, get it from the exec-file command
>       -- with a good, common error message if none is specified.  */
> @@ -365,12 +508,6 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>  
>    if (pid == 0)
>      {
> -      /* Close all file descriptors except those that gdb inherited
> - (usually 0/1/2), so they don't leak to the inferior.  Note
> - that this closes the file descriptors of all secondary
> - UIs.  */
> -      close_most_fds ();
> -
>        /* Change to the requested working directory if the user
>   requested it.  */
>        if (inferior_cwd != NULL)
> @@ -392,7 +529,10 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>           for the inferior.  */
>  
>        /* "Trace me, Dr. Memory!"  */
> -      (*traceme_fun) ();
> +      if (traceme_info.check_trace_me_fail_reason)
> + (*traceme_info.u.traceme_fun_check) (trace_pipe.get_write_end ());
> +      else
> + (*traceme_info.u.traceme_fun_nocheck) ();
>  
>        /* The call above set this process (the "child") as debuggable
>          by the original gdb process (the "parent").  Since processes
> @@ -403,6 +543,12 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>          saying "not parent".  Sorry; you'll have to use print
>          statements!  */
>  
> +      /* Close all file descriptors except those that gdb inherited
> + (usually 0/1/2), so they don't leak to the inferior.  Note
> + that this closes the file descriptors of all secondary
> + UIs, and the trace errno pipe (if it's open).  */
> +      close_most_fds ();
> +
>        restore_original_signals_state ();
>  
>        /* There is no execlpe call, so we have to set the environment
> @@ -431,6 +577,13 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>        _exit (0177);
>      }
>  
> +  if (traceme_info.check_trace_me_fail_reason)
> +    {
> +      /* Check the trace errno, and inform the user about the reason
> + of the failure, if there was any.  */
> +      check_child_trace_me_errno (trace_pipe.get_read_end ());
> +    }
> +

check_child_trace_me_errno can throw an error.  So it should be done after
we've restored all global state.  See the environ restore just below ...

>    /* Restore our environment in case a vforked child clob'd it.  */
>    environ = save_our_env;

... here.  You'd miss restoring this.

>  
> @@ -448,6 +601,48 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>    return pid;
>  }
>  
> +/* See fork-inferior.h.  */
> +
> +pid_t
> +fork_inferior (const char *exec_file_arg, const std::string &allargs,
> +       char **env, void (*traceme_fun) (),
> +       gdb::function_view<void (int)> init_trace_fun,
> +       void (*pre_trace_fun) (),
> +       const char *shell_file_arg,
> +               void (*exec_fun)(const char *file, char * const *argv,

Something odd with indentation here.  Likely tabs vs spaces.

> +                                char * const *env))
> +{
> +  struct traceme_info traceme_info;
> +
> +  traceme_info.check_trace_me_fail_reason = false;
> +  traceme_info.u.traceme_fun_nocheck = traceme_fun;
> +
> +  return fork_inferior_1 (exec_file_arg, allargs, env, traceme_info,
> +  init_trace_fun, pre_trace_fun, shell_file_arg,
> +  exec_fun);
> +}
> +
> +/* See fork-inferior.h.  */
> +
> +pid_t
> +fork_inferior (const char *exec_file_arg, const std::string &allargs,
> +       char **env, void (*traceme_fun) (int trace_errno_pipe),
> +       gdb::function_view<void (int)> init_trace_fun,
> +       void (*pre_trace_fun) (),
> +       const char *shell_file_arg,
> +               void (*exec_fun)(const char *file, char * const *argv,

Ditto re. indentation.


> +                                char * const *env))
> +{
> +  struct traceme_info traceme_info;
> +
> +  traceme_info.check_trace_me_fail_reason = true;
> +  traceme_info.u.traceme_fun_check = traceme_fun;
> +
> +  return fork_inferior_1 (exec_file_arg, allargs, env, traceme_info,
> +  init_trace_fun, pre_trace_fun, shell_file_arg,
> +  exec_fun);
> +}
> +
>  /* See nat/fork-inferior.h.  */
>  
>  ptid_t
> @@ -592,7 +787,7 @@ trace_start_error (const char *fmt, ...)
>  /* See nat/fork-inferior.h.  */
>  
>  void
> -trace_start_error_with_name (const char *string)
> +trace_start_error_with_name (const char *string, const char *append)
>  {
> -  trace_start_error ("%s: %s", string, safe_strerror (errno));
> +  trace_start_error ("%s: %s%s", string, safe_strerror (errno), append);
>  }
> diff --git a/gdb/nat/fork-inferior.h b/gdb/nat/fork-inferior.h
> index cf6f137edd..b67215353f 100644
> --- a/gdb/nat/fork-inferior.h
> +++ b/gdb/nat/fork-inferior.h
> @@ -32,17 +32,41 @@ struct process_stratum_target;
>  #define START_INFERIOR_TRAPS_EXPECTED 1
>  
>  /* Start an inferior Unix child process and sets inferior_ptid to its
> -   pid.  EXEC_FILE is the file to run.  ALLARGS is a string containing
> -   the arguments to the program.  ENV is the environment vector to
> -   pass.  SHELL_FILE is the shell file, or NULL if we should pick
> -   one.  EXEC_FUN is the exec(2) function to use, or NULL for the default
> -   one.  */
> -
> -/* This function is NOT reentrant.  Some of the variables have been
> -   made static to ensure that they survive the vfork call.  */
> +   pid.
> +
> +   EXEC_FILE is the file to run.
> +
> +   ALLARGS is a string containing the arguments to the program.
> +
> +   ENV is the environment vector to pass.
> +
> +   SHELL_FILE is the shell file, or NULL if we should pick one.
> +
> +   EXEC_FUN is the exec(2) function to use, or NULL for the default
> +   one.
> +
> +   This function is NOT reentrant.  Some of the variables have been
> +   made static to ensure that they survive the vfork call.
> +
> +   This function does not check whether the call to TRACEME_FUN
> +   succeeded or not.  */
>  extern pid_t fork_inferior (const char *exec_file_arg,
>      const std::string &allargs,
> -    char **env, void (*traceme_fun) (),
> +    char **env,
> +    void (*traceme_fun) (),
> +    gdb::function_view<void (int)> init_trace_fun,
> +    void (*pre_trace_fun) (),
> +    const char *shell_file_arg,
> +    void (*exec_fun) (const char *file,
> +      char * const *argv,
> +      char * const *env));
> +
> +/* Like fork_inferior above, but check whether the call to TRACEME_FUN
> +   succeeded or not.  */
> +extern pid_t fork_inferior (const char *exec_file_arg,
> +    const std::string &allargs,
> +    char **env,
> +    void (*traceme_fun) (int trace_errno_pipe),
>      gdb::function_view<void (int)> init_trace_fun,
>      void (*pre_trace_fun) (),
>      const char *shell_file_arg,
> @@ -82,9 +106,48 @@ extern void trace_start_error (const char *fmt, ...)
>    ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (1, 2);
>  
>  /* Like "trace_start_error", but the error message is constructed by
> -   combining STRING with the system error message for errno.  This
> -   function does not return.  */
> -extern void trace_start_error_with_name (const char *string)
> +   combining STRING with the system error message for errno, and
> +   (optionally) with APPEND.  This function does not return.  */
> +extern void trace_start_error_with_name (const char *string,
> + const char *append = "")
>    ATTRIBUTE_NORETURN;
>  
> +/* Pointer to function which can be called by
> +   'check_child_trace_me_errno' when we need to determine the reason
> +   of a e.g. 'ptrace (PTRACE_ME, ...)' failure.  ERR is the ERRNO
> +   value set by the failing ptrace call.
> +
> +   By default, the function returns an empty string (see
> +   fork-inferior.c).
> +
> +   This pointer can be overriden by targets that want to personalize
> +   the error message printed when trace fails (see linux-nat.c or
> +   gdbserver/linux-low.c, for example).  */
> +extern std::string (*trace_me_fail_reason) (int err);
> +
> +/* Check the "trace me" errno (generated when executing e.g. 'ptrace
> +   (PTRACE_ME, ...)') of the child process that was created by
> +   GDB/GDBserver when creating an inferior.  The errno value will be
> +   passed via a pipe (see 'fork_inferior'), and READPIPE is the read
> +   end of the pipe.
> +
> +   If possible (i.e., if 'trace_me_fail_reason' is defined by the
> +   target), then we also try to determine the possible reason for a
> +   failure.
> +
> +   The idea is to wait a few seconds (via 'select') until something is
> +   written on READPIPE.  When that happens, we check if the child's
> +   trace errno is different than 0.  If it is, we call the function
> +   'trace_me_fail_reason' and try to obtain the reason for the
> +   failure, and then throw an exception (with the reason as the
> +   exception's message).
> +
> +   If nothing is written on the pipe, or if 'select' fails, we also
> +   throw exceptions.  */
> +extern void check_child_trace_me_errno (int readpipe);
> +
> +/* Helper function to write TRACE_ERRNO to WRITEPIPE, which handles
> +   EINTR/EAGAIN and throws an exception if there was an error.  */
> +extern void write_trace_errno_to_pipe (int writepipe, int trace_errno);
> +
>  #endif /* NAT_FORK_INFERIOR_H */
>

Thanks,
Pedro Alves

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 4/5] Extend GNU/Linux to check for ptrace error

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
On 3/17/20 3:47 PM, Sergio Durigan Junior via Gdb-patches wrote:

> This patch implements the ptrace-errno-checking on the GNU/Linux
> target (both native and remote).  It builds on top of the previous
> 'fork_inferior' extension patch.
>
> The idea is to provide a new 'traceme_fun' for each ptrace backend,
> which will accept a new integer argument representing the write end of
> the ptrace status pipe (that was created in 'fork_inferior').  This
> function will invoke the actual tracing syscall (which is 'ptrace' in
> this case), get its errno value and write it back via the pipe.  You
> can see examples of this new approach by looking at
> 'inf_ptrace_me' (GDB) or 'linux_ptrace_fun' (gdbserver).
>
> The rest of the patch implements the necessary machinery to do
> something useful with the errno information that we received from
> 'ptrace'.
>
> In Fedora GDB, we carry the following patch:
>
>   https://src.fedoraproject.org/rpms/gdb/blob/8ac06474ff1e2aa4920d14e0666b083eeaca8952/f/gdb-attach-fail-reasons-5of5.patch
>
> Its purpose is to try to detect a specific scenario where SELinux's
> 'deny_ptrace' option is enabled, which prevents GDB from ptrace'ing in
> order to debug the inferior (PTRACE_ATTACH and PTRACE_TRACEME will
> fail with EACCES in this case).
>
> I like the idea of improving error detection and providing more
> information to the user (a simple "Permission denied" can be really
> frustrating), but I don't fully agree with the way the patch was
> implemented: it makes GDB link against libselinux only for the sake of
> consulting the 'deny_ptrace' setting, and then prints a warning if
> ptrace failed and this setting is on.
>
> There is now a new function, 'linux_ptrace_restricted_fail_reason',
> which does a few things to check what's wrong with ptrace:
>
>   - It dlopen's "libselinux.so.1" and checks if the "deny_ptrace"
>     option is enabled.
>
>   - It reads the contents of "/proc/sys/kernel/yama/ptrace_scope" and
>     checks if it's different than 0.
>
> For each of these checks, if it succeeds, the user will see a message
> informing about the restriction in place, and how it can be disabled.
> For example, if "deny_ptrace" is enabled, the user will see:
>
>   # gdb /usr/bin/true
>   ...
>   (gdb) run
>   Starting program: /usr/bin/true
>   warning: Could not trace the inferior process.
>   warning: ptrace: Permission denied
>
>   The SELinux 'deny_ptrace' option is enabled and preventing GDB
>   from using 'ptrace'.  You can disable it by executing (as root):
>
>     setsebool deny_ptrace off
>
>   If you are debugging the inferior remotely, the ptrace restriction(s) must
>   be disabled in the target system (e.g., where GDBserver is running).
>
> In case "/proc/sys/kernel/yama/ptrace_scope" is > 0:
>
>   # gdb /usr/bin/true
>   ...
>   (gdb) run
>   Starting program: /usr/bin/true
>   warning: Could not trace the inferior process.
>   warning: ptrace: Operation not permitted
>
>   The Linux kernel's Yama ptrace scope is in effect, which can prevent
>   GDB from using 'ptrace'.  You can disable it by executing (as root):
>
>     echo 0 > /proc/sys/kernel/yama/ptrace_scope
>
>   If you are debugging the inferior remotely, the ptrace restriction(s) must
>   be disabled in the target system (e.g., where GDBserver is running).
>
> If both restrictions are enabled, both messages will show up.
>
> This works for gdbserver as well, and actually fixes a latent bug I
> found: when ptrace is restricted, gdbserver would hang due to an
> unchecked ptrace call:
>
>   # gdbserver :9988 /usr/bin/true
>   gdbserver: linux_ptrace_test_ret_to_nx: Cannot PTRACE_TRACEME: Operation not permitted
>   gdbserver: linux_ptrace_test_ret_to_nx: status 256 is not WIFSTOPPED!
>   gdbserver: linux_ptrace_test_ret_to_nx: failed to kill child pid 2668100 No such process
>   [ Here you would have to issue a C-c ]
>
> Now, you will see:
>
>   # gdbserver :9988 /usr/bin/true
>   gdbserver: linux_ptrace_test_ret_to_nx: Cannot PTRACE_TRACEME: Permission denied
>   gdbserver: linux_ptrace_test_ret_to_nx: status 256 is not WIFSTOPPED!
>   gdbserver: linux_ptrace_test_ret_to_nx: failed to kill child pid 2766868 No such process
>   gdbserver: Could not trace the inferior process.
>   gdbserver: ptrace: Permission denied
>
>   The SELinux 'deny_ptrace' option is enabled and preventing GDB
>   from using 'ptrace'.  You can disable it by executing (as root):
>
>     setsebool deny_ptrace off
>
>   If you are debugging the inferior remotely, the ptrace restriction(s) need
>   to be disabled in the target system (e.g., where GDBserver is running).
>   Exiting.
>   #
>
> (I decided to keep all the other messages, even though I find them a
> bit distracting).
>
> If GDB can't determine the cause for the failure, it will still print
> the generic error message which tells the user to check our
> documentation:
>
>   There might be restrictions preventing ptrace from working.  Please see
>   the appendix "Linux kernel ptrace restrictions" in the GDB documentation
>   for more details.
>   If you are debugging the inferior remotely, the ptrace restriction(s) need
>   to be disabled in the target system (e.g., where GDBserver is running).
>
> This means that the series expands our documentation (in the next
> patch) and creates a new appendix section named "Linux kernel ptrace
> restrictions", with sub-sections for each possible restriction that
> might be in place.
>
> Notice how, on every message, we instruct the user to "do the right
> thing" if gdbserver is being used.  This is because if the user
> started gdbserver *before* any ptrace restriction was in place, and
> then, for some reason, one or more restrictions get enabled, then the
> error message will be displayed both on gdbserver *and* on the
> connected GDB.  Since the user will be piloting GDB, it's important to
> explicitly say that the ptrace restrictions are enabled in the target,
> where gdbserver is running.
>
> The current list of possible restrictions is:
>
>   - SELinux's 'deny_ptrace' option (detected).
>
>   - YAMA's /proc/sys/kernel/yama/ptrace_scope setting (detected).
>
>   - seccomp on Docker containers (I couldn't find how to detect).
>
> It's important to mention that all of this is Linux-specific; as far
> as I know, SELinux, YAMA and seccomp are Linux-only features.
>
> gdb/ChangeLog:
> yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>
>
> * inf-ptrace.c: Include "nat/fork-inferior.h".
> (inf_ptrace_me): New parameter "trace_errno_wpipe".  Check
> "ptrace" errno.
> (inf_ptrace_target::attach): Rewrite to use
> "inf_ptrace_target::ptrace_attach".
> (inf_ptrace_target::ptrace_attach): New function, almost
> identical to the previous "inf_ptrace_target::attach".
> * inf-ptrace.h (struct inf_ptrace_target) <int ptrace_attach>:
> New method.
> * linux-nat.c: Include "nat/fork-inferior.h".
> (attach_proc_task_lwp_callback): Call
> "linux_ptrace_attach_fail_reason_lwp" instead of
> "linux_ptrace_attach_fail_reason_string".
> (linux_nat_target::attach): Save "ERRNO".  Pass it to
> "linux_ptrace_attach_fail_reason".
> (_initialize_linux_nat): Set "trace_me_fail_reason".
> * nat/linux-ptrace.c: Include "gdbsupport/gdb-dlfcn.h",
> "nat/fork-inferior.h" and "gdbsupport/filestuff.h".
> (selinux_ftype): New type.
> (linux_ptrace_restricted_fail_reason): New function.
> (linux_ptrace_attach_fail_reason_1): New function, renamed
> from "linux_ptrace_attach_fail_reason".
> (linux_ptrace_attach_fail_reason): New function.
> (linux_ptrace_attach_fail_reason_lwp): Likewise.
> (linux_ptrace_me_fail_reason): Likewise.
> (errno_pipe): New variable.
> (linux_child_function): Check "ptrace" errno.  Send it through
> the pipe.
> (linux_check_ptrace_features): Initialize pipe.  Check
> "ptrace" errno sent through the pipe.
> * nat/linux-ptrace.h (linux_ptrace_attach_fail_reason): New
> function.
> (linux_ptrace_attach_fail_reason_lwp): Likewise.
> (linux_ptrace_me_fail_reason): Likewise.
> * remote.c (extended_remote_target::attach): Check error
> message on PACKET_ERROR.
> (remote_target::extended_remote_run): Likewise.
>
> gdbserver/ChangeLog:
> yyyy-mm-dd  Sergio Durigan Junior  <[hidden email]>
>
> * linux-low.cc (linux_ptrace_fun): New parameter
> "trace_errno_wpipe".  Check "ptrace" errno.
> (attach_proc_task_lwp_callback): Call
> "linux_ptrace_attach_fail_reason_lwp" instead of
> "linux_ptrace_attach_fail_reason_string".
> (linux_process_target::attach): Likewise.
> (initialize_low): Set "trace_me_fail_reason".
> * server.cc (handle_v_attach): Check if "attach_inferior"
> succeeded.
> (handle_v_run): Likewise.
> * thread-db.cc (attach_thread): Call
> "linux_ptrace_attach_fail_reason_lwp" instead of
> "linux_ptrace_attach_fail_reason_string".
> ---
>  gdb/inf-ptrace.c        |  34 +++++++-
>  gdb/inf-ptrace.h        |   2 +
>  gdb/linux-nat.c         |  24 +++---
>  gdb/nat/fork-inferior.c |   6 +-
>  gdb/nat/fork-inferior.h |   2 +-
>  gdb/nat/linux-ptrace.c  | 178 ++++++++++++++++++++++++++++++++++++++--
>  gdb/nat/linux-ptrace.h  |  27 ++++--
>  gdb/remote.c            |  40 ++++++++-
>  gdbserver/linux-low.cc  |  31 +++++--
>  gdbserver/server.cc     |  38 ++++++++-
>  gdbserver/thread-db.cc  |   2 +-
>  11 files changed, 339 insertions(+), 45 deletions(-)
>
> diff --git a/gdb/inf-ptrace.c b/gdb/inf-ptrace.c
> index db17a76d94..941f019709 100644
> --- a/gdb/inf-ptrace.c
> +++ b/gdb/inf-ptrace.c
> @@ -34,6 +34,7 @@
>  #include "nat/fork-inferior.h"
>  #include "utils.h"
>  #include "gdbarch.h"
> +#include "nat/fork-inferior.h"
>  
>  
>  
> @@ -97,10 +98,23 @@ inf_ptrace_target::remove_fork_catchpoint (int pid)
>  /* Prepare to be traced.  */
>  
>  static void
> -inf_ptrace_me (void)
> +inf_ptrace_me (int trace_errno_wpipe)
>  {
>    /* "Trace me, Dr. Memory!"  */
> -  if (ptrace (PT_TRACE_ME, 0, (PTRACE_TYPE_ARG3) 0, 0) < 0)
> +  int ret = ptrace (PT_TRACE_ME, 0, (PTRACE_TYPE_ARG3) 0, 0);
> +  int ptrace_errno = ret < 0 ? errno : 0;
> +
> +  try
> +    {
> +      write_trace_errno_to_pipe (trace_errno_wpipe, ptrace_errno);
> +    }
> +  catch (const gdb_exception &e)
> +    {
> +      warning ("%s", e.what ());
> +      _exit (0177);
> +    }

We've been avoiding try/catch in an async-signal-safe-only environment
(between fork and exec/exit).  This is another spot leaking in.

AFAICT, all cases of write_trace_errno_to_pipe throwing end up
caught be the immediate caller catching the error, warning and
calling _exit.  So how about doing the warning+_exit directly
within write_trace_errno_to_pipe and thus avoid the try/catch?

> +
> +  if (ret < 0)
>      trace_start_error_with_name ("ptrace");

Seems like errno was already lost when you get here, since
write_trace_errno_to_pipe clobbers errno.

BTW, you could do with a single ret < 0 check, I think?  Like:

  if (ret < 0)
   {
     int ptrace_errno = errno;

     write_trace_errno_to_pipe (trace_errno_wpipe, ptrace_errno);

     errno = ptrace_errno;

     trace_start_error_with_name ("ptrace");
   }

Though you could make (and document) write_trace_errno_to_pipe
preserve errno itself.  I'd even consider removing its
trace_errno parameter, resulting in this on the caller side:

  if (ret < 0)
   {
     write_trace_errno_to_pipe (trace_errno_wpipe);
     trace_start_error_with_name ("ptrace");
   }

Note how trace_start_error_with_name already uses the global
errno, so it wouldn't be strange.


>  }
>  
> @@ -185,6 +199,18 @@ inf_ptrace_target::mourn_inferior ()
>  
>  void
>  inf_ptrace_target::attach (const char *args, int from_tty)
> +{
> +   errno = ptrace_attach (args, from_tty);
> +   if (errno != 0)
> +     perror_with_name (("ptrace"));
> +}
> +
> +/* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
> +   be chatty about it.  Return ERRNO if the call to ptrace failed; 0
> +   otherwise.  */

This should also mention that we throw an error for other reasons.

Something like:

  Returns ERRNO if the call to ptrace failed; 0 if ptrace succeeded.
  Throws an error if it fails for reasons other than a ptrace failure.

> +
> +int
> +inf_ptrace_target::ptrace_attach (const char *args, int from_tty)
>  {
>    pid_t pid;
>    struct inferior *inf;
> @@ -223,7 +249,7 @@ inf_ptrace_target::attach (const char *args, int from_tty)
>    errno = 0;
>    ptrace (PT_ATTACH, pid, (PTRACE_TYPE_ARG3)0, 0);
>    if (errno != 0)
> -    perror_with_name (("ptrace"));
> +    return errno;
>  #else
>    error (_("This system does not support attaching to a process"));
>  #endif
> @@ -241,6 +267,8 @@ inf_ptrace_target::attach (const char *args, int from_tty)
>    set_executing (this, thr->ptid, true);
>  
>    unpusher.release ();
> +
> +  return 0;
>  }
>  
>  #ifdef PT_GET_PROCESS_STATE
> diff --git a/gdb/inf-ptrace.h b/gdb/inf-ptrace.h
> index dd0733736f..ca36ca3af3 100644
> --- a/gdb/inf-ptrace.h
> +++ b/gdb/inf-ptrace.h
> @@ -31,6 +31,8 @@ struct inf_ptrace_target : public inf_child_target
>  
>    void attach (const char *, int) override;
>  
> +  int ptrace_attach (const char *, int);
> +
>    void detach (inferior *inf, int) override;
>  
>    void resume (ptid_t, int, enum gdb_signal) override;
> diff --git a/gdb/linux-nat.c b/gdb/linux-nat.c
> index 81af83c4ac..cc044ee3ac 100644
> --- a/gdb/linux-nat.c
> +++ b/gdb/linux-nat.c
> @@ -31,6 +31,7 @@
>  #include "nat/linux-ptrace.h"
>  #include "nat/linux-procfs.h"
>  #include "nat/linux-personality.h"
> +#include "nat/fork-inferior.h"
>  #include "linux-fork.h"
>  #include "gdbthread.h"
>  #include "gdbcmd.h"
> @@ -1136,7 +1137,7 @@ attach_proc_task_lwp_callback (ptid_t ptid)
>    else
>      {
>        std::string reason
> - = linux_ptrace_attach_fail_reason_string (ptid, err);
> + = linux_ptrace_attach_fail_reason_lwp (ptid, err);
>  
>        warning (_("Cannot attach to lwp %d: %s"),
>         lwpid, reason.c_str ());
> @@ -1185,20 +1186,15 @@ linux_nat_target::attach (const char *args, int from_tty)
>    /* Make sure we report all signals during attach.  */
>    pass_signals ({});
>  
> -  try
> -    {
> -      inf_ptrace_target::attach (args, from_tty);
> -    }
> -  catch (const gdb_exception_error &ex)
> +  int err = inf_ptrace_target::ptrace_attach (args, from_tty);
> +
> +  if (err != 0)
>      {
>        pid_t pid = parse_pid_to_attach (args);
> -      std::string reason = linux_ptrace_attach_fail_reason (pid);
> +      std::string reason = linux_ptrace_attach_fail_reason (pid, err);
>  
> -      if (!reason.empty ())
> - throw_error (ex.error, "warning: %s\n%s", reason.c_str (),
> -     ex.what ());
> -      else
> - throw_error (ex.error, "%s", ex.what ());
> +      error (_("warning: ptrace: %s\n%s"),
> +       safe_strerror (err), reason.c_str ());
>      }
>  
>    /* The ptrace base target adds the main thread with (pid,0,0)
> @@ -4582,6 +4578,10 @@ Enables printf debugging output."),
>    sigemptyset (&blocked_mask);
>  
>    lwp_lwpid_htab_create ();
> +
> +  /* Set the proper function to generate a message when ptrace
> +     fails.  */
> +  trace_me_fail_reason = linux_ptrace_me_fail_reason;
>  }
>  
>  
> diff --git a/gdb/nat/fork-inferior.c b/gdb/nat/fork-inferior.c
> index 223ff44195..eb4c4625d7 100644
> --- a/gdb/nat/fork-inferior.c
> +++ b/gdb/nat/fork-inferior.c
> @@ -394,9 +394,9 @@ struct traceme_info
>  
>         This function will usually perform the call to whatever trace
>         function needed to start tracing the inferior, but will also
> -       write its errno value to TRACE_ERRNO_PIPE, so that
> +       write its errno value to TRACE_ERRNO_WPIPE, so that
>         fork_inferior_1 can check whether it suceeded.  */
> -    void (*traceme_fun_check) (int trace_errno_pipe);
> +    void (*traceme_fun_check) (int trace_errno_wpipe);

I was surprised to see this renaming going on this patch.  Why not
name the variable like that in the previous patch, where it was
introduced, to begin with?

>    } u;
>  };
>  
> @@ -626,7 +626,7 @@ fork_inferior (const char *exec_file_arg, const std::string &allargs,
>  
>  pid_t
>  fork_inferior (const char *exec_file_arg, const std::string &allargs,
> -       char **env, void (*traceme_fun) (int trace_errno_pipe),
> +       char **env, void (*traceme_fun) (int trace_errno_wpipe),

Ditto.  Etc.

>         gdb::function_view<void (int)> init_trace_fun,
>         void (*pre_trace_fun) (),
>         const char *shell_file_arg,
> diff --git a/gdb/nat/fork-inferior.h b/gdb/nat/fork-inferior.h
> index b67215353f..3fbead2e33 100644
> --- a/gdb/nat/fork-inferior.h
> +++ b/gdb/nat/fork-inferior.h
> @@ -66,7 +66,7 @@ extern pid_t fork_inferior (const char *exec_file_arg,
>  extern pid_t fork_inferior (const char *exec_file_arg,
>      const std::string &allargs,
>      char **env,
> -    void (*traceme_fun) (int trace_errno_pipe),
> +    void (*traceme_fun) (int trace_errno_wpipe),
>      gdb::function_view<void (int)> init_trace_fun,
>      void (*pre_trace_fun) (),
>      const char *shell_file_arg,
> diff --git a/gdb/nat/linux-ptrace.c b/gdb/nat/linux-ptrace.c
> index 5335d69092..b3fcf8bc07 100644
> --- a/gdb/nat/linux-ptrace.c
> +++ b/gdb/nat/linux-ptrace.c
> @@ -21,6 +21,9 @@
>  #include "linux-procfs.h"
>  #include "linux-waitpid.h"
>  #include "gdbsupport/buffer.h"
> +#include "gdbsupport/gdb-dlfcn.h"
> +#include "nat/fork-inferior.h"
> +#include "gdbsupport/filestuff.h"
>  #ifdef HAVE_SYS_PROCFS_H
>  #include <sys/procfs.h>
>  #endif
> @@ -30,11 +33,93 @@
>     of 0 means there are no supported features.  */
>  static int supported_ptrace_options = -1;
>  
> -/* Find all possible reasons we could fail to attach PID and return these
> -   as a string.  An empty string is returned if we didn't find any reason.  */
> +typedef int (*selinux_ftype) (const char *);
>  
> -std::string
> -linux_ptrace_attach_fail_reason (pid_t pid)
> +/* Helper function which checks if ptrace is probably restricted
> +   (i.e., if ERR is either EACCES or EPERM), and returns a string with
> +   possible workarounds.  */
> +
> +static std::string
> +linux_ptrace_restricted_fail_reason (int err)
> +{
> +  if (err != EACCES && err != EPERM)
> +    {
> +      /* It just makes sense to perform the checks below if errno was
> + either EACCES or EPERM.  */
> +      return {};
> +    }
> +
> +  std::string ret;
> +  gdb_dlhandle_up handle;
> +
> +  try
> +    {
> +      handle = gdb_dlopen ("libselinux.so.1");
> +    }
> +  catch (const gdb_exception_error &e)
> +    {
> +    }
> +
> +  if (handle != nullptr)
> +    {
> +      selinux_ftype selinux_get_bool
> + = (selinux_ftype) gdb_dlsym (handle, "security_get_boolean_active");
> +
> +      if (selinux_get_bool != NULL
> +  && (*selinux_get_bool) ("deny_ptrace") == 1)
> + string_appendf (ret,
> + _("\n\
> +The SELinux 'deny_ptrace' option is enabled and preventing GDB\n\
> +from using 'ptrace'.  You can disable it by executing (as root):\n\
> +\n\
> +  setsebool deny_ptrace off\n"));
> +    }
> +
> +  gdb_file_up yama_ptrace_scope
> +    = gdb_fopen_cloexec ("/proc/sys/kernel/yama/ptrace_scope", "r");
> +
> +  if (yama_ptrace_scope != nullptr)
> +    {
> +      char yama_scope = fgetc (yama_ptrace_scope.get ());
> +
> +      if (yama_scope != '0')
> + string_appendf (ret,
> + _("\n\
> +The Linux kernel's Yama ptrace scope is in effect, which can prevent\n\
> +GDB from using 'ptrace'.  You can disable it by executing (as root):\n\
> +\n\
> +  echo 0 > /proc/sys/kernel/yama/ptrace_scope\n"));
> +    }
> +
> +  if (ret.empty ())
> +    {
> +      /* It wasn't possible to determine the exact reason for the
> + ptrace error.  Let's just emit a generic error message
> + pointing the user to our documentation, where she can find
> + instructions on how to try to diagnose the problem.  */
> +      ret = _("\n\
> +There might be restrictions preventing ptrace from working.  Please see\n\
> +the appendix \"Linux kernel ptrace restrictions\" in the GDB documentation\n\
> +for more details.");
> +    }
> +
> +  /* The user may be debugging remotely, so we have to warn that
> +     the instructions above should be performed in the target.  */
> +  string_appendf (ret,
> +  _("\n\
> +If you are debugging the inferior remotely, the ptrace restriction(s) must\n\
> +be disabled in the target system (e.g., where GDBserver is running)."));
> +
> +  return ret;
> +}
> +
> +/* Find all possible reasons we could fail to attach PID and return
> +   these as a string.  An empty string is returned if we didn't find
> +   any reason.  Helper for linux_ptrace_attach_fail_reason and
> +   linux_ptrace_attach_fail_reason_lwp.  */
> +
> +static std::string
> +linux_ptrace_attach_fail_reason_1 (pid_t pid)
>  {
>    pid_t tracerpid = linux_proc_get_tracerpid_nowarn (pid);
>    std::string result;
> @@ -56,10 +141,24 @@ linux_ptrace_attach_fail_reason (pid_t pid)
>  /* See linux-ptrace.h.  */
>  
>  std::string
> -linux_ptrace_attach_fail_reason_string (ptid_t ptid, int err)
> +linux_ptrace_attach_fail_reason (pid_t pid, int err)
> +{
> +  std::string result = linux_ptrace_attach_fail_reason_1 (pid);
> +  std::string ptrace_restrict = linux_ptrace_restricted_fail_reason (err);
> +
> +  if (!ptrace_restrict.empty ())
> +    result += "\n" + ptrace_restrict;
> +
> +  return result;
> +}
> +
> +/* See linux-ptrace.h.  */
> +
> +std::string
> +linux_ptrace_attach_fail_reason_lwp (ptid_t ptid, int err)
>  {
>    long lwpid = ptid.lwp ();
> -  std::string reason = linux_ptrace_attach_fail_reason (lwpid);
> +  std::string reason = linux_ptrace_attach_fail_reason_1 (lwpid);
>  
>    if (!reason.empty ())
>      return string_printf ("%s (%d), %s", safe_strerror (err), err,
> @@ -68,6 +167,14 @@ linux_ptrace_attach_fail_reason_string (ptid_t ptid, int err)
>      return string_printf ("%s (%d)", safe_strerror (err), err);
>  }
>  
> +/* See linux-ptrace.h.  */
> +
> +std::string
> +linux_ptrace_me_fail_reason (int err)
> +{
> +  return linux_ptrace_restricted_fail_reason (err);
> +}
> +
>  #if defined __i386__ || defined __x86_64__
>  
>  /* Address of the 'ret' instruction in asm code block below.  */
> @@ -257,6 +364,12 @@ linux_ptrace_test_ret_to_nx (void)
>  #endif /* defined __i386__ || defined __x86_64__ */
>  }
>  
> +/* If the PTRACE_TRACEME call on linux_child_function errors, we need
> +   to be able to send ERRNO back to the parent so that it can check
> +   whether there are restrictions in place preventing ptrace from
> +   working.  We do that with a pipe.  */
> +static int errno_pipe[2];
> +

We're missing a comment somewhere saying that we do that on the parent side
to avoid doing non-async-signal-safe things in the child.  Here might be
a good place, but on the gdb side we could use some comment about it too.


>  /* Helper function to fork a process and make the child process call
>     the function FUNCTION, passing CHILD_STACK as parameter.
>  
> @@ -321,7 +434,30 @@ linux_grandchild_function (void *child_stack)
>  static int
>  linux_child_function (void *child_stack)
>  {
> -  ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);
> +  /* Close read end.  */
> +  close (errno_pipe[0]);
> +
> +  int ret = ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
> +    (PTRACE_TYPE_ARG4) 0);
> +  int ptrace_errno = ret < 0 ? errno : 0;
> +
> +  /* Write ERRNO to the pipe, even if it's zero, and close the writing
> +     end of the pipe.  */
> +  try
> +    {
> +      write_trace_errno_to_pipe (errno_pipe[1], ptrace_errno);
> +    }
> +  catch (const gdb_exception &e)
> +    {
> +      warning ("%s", e.what ());
> +      _exit (0177);
> +    }

Here's another spot that should do away with try/catch.

> +
> +  close (errno_pipe[1]);
> +
> +  if (ret != 0)
> +    trace_start_error_with_name ("ptrace");
> +
>    kill (getpid (), SIGSTOP);
>  
>    /* Fork a grandchild.  */
> @@ -346,12 +482,40 @@ linux_check_ptrace_features (void)
>    /* Initialize the options.  */
>    supported_ptrace_options = 0;
>  
> +  /* Initialize our pipe.  */
> +  if (gdb_pipe_cloexec (errno_pipe) < 0)
> +    perror_with_name ("gdb_pipe_cloexec");
> +
>    /* Fork a child so we can do some testing.  The child will call
>       linux_child_function and will get traced.  The child will
>       eventually fork a grandchild so we can test fork event
>       reporting.  */
>    child_pid = linux_fork_to_function (NULL, linux_child_function);
>  
> +  /* We don't need the write end of the pipe anymore.  */
> +  close (errno_pipe[1]);
> +
> +  try
> +    {
> +      /* Check whether 'ptrace (PTRACE_ME, ...)' failed when being
> + invoked by the child.  If it did, we might get the
> + possible reason for it as the exception message.  */
> +      check_child_trace_me_errno (errno_pipe[0]);

This is assuming that close doesn't clober errno, which in general
is not garanteed:

  https://pubs.opengroup.org/onlinepubs/9699919799/functions/errno.html#tag_16_110

"The setting of errno after a successful call to a function is unspecified
unless the description of that function specifies that errno shall not
be modified."

A quick web search finds this for example:

 https://git.furworks.de/opensourcemirror/git/commit/06121a0a8328c8aaa7a023cf6ebb142e9dc2b45c

> +    }
> +  catch (const gdb_exception &e)
> +    {
> +      /* Close the pipe so we don't leak fd's.  */

fd's -> fds

> +      close (errno_pipe[0]);
> +
> +      /* A failure here means that PTRACE_ME failed, which means that
> + GDB/gdbserver will most probably not work correctly.  If we
> + want to be pedantic, we could just call 'exit' here.
> + However, let's just re-throw the exception.  */
> +      throw;
> +    }
> +
> +  close (errno_pipe[0]);
> +
>    ret = my_waitpid (child_pid, &status, 0);
>    if (ret == -1)
>      perror_with_name (("waitpid"));
> diff --git a/gdb/nat/linux-ptrace.h b/gdb/nat/linux-ptrace.h
> index 65568301f2..7cb77114ca 100644
> --- a/gdb/nat/linux-ptrace.h
> +++ b/gdb/nat/linux-ptrace.h
> @@ -176,12 +176,27 @@ struct buffer;
>  # define TRAP_HWBKPT 4
>  #endif
>  
> -extern std::string linux_ptrace_attach_fail_reason (pid_t pid);
> -
> -/* Find all possible reasons we could have failed to attach to PTID
> -   and return them as a string.  ERR is the error PTRACE_ATTACH failed
> -   with (an errno).  */
> -extern std::string linux_ptrace_attach_fail_reason_string (ptid_t ptid, int err);
> +/* Find all possible reasons we could fail to attach PID and return
> +   these as a string.  An empty string is returned if we didn't find
> +   any reason.  If ERR is EACCES or EPERM, we also add a warning about
> +   possible restrictions to use ptrace.  */
> +extern std::string linux_ptrace_attach_fail_reason (pid_t pid, int err);
> +
> +/* Find all possible reasons we could have failed to attach to PID's
> +   LWPID and return them as a string.  ERR is the error PTRACE_ATTACH
> +   failed with (an errno).  Unlike linux_ptrace_attach_fail_reason,
> +   this function should be used when attaching to an LWP other than
> +   the leader; it does not warn about ptrace restrictions.  */
> +extern std::string linux_ptrace_attach_fail_reason_lwp (ptid_t pid, int err);
> +
> +/* When the call to 'ptrace (PTRACE_TRACEME...' fails, and we have
> +   already forked, this function can be called in order to try to
> +   obtain the reason why ptrace failed.  ERR should be the ERRNO value
> +   returned by ptrace.
> +
> +   This function will return a 'std::string' containing the fail
> +   reason, or an empty string otherwise.  */
> +extern std::string linux_ptrace_me_fail_reason (int err);
>  
>  extern void linux_ptrace_init_warnings (void);
>  extern void linux_check_ptrace_features (void);
> diff --git a/gdb/remote.c b/gdb/remote.c
> index 0f78b1be1b..aacbdf1984 100644
> --- a/gdb/remote.c
> +++ b/gdb/remote.c
> @@ -5882,9 +5882,26 @@ extended_remote_target::attach (const char *args, int from_tty)
>        break;
>      case PACKET_UNKNOWN:
>        error (_("This target does not support attaching to a process"));
> +    case PACKET_ERROR:
> +      {
> + std::string errmsg = rs->buf.data ();

This is taking a deep copy which seems unnecessary.

The code would look almost the same without it.  Like:

        const char *errmsg = rs->buf.data ();

        /* Check if we have a specific error (i.e., not a generic
           "E01") coming from the target.  If there is, we print it
           here.  */
        if (startswith (errmsg, "E."))
          {
            /* Get rid of the "E." prefix.  */
            errmsg += 2;
          }

        error (_("Attaching to %s failed%s%s"),
               target_pid_to_str (ptid_t (pid)).c_str (),
               errmsg != '\0' ? "\n" : "",
               errmsg);


> +
> + /* Check if we have a specific error (i.e., not a generic
> +   "E01") coming from the target.  If there is, we print it
> +   here.  */
> + if (startswith (errmsg.c_str (), "E."))
> +  {
> +    /* Get rid of the "E." prefix.  */
> +    errmsg.erase (0, 2);
> +  }
> +
> + error (_("Attaching to %s failed%s%s"),
> +       target_pid_to_str (ptid_t (pid)).c_str (),
> +       !errmsg.empty () ? "\n" : "",
> +       errmsg.c_str ());
> +      }
>      default:
> -      error (_("Attaching to %s failed"),
> -     target_pid_to_str (ptid_t (pid)).c_str ());
> +      gdb_assert_not_reached (_("bad switch"));
>      }
>  
>    set_current_inferior (remote_add_inferior (false, pid, 1, 0));
> @@ -10024,8 +10041,23 @@ remote_target::extended_remote_run (const std::string &args)
>   error (_("Running the default executable on the remote target failed; "
>   "try \"set remote exec-file\"?"));
>        else
> - error (_("Running \"%s\" on the remote target failed"),
> -       remote_exec_file);
> + {
> +  std::string errmsg = rs->buf.data ();
> +
> +  /* Check if we have a specific error (i.e., not a generic
> +     "E01") coming from the target.  If there is, we print it
> +     here.  */
> +  if (startswith (errmsg.c_str (), "E."))
> +    {
> +      /* Get rid of the "E." prefix.  */
> +      errmsg.erase (0, 2);
> +    }
> +
> +  error (_("Running \"%s\" on the remote target failed%s%s"),
> + remote_exec_file,
> + !errmsg.empty () ? "\n" : "",
> + errmsg.c_str ());

Ditto.

> + }
>      default:
>        gdb_assert_not_reached (_("bad switch"));
>      }
> diff --git a/gdbserver/linux-low.cc b/gdbserver/linux-low.cc
> index 2872bc78da..42283802dd 100644
> --- a/gdbserver/linux-low.cc
> +++ b/gdbserver/linux-low.cc
> @@ -968,10 +968,24 @@ add_lwp (ptid_t ptid)
>     actually initiating the tracing of the inferior.  */
>  
>  static void
> -linux_ptrace_fun ()
> +linux_ptrace_fun (int ptrace_errno_wpipe)
>  {
> -  if (ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
> -      (PTRACE_TYPE_ARG4) 0) < 0)
> +  int ret = ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
> +    (PTRACE_TYPE_ARG4) 0);
> +  int ptrace_errno = ret < 0 ? errno : 0;
> +
> +  try
> +    {
> +      write_trace_errno_to_pipe (ptrace_errno_wpipe, ptrace_errno);
> +    }
> +  catch (const gdb_exception &e)
> +    {
> +      warning ("%s", e.what ());
> +      _exit (0177);
> +    }

Another spot that could do without try/catch.

> +
> +  errno = ptrace_errno;
> +  if (ret < 0)
>      trace_start_error_with_name ("ptrace");
>  
>    if (setpgid (0, 0) < 0)
> @@ -1170,7 +1184,7 @@ attach_proc_task_lwp_callback (ptid_t ptid)
>        else if (err != 0)
>   {
>    std::string reason
> -    = linux_ptrace_attach_fail_reason_string (ptid, err);
> +    = linux_ptrace_attach_fail_reason_lwp (ptid, err);
>  
>    warning (_("Cannot attach to lwp %d: %s"), lwpid, reason.c_str ());
>   }
> @@ -1202,8 +1216,8 @@ linux_process_target::attach (unsigned long pid)
>      {
>        remove_process (proc);
>  
> -      std::string reason = linux_ptrace_attach_fail_reason_string (ptid, err);
> -      error ("Cannot attach to process %ld: %s", pid, reason.c_str ());
> +      std::string reason = linux_ptrace_attach_fail_reason (pid, err);
> +      error (_("Cannot attach to process %ld: %s"), pid, reason.c_str ());
>      }
>  
>    /* Don't ignore the initial SIGSTOP if we just attached to this
> @@ -7552,5 +7566,10 @@ initialize_low (void)
>  
>    initialize_low_arch ();
>  
> +  /* Initialize the 'trace_me_fail_reason' function pointer.  We will
> +     use this to determine the reason for possible failures when
> +     invoking 'ptrace (PTRACE_ME, ...)'.  */
> +  trace_me_fail_reason = linux_ptrace_me_fail_reason;
> +
>    linux_check_ptrace_features ();
>  }
> diff --git a/gdbserver/server.cc b/gdbserver/server.cc
> index 43962adc86..003385f42a 100644
> --- a/gdbserver/server.cc
> +++ b/gdbserver/server.cc
> @@ -2892,9 +2892,31 @@ handle_v_attach (char *own_buf)
>  {
>    client_state &cs = get_client_state ();
>    int pid;
> +  int ret;
>  
>    pid = strtol (own_buf + 8, NULL, 16);
> -  if (pid != 0 && attach_inferior (pid) == 0)
> +
> +  if (pid <= 0)
> +    {
> +      write_enn (own_buf);
> +      return 0;
> +    }
> +
> +  try
> +    {
> +      /* Attach to the specified PID.  This function can throw, so we
> + make sure to catch the exception and send it (as an error
> + packet) back to GDB.  */
> +      ret = attach_inferior (pid);
> +    }
> +  catch (const gdb_exception_error &e)
> +    {
> +      fprintf (stderr, "%s\n", e.what ());
> +      snprintf (own_buf, PBUFSIZ, "E.%s", e.what ());
> +      return 0;
> +    }
> +
> +  if (ret == 0)
>      {
>        /* Don't report shared library events after attaching, even if
>   some libraries are preloaded.  GDB will always poll the
> @@ -3030,7 +3052,19 @@ handle_v_run (char *own_buf)
>    free_vector_argv (program_args);
>    program_args = new_argv;
>  
> -  target_create_inferior (program_path.get (), program_args);
> +  try
> +    {
> +      /* Create the inferior.  This function can throw, so we make
> + sure to catch the exception and send it (as an error packet)
> + back to GDB.  */
> +      target_create_inferior (program_path.get (), program_args);
> +    }
> +  catch (const gdb_exception_error &e)
> +    {
> +      fprintf (stderr, "%s\n", e.what ());
> +      snprintf (own_buf, PBUFSIZ, "E.%s", e.what ());
> +      return 0;
> +    }
>  
>    if (cs.last_status.kind == TARGET_WAITKIND_STOPPED)
>      {
> diff --git a/gdbserver/thread-db.cc b/gdbserver/thread-db.cc
> index 2bb6d28820..60ceb7b663 100644
> --- a/gdbserver/thread-db.cc
> +++ b/gdbserver/thread-db.cc
> @@ -224,7 +224,7 @@ attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p)
>    err = linux_attach_lwp (ptid);
>    if (err != 0)
>      {
> -      std::string reason = linux_ptrace_attach_fail_reason_string (ptid, err);
> +      std::string reason = linux_ptrace_attach_fail_reason_lwp (ptid, err);
>  
>        warning ("Could not attach to thread %ld (LWP %d): %s",
>         (unsigned long) ti_p->ti_tid, ti_p->ti_lid, reason.c_str ());
>


--
Thanks,
Pedro Alves

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 4/5] Extend GNU/Linux to check for ptrace error

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
On Tue, 17 Mar 2020 11:47:18 -0400
Sergio Durigan Junior <[hidden email]> wrote:

> +  /* The user may be debugging remotely, so we have to warn that
> +     the instructions above should be performed in the target.  */
> +  string_appendf (ret,
> +  _("\n\
> +If you are debugging the inferior remotely, the ptrace restriction(s) must\n\
> +be disabled in the target system (e.g., where GDBserver is running)."));

It seems to me that we ought to be able to know if the user is debugging
remotely.  If possible, I'd like to see a more targeted message when
debugging remotely.  The message can then be suppressed entirely for
native debugging.  The new message might look something like this:

    You are debugging the inferior remotely, so the ptrace restriction(s)
    must be disabled in the target system (i.e. where GDBserver is running).

If that's not feasible for some reason, "e.g." should still be changed
to "i.e.".

Kevin

Reply | Threaded
Open this post in threaded view
|

Re: [PATCH v2 2/5] Don't reset errno/bfd_error on 'throw_perror_with_name'

Sourceware - gdb-patches mailing list
In reply to this post by Sourceware - gdb-patches mailing list
On 3/17/20 3:47 PM, Sergio Durigan Junior via Gdb-patches wrote:

> the commit that "introduced" it is:
>
>   commit c906108c21474dfb4ed285bcc0ac6fe02cd400cc
>   Author: Stan Shebs <[hidden email]>
>   Date:   Fri Apr 16 01:35:26 1999 +0000
>
>       Initial creation of sourceware repository
>
> so yeah...

Given the previous discussions, I'd appreciate this comment was
updated/clarified.

>
> If we go to the POSIX specification for 'perror', it doesn't really
> say anything about whether errno should be preserved or not.  It does,
> however, say that 'perror's messages should be the same as those
> returned by 'strerror', and 'strerror' is not supposed to alter errno
> if the call is successful.
>
> Maybe when our wrapper was written it was OK to modify errno, I don't
> know.  But I'd like to propose that we stick to POSIX in this case.
>

This really has nothing to do with POSIX, because this isn't a
normal wrapper.  Control is not returning, we're throwing.  As I
mentioned before, we shouldn't be relying on errno being preserved
across throw/catch.  For _that_ reason, I'm still OK with this patch,
(even though I disagree with the given rationale).

Thanks,
Pedro Alves

12345