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 gcc). 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=( 40 "$1" 41 "-buildmode=pie" 42 ) 43 shift 44 ;; 45 tool) 46 case "$2" in 47 asm) 48 # Handle direct assembler invocations ("go tool asm <args>"). 49 pie_flags=( 50 "$1" 51 "$2" 52 "-shared" 53 ) 54 shift 2 55 ;; 56 compile) 57 # Handle direct compiler invocations ("go tool compile <args>"). 58 pie_flags=( 59 "$1" 60 "$2" 61 "-shared" 62 "-installsuffix=shared" 63 ) 64 shift 2 65 ;; 66 link) 67 # Handle direct linker invocations ("go tool link <args>"). 68 pie_flags=( 69 "$1" 70 "$2" 71 "-installsuffix=shared" 72 "-buildmode=pie" 73 "-extld" 74 "${CC}" 75 ) 76 shift 2 77 ;; 78 esac 79 ;; 80 esac 81fi 82 83exec go "${pie_flags[@]}" "$@" 84