Slide 1

Slide 1 text

From cgo back to Go Filippo Valsorda

Slide 2

Slide 2 text

“cgo is not Go” —Dave Cheney http://dave.cheney.net/2016/01/18/cgo-is-not-go

Slide 3

Slide 3 text

• Effortless memory management • Runtime speed • Awesome tooling • Fast builds • Static binaries • Reproducible builds • go get • Super-easy cross compiling

Slide 4

Slide 4 text

Then you import “C”

Slide 5

Slide 5 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 6

Slide 6 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 7

Slide 7 text

Go memory C memory GC

Slide 8

Slide 8 text

Go memory C memory GC make([]byte, 1024) &MyStruct{}

Slide 9

Slide 9 text

Go memory C memory GC []byte *MyStruct

Slide 10

Slide 10 text

Go memory C memory GC []byte

Slide 11

Slide 11 text

Go memory C memory GC []byte

Slide 12

Slide 12 text

Go memory C memory GC []byte *uint8_t C.some_func()

Slide 13

Slide 13 text

Go memory C memory GC []byte

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

Go memory C memory GC []byte *uint8_t C.some_func()

Slide 16

Slide 16 text

Go memory C memory GC []byte *uint8_t

Slide 17

Slide 17 text

Go memory C memory GC *uint8_t

Slide 18

Slide 18 text

Go memory C memory GC *uint8_t

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

// typedef struct { // int a, b, c; // } someStruct; // // someStruct *someReference; // void storeReference(someStruct *s) { // someReference = s; // } // int retrieveReference() { // return someReference->a; // } import "C" import "runtime" func main() { passSomeMemory() runtime.GC() println(getSomeMemory()) } func passSomeMemory() { someGoMemory := &C.someStruct{ a: 1, b: 2, c: 3, } C.storeReference(someGoMemory) } func getSomeMemory() int { return int(C.retrieveReference()) } Output: 1

Slide 22

Slide 22 text

Output: 1 // typedef struct { // int a, b, c; // } someStruct; // // someStruct *someReference; // void storeReference(someStruct *s) { // someReference = s; // } // int retrieveReference() { // return someReference->a; // } import "C" import "runtime" func main() { passSomeMemory() runtime.GC() println(getSomeMemory()) } func passSomeMemory() { someGoMemory := &C.someStruct{ a: 1, b: 2, c: 3, } C.storeReference(someGoMemory) } func getSomeMemory() int { return int(C.retrieveReference()) } 537247792

Slide 23

Slide 23 text

The cgo rules You may pass a Go pointer … if it doesn’t point to other pointers … and C can’t keep a reference to it

Slide 24

Slide 24 text

The GC must see all the Go pointers.

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

// #include // // typedef struct { // int a, b, c; // } someStruct; // // void processStruct(someStruct *s) {} import "C" func ProcessStruct() { someCMemory := C.calloc(1, C.sizeof_someStruct) defer C.free(someCMemory) s := (*C.someStruct)(someCMemory) C.processStruct(s) }

Slide 28

Slide 28 text

// #include // // typedef struct { // int a, b, c; // } someStruct; // // void processStruct(someStruct *s) {} import "C" func ProcessStruct() { someCMemory := C.calloc(1, C.sizeof_someStruct) defer C.free(someCMemory) s := (*C.someStruct)(someCMemory) C.processStruct(s) }

Slide 29

Slide 29 text

Copy. Copy. Copy.

Slide 30

Slide 30 text

// #include // // typedef struct { // int a, b, c; // char *str; // } someStruct; // // void processStruct(someStruct *s) {} import "C" import "unsafe" func ProcessStruct(str string) { s := (*C.someStruct)(C.calloc(1, C.sizeof_someStruct)) defer C.free(unsafe.Pointer(s)) s.str = C.CString(str) defer C.free(unsafe.Pointer(s.str)) C.processStruct(s) }

Slide 31

Slide 31 text

// #include // #include // #include // typedef struct { uint8_t *data; size_t data_len; } someStruct; // void processStruct(someStruct *s) {} import "C" import "unsafe" func ProcessStruct(data []byte) { s := (*C.someStruct)(C.calloc(1, C.sizeof_someStruct)) defer C.free(unsafe.Pointer(s)) cMem := C.calloc(1, C.size_t(len(data))) defer C.free(cMem) s.data = (*C.uint8_t)(C.memmove( cMem, unsafe.Pointer(&data[0]), C.size_t(len(data)))) s.data_len = C.size_t(len(data)) C.processStruct(s) }

