rules_go icon indicating copy to clipboard operation
rules_go copied to clipboard

Remove -pie from LDFLAGS if buildmode is not pie

Open siddharthab opened this issue 9 months ago • 4 comments

What version of rules_go are you using?

0.41.0

What version of gazelle are you using?

N/A

What version of Bazel are you using?

6.3.2

Does this issue reproduce with the latest releases of all the above?

Yes

What operating system and processor architecture are you using?

Debian 12

Any other potentially useful information about your toolchain?

LLVM 15 with LLD. On Debian like systems, can be set up with:

sudo apt-get install clang-15 lld-15

What did you do?

CASE 1: Tried to build and run a cgo test target within this project with the --force_pic flag.

CC=clang-15 bazel run --force_pic //tests/core/cgo:c_srcs

CASE 2: Instead of one of the tests from this repo, a simpler Go program can also be:

// File main.go
package main

// #cgo LDFLAGS: -lm
// #include <math.h>
import "C"
import "fmt"

func main() {
	fmt.Println(int(C.sqrt(100.0)))
}

with a build target that is simply:

go_binary(
  name = "main",
  srcs = ["main.go"],
  cgo = True,
)

What did you expect to see?

The test target run completing successfully, and/or the simpler Go program run completing successfully.

What did you see instead?

runtime: pcHeader: magic= 0xfffffff1 pad1= 0 pad2= 0 minLC= 1 ptrSize= 8 pcHeader.textStart= 0x9dc40 text= 0x5611882ecc40 pluginpath= 
fatal error: invalid function symbol table
runtime: panic before malloc heap initialized

runtime stack:
runtime.throw({0x561188274f78?, 0x0?})
	GOROOT/src/runtime/panic.go:1047 +0x5d fp=0x7ffd1e384c80 sp=0x7ffd1e384c50 pc=0x56118831cefd
runtime.moduledataverify1(0x7ffd1e384dac?)
	GOROOT/src/runtime/symtab.go:627 +0x806 fp=0x7ffd1e384d80 sp=0x7ffd1e384c80 pc=0x5611883384e6
runtime.moduledataverify(...)
	GOROOT/src/runtime/symtab.go:613
runtime.schedinit()
	GOROOT/src/runtime/proc.go:710 +0x3a fp=0x7ffd1e384de0 sp=0x7ffd1e384d80 pc=0x5611883209da
runtime.rt0_go()
	src/runtime/asm_amd64.s:349 +0x11c fp=0x7ffd1e384de8 sp=0x7ffd1e384de0 pc=0x561188347ddc

Notes

This crash is happening because force_pic is sending the -pie flag to the linker, which gets passed along as part of CGO_LDFLAGS. But because the buildmode is not set to "pie" in the go_binary target, I think the stdlib is mismatched.

This is not a problem with the standard Go toolchain because it filters out the "-pie" flag from CGO_LDFLAGS.

Building under normal buildmode, will filter out "-pie" from the linker command. Notice that there were no -extldflags set for the link step.

CC=clang-15 CGO_LDFLAGS='-v -fuse-ld=lld -pie' go build -x main.go

To force sending "-pie" to the linker, you will have to explicitly set -extldflags.

CC=clang-15 CGO_LDFLAGS='-v -fuse-ld=lld' go build -ldflags -extldflags='-pie' -x main.go

siddharthab avatar Sep 13 '23 23:09 siddharthab