diff --git a/dev-tools/mage/build.go b/dev-tools/mage/build.go index 20a6946d779..5c5156adf44 100644 --- a/dev-tools/mage/build.go +++ b/dev-tools/mage/build.go @@ -62,9 +62,38 @@ func DefaultBuildArgs() BuildArgs { if versionQualified { args.Vars[elasticBeatsModulePath+"/libbeat/version.qualifier"] = "{{ .Qualifier }}" } + + if positionIndependendCodeSupported() { + args.ExtraFlags = append(args.ExtraFlags, "-buildmode", "pie") + } + return args } +// positionIndependendCodeSupported checks if the target platform support position independen code (or ASLR). +// +// The list of supported platforms is compiled based on the Go release notes: https://golang.org/doc/devel/release.html +// The list has been updated according to the Go version: 1.16 +func positionIndependendCodeSupported() bool { + return oneOf(Platform.GOOS, "darwin") || + (Platform.GOOS == "linux" && oneOf(Platform.GOARCH, "riscv64", "amd64", "arm", "arm64", "ppc64le", "386")) || + (Platform.GOOS == "aix" && Platform.GOARCH == "ppc64") || + + // Windows 32bit supports ASLR, but Windows Server 2003 and earlier do not. + // According to the support matrix (https://www.elastic.co/support/matrix), these old versions + // are not supported. + (Platform.GOOS == "windows") +} + +func oneOf(value string, lst ...string) bool { + for _, other := range lst { + if other == value { + return true + } + } + return false +} + // DefaultGolangCrossBuildArgs returns the default BuildArgs for use in // cross-builds. func DefaultGolangCrossBuildArgs() BuildArgs {