Slide 32

Slide 32 text

// #include // #include // #include // // typedef struct { // uint8_t *data; // size_t data_len; // } someStruct; // // void processStruct(someStruct *s) {} import "C" import "unsafe" type SomeStruct struct { Data []byte } func ProcessStruct(s *SomeStruct) { [...] }

Slide 33

Slide 33 text

// #cgo pkg-config: sqlite3 // #include import "C" import "errors" type DB struct { db *C.sqlite3 } func Open(filename string) (d *DB, err error) { d = &DB{} if C.sqlite3_open(C.CString(filename), &d.db) != C.SQLITE_OK { err = errors.New(C.GoString(C.sqlite3_errmsg(d.db))) C.sqlite3_close(d.db) } return } func (d *DB) Close() { C.sqlite3_close(d.db) } Wrapper types

Slide 34

Slide 34 text

The arena pattern

Slide 35

Slide 35 text

type arena []unsafe.Pointer func (a *arena) calloc(count, size int) unsafe.Pointer { ptr := C.calloc(C.size_t(count), C.size_t(size)) *a = append(*a, ptr) return ptr } func (a *arena) free() { for _, ptr := range *a { C.free(ptr) } }

Slide 36

Slide 36 text

func ProcessStruct(s *SomeStruct) { ar := &arena{} defer ar.free() cs := (*C.someStruct)(ar.calloc(C.sizeof_someStruct, 1)) cMem := ar.calloc(1, len(s.Data)) cs.data = (*C.uint8_t)(C.memmove(cMem, unsafe.Pointer(&s.Data[0]), C.size_t(len(s.Data)))) cs.data_len = C.size_t(len(s.Data)) C.processStruct(cs) }

Slide 37

Slide 37 text

type arena []unsafe.Pointer func (a *arena) calloc(count, size int) unsafe.Pointer { ptr := C.calloc(C.size_t(count), C.size_t(size)) *a = append(*a, ptr) return ptr } func (a *arena) copy(data []byte) unsafe.Pointer { ptr := a.calloc(1, len(data)) C.memmove(ptr, unsafe.Pointer(&data[0]), C.size_t(len(data))) return ptr } func (a *arena) free() { for _, ptr := range *a { C.free(ptr) } }

Slide 38

Slide 38 text

func ProcessStruct(s *SomeStruct) { ar := &arena{} defer ar.free() cs := (*C.someStruct)(ar.calloc(C.sizeof_someStruct, 1)) cs.data = (*C.uint8_t)(ar.copy(s.Data)) cs.data_len = C.size_t(len(s.Data)) C.processStruct(cs) }

Slide 39

Slide 39 text

If you really have to…

Slide 40

Slide 40 text

// #include // #include // // void processBigData(uint8_t *data, size_t data_len) {} import "C" func ProcessBigData(bigData []byte) { cBigData = (*C.uint8_t)(&bigData[0]) cBigDataLen = C.size_t(len(bigData)) C.processBigData(cBigData, cBigDataLen) }

Slide 41

Slide 41 text

Go memory C memory GC []byte

Slide 42

Slide 42 text

Go memory C memory GC []byte *uint8_t C.some_func()

Slide 43

Slide 43 text

Go memory C memory GC []byte

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

// typedef struct { // int a, b, c; // } someStruct; // // typedef struct { // someStruct *x, *y; // } complexStruct; // // void processStruct(complexStruct *s) {} import "C" func main() { someGoMemory := &C.someStruct{ a: 1, b: 2, c: 3, } C.processStruct(&C.complexStruct{ x: someGoMemory, y: nil, }) }

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

panic: runtime error: cgo argument has Go pointer to Go pointer

Slide 49

Slide 49 text

GODEBUG=cgocheck=2

Slide 50

Slide 50 text

go doc cmd/cgo

Slide 51

Slide 51 text

Callbacks

Slide 52

Slide 52 text

int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ );

Slide 53

Slide 53 text

var zErrMsg *C.char rc = C.sqlite3_exec(d.db, sqlStatement, ???, ???, &zErrMsg) if rc != C.SQLITE_OK { log.Printf("SQL error: %s\n", C.GoString(zErrMsg)) C.sqlite3_free(unsafe.Pointer(zErrMsg)) }

Slide 54

Slide 54 text

package main import "C" import "unsafe" //export callback func callback(userData uintptr, _ C.int, _ **C.char, _ **C.char) C.int { return 0 }

Slide 55

Slide 55 text

