[2/4] Handle copy relocations

Message ID 20190627145235.21222-3-tromey@adacore.com
State Superseded
Headers show
Series
  • Handle copy relocations and add $_ada_exception
Related show

Commit Message

Tom Tromey June 27, 2019, 2:52 p.m.
In ELF, if a data symbol is defined in a shared library and used by
the main program, it will be subject to a "copy relocation".  In this
scenario, the main program has a copy of the symbol in question, and a
relocation that tells ld.so to copy the data from the shared library.
Then the symbol in the main program is used to satisfy all references.

This patch changes gdb to handle this scenario.  Data symbols coming
from ELF shared libraries get a special flag that indicates that the
symbol's address may be subject to copy relocation.

I looked briefly into handling copy relocations by looking at the
actual relocations in the main program, but this seemed difficult to
do with BFD.

Note that no caching is done here.  Perhaps this could be changed if
need be; I wanted to avoid possible problems with either objfile
lifetimes and changes, or conflicts with the long-term (vapor-ware)
objfile splitting project.

gdb/ChangeLog
2019-06-27  Tom Tromey  <tromey@adacore.com>

	* symmisc.c (dump_msymbols): Don't use MSYMBOL_VALUE_ADDRESS.
	* ada-lang.c (lesseq_defined_than): Handle
	LOC_STATIC.
	* dwarf2read.c (dwarf2_per_objfile): Add can_copy
	parameter.
	(dwarf2_has_info): Likewise.
	(new_symbol): Set maybe_copied on symbol when
	appropriate.
	* dwarf2read.h (dwarf2_per_objfile): Add can_copy
	parameter.
	<can_copy>: New member.
	* elfread.c (record_minimal_symbol): Set maybe_copied
	on symbol when appropriate.
	(elf_symfile_read): Update call to dwarf2_has_info.
	* minsyms.c (lookup_minimal_symbol_linkage): New
	function.
	* minsyms.h (lookup_minimal_symbol_linkage): Declare.
	* symtab.c (get_symbol_address, get_msymbol_address):
	New functions.
	* symtab.h (get_symbol_address, get_msymbol_address):
	Declare.
	(SYMBOL_VALUE_ADDRESS, MSYMBOL_VALUE_ADDRESS): Handle
	maybe_copied.
	(struct symbol, struct minimal_symbol) <maybe_copied>:
	New member.
---
 gdb/ChangeLog    | 28 ++++++++++++++++++++++++++++
 gdb/ada-lang.c   |  9 +++++++++
 gdb/dwarf2read.c | 36 ++++++++++++++++++------------------
 gdb/dwarf2read.h | 10 ++++++++--
 gdb/elfread.c    | 16 +++++++++++-----
 gdb/minsyms.c    | 20 ++++++++++++++++++++
 gdb/minsyms.h    |  7 +++++++
 gdb/symfile.h    |  3 ++-
 gdb/symmisc.c    | 10 +++++++---
 gdb/symtab.c     | 47 +++++++++++++++++++++++++++++++++++++++++++++++
 gdb/symtab.h     | 42 +++++++++++++++++++++++++++++++++++++++---
 11 files changed, 196 insertions(+), 32 deletions(-)

-- 
2.20.1

Comments

Pedro Alves July 20, 2019, 1:10 a.m. | #1
On 6/27/19 3:52 PM, Tom Tromey wrote:
> In ELF, if a data symbol is defined in a shared library and used by

> the main program, it will be subject to a "copy relocation".  


To be more correct, this depends on ABI, or how you compile your
binary.  Compiling the main binary as PIC/PIE may or may not use
copy relocations and use GOT accesses instead, for example.

> In this

> scenario, the main program has a copy of the symbol in question, and a

> relocation that tells ld.so to copy the data from the shared library.

> Then the symbol in the main program is used to satisfy all references.

> 

> This patch changes gdb to handle this scenario.  Data symbols coming

> from ELF shared libraries get a special flag that indicates that the

> symbol's address may be subject to copy relocation.

> 

> I looked briefly into handling copy relocations by looking at the

> actual relocations in the main program, but this seemed difficult to

> do with BFD.

> 

> Note that no caching is done here.  Perhaps this could be changed if

> need be; I wanted to avoid possible problems with either objfile

> lifetimes and changes, or conflicts with the long-term (vapor-ware)

> objfile splitting project.


I'm surprised to find no tests in this patch?

I'm not sure whether this is the right approach, since it seems to assume
that interposition/preemption happens, while it may not, given
possibility of attribute visibility hidden/protected.  Ideally whatever
design we take considers how no-preemption would be addressed.

This came up earlier here:

 https://sourceware.org/ml/gdb-patches/2017-10/msg00710.html

I've taken the examples from that email and converted them to
a proper testcase today.  See below.

