aboutsummaryrefslogtreecommitdiff
path: root/go/go_target
blob: 057863778b68c52327d49b213827c6441bd8872d (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/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 gcc). 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"
				"-buildmode=pie"
			)
			shift
			;;
		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"
						"-installsuffix=shared"
					)
					shift 2
					;;
				link)
					# Handle direct linker invocations ("go tool link <args>").
					pie_flags=(
						"$1"
						"$2"
						"-installsuffix=shared"
						"-buildmode=pie"
						"-extld"
						"${CC}"
					)
					shift 2
					;;
			esac
			;;
	esac
fi

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