// #cgo pkg-config: sqlite3 // #include // int callback(void*, int, char**, char**); import "C" [...] var zErrMsg *C.char rc = C.sqlite3_exec(d.db, sqlStatement, (*[0]byte)(C.callback), unsafe.Pointer(nil), &zErrMsg) if rc != C.SQLITE_OK { log.Printf("SQL error: %s\n", C.GoString(zErrMsg)) C.sqlite3_free(unsafe.Pointer(zErrMsg)) }

Slide 56

Slide 56 text

// NOTE: it’s up to you to manage concurrency (i.e. with a RWMutex) var handles = make(map[uintptr]interface{}) // NOTE: use low numbers not to overlap with Go memory handles[uintptr(42)] = "some Go memory" rc = C.sqlite3_exec(d.db, sqlStatement, (*[0]byte)(C.callback), unsafe.Pointer(uintptr(42)), &zErrMsg) //export callback func callback(userData uintptr, _ C.int, _ **C.char, _ **C.char) C.int { goData := handles[userData] [...] } Example: https://github.com/mattn/go-sqlite3/blob/ 76e335f60bbcee20755df9864f0153af1a80ad2d/callback.go#L52

Slide 57

Slide 57 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 58

Slide 58 text

package main // #cgo LDFLAGS: -lm // #include // void slow_func() { // double a; int i; // for (i = 1; i < 1e8; i++) { // a = pow(a, 3); // } // } import "C" import "os" import "runtime/pprof" func main() { f, _ := os.Create("cgo.pprof") pprof.StartCPUProfile(f) C.slow_func() pprof.StopCPUProfile() }

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

$ apt-get install linux-tools-generic $ go version go version go1.7rc1 linux/amd64 $ perf record ./slow $ perf report

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 63

Slide 63 text

package main // #cgo LDFLAGS: -lm // #include import "C" func main() { var a C.double for i := 1; i < 1e8; i++ { a = C.pow(a, 3) } }

Slide 64

Slide 64 text

package main // #cgo LDFLAGS: -lm // #include // void powloop() { // double a; int i; // for (i = 1; i < 1e8; i++) { // a = pow(a, 3); // } // } import "C" func main() { C.powloop() }

Slide 65

Slide 65 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 66

Slide 66 text

$ cat $GOPATH/src/github.com/FiloSottile/hashpass/main.go package main // #cgo pkg-config: libsodium // #include import "C" func main() { C.sodium_init() println(hashPass("Correct Horse Battery Staple")) } func hashPass(pass string) string { cMem := C.calloc(1, C.crypto_pwhash_STRBYTES) defer C.free(cMem) res := (*C.char)(cMem) C.crypto_pwhash_str(res, C.CString(pass), (C.ulonglong)(len(pass)), C.crypto_pwhash_OPSLIMIT_SENSITIVE, C.crypto_pwhash_MEMLIMIT_SENSITIVE) return C.GoStringN(res, C.crypto_pwhash_STRBYTES) }

Slide 67

Slide 67 text

$ (cd libsodium-1.0.10 && ./configure && make install) $ go build github.com/FiloSottile/hashpass $ ./hashpass $argon2i$v=19$m=524288,t=8,p=1$ISqzZv/SaISgeOJTsWIc4Q $w5PTypPasNCkQhm6mnfMhYqpkoGXn0UCO42J6Qjrnko $ file hashpass hashpass: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=dbae930638bb69e5c461a33d1823906928bb3706, not stripped

Slide 68

Slide 68 text

