Skip to content

Commit b4ce38e

Browse files
cmd/cgo: throw if C.malloc returns nil
Change-Id: If7740ac7b6c4190db5a1ab4100d12cf16dc79c84 Reviewed-on: https://go-review.googlesource.com/31768 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Russ Cox <[email protected]>
1 parent 643c6b3 commit b4ce38e

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

misc/cgo/errors/malloc.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright 2016 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// Test that C.malloc does not return nil.
6+
7+
package main
8+
9+
// #include <stdlib.h>
10+
import "C"
11+
12+
import (
13+
"fmt"
14+
)
15+
16+
func main() {
17+
p := C.malloc(C.size_t(^uintptr(0)))
18+
if p == nil {
19+
fmt.Println("malloc: C.malloc returned nil")
20+
// Just exit normally--the test script expects this
21+
// program to crash, so exiting normally indicates failure.
22+
}
23+
}

misc/cgo/errors/test.bash

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,5 +59,15 @@ if ! go run ptr.go; then
5959
exit 1
6060
fi
6161

62+
# The malloc.go test should crash.
63+
rm -f malloc.out
64+
if go run malloc.go >malloc.out 2>&1; then
65+
echo "`go run malloc.go` succeeded unexpectedly"
66+
cat malloc.out
67+
rm -f malloc.out
68+
exit 1
69+
fi
70+
rm -f malloc.out
71+
6272
rm -rf errs _obj
6373
exit 0

src/cmd/cgo/out.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1463,9 +1463,15 @@ const cMallocDefGo = `
14631463
var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte
14641464
var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc)
14651465
1466+
//go:linkname runtime_throw runtime.throw
1467+
func runtime_throw(string)
1468+
14661469
//go:cgo_unsafe_args
14671470
func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) {
14681471
_cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0)))
1472+
if r1 == nil {
1473+
runtime_throw("runtime: C malloc failed")
1474+
}
14691475
return
14701476
}
14711477
`

0 commit comments

Comments
 (0)