diff --git a/gdb/inf-ptrace.c b/gdb/inf-ptrace.c
index db17a76d94..8fb7264700 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");
 }
 
diff --git a/gdb/linux-nat.c b/gdb/linux-nat.c
index 81af83c4ac..31a5da8b52 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 ());
@@ -1191,8 +1192,9 @@ linux_nat_target::attach (const char *args, int 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);
+      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 (),
@@ -4582,6 +4584,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 4a70ab3fb0..7e0655974c 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));
@@ -10003,8 +10020,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 a4cb1eb418..d0b0c5a4ad 100644
--- a/gdbserver/server.cc
+++ b/gdbserver/server.cc
@@ -2891,9 +2891,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
@@ -3029,7 +3051,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 ());