$ go build -v -x github.com/FiloSottile/hashpass WORK=/tmp/go-build285911135 github.com/FiloSottile/hashpass mkdir -p $WORK/github.com/FiloSottile/hashpass/_obj/ mkdir -p $WORK/github.com/FiloSottile/hashpass/_obj/exe/ cd /Users/filippo/go/src/github.com/FiloSottile/hashpass pkg-config --cflags libsodium pkg-config --libs libsodium CGO_LDFLAGS="-g" "-O2" "-L/usr/local/lib" "-lsodium" /usr/local/go/pkg/tool/linux_amd64/cgo -objdir $WORK/github.com/FiloSottile/hashpass/ _obj/ -importpath github.com/FiloSottile/hashpass -- -I/usr/local/include -I $WORK/github.com/FiloSottile/hashpass/_obj/ main.go gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -I/usr/local/include -I $WORK/github.com/FiloSottile/hashpass/_obj/ -g -O2 -o $WORK/ github.com/FiloSottile/hashpass/_obj/_cgo_main.o -c $WORK/github.com/FiloSottile/hashpass/_obj/_cgo_main.c gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -I/usr/local/include -I $WORK/github.com/FiloSottile/hashpass/_obj/ -g -O2 -o $WORK/ github.com/FiloSottile/hashpass/_obj/_cgo_export.o -c $WORK/github.com/FiloSottile/hashpass/_obj/_cgo_export.c gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -I/usr/local/include -I $WORK/github.com/FiloSottile/hashpass/_obj/ -g -O2 -o $WORK/ github.com/FiloSottile/hashpass/_obj/main.cgo2.o -c $WORK/github.com/FiloSottile/hashpass/_obj/main.cgo2.c gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -o $WORK/github.com/FiloSottile/hashpass/_obj/_cgo_.o $WORK/github.com/FiloSottile/ hashpass/_obj/_cgo_main.o $WORK/github.com/FiloSottile/hashpass/_obj/_cgo_export.o $WORK/github.com/FiloSottile/hashpass/_obj/main.cgo2.o -g -O2 -L/usr/local/lib -lsodium /usr/local/go/pkg/tool/linux_amd64/cgo -objdir $WORK/github.com/FiloSottile/hashpass/_obj/ -dynpackage main -dynimport $WORK/github.com/ FiloSottile/hashpass/_obj/_cgo_.o -dynout $WORK/github.com/FiloSottile/hashpass/_obj/_cgo_import.go cd $WORK gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -no-pie -c trivial.c cd /Users/filippo/go/src/github.com/FiloSottile/hashpass gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -o $WORK/github.com/FiloSottile/hashpass/_obj/_all.o $WORK/github.com/FiloSottile/ hashpass/_obj/_cgo_export.o $WORK/github.com/FiloSottile/hashpass/_obj/main.cgo2.o -g -O2 -L/usr/local/lib -Wl,-r -nostdlib -Wl,--build- id=none /usr/local/go/pkg/tool/linux_amd64/compile -o $WORK/github.com/FiloSottile/hashpass.a -trimpath $WORK -p main -buildid ce5e1a0eab9fd96772b6a135be9ae6179cae3208 -D _/Users/filippo/go/src/github.com/FiloSottile/hashpass -I $WORK -pack $WORK/github.com/ FiloSottile/hashpass/_obj/_cgo_gotypes.go $WORK/github.com/FiloSottile/hashpass/_obj/main.cgo1.go $WORK/github.com/FiloSottile/hashpass/ _obj/_cgo_import.go pack r $WORK/github.com/FiloSottile/hashpass.a $WORK/github.com/FiloSottile/hashpass/_obj/_all.o # internal cd . /usr/local/go/pkg/tool/linux_amd64/link -o $WORK/github.com/FiloSottile/hashpass/_obj/exe/a.out -L $WORK -extld=gcc -buildmode=exe - buildid=ce5e1a0eab9fd96772b6a135be9ae6179cae3208 $WORK/github.com/FiloSottile/hashpass.a cp $WORK/github.com/FiloSottile/hashpass/_obj/exe/a.out hashpass

Slide 69

Slide 69 text

$ cat $GOPATH/src/github.com/FiloSottile/hashpass/sodium/hash.go package sodium // #cgo pkg-config: libsodium // #include import "C" func init() { C.sodium_init() } func HashPass(pass string) string { cMem := C.calloc(1, C.crypto_pwhash_STRBYTES) defer C.free(cMem) res := (*C.char)(cMem) C.crypto_pwhash_str(res, C.CString(pass), (C.ulonglong)(len(pass)), C.crypto_pwhash_OPSLIMIT_SENSITIVE, C.crypto_pwhash_MEMLIMIT_SENSITIVE) return C.GoStringN(res, C.crypto_pwhash_STRBYTES) }

Slide 70

Slide 70 text

