|
| 1 | +// +build amd64,linux |
| 2 | + |
| 3 | +// Copyright 2018 The Go Authors. All rights reserved. |
| 4 | +// Use of this source code is governed by a BSD-style |
| 5 | +// license that can be found in the LICENSE file. |
| 6 | + |
| 7 | +package cgotest |
| 8 | + |
| 9 | +// Test that C.GoString uses IndexByte in safe manner. |
| 10 | + |
| 11 | +/* |
| 12 | +#include <sys/mman.h> |
| 13 | +
|
| 14 | +// Returns string with null byte at the last valid address |
| 15 | +char* dangerousString1() { |
| 16 | + int pageSize = 4096; |
| 17 | + char *data = mmap(0, 2 * pageSize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, 0, 0); |
| 18 | + mprotect(data + pageSize,pageSize,PROT_NONE); |
| 19 | + int start = pageSize - 123 - 1; // last 123 bytes of first page + 1 null byte |
| 20 | + int i = start; |
| 21 | + for (; i < pageSize; i++) { |
| 22 | + data[i] = 'x'; |
| 23 | + } |
| 24 | + data[pageSize -1 ] = 0; |
| 25 | + return data+start; |
| 26 | +} |
| 27 | +
|
| 28 | +char* dangerousString2() { |
| 29 | + int pageSize = 4096; |
| 30 | + char *data = mmap(0, 3 * pageSize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, 0, 0); |
| 31 | + mprotect(data + 2 * pageSize,pageSize,PROT_NONE); |
| 32 | + int start = pageSize - 123 - 1; // last 123 bytes of first page + 1 null byte |
| 33 | + int i = start; |
| 34 | + for (; i < 2 * pageSize; i++) { |
| 35 | + data[i] = 'x'; |
| 36 | + } |
| 37 | + data[2*pageSize -1 ] = 0; |
| 38 | + return data+start; |
| 39 | +} |
| 40 | +*/ |
| 41 | +import "C" |
| 42 | + |
| 43 | +import ( |
| 44 | + "testing" |
| 45 | +) |
| 46 | + |
| 47 | +func test24206(t *testing.T) { |
| 48 | + if l := len(C.GoString(C.dangerousString1())); l != 123 { |
| 49 | + t.Errorf("Incorrect string length - got %d, want 123", l) |
| 50 | + } |
| 51 | + if l := len(C.GoString(C.dangerousString2())); l != 4096+123 { |
| 52 | + t.Errorf("Incorrect string length - got %d, want %d", l, 4096+123) |
| 53 | + } |
| 54 | +} |
0 commit comments