Skip to content

Commit 244c8b0

Browse files
committed
cmd/cgo: allow cgo to pass strings or []bytes bigger than 1<<30
There's no real reason to limit to 1<<30 bytes. Maybe it would catch some mistakes, but probably ones that would quickly manifest in other ways. We can't use the fancy new unsafe.Slice function because this code may still be generated for people with 1.16 or earlier in their go.mod file. Use unsafe shenanigans instead. Fixes #53965 Fixes #53958 Change-Id: Ibfa095192f50276091d6c2532e8ccd7832b57ca8 Reviewed-on: https://go-review.googlesource.com/c/go/+/418557 Run-TryBot: Keith Randall <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Keith Randall <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent df38614 commit 244c8b0

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/cmd/cgo/out.go

+18-5
Original file line numberDiff line numberDiff line change
@@ -1653,10 +1653,18 @@ const cStringDef = `
16531653
// freed, such as by calling C.free (be sure to include stdlib.h
16541654
// if C.free is needed).
16551655
func _Cfunc_CString(s string) *_Ctype_char {
1656+
if len(s)+1 <= 0 {
1657+
panic("string too large")
1658+
}
16561659
p := _cgo_cmalloc(uint64(len(s)+1))
1657-
pp := (*[1<<30]byte)(p)
1658-
copy(pp[:], s)
1659-
pp[len(s)] = 0
1660+
sliceHeader := struct {
1661+
p unsafe.Pointer
1662+
len int
1663+
cap int
1664+
}{p, len(s)+1, len(s)+1}
1665+
b := *(*[]byte)(unsafe.Pointer(&sliceHeader))
1666+
copy(b, s)
1667+
b[len(s)] = 0
16601668
return (*_Ctype_char)(p)
16611669
}
16621670
`
@@ -1670,8 +1678,13 @@ const cBytesDef = `
16701678
// if C.free is needed).
16711679
func _Cfunc_CBytes(b []byte) unsafe.Pointer {
16721680
p := _cgo_cmalloc(uint64(len(b)))
1673-
pp := (*[1<<30]byte)(p)
1674-
copy(pp[:], b)
1681+
sliceHeader := struct {
1682+
p unsafe.Pointer
1683+
len int
1684+
cap int
1685+
}{p, len(b), len(b)}
1686+
s := *(*[]byte)(unsafe.Pointer(&sliceHeader))
1687+
copy(s, b)
16751688
return p
16761689
}
16771690
`

0 commit comments

Comments
 (0)