$ go build -v —i github.com/FiloSottile/hashpass github.com/FiloSottile/hashpass/sodium github.com/FiloSottile/hashpass $ go build -v -x github.com/FiloSottile/hashpass WORK=/tmp/go-build607855468 github.com/FiloSottile/hashpass mkdir -p $WORK/github.com/FiloSottile/hashpass/_obj/ mkdir -p $WORK/github.com/FiloSottile/hashpass/_obj/exe/ cd /Users/filippo/go/src/github.com/FiloSottile/hashpass /usr/local/go/pkg/tool/linux_amd64/compile -o $WORK/github.com/FiloSottile/ hashpass.a -trimpath $WORK -p main -complete -buildid 099121d2abae4b427870cba7785d01725b6dca64 -D _/Users/filippo/go/src/github.com/ FiloSottile/hashpass -I $WORK -I /Users/filippo/go/pkg/linux_amd64 -pack ./main.go cd . /usr/local/go/pkg/tool/linux_amd64/link -o $WORK/github.com/FiloSottile/hashpass/ _obj/exe/a.out -L $WORK -L /Users/filippo/go/pkg/linux_amd64 -extld=gcc - buildmode=exe -buildid=099121d2abae4b427870cba7785d01725b6dca64 $WORK/github.com/ FiloSottile/hashpass.a cp $WORK/github.com/FiloSottile/hashpass/_obj/exe/a.out hashpass

Slide 71

Slide 71 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 72

Slide 72 text

$ mv libsodium-1.0.10 \ $GOPATH/src/github.com/FiloSottile/hashpass/sodium/_libsodium-1.0.10 $ head $GOPATH/src/github.com/FiloSottile/hashpass/sodium/hash.go package sodium // #cgo CFLAGS: -I${SRCDIR}/_libsodium-1.0.10/src/libsodium/include/ // #cgo LDFLAGS: -L${SRCDIR}/_libsodium-1.0.10/src/libsodium/.libs/ -lsodium // #include import "C" $ (cd $GOPATH/src/github.com/FiloSottile/hashpass/sodium/_libsodium-1.0.10 && \ ./configure && make) $ go build github.com/FiloSottile/hashpass

Slide 73

Slide 73 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 74

Slide 74 text

$ go build -ldflags="-extldflags -static" github.com/FiloSottile/hashpass $ file hashpass hashpass: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=b0b0ccdbb3860c12c49e8034ce8fd854b9943eb3, not stripped

Slide 75

Slide 75 text

$ apt-get install musl-tools $ export CC=musl-gcc $ (cd $GOPATH/src/github.com/FiloSottile/hashpass/sodium/_libsodium-1.0.10 && \ make clean && ./configure && make) $ go install -installsuffix musl github.com/FiloSottile/hashpass/sodium $ go build -installsuffix musl -ldflags="-extldflags -static" github.com/ FiloSottile/hashpass $ file hashpass hashpass: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped

Slide 76

Slide 76 text

os/user net crypto/x509

Slide 77

Slide 77 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 78

Slide 78 text

$ cd $GOPATH/src/github.com/FiloSottile/hashpass/sodium $ (cd _libsodium-1.0.10 && ./configure && make) $ mkdir _linux_amd64 $ cp _libsodium-1.0.10/src/libsodium/include/sodium{,.h} _linux_amd64 $ cp _libsodium-1.0.10/src/libsodium/.libs/*.a _linux_amd64 $ head $GOPATH/src/github.com/FiloSottile/hashpass/sodium/hash.go package sodium // #cgo linux,amd64 CFLAGS: -I${SRCDIR}/_linux_amd64/ // #cgo linux,amd64 LDFLAGS: -L${SRCDIR}/_linux_amd64/ // #cgo !linux !amd64 CFLAGS: -I${SRCDIR}/_libsodium-1.0.10/src/libsodium/include/ // #cgo !linux !amd64 LDFLAGS: -L${SRCDIR}/_libsodium-1.0.10/src/libsodium/.libs/ // #cgo LDFLAGS: -lsodium // #include import “C" $ go get github.com/FiloSottile/hashpass

Slide 79

Slide 79 text

• Effortless memory management • Awesome tooling • Runtime speed • Quick compilation • Reproducible builds • Static binaries • go get • Super-easy cross compiling

Slide 80

Slide 80 text

musl based OS X → Linux cross-compilers brew install https://gist.github.com/FiloSottile/ 01d2bbfaf63ae1b6e373e6bc874fefc6/raw/ f74e34dbf2823e953af28c6b77b7a5139a4f2876/musl-cross.rb $ CC=x86_64-linux-musl-cc CGO_ENABLED=1 GOOS=linux go build -i \ -ldflags '-extldflags -static' github.com/FiloSottile/hashpass

Slide 81

Slide 81 text

• Effortless memory management • Runtime speed • Awesome tooling • Fast builds • Static binaries • Reproducible builds • go get • Super-easy cross compiling

Slide 82

Slide 82 text

Questions? Filippo Valsorda @FiloSottile [email protected] Olga Shalakhina artwork under CC 3.0 license based on Renee French under Creative Commons 3.0 Attributions.