From 63169c8bdf3e7ac5006c8976b0631b281eb49394 Mon Sep 17 00:00:00 2001 From: Meng Zhuo Date: Sat, 26 Mar 2022 14:44:09 +0800 Subject: [PATCH] cmd/link: zero elf addr for debug sections The Addr should be zero if SHF_ALLOC is not set. Update #51939 Change-Id: I030f6243d05efabe6b9ebf558e9c0201f7922d23 Reviewed-on: https://go-review.googlesource.com/c/go/+/395919 Trust: mzh Run-TryBot: mzh TryBot-Result: Gopher Robot Reviewed-by: Cherry Mui --- src/cmd/link/elf_test.go | 28 ++++++++++++++++++++++++++++ src/cmd/link/internal/ld/elf.go | 8 +++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/cmd/link/elf_test.go b/src/cmd/link/elf_test.go index 318bd76abae..5b7b95757b8 100644 --- a/src/cmd/link/elf_test.go +++ b/src/cmd/link/elf_test.go @@ -469,3 +469,31 @@ func TestPIESize(t *testing.T) { }) } } + +func TestIssue51939(t *testing.T) { + testenv.MustHaveGoBuild(t) + t.Parallel() + td := t.TempDir() + goFile := filepath.Join(td, "issue51939.go") + if err := os.WriteFile(goFile, []byte(goSource), 0444); err != nil { + t.Fatal(err) + } + outFile := filepath.Join(td, "issue51939.exe") + goTool := testenv.GoToolPath(t) + cmd := exec.Command(goTool, "build", "-o", outFile, goFile) + if out, err := cmd.CombinedOutput(); err != nil { + t.Logf("%s", out) + t.Fatal(err) + } + + ef, err := elf.Open(outFile) + if err != nil { + t.Fatal(err) + } + + for _, s := range ef.Sections { + if s.Flags&elf.SHF_ALLOC == 0 && s.Addr != 0 { + t.Errorf("section %s should not allocated with addr %x", s.Name, s.Addr) + } + } +} diff --git a/src/cmd/link/internal/ld/elf.go b/src/cmd/link/internal/ld/elf.go index cb094a373a2..08de21cab60 100644 --- a/src/cmd/link/internal/ld/elf.go +++ b/src/cmd/link/internal/ld/elf.go @@ -1100,16 +1100,18 @@ func elfshbits(linkmode LinkMode, sect *sym.Section) *ElfShdr { sh.Flags |= uint64(elf.SHF_TLS) sh.Type = uint32(elf.SHT_NOBITS) } + if linkmode != LinkExternal { + sh.Addr = sect.Vaddr + } + if strings.HasPrefix(sect.Name, ".debug") || strings.HasPrefix(sect.Name, ".zdebug") { sh.Flags = 0 + sh.Addr = 0 if sect.Compressed { sh.Flags |= uint64(elf.SHF_COMPRESSED) } } - if linkmode != LinkExternal { - sh.Addr = sect.Vaddr - } sh.Addralign = uint64(sect.Align) sh.Size = sect.Length if sect.Name != ".tbss" {