Skip to content

Commit

Permalink
cmd/link: detect -X setting non-string variable
Browse files Browse the repository at this point in the history
Fixes golang#9621.

Change-Id: Ib9c6001378364af899f57fd4b89fb23af2042923
Reviewed-on: https://go-review.googlesource.com/11694
Reviewed-by: Brad Fitzpatrick <[email protected]>
Run-TryBot: Russ Cox <[email protected]>
  • Loading branch information
rsc committed Jun 29, 2015
1 parent c418fe7 commit 69f0d4c
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/cmd/link/internal/ld/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,8 @@ func strnput(s string, n int) {
}
}

var strdata []*LSym

func addstrdata1(arg string) {
i := strings.Index(arg, "=")
if i < 0 {
Expand Down Expand Up @@ -944,9 +946,21 @@ func addstrdata(name string, value string) {
// we know before entering this function.
s.Reachable = reachable

strdata = append(strdata, s)

sp.Reachable = reachable
}

func checkstrdata() {
for _, s := range strdata {
if s.Type == obj.STEXT {
Diag("cannot use -X with text symbol %s", s.Name)
} else if s.Gotype != nil && s.Gotype.Name != "type.string" {
Diag("cannot use -X with non-string symbol %s", s.Name)
}
}
}

func Addstring(s *LSym, str string) int64 {
if s.Type == 0 {
s.Type = obj.SNOPTRDATA
Expand Down
1 change: 1 addition & 0 deletions src/cmd/link/internal/ld/pobj.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ func Ldmain() {
}

checkgo()
checkstrdata()
deadcode()
callgraph()

Expand Down
3 changes: 3 additions & 0 deletions test/linkx.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import "fmt"
var tbd string
var overwrite string = "dibs"

var b bool
var x int

func main() {
fmt.Println(tbd)
fmt.Println(overwrite)
Expand Down
18 changes: 18 additions & 0 deletions test/linkx_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"fmt"
"os"
"os/exec"
"strings"
)

func main() {
Expand Down Expand Up @@ -49,4 +50,21 @@ func test(sep string) {
fmt.Println("-X linker flag should not accept keys without values")
os.Exit(1)
}

// Issue 9621
cmd = exec.Command("go", "run", "-ldflags=-X main.b=false -X main.x=42", "linkx.go")
outx, err := cmd.CombinedOutput()
if err == nil {
fmt.Println("-X linker flag should not overwrite non-strings")
os.Exit(1)
}
outstr := string(outx)
if !strings.Contains(outstr, "main.b") {
fmt.Printf("-X linker flag did not diagnose overwrite of main.b\n")
os.Exit(1)
}
if !strings.Contains(outstr, "main.x") {
fmt.Printf("-X linker flag did not diagnose overwrite of main.x\n")
os.Exit(1)
}
}

0 comments on commit 69f0d4c

Please sign in to comment.