github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/link/internal/ld/elf_test.go (about)

     1  // +build cgo
     2  
     3  // Copyright 2019 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package ld
     8  
     9  import (
    10  	"debug/elf"
    11  	"github.com/gagliardetto/golang-go/not-internal/testenv"
    12  	"io/ioutil"
    13  	"os"
    14  	"os/exec"
    15  	"path/filepath"
    16  	"testing"
    17  )
    18  
    19  func TestDynSymShInfo(t *testing.T) {
    20  	t.Parallel()
    21  	testenv.MustHaveGoBuild(t)
    22  	dir, err := ioutil.TempDir("", "go-build-issue33358")
    23  	if err != nil {
    24  		t.Fatal(err)
    25  	}
    26  	defer os.RemoveAll(dir)
    27  
    28  	const prog = `
    29  package main
    30  
    31  import "net"
    32  
    33  func main() {
    34  	net.Dial("", "")
    35  }
    36  `
    37  	src := filepath.Join(dir, "issue33358.go")
    38  	if err := ioutil.WriteFile(src, []byte(prog), 0666); err != nil {
    39  		t.Fatal(err)
    40  	}
    41  
    42  	binFile := filepath.Join(dir, "issue33358")
    43  	cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", binFile, src)
    44  	if out, err := cmd.CombinedOutput(); err != nil {
    45  		t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
    46  	}
    47  
    48  	fi, err := os.Open(binFile)
    49  	if err != nil {
    50  		t.Fatalf("failed to open built file: %v", err)
    51  	}
    52  
    53  	elfFile, err := elf.NewFile(fi)
    54  	if err != nil {
    55  		t.Skip("The system may not support ELF, skipped.")
    56  	}
    57  
    58  	section := elfFile.Section(".dynsym")
    59  	if section == nil {
    60  		t.Fatal("no dynsym")
    61  	}
    62  
    63  	symbols, err := elfFile.DynamicSymbols()
    64  	if err != nil {
    65  		t.Fatalf("failed to get dynamic symbols: %v", err)
    66  	}
    67  
    68  	var numLocalSymbols uint32
    69  	for i, s := range symbols {
    70  		if elf.ST_BIND(s.Info) != elf.STB_LOCAL {
    71  			numLocalSymbols = uint32(i + 1)
    72  			break
    73  		}
    74  	}
    75  
    76  	if section.Info != numLocalSymbols {
    77  		t.Fatalf("Unexpected sh info, want greater than 0, got: %d", section.Info)
    78  	}
    79  }