• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/bin/bash
2set -e -o pipefail
3
4# This script wraps the go cross compilers.
5#
6# It ensures that Go binaries are linked with an external linker
7# by default (cross clang). Appropriate flags are added to build a
8# position independent executable (PIE) for ASLR.
9# "export GOPIE=0" to temporarily disable this behavior.
10
11function pie_enabled()
12	{
13	[[ "${GOPIE}" != "0" ]]
14	}
15
16function has_ldflags()
17	{
18	# Check if any linker flags are present in argv.
19	for arg in "$@"
20	do
21		case "${arg}" in
22			-ldflags | -ldflags=*) return 0 ;;
23			-linkmode | -linkmode=*) return 0 ;;
24			-buildmode | -buildmode=*) return 0 ;;
25			-installsuffix | -installsuffix=*) return 0 ;;
26			-extld | -extld=*) return 0 ;;
27			-extldflags | -extldflags=*) return 0 ;;
28		esac
29	done
30	return 1
31	}
32
33pie_flags=()
34if pie_enabled && ! has_ldflags "$@"
35then
36	case "$1" in
37		build | install | run | test)
38			# Add "-buildmode=pie" to "go build|install|run|test" commands.
39			pie_flags=( "$1" )
40			shift
41			[[ "${GOOS}" == "android" ]] || pie_flags+=( "-buildmode=pie" )
42			;;
43		tool)
44			case "$2" in
45				asm)
46					# Handle direct assembler invocations ("go tool asm <args>").
47					pie_flags=( "$1" "$2" "-shared" )
48					shift 2
49					;;
50				compile)
51					# Handle direct compiler invocations ("go tool compile <args>").
52					pie_flags=( "$1" "$2" "-shared" )
53					shift 2
54					[[ "${GOOS}" == "android" ]] || pie_flags+=( "-installsuffix=shared" )
55					;;
56				link)
57					# Handle direct linker invocations ("go tool link <args>").
58					pie_flags=( "$1" "$2" "-extld" "${CC}" "-buildmode=pie" )
59					shift 2
60					[[ "${GOOS}" == "android" ]] || pie_flags+=( "-installsuffix=shared" )
61					;;
62			esac
63			;;
64	esac
65fi
66
67exec go "${pie_flags[@]}" "$@"
68