about summary refs log tree commit diff
path: root/vendor/modernc.org/libc/mem_brk_musl.go
blob: 260132a576c18d7ed8d3cf17c019b3cc42644050 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Copyright 2023 The Libc Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build libc.membrk && !libc.memgrind && linux && (amd64 || arm64 || loong64)

// This is a debug-only version of the memory handling functions. When a
// program is built with -tags=libc.membrk a simple but safe version of malloc
// and friends is used that works like sbrk(2). Additionally free becomes a
// nop.

// The fixed heap is initially filled with random bytes from a full cycle PRNG,
// program startup time is substantially prolonged.

package libc // import "modernc.org/libc"

import (
	"fmt"
	"math"
	"math/bits"
	"runtime"
	"strings"
	"time"
	"unsafe"

	"modernc.org/mathutil"
)

const (
	isMemBrk = true

	heapSize = 1 << 30
)

var (
	brkIndex    uintptr
	heap        [heapSize]byte
	heapP       uintptr
	heap0       uintptr
	heapRecords []heapRecord
	heapUsable  = map[uintptr]Tsize_t{}
	heapFree    = map[uintptr]struct{}{}
	rng         *mathutil.FC32
)

type heapRecord struct {
	p  uintptr
	pc uintptr
}

func (r *heapRecord) String() string {
	return fmt.Sprintf("[p=%#0x usable=%v pc=%s]", r.p, Xmalloc_usable_size(nil, r.p), pc2origin(r.pc))
}

func init() {
	if roundup(heapGuard, heapAlign) != heapGuard {
		panic("internal error")
	}

	heap0 = uintptr(unsafe.Pointer(&heap[0]))
	heapP = roundup(heap0, heapAlign)
	var err error
	if rng, err = mathutil.NewFC32(math.MinInt32, math.MaxInt32, true); err != nil {
		panic(err)
	}

	rng.Seed(time.Now().UnixNano())
	for i := range heap {
		heap[i] = byte(rng.Next())
	}
}

func pc2origin(pc uintptr) string {
	f := runtime.FuncForPC(pc)
	var fn, fns string
	var fl int
	if f != nil {
		fn, fl = f.FileLine(pc)
		fns = f.Name()
		if x := strings.LastIndex(fns, "."); x > 0 {
			fns = fns[x+1:]
		}
	}
	return fmt.Sprintf("%s:%d:%s", fn, fl, fns)
}

func malloc0(tls *TLS, pc uintptr, n0 Tsize_t, zero bool) (r uintptr) {
	usable := roundup(uintptr(n0), heapAlign)
	rq := usable + 2*heapGuard
	if brkIndex+rq > uintptr(len(heap)) {
		tls.setErrno(ENOMEM)
		return 0
	}

	r, brkIndex = heapP+brkIndex, brkIndex+rq
	heapRecords = append(heapRecords, heapRecord{p: r, pc: pc})
	r += heapGuard
	heapUsable[r] = Tsize_t(usable)
	if zero {
		n := uintptr(n0)
		for i := uintptr(0); i < n; i++ {
			*(*byte)(unsafe.Pointer(r + i)) = 0
		}
	}
	return r
}

func Xmalloc(tls *TLS, n Tsize_t) (r uintptr) {
	if __ccgo_strace {
		trc("tls=%v n=%v, (%v:)", tls, n, origin(2))
		defer func() { trc("-> %v", r) }()
	}

	if n > math.MaxInt {
		tls.setErrno(ENOMEM)
		return 0
	}

	if n == 0 {
		// malloc(0) should return unique pointers
		// (often expected and gnulib replaces malloc if malloc(0) returns 0)
		n = 1
	}

	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	pc, _, _, _ := runtime.Caller(1)
	return malloc0(tls, pc, n, false)
}

func Xcalloc(tls *TLS, m Tsize_t, n Tsize_t) (r uintptr) {
	if __ccgo_strace {
		trc("tls=%v m=%v n=%v, (%v:)", tls, m, n, origin(2))
		defer func() { trc("-> %v", r) }()
	}

	hi, rq := bits.Mul(uint(m), uint(n))
	if hi != 0 || rq > math.MaxInt {
		tls.setErrno(ENOMEM)
		return 0
	}

	if rq == 0 {
		rq = 1
	}

	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	pc, _, _, _ := runtime.Caller(1)
	return malloc0(tls, pc, Tsize_t(rq), true)
}

