aboutsummaryrefslogtreecommitdiff
path: root/go/go_target
blob: 8943d813c4e73023affd56c48a19209acf33c4e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/bin/bash
set -e -o pipefail

# This script wraps the go cross compilers.
#
# It ensures that Go binaries are linked with an external linker
# by default (cross clang). Appropriate flags are added to build a
# position independent executable (PIE) for ASLR.
# "export GOPIE=0" to temporarily disable this behavior.

function pie_enabled()
	{
	[[ "${GOPIE}" != "0" ]]
	}

function has_ldflags()
	{
	# Check if any linker flags are present in argv.
	for arg in "$@"
	do
		case "${arg}" in
			-ldflags | -ldflags=*) return 0 ;;
			-linkmode | -linkmode=*) return 0 ;;
			-buildmode | -buildmode=*) return 0 ;;
			-installsuffix | -installsuffix=*) return 0 ;;
			-extld | -extld=*) return 0 ;;
			-extldflags | -extldflags=*) return 0 ;;
		esac
	done
	return 1
	}

pie_flags=()
if pie_enabled && ! has_ldflags "$@"
then
	case "$1" in
		build | install | run | test)
			# Add "-buildmode=pie" to "go build|install|run|test" commands.
			pie_flags=( "$1" )
			shift
			[[ "${GOOS}" == "android" ]] || pie_flags+=( "-buildmode=pie" )
			;;
		tool)
			case "$2" in
				asm)
					# Handle direct assembler invocations ("go tool asm <args>").
					pie_flags=( "$1" "$2" "-shared" )
					shift 2
					;;
				compile)
					# Handle direct compiler invocations ("go tool compile <args>").
					pie_flags=( "$1" "$2" "-shared" )
					shift 2
					[[ "${GOOS}" == "android" ]] || pie_flags+=( "-installsuffix=shared" )
					;;
				link)
					# Handle direct linker invocations ("go tool link <args>").
					pie_flags=( "$1" "$2" "-extld" "${CC}" "-buildmode=pie" )
					shift 2
					[[ "${GOOS}" == "android" ]] || pie_flags+=( "-installsuffix=shared" )
					;;
			esac
			;;
	esac
fi

exec go "${pie_flags[@]}" "$@"