cgo: interpret $CGOPKGDIR as absolute path if rooted

R=dho
CC=golang-dev
https://golang.org/cl/180099
diff --git a/src/Make.pkg b/src/Make.pkg
index 890f43d..b315b2e 100644
--- a/src/Make.pkg
+++ b/src/Make.pkg
@@ -23,7 +23,11 @@
 TARG_words=$(subst /, ,$(TARG))
 elem=$(word $(words $(TARG_words)),$(TARG_words))
 
-dir=$(patsubst %/$(elem),%,./$(TARG))
+ifeq ($(elem),$(TARG))
+dir=
+else
+dir=$(patsubst %/$(elem),%,$(TARG))
+endif
 
 # ugly hack to deal with whitespaces in $GOROOT
 nullstring :=
diff --git a/src/cmd/cgo/main.go b/src/cmd/cgo/main.go
index d1b551b..607f26b 100644
--- a/src/cmd/cgo/main.go
+++ b/src/cmd/cgo/main.go
@@ -126,8 +126,11 @@
 		if nerrors > 0 {
 			os.Exit(2)
 		}
-
-		p.PackagePath = os.Getenv("CGOPKGPATH") + "/" + p.Package
+		pkg := p.Package
+		if dir := os.Getenv("CGOPKGPATH"); dir != "" {
+			pkg = dir + "/" + pkg
+		}
+		p.PackagePath = pkg
 		p.writeOutput(input)
 	}
 
diff --git a/src/cmd/cgo/out.go b/src/cmd/cgo/out.go
index 8720d6f..4c72f4c 100644
--- a/src/cmd/cgo/out.go
+++ b/src/cmd/cgo/out.go
@@ -24,6 +24,10 @@
 // (The comments here say 6g and 6c but the code applies to the 8 and 5 tools too.)
 func (p *Prog) writeDefs() {
 	pkgroot := os.Getenv("GOROOT") + "/pkg/" + os.Getenv("GOOS") + "_" + os.Getenv("GOARCH")
+	path := p.PackagePath
+	if !strings.HasPrefix(path, "/") {
+		path = pkgroot + "/" + path
+	}
 
 	fgo2 := creat("_cgo_gotypes.go")
 	fc := creat("_cgo_defun.c")
@@ -46,7 +50,7 @@
 	fmt.Fprintf(fc, cProlog, pkgroot, pkgroot, pkgroot, pkgroot, p.Package, p.Package)
 
 	for name, def := range p.Vardef {
-		fmt.Fprintf(fc, "#pragma dynld %s·_C_%s %s \"%s/%s.so\"\n", p.Package, name, name, pkgroot, p.PackagePath)
+		fmt.Fprintf(fc, "#pragma dynld %s·_C_%s %s \"%s.so\"\n", p.Package, name, name, path)
 		fmt.Fprintf(fgo2, "var _C_%s ", name)
 		printer.Fprint(fgo2, &ast.StarExpr{X: def.Go})
 		fmt.Fprintf(fgo2, "\n")
@@ -121,7 +125,7 @@
 
 		// C wrapper calls into gcc, passing a pointer to the argument frame.
 		// Also emit #pragma to get a pointer to the gcc wrapper.
-		fmt.Fprintf(fc, "#pragma dynld _cgo_%s _cgo_%s \"%s/%s.so\"\n", name, name, pkgroot, p.PackagePath)
+		fmt.Fprintf(fc, "#pragma dynld _cgo_%s _cgo_%s \"%s.so\"\n", name, name, path)
 		fmt.Fprintf(fc, "void (*_cgo_%s)(void*);\n", name)
 		fmt.Fprintf(fc, "\n")
 		fmt.Fprintf(fc, "void\n")