cmd/go: if -msan, pass -fsanitize=memory to cgo builds

Also fix the msan_fail test.  It was bogus, since it always aborted one
way or another.

Change-Id: Ic693327d1bddb7bc5c7d859ac047fc93cb9b5b1c
Reviewed-on: https://go-review.googlesource.com/16172
Reviewed-by: David Crawshaw <crawshaw@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/misc/cgo/testsanitizers/msan_fail.go b/misc/cgo/testsanitizers/msan_fail.go
index 3be656f..50379a9 100644
--- a/misc/cgo/testsanitizers/msan_fail.go
+++ b/misc/cgo/testsanitizers/msan_fail.go
@@ -13,7 +13,8 @@
 
 void g(int32_t *p, int n) {
   if (p[4] != 1) {
-    abort();
+    // We shouldn't get here; msan should stop us first.
+    exit(0);
   }
 }
 */
diff --git a/src/cmd/go/build.go b/src/cmd/go/build.go
index 8df312a..1ec98aa 100644
--- a/src/cmd/go/build.go
+++ b/src/cmd/go/build.go
@@ -2893,6 +2893,11 @@
 		cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc")
 	}
 
+	if buildMSan && p.ImportPath != "runtime/cgo" {
+		cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...)
+		cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...)
+	}
+
 	// Allows including _cgo_export.h from .[ch] files in the package.
 	cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", obj)