func Xrealloc(tls *TLS, p uintptr, n Tsize_t) (r uintptr) {
	if __ccgo_strace {
		trc("tls=%v p=%v n=%v, (%v:)", tls, p, n, origin(2))
		defer func() { trc("-> %v", r) }()
	}

	if n == 0 {
		Xfree(tls, p)
		return 0
	}

	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	pc, _, _, _ := runtime.Caller(1)
	if p == 0 {
		return malloc0(tls, pc, n, false)
	}

	usable := heapUsable[p]
	if usable == 0 {
		panic(todo("realloc of unallocated memory: %#0x", p))
	}

	if usable >= n { // in place
		return p
	}

	// malloc
	r = malloc0(tls, pc, n, false)
	copy(unsafe.Slice((*byte)(unsafe.Pointer(r)), usable), unsafe.Slice((*byte)(unsafe.Pointer(p)), usable))
	Xfree(tls, p)
	return r
}

func Xfree(tls *TLS, p uintptr) {
	if __ccgo_strace {
		trc("tls=%v p=%v, (%v:)", tls, p, origin(2))
	}

	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	if p == 0 {
		return
	}

	if _, ok := heapUsable[p]; !ok {
		panic(todo("free of unallocated memory: %#0x", p))
	}

	if _, ok := heapFree[p]; ok {
		panic(todo("double free: %#0x", p))
	}

	heapFree[p] = struct{}{}
}

func Xmalloc_usable_size(tls *TLS, p uintptr) (r Tsize_t) {
	if __ccgo_strace {
		trc("tls=%v p=%v, (%v:)", tls, p, origin(2))
		defer func() { trc("-> %v", r) }()
	}
	if p == 0 {
		return 0
	}

	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	return heapUsable[p]
}

func MemAudit() (r []*MemAuditError) {
	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	a := heapRecords
	auditP := heap0
	rng.Seek(0)
	for _, v := range a {
		heapP := v.p
		mallocP := heapP + heapGuard
		usable := heapUsable[mallocP]
		for ; auditP < mallocP; auditP++ {
			if g, e := *(*byte)(unsafe.Pointer(auditP)), byte(rng.Next()); g != e {
				r = append(r, &MemAuditError{Caller: pc2origin(v.pc), Message: fmt.Sprintf("guard area before %#0x, %v is corrupted at %#0x, got %#02x, expected %#02x", mallocP, usable, auditP, g, e)})
			}
		}
		for i := 0; Tsize_t(i) < usable; i++ {
			rng.Next()
		}
		auditP = mallocP + uintptr(usable)
		z := roundup(auditP, heapAlign)
		z += heapGuard
		for ; auditP < z; auditP++ {
			if g, e := *(*byte)(unsafe.Pointer(auditP)), byte(rng.Next()); g != e {
				r = append(r, &MemAuditError{Caller: pc2origin(v.pc), Message: fmt.Sprintf("guard area after %#0x, %v is corrupted at %#0x, got %#02x, expected %#02x", mallocP, usable, auditP, g, e)})
			}
		}
	}
	z := heap0 + uintptr(len(heap))
	for ; auditP < z; auditP++ {
		if g, e := *(*byte)(unsafe.Pointer(auditP)), byte(rng.Next()); g != e {
			r = append(r, &MemAuditError{Caller: "-", Message: fmt.Sprintf("guard area after used heap is corrupted at %#0x, got %#02x, expected %#02x", auditP, g, e)})
			return r // Report only the first fail
		}
	}
	return r
}

func UsableSize(p uintptr) Tsize_t {
	if p == 0 {
		return 0
	}

	allocatorMu.Lock()

	defer allocatorMu.Unlock()

	return heapUsable[p]
}

// MemAuditStart locks the memory allocator, initializes and enables memory
// auditing. Finaly it unlocks the memory allocator.
//
// Some memory handling errors, like double free or freeing of unallocated
// memory, will panic when memory auditing is enabled.
//
// This memory auditing functionality has to be enabled using the libc.memgrind
// build tag.
//
// It is intended only for debug/test builds. It slows down memory allocation
// routines and it has additional memory costs.
func MemAuditStart() {}

// MemAuditReport locks the memory allocator, reports memory leaks, if any.
// Finally it disables memory auditing and unlocks the memory allocator.
//
// This memory auditing functionality has to be enabled using the libc.memgrind
// build tag.
//
// It is intended only for debug/test builds. It slows down memory allocation
// routines and it has additional memory costs.
func MemAuditReport() error { return nil }