With current master, we get:

 FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=0: version_id_main=0: 'print-file-var-lib2.c'::this_version_id == v2
 FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=0: version_id_main=1: 'print-file-var-lib1.c'::this_version_id == v1
 FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=0: version_id_main=1: 'print-file-var-lib2.c'::this_version_id == v2
 FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=1: version_id_main=0: 'print-file-var-lib2.c'::this_version_id == v2
 FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=1: version_id_main=1: 'print-file-var-lib1.c'::this_version_id == v1
 FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=1: version_id_main=1: 'print-file-var-lib2.c'::this_version_id == v2

Your patch curiously doesn't make a difference here.  Could we add
something here to show what your patch improves?

But I'm wondering whether fixing the hidden=1 cases would fit
with the design of your patch, or does that scenario require
thinking about all this differently?

From ffe918c15e9dc10540ed1590d9d37fee3fcea844 Mon Sep 17 00:00:00 2001
From: Pedro Alves <palves@redhat.com>

Date: Sat, 20 Jul 2019 01:20:35 +0100
Subject: [PATCH] Make print-file-var.exp test attribute visibility hidden,
 dlopen, and main symbol

Make gdb.base/print-file-var.exp test all combinations of:

  - attribute hidden in the this_version_id symbols or not
  - dlopen or not
  - this_version_id symbol in main file or not

I did not reindent the body of "test" in order to keep the patch
readable.  To be reindended before pushing.

gdb/ChangeLog:
yyyy-mm-dd  Pedro Alves  <palves@redhat.com>

	* gdb.base/print-file-var-lib1.c: Include <stdio.h> and
	"print-file-var.h".
	(this_version_id) Use ATTRIBUTE_VISIBILITY.
	(get_version_1): Print this_version_id and its address.
	* gdb.base/print-file-var-lib2.c: Include <stdio.h> and
	"print-file-var.h".
	(this_version_id) Use ATTRIBUTE_VISIBILITY.
	(get_version_2): Print this_version_id and its address.
	* gdb.base/print-file-var-main.c: Include <dlfcn.h>, <assert.h>,
	<stddef.h> and "print-file-var.h".
	[VERSION_ID_MAIN] (this_version_id): Define.
	(main): Define v0.  Use dlopen if SHLIB_NAME is defined.
	* gdb.base/print-file-var.exp (test): New, factored out from top
	level.
	(top level): Test all combinations of attribute hidden or not,
	dlopen or not, and this_version_id symbol in main file or not.
---
 gdb/testsuite/gdb.base/print-file-var-lib1.c |  7 ++-
 gdb/testsuite/gdb.base/print-file-var-lib2.c |  6 ++-
 gdb/testsuite/gdb.base/print-file-var-main.c | 38 +++++++++++---
 gdb/testsuite/gdb.base/print-file-var.exp    | 76 +++++++++++++++++++++-------
 gdb/testsuite/gdb.base/print-file-var.h      | 26 ++++++++++
 5 files changed, 127 insertions(+), 26 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/print-file-var.h

diff --git a/gdb/testsuite/gdb.base/print-file-var-lib1.c b/gdb/testsuite/gdb.base/print-file-var-lib1.c
index b5f4fb90b39..aec04a9b02b 100644
--- a/gdb/testsuite/gdb.base/print-file-var-lib1.c
+++ b/gdb/testsuite/gdb.base/print-file-var-lib1.c
@@ -14,10 +14,15 @@
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
-int this_version_id = 104;
+#include <stdio.h>
+#include "print-file-var.h"
+
+ATTRIBUTE_VISIBILITY int this_version_id = 104;
 
 int
 get_version_1 (void)
 {
+  printf ("get_version_1: &this_version_id=%p, this_version_id=%d\n", &this_version_id, this_version_id);
+
   return this_version_id;
 }
diff --git a/gdb/testsuite/gdb.base/print-file-var-lib2.c b/gdb/testsuite/gdb.base/print-file-var-lib2.c
index 28bd1acb17f..4dfdfa04c99 100644
--- a/gdb/testsuite/gdb.base/print-file-var-lib2.c
+++ b/gdb/testsuite/gdb.base/print-file-var-lib2.c
@@ -14,10 +14,14 @@
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
-int this_version_id = 203;
+#include <stdio.h>
+#include "print-file-var.h"
+
+ATTRIBUTE_VISIBILITY int this_version_id = 203;
 
 int
 get_version_2 (void)
 {
+  printf ("get_version_2: &this_version_id=%p, this_version_id=%d\n", &this_version_id, this_version_id);
   return this_version_id;
 }
