summaryrefslogtreecommitdiff
path: root/hack/make/.binary
blob: 5bc95e76e2c2f0384f8b9e9f3cc7a2deaf48824f (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
#!/usr/bin/env bash
set -e

# a helper to provide ".exe" when it's appropriate
binary_extension() {
	if [ "$(go env GOOS)" = 'windows' ]; then
		echo -n '.exe'
	fi
}

BINARY_EXTENSION="$(binary_extension)"
BINARY_FULLNAME="$BINARY_NAME$BINARY_EXTENSION"

source "${MAKEDIR}/.go-autogen"

(
	export GOGC=${DOCKER_BUILD_GOGC:-1000}

	if [ "$(go env GOOS)/$(go env GOARCH)" != "$(go env GOHOSTOS)/$(go env GOHOSTARCH)" ]; then
		# must be cross-compiling!
		if [ "$(go env GOOS)/$(go env GOARCH)" = "linux/arm" ]; then
			# specify name of the target ARM architecture
			case "$(go env GOARM)" in
				5)
					export CGO_CFLAGS="-march=armv5t"
					export CGO_CXXFLAGS="-march=armv5t"
					;;
				6)
					export CGO_CFLAGS="-march=armv6"
					export CGO_CXXFLAGS="-march=armv6"
					;;
				7)
					export CGO_CFLAGS="-march=armv7-a"
					export CGO_CXXFLAGS="-march=armv7-a"
					;;
			esac
		fi
	fi

	# -buildmode=pie is not supported on Windows arm64 and Linux mips*, ppc64be
	# https://github.com/golang/go/blob/go1.19.4/src/cmd/internal/sys/supported.go#L125-L132
	if ! [ "$DOCKER_STATIC" = "1" ]; then
		# -buildmode=pie not supported when -race is enabled
		if [[ " $BUILDFLAGS " != *" -race "* ]]; then
			case "$(go env GOOS)/$(go env GOARCH)" in
				windows/arm64 | linux/mips* | linux/ppc64) ;;
				*)
					BUILDFLAGS+=("-buildmode=pie")
					;;
			esac
		fi
	fi

	# only necessary for non-sandboxed invocation where TARGETPLATFORM is empty
	PLATFORM_NAME=$TARGETPLATFORM
	if [ -z "$PLATFORM_NAME" ]; then
		PLATFORM_NAME="$(go env GOOS)/$(go env GOARCH)"
		if [ -n "$(go env GOARM)" ]; then
			PLATFORM_NAME+="/v$(go env GOARM)"
		elif [ -n "$(go env GOAMD64)" ] && [ "$(go env GOAMD64)" != "v1" ]; then
			PLATFORM_NAME+="/$(go env GOAMD64)"
		fi
	fi

	# This is a workaround to have buildinfo with deps embedded in the binary. We
	# need to create a go.mod file before building with -modfile=vendor.mod,
	# otherwise it fails with: "-modfile cannot be used to set the module root directory."
	if [ ! -f "go.mod" ]; then
		printf '%s\n\n%s' 'module github.com/docker/docker' 'go 1.19' > "go.mod"
		trap 'rm -f go.mod' EXIT
	fi

	echo "Building $([ "$DOCKER_STATIC" = "1" ] && echo "static" || echo "dynamic") $DEST/$BINARY_FULLNAME ($PLATFORM_NAME)..."
	if [ -n "$DOCKER_DEBUG" ]; then
		set -x
	fi
	GO111MODULE=on go build -mod=vendor -modfile=vendor.mod -o "$DEST/$BINARY_FULLNAME" "${BUILDFLAGS[@]}" -ldflags "$LDFLAGS $LDFLAGS_STATIC $DOCKER_LDFLAGS" ${GO_PACKAGE}
)

echo "Created binary: $DEST/$BINARY_FULLNAME"