diff --git a/gdb/testsuite/gdb.base/print-file-var-main.c b/gdb/testsuite/gdb.base/print-file-var-main.c
index ddc54f14d98..29d4fed22d1 100644
--- a/gdb/testsuite/gdb.base/print-file-var-main.c
+++ b/gdb/testsuite/gdb.base/print-file-var-main.c
@@ -14,21 +14,45 @@
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
+#ifdef SHLIB_NAME
+# include <dlfcn.h>
+#endif
+
+#include <assert.h>
+#include <stddef.h>
+
+#include "print-file-var.h"
+
 extern int get_version_1 (void);
 extern int get_version_2 (void);
 
+#if VERSION_ID_MAIN
+ATTRIBUTE_VISIBILITY int this_version_id = 55;
+#endif
+
 int
 main (void)
 {
+#if VERSION_ID_MAIN
+  int vm = this_version_id;
+#endif
   int v1 = get_version_1 ();
-  int v2 = get_version_2 ();
+  int v2;
 
-  if (v1 != 104)
-    return 1;
-  /* The value returned by get_version_2 depends on the target system.  */
-  if (v2 != 104 && v2 != 203)
-    return 2;
+#ifdef SHLIB_NAME
+  {
+    void *handle = dlopen (SHLIB_NAME, RTLD_LAZY);
+    int (*getver2) (void);
+
+    assert (handle != NULL);
+
+    getver2 = (int (*)(void)) dlsym (handle, "get_version_2");
+
+    v2 = getver2 ();
+  }
+#else
+  v2 = get_version_2 ();
+#endif
 
   return 0; /* STOP */
 }
-
diff --git a/gdb/testsuite/gdb.base/print-file-var.exp b/gdb/testsuite/gdb.base/print-file-var.exp
index 1f733fb4dee..4f4afc161e2 100644
--- a/gdb/testsuite/gdb.base/print-file-var.exp
+++ b/gdb/testsuite/gdb.base/print-file-var.exp
@@ -17,15 +17,23 @@ if {[skip_shlib_tests]} {
     return -1
 }
 
-set executable print-file-var-main
+proc test {hidden dlopen version_id_main} {
+    global srcdir subdir
+
+set main "print-file-var-main"
+
+set suffix "-hidden$hidden-dlopen$dlopen-version_id_main$version_id_main"
+
+set executable $main$suffix
 
 set lib1 "print-file-var-lib1"
 set lib2 "print-file-var-lib2"
 
-set libobj1 [standard_output_file ${lib1}.so]
-set libobj2 [standard_output_file ${lib2}.so]
+set libobj1 [standard_output_file ${lib1}$suffix.so]
+set libobj2 [standard_output_file ${lib2}$suffix.so]
 
 set lib_opts { debug additional_flags=-fPIC }
+lappend lib_opts "additional_flags=-DHIDDEN=$hidden"
 
 if { [gdb_compile_shlib ${srcdir}/${subdir}/${lib1}.c \
                         ${libobj1} \
@@ -37,10 +45,21 @@ if { [gdb_compile_shlib ${srcdir}/${subdir}/${lib2}.c \
                         ${lib_opts} ] != "" } {
     return -1
 }
-if { [gdb_compile "${srcdir}/${subdir}/${executable}.c" \
+
+set main_opts [list debug shlib=${libobj1}]
+
+if {$dlopen} {
+    lappend main_opts "shlib_load" "additional_flags=-DSHLIB_NAME=\"$libobj2\""
+} else {
+    lappend main_opts "shlib=${libobj2}"
+}
+
+lappend main_opts "additional_flags=-DVERSION_ID_MAIN=$version_id_main"
+
+if { [gdb_compile "${srcdir}/${subdir}/${main}.c" \
                   [standard_output_file ${executable}] \
                   executable \
-                  [list debug shlib=${libobj1} shlib=${libobj2}]]
+                  $main_opts]
      != ""} {
     return -1
 }
@@ -55,7 +74,7 @@ if ![runto_main] {
 }
 
 # Try printing "this_version_num" qualified with the name of the file
-# where the variables are defined.  There are two global variables
+# where the variables are defined.  There are three global variables
 # with that name, and some systems such as GNU/Linux merge them
 # into one single entity, while some other systems such as Windows
 # keep them separate.  In the first situation, we have to verify
@@ -65,28 +84,51 @@ if ![runto_main] {
 # defined in the given filename.
 #
 # To avoid adding target-specific code in this testcase, the program
-# sets two local variable named 'v1' and 'v2' with the value of
+# sets three local variables named 'vm', 'v1' and 'v2' with the value of
 # our global variables.  This allows us to compare the value that
 # GDB returns for each query against the actual value seen by
 # the program itself.
 
-# Get past the initialization of variables 'v1' and 'v2'.
+# Get past the initialization of the v* variables.
 
 set bp_location \
-    [gdb_get_line_number "STOP" "${executable}.c"]
-gdb_test "break $executable.c:$bp_location" \
+    [gdb_get_line_number "STOP" "${main}.c"]
+gdb_test "break $main.c:$bp_location" \
          "Breakpoint \[0-9\]+ at 0x\[0-9a-fA-F\]+: .*" \
-         "breapoint past v1 & v2 initialization"
+         "breapoint at STOP marker"
 
 gdb_test "continue" \
          "Breakpoint \[0-9\]+, main \\(\\) at.*STOP.*" \
          "continue to STOP marker"
 
-# Now check the value of this_version_id in both print-file-var-lib1.c
-# and print-file-var-lib2.c.
+# Now check the value of this_version_id in all of
+# print-file-var-main.c, print-file-var-lib1.c and
+# print-file-var-lib2.c.
+
+# Compare the values of $sym1 and $sym2.
+proc compare {sym1 sym2} {
+    # Done this way instead of comparing the symbols with "print $sym1
+    # == sym2" in GDB directly so that the values of the symbols end
+    # up visible in the logs, for debug purposes.
+    set vsym1 [get_integer_valueof $sym1 -1]
+    set vsym2 [get_integer_valueof $sym2 -1]
+    gdb_assert {$vsym1 == $vsym2} "$sym1 == $sym2"
+}
+
+if $version_id_main {
+    compare "'print-file-var-main.c'::this_version_id" "vm"
+    compare "this_version_id" "vm"
+}
 
-gdb_test "print 'print-file-var-lib1.c'::this_version_id == v1" \
-         " = 1"
+compare "'print-file-var-lib1.c'::this_version_id" "v1"
+compare "'print-file-var-lib2.c'::this_version_id" "v2"
 
-gdb_test "print 'print-file-var-lib2.c'::this_version_id == v2" \
-         " = 1"
+}
+
+foreach_with_prefix hidden {0 1} {
+    foreach_with_prefix dlopen {0 1} {
+	foreach_with_prefix version_id_main {0 1} {
+	    test $hidden $dlopen $version_id_main
+	}
+    }
+}
diff --git a/gdb/testsuite/gdb.base/print-file-var.h b/gdb/testsuite/gdb.base/print-file-var.h
new file mode 100644
index 00000000000..fe7a3460edb
--- /dev/null
+++ b/gdb/testsuite/gdb.base/print-file-var.h
@@ -0,0 +1,26 @@
+/* This testcase is part of GDB, the GNU debugger.
+   Copyright 2019 Free Software Foundation, Inc.
+
+   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 PRINT_FILE_VAR_H
+#define PRINT_FILE_VAR_H
+
+#if HIDDEN
+# define ATTRIBUTE_VISIBILITY __attribute__((visibility ("hidden")))
+#else
+# define ATTRIBUTE_VISIBILITY
+#endif
+
+#endif /* PRINT_FILE_VAR_H */
-- 
2.14.5
Tom Tromey July 30, 2019, 9 p.m. | #2
Pedro> To be more correct, this depends on ABI, or how you compile your
Pedro> binary.  Compiling the main binary as PIC/PIE may or may not use
Pedro> copy relocations and use GOT accesses instead, for example.

Yes, thanks for mentioning that.

Pedro> I'm surprised to find no tests in this patch?

The existing Ada exception-catching tests cover this, so I didn't add a
new test.

Pedro>  FAIL: gdb.base/print-file-var.exp: hidden=1: dlopen=0: version_id_main=0: 'print-file-var-lib2.c'::this_version_id == v2

I haven't investigated the other failures yet, but I think this one in
particular is an existing bug in c-exp.y.  What happens is that this
does not actually look up the symbol from that source file!  Instead it
finds the symbol in print-file-var-lib1.c.

Pedro> But I'm wondering whether fixing the hidden=1 cases would fit
Pedro> with the design of your patch, or does that scenario require
Pedro> thinking about all this differently?

I think applying the appended probably makes sense.  This rules out
symbols where the corresponding minsym is hidden.

Tom

diff --git a/gdb/dwarf2read.c b/gdb/dwarf2read.c
index f81efb4f433..90dfde0f1e9 100644
--- a/gdb/dwarf2read.c
+++ b/gdb/dwarf2read.c
@@ -21653,11 +21653,19 @@ new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
 	      else if (attr2 && (DW_UNSND (attr2) != 0))
 		{
 		  if (SYMBOL_CLASS (sym) == LOC_STATIC
-		      && (objfile->flags & OBJF_MAINLINE) == 0)
+		      && (objfile->flags & OBJF_MAINLINE) == 0
+		      && dwarf2_per_objfile->can_copy)
 		    {
 		      /* A global static variable might be subject to
-			 copy relocation.  */
-		      sym->maybe_copied = dwarf2_per_objfile->can_copy;
+			 copy relocation.  We first check for a local
+			 minsym, though, because maybe the symbol was
+			 marked hidden, in which case this would not
+			 apply.  */
+		      minimal_symbol *found
+			= (lookup_minimal_symbol_linkage
+			   (SYMBOL_LINKAGE_NAME (sym), objfile));
+		      if (found != nullptr)
+			sym->maybe_copied = 1;
 		    }
 
 		  /* A variable with DW_AT_external is never static,
Tom Tromey July 30, 2019, 9:28 p.m. | #3
Tom> I haven't investigated the other failures yet, but I think this one in
Tom> particular is an existing bug in c-exp.y.  What happens is that this
Tom> does not actually look up the symbol from that source file!  Instead it
Tom> finds the symbol in print-file-var-lib1.c.

Digging a bit deeper, the culprit seems to be lookup_global_symbol.
I think this function should respect a block that's passed in.

However, this code also calls
gdbarch_iterate_over_objfiles_in_search_order and solib_global_lookup,
and now I wonder if one or both of these needs to be changed
as well.

For example, if stopped in the library, "print this_version_id" should
probably follow the expected-by-the-library-author lookup, but currently
I think will not.

Maybe windows_iterate_over_objfiles_in_search_order should just be the
default.  I am not sure.

Tom
Tom Tromey July 31, 2019, 7:21 p.m. | #4
Tom> Digging a bit deeper, the culprit seems to be lookup_global_symbol.
Tom> I think this function should respect a block that's passed in.

I managed to get the new test completely passing.

I changed basic_lookup_symbol_nonlocal to search the block's global
block, and I removed the long comments fro 2002-3 about why this isn't
done.  TBH I think all of that was just mistaken.

This change got to just 2 failures.  The last two were both the
"hidden0...main0" variants, which print:

get_version_1: &this_version_id=0x7ffff7fca010, this_version_id=104
get_version_2: &this_version_id=0x7ffff7fca010, this_version_id=104

So, I think for these the answer is to change the new get_symbol_address
to search all objfiles in order.  I'm slightly unhappy with this but it
seems correct enough.

I'm re-testing the series and will resubmit it once that's done,
assuming there aren't regressions.

thanks,
Tom

Patch

diff --git a/gdb/ada-lang.c b/gdb/ada-lang.c
index 1e996557b6e..5a055fced7b 100644
--- a/gdb/ada-lang.c
+++ b/gdb/ada-lang.c
@@ -4734,6 +4734,15 @@  lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
     case LOC_CONST:
       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
+
+    case LOC_STATIC:
+      {
+        const char *name0 = SYMBOL_LINKAGE_NAME (sym0);
+        const char *name1 = SYMBOL_LINKAGE_NAME (sym1);
+        return (strcmp (name0, name1) == 0
+                && SYMBOL_VALUE_ADDRESS (sym0) == SYMBOL_VALUE_ADDRESS (sym1));
+      }
+
     default:
       return 0;
     }
diff --git a/gdb/dwarf2read.c b/gdb/dwarf2read.c
index 2945a2d090d..eec6eea9085 100644
--- a/gdb/dwarf2read.c
+++ b/gdb/dwarf2read.c
@@ -2126,8 +2126,10 @@  attr_value_as_address (struct attribute *attr)
 /* See declaration.  */
 
 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
-					const dwarf2_debug_sections *names)
-  : objfile (objfile_)
+					const dwarf2_debug_sections *names,
+					bool can_copy_)
+  : objfile (objfile_),
+    can_copy (can_copy_)
 {
   if (names == NULL)
     names = &dwarf2_elf_names;
@@ -2202,11 +2204,14 @@  private:
 /* Try to locate the sections we need for DWARF 2 debugging
    information and return true if we have enough to do something.
    NAMES points to the dwarf2 section names, or is NULL if the standard
-   ELF names are used.  */
+   ELF names are used.  CAN_COPY is true for formats where symbol
+   interposition is possible and so symbol values must follow copy
+   relocation rules.  */
 
 int
 dwarf2_has_info (struct objfile *objfile,
-                 const struct dwarf2_debug_sections *names)
+                 const struct dwarf2_debug_sections *names,
+		 bool can_copy)
 {
   if (objfile->flags & OBJF_READNEVER)
     return 0;
@@ -2216,7 +2221,8 @@  dwarf2_has_info (struct objfile *objfile,
 
   if (dwarf2_per_objfile == NULL)
     dwarf2_per_objfile = dwarf2_objfile_data_key.emplace (objfile, objfile,
-							  names);
+							  names,
+							  can_copy);
 
   return (!dwarf2_per_objfile->info.is_virtual
 	  && dwarf2_per_objfile->info.s.section != NULL
@@ -21610,19 +21616,13 @@  new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
 		}
 	      else if (attr2 && (DW_UNSND (attr2) != 0))
 		{
-		  /* Workaround gfortran PR debug/40040 - it uses
-		     DW_AT_location for variables in -fPIC libraries which may
-		     get overriden by other libraries/executable and get
-		     a different address.  Resolve it by the minimal symbol
-		     which may come from inferior's executable using copy
-		     relocation.  Make this workaround only for gfortran as for
-		     other compilers GDB cannot guess the minimal symbol
-		     Fortran mangling kind.  */
-		  if (cu->language == language_fortran && die->parent
-		      && die->parent->tag == DW_TAG_module
-		      && cu->producer
-		      && startswith (cu->producer, "GNU Fortran"))
-		    SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
+		  if (SYMBOL_CLASS (sym) == LOC_STATIC
+		      && (objfile->flags & OBJF_MAINLINE) == 0)
+		    {
+		      /* A global static variable might be subject to
+			 copy relocation.  */
+		      sym->maybe_copied = dwarf2_per_objfile->can_copy;
+		    }
 
 		  /* A variable with DW_AT_external is never static,
 		     but it may be block-scoped.  */
diff --git a/gdb/dwarf2read.h b/gdb/dwarf2read.h
index 9251bde1259..9c56a57b6bb 100644
--- a/gdb/dwarf2read.h
+++ b/gdb/dwarf2read.h
@@ -104,9 +104,12 @@  struct dwarf2_per_objfile
 {
   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
      dwarf2 section names, or is NULL if the standard ELF names are
-     used.  */
+     used.  CAN_COPY is true for formats where symbol
+     interposition is possible and so symbol values must follow copy
+     relocation rules.  */
   dwarf2_per_objfile (struct objfile *objfile,
-		      const dwarf2_debug_sections *names);
+		      const dwarf2_debug_sections *names,
+		      bool can_copy);
 
   ~dwarf2_per_objfile ();
 
@@ -206,6 +209,9 @@  public:
      original data was compressed using 'dwz -m'.  */
   std::unique_ptr<struct dwz_file> dwz_file;
 
+  /* Whether copy relocations are supported by this object format.  */
+  bool can_copy;
+
   /* A flag indicating whether this objfile has a section loaded at a
      VMA of 0.  */
   bool has_section_at_zero = false;
diff --git a/gdb/elfread.c b/gdb/elfread.c
index 630550b80dc..b2fade4124b 100644
--- a/gdb/elfread.c
+++ b/gdb/elfread.c
@@ -203,10 +203,16 @@  record_minimal_symbol (minimal_symbol_reader &reader,
       || ms_type == mst_text_gnu_ifunc)
     address = gdbarch_addr_bits_remove (gdbarch, address);
 
-  return reader.record_full (name, name_len, copy_name, address,
-			     ms_type,
-			     gdb_bfd_section_index (objfile->obfd,
-						    bfd_section));
+  struct minimal_symbol *result
+    = reader.record_full (name, name_len, copy_name, address,
+			  ms_type,
+			  gdb_bfd_section_index (objfile->obfd,
+						 bfd_section));
+  if ((objfile->flags & OBJF_MAINLINE) == 0
+      && (ms_type == mst_data || ms_type == mst_bss))
+    result->maybe_copied = 1;
+
+  return result;
 }
 
 /* Read the symbol table of an ELF file.
@@ -1239,7 +1245,7 @@  elf_symfile_read (struct objfile *objfile, symfile_add_flags symfile_flags)
 				bfd_section_size (abfd, str_sect));
     }
 
-  if (dwarf2_has_info (objfile, NULL))
+  if (dwarf2_has_info (objfile, NULL, true))
     {
       dw_index_kind index_kind;
 
diff --git a/gdb/minsyms.c b/gdb/minsyms.c
index e64e5df1a18..d9abce851e4 100644
--- a/gdb/minsyms.c
+++ b/gdb/minsyms.c
@@ -519,6 +519,26 @@  iterate_over_minimal_symbols
 
 /* See minsyms.h.  */
 
+struct minimal_symbol *
+lookup_minimal_symbol_linkage (const char *name, struct objfile *objf)
+{
+  unsigned int hash = msymbol_hash (name) % MINIMAL_SYMBOL_HASH_SIZE;
+
+  for (minimal_symbol *msymbol = objf->per_bfd->msymbol_hash[hash];
+       msymbol != NULL;
+       msymbol = msymbol->hash_next)
+    {
+      if (strcmp (MSYMBOL_LINKAGE_NAME (msymbol), name) == 0
+	  && (MSYMBOL_TYPE (msymbol) == mst_data
+	      || MSYMBOL_TYPE (msymbol) == mst_bss))
+	return msymbol;
+    }
+
+  return nullptr;
+}
+
+/* See minsyms.h.  */
+
 struct bound_minimal_symbol
 lookup_minimal_symbol_text (const char *name, struct objfile *objf)
 {
diff --git a/gdb/minsyms.h b/gdb/minsyms.h
index bb43165620d..fae6cd25496 100644
--- a/gdb/minsyms.h
+++ b/gdb/minsyms.h
@@ -193,6 +193,13 @@  struct bound_minimal_symbol lookup_minimal_symbol (const char *,
 
 struct bound_minimal_symbol lookup_bound_minimal_symbol (const char *);
 
+/* Look through the minimal symbols in OBJF for a global (not
+   file-local) minsym whose linkage name is NAME.  Returns a minimal
+   symbol that matches, or nullptr otherwise.  */
+
+struct minimal_symbol *lookup_minimal_symbol_linkage
+  (const char *name, struct objfile *objf);
+
 /* Look through all the current minimal symbol tables and find the
    first minimal symbol that matches NAME and has text type.  If OBJF
    is non-NULL, limit the search to that objfile.  Returns a bound
diff --git a/gdb/symfile.h b/gdb/symfile.h
index daddd2e21ab..35c7f9e4d87 100644
--- a/gdb/symfile.h
+++ b/gdb/symfile.h
@@ -579,7 +579,8 @@  struct dwarf2_debug_sections {
 };
 
 extern int dwarf2_has_info (struct objfile *,
-                            const struct dwarf2_debug_sections *);
+                            const struct dwarf2_debug_sections *,
+			    bool = false);
 
 /* Dwarf2 sections that can be accessed by dwarf2_get_section_info.  */
 enum dwarf2_section_enum {
diff --git a/gdb/symmisc.c b/gdb/symmisc.c
index 7666de390cd..db93d716704 100644
--- a/gdb/symmisc.c
+++ b/gdb/symmisc.c
@@ -236,9 +236,13 @@  dump_msymbols (struct objfile *objfile, struct ui_file *outfile)
 	  break;
 	}
       fprintf_filtered (outfile, "[%2d] %c ", index, ms_type);
-      fputs_filtered (paddress (gdbarch, MSYMBOL_VALUE_ADDRESS (objfile,
-								msymbol)),
-		      outfile);
+
+      /* Use the relocated address as shown in the symbol here -- do
+	 not try to respect copy relocations.  */
+      CORE_ADDR addr = (msymbol->value.address
+			+ ANOFFSET (objfile->section_offsets,
+				    msymbol->section));
+      fputs_filtered (paddress (gdbarch, addr), outfile);
       fprintf_filtered (outfile, " %s", MSYMBOL_LINKAGE_NAME (msymbol));
       if (section)
 	{
diff --git a/gdb/symtab.c b/gdb/symtab.c
index 4920d94a247..4906e9cfb9b 100644
--- a/gdb/symtab.c
+++ b/gdb/symtab.c
@@ -6003,6 +6003,53 @@  symbol_set_symtab (struct symbol *symbol, struct symtab *symtab)
   symbol->owner.symtab = symtab;
 }
 
+/* See symtab.h.  */
+
+CORE_ADDR
+get_symbol_address (const struct symbol *sym)
+{
+  gdb_assert (sym->maybe_copied);
+  gdb_assert (SYMBOL_CLASS (sym) == LOC_STATIC);
+
+  const char *linkage_name = SYMBOL_LINKAGE_NAME (sym);
+
+  for (objfile *objfile : current_program_space->objfiles ())
+    {
+      if ((objfile->flags & OBJF_MAINLINE) != 0)
+	{
+	  minimal_symbol *minsym
+	    = lookup_minimal_symbol_linkage (linkage_name, objfile);
+	  if (minsym != nullptr)
+	    return MSYMBOL_VALUE_ADDRESS (objfile, minsym);
+	}
+    }
+  return sym->ginfo.value.address;
+}
+
+/* See symtab.h.  */
+
+CORE_ADDR
+get_msymbol_address (struct objfile *objf, const struct minimal_symbol *minsym)
+{
+  gdb_assert (minsym->maybe_copied);
+  gdb_assert ((objf->flags & OBJF_MAINLINE) == 0);
+
+  const char *linkage_name = MSYMBOL_LINKAGE_NAME (minsym);
+
+  for (objfile *objfile : current_program_space->objfiles ())
+    {
+      if ((objfile->flags & OBJF_MAINLINE) != 0)
+	{
+	  minimal_symbol *found
+	    = lookup_minimal_symbol_linkage (linkage_name, objfile);
+	  if (found != nullptr)
+	    return MSYMBOL_VALUE_ADDRESS (objfile, found);
+	}
+    }
+  return (minsym->value.address
+	  + ANOFFSET (objf->section_offsets, minsym->section));
+}
+
 
 
 void
diff --git a/gdb/symtab.h b/gdb/symtab.h
index 7b3bb5d3775..4455bb09b83 100644
--- a/gdb/symtab.h
+++ b/gdb/symtab.h
@@ -454,6 +454,14 @@  extern const char *symbol_get_demangled_name
 
 extern CORE_ADDR symbol_overlayed_address (CORE_ADDR, struct obj_section *);
 
+/* Return the address of SYM.  The MAYBE_COPIED flag must be set on
+   SYM.  If SYM appears in the main program's minimal symbols, then
+   that minsym's address is returned; otherwise, SYM's address is
+   returned.  This should generally only be used via the
+   SYMBOL_VALUE_ADDRESS macro.  */
+
+extern CORE_ADDR get_symbol_address (const struct symbol *sym);
+
 /* Note that all the following SYMBOL_* macros are used with the
    SYMBOL argument being either a partial symbol or
    a full symbol.  Both types have a ginfo field.  In particular
@@ -463,7 +471,9 @@  extern CORE_ADDR symbol_overlayed_address (CORE_ADDR, struct obj_section *);
    field only, instead of the SYMBOL parameter.  */
 
 #define SYMBOL_VALUE(symbol)		(symbol)->ginfo.value.ivalue
-#define SYMBOL_VALUE_ADDRESS(symbol)	((symbol)->ginfo.value.address + 0)
+#define SYMBOL_VALUE_ADDRESS(symbol)			      \
+  (((symbol)->maybe_copied) ? get_symbol_address (symbol)     \
+   : ((symbol)->ginfo.value.address))
 #define SET_SYMBOL_VALUE_ADDRESS(symbol, new_value)	\
   ((symbol)->ginfo.value.address = (new_value))
 #define SYMBOL_VALUE_BYTES(symbol)	(symbol)->ginfo.value.bytes
@@ -671,6 +681,14 @@  struct minimal_symbol : public general_symbol_info
      the object file format may not carry that piece of information.  */
   unsigned int has_size : 1;
 
+  /* For data symbols only, if this is set, then the symbol might be
+     subject to copy relocation.  In this case, a minimal symbol
+     matching the symbol's linkage name is first looked for in the
+     main objfile.  If found, then that address is used; otherwise the
+     address in this symbol is used.  */
+
+  unsigned maybe_copied : 1;
+
   /* Minimal symbols with the same hash key are kept on a linked
      list.  This is the link.  */
 
@@ -690,6 +708,15 @@  struct minimal_symbol : public general_symbol_info
   bool text_p () const;
 };
 
+/* Return the address of MINSYM, which comes from OBJF.  The
+   MAYBE_COPIED flag must be set on MINSYM.  If MINSYM appears in the
+   main program's minimal symbols, then that minsym's address is
+   returned; otherwise, MINSYM's address is returned.  This should
+   generally only be used via the MSYMBOL_VALUE_ADDRESS macro.  */
+
+extern CORE_ADDR get_msymbol_address (struct objfile *objf,
+				      const struct minimal_symbol *minsym);
+
 #define MSYMBOL_TARGET_FLAG_1(msymbol)  (msymbol)->target_flag_1
 #define MSYMBOL_TARGET_FLAG_2(msymbol)  (msymbol)->target_flag_2
 #define MSYMBOL_SIZE(msymbol)		((msymbol)->size + 0)
@@ -708,8 +735,9 @@  struct minimal_symbol : public general_symbol_info
 /* The relocated address of the minimal symbol, using the section
    offsets from OBJFILE.  */
 #define MSYMBOL_VALUE_ADDRESS(objfile, symbol)				\
-  ((symbol)->value.address					\
-   + ANOFFSET ((objfile)->section_offsets, ((symbol)->section)))
+  (((symbol)->maybe_copied) ? get_msymbol_address (objfile, symbol)	\
+   : ((symbol)->value.address						\
+      + ANOFFSET ((objfile)->section_offsets, ((symbol)->section))))
 /* For a bound minsym, we can easily compute the address directly.  */
 #define BMSYMBOL_VALUE_ADDRESS(symbol) \
   MSYMBOL_VALUE_ADDRESS ((symbol).objfile, (symbol).minsym)
@@ -1112,6 +1140,14 @@  struct symbol
   /* Whether this is an inlined function (class LOC_BLOCK only).  */
   unsigned is_inlined : 1;
 
+  /* For LOC_STATIC only, if this is set, then the symbol might be
+     subject to copy relocation.  In this case, a minimal symbol
+     matching the symbol's linkage name is first looked for in the
+     main objfile.  If found, then that address is used; otherwise the
+     address in this symbol is used.  */
+
+  unsigned maybe_copied : 1;
+
   /* The concrete type of this symbol.  */
 
   ENUM_BITFIELD (symbol_subclass_kind) subclass : 2;