slice.go 6.88 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package runtime

import (
	"unsafe"
)

11
type slice struct {
12 13 14 15 16
	array unsafe.Pointer
	len   int
	cap   int
}

17 18 19 20 21 22 23
// An notInHeapSlice is a slice backed by go:notinheap memory.
type notInHeapSlice struct {
	array *notInHeap
	len   int
	cap   int
}

24 25 26 27
// maxElems is a lookup table containing the maximum capacity for a slice.
// The index is the size of the slice element.
var maxElems = [...]uintptr{
	^uintptr(0),
28 29 30 31 32 33 34 35
	maxAlloc / 1, maxAlloc / 2, maxAlloc / 3, maxAlloc / 4,
	maxAlloc / 5, maxAlloc / 6, maxAlloc / 7, maxAlloc / 8,
	maxAlloc / 9, maxAlloc / 10, maxAlloc / 11, maxAlloc / 12,
	maxAlloc / 13, maxAlloc / 14, maxAlloc / 15, maxAlloc / 16,
	maxAlloc / 17, maxAlloc / 18, maxAlloc / 19, maxAlloc / 20,
	maxAlloc / 21, maxAlloc / 22, maxAlloc / 23, maxAlloc / 24,
	maxAlloc / 25, maxAlloc / 26, maxAlloc / 27, maxAlloc / 28,
	maxAlloc / 29, maxAlloc / 30, maxAlloc / 31, maxAlloc / 32,
36 37 38 39 40 41 42
}

// maxSliceCap returns the maximum capacity for a slice.
func maxSliceCap(elemsize uintptr) uintptr {
	if elemsize < uintptr(len(maxElems)) {
		return maxElems[elemsize]
	}
43
	return maxAlloc / elemsize
44 45
}

46
func makeslice(et *_type, len, cap int) slice {
47
	// NOTE: The len > maxElements check here is not strictly necessary,
48 49 50 51
	// but it produces a 'len out of range' error instead of a 'cap out of range' error
	// when someone does make([]T, bignumber). 'cap out of range' is true too,
	// but since the cap is only being supplied implicitly, saying len is clearer.
	// See issue 4085.
52
	maxElements := maxSliceCap(et.size)
53
	if len < 0 || uintptr(len) > maxElements {
54 55
		panic(errorString("makeslice: len out of range"))
	}
56

57
	if cap < len || uintptr(cap) > maxElements {
58 59
		panic(errorString("makeslice: cap out of range"))
	}
60

61
	p := mallocgc(et.size*uintptr(cap), et, true)
62
	return slice{p, len, cap}
63 64
}

65 66 67 68 69 70 71 72 73 74 75 76 77 78
func makeslice64(et *_type, len64, cap64 int64) slice {
	len := int(len64)
	if int64(len) != len64 {
		panic(errorString("makeslice: len out of range"))
	}

	cap := int(cap64)
	if int64(cap) != cap64 {
		panic(errorString("makeslice: cap out of range"))
	}

	return makeslice(et, len, cap)
}

79
// growslice handles slice growth during append.
80
// It is passed the slice element type, the old slice, and the desired new minimum capacity,
81 82
// and it returns a new slice with at least that capacity, with the old data
// copied into it.
83 84 85 86 87 88
// The new slice's length is set to the old slice's length,
// NOT to the new requested capacity.
// This is for codegen convenience. The old slice's length is used immediately
// to calculate where to write new values during an append.
// TODO: When the old backend is gone, reconsider this decision.
// The SSA backend might prefer the new length or to return only ptr/cap and save stack space.
89
func growslice(et *_type, old slice, cap int) slice {
90
	if raceenabled {
91
		callerpc := getcallerpc()
92
		racereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, funcPC(growslice))
93
	}
94
	if msanenabled {
95
		msanread(old.array, uintptr(old.len*int(et.size)))
96
	}
97 98

	if et.size == 0 {
99 100 101
		if cap < old.cap {
			panic(errorString("growslice: cap out of range"))
		}
102 103
		// append should not create a slice with nil pointer but non-zero len.
		// We assume that append doesn't need to preserve old.array in this case.
104
		return slice{unsafe.Pointer(&zerobase), old.len, cap}
105 106 107
	}

	newcap := old.cap
108 109
	doublecap := newcap + newcap
	if cap > doublecap {
110 111
		newcap = cap
	} else {
112 113 114
		if old.len < 1024 {
			newcap = doublecap
		} else {
115 116 117
			// Check 0 < newcap to detect overflow
			// and prevent an infinite loop.
			for 0 < newcap && newcap < cap {
118 119
				newcap += newcap / 4
			}
120 121 122 123 124
			// Set newcap to the requested cap when
			// the newcap calculation overflowed.
			if newcap <= 0 {
				newcap = cap
			}
125 126
		}
	}
127

128
	var overflow bool
129
	var lenmem, newlenmem, capmem uintptr
130 131 132 133
	const ptrSize = unsafe.Sizeof((*byte)(nil))
	switch et.size {
	case 1:
		lenmem = uintptr(old.len)
134
		newlenmem = uintptr(cap)
135
		capmem = roundupsize(uintptr(newcap))
136
		overflow = uintptr(newcap) > maxAlloc
137
		newcap = int(capmem)
138 139
	case ptrSize:
		lenmem = uintptr(old.len) * ptrSize
140
		newlenmem = uintptr(cap) * ptrSize
141
		capmem = roundupsize(uintptr(newcap) * ptrSize)
142
		overflow = uintptr(newcap) > maxAlloc/ptrSize
143 144 145
		newcap = int(capmem / ptrSize)
	default:
		lenmem = uintptr(old.len) * et.size
146
		newlenmem = uintptr(cap) * et.size
147
		capmem = roundupsize(uintptr(newcap) * et.size)
148
		overflow = uintptr(newcap) > maxSliceCap(et.size)
149
		newcap = int(capmem / et.size)
150 151
	}

152 153 154 155 156 157 158 159 160 161 162 163 164 165
	// The check of overflow (uintptr(newcap) > maxSliceCap(et.size))
	// in addition to capmem > _MaxMem is needed to prevent an overflow
	// which can be used to trigger a segfault on 32bit architectures
	// with this example program:
	//
	// type T [1<<27 + 1]int64
	//
	// var d T
	// var s []T
	//
	// func main() {
	//   s = append(s, d, d, d, d)
	//   print(len(s), "\n")
	// }
166
	if cap < old.cap || overflow || capmem > maxAlloc {
167
		panic(errorString("growslice: cap out of range"))
168 169
	}

170 171
	var p unsafe.Pointer
	if et.kind&kindNoPointers != 0 {
172
		p = mallocgc(capmem, nil, false)
173
		memmove(p, old.array, lenmem)
174 175
		// The append() that calls growslice is going to overwrite from old.len to cap (which will be the new length).
		// Only clear the part that will not be overwritten.
176
		memclrNoHeapPointers(add(p, newlenmem), capmem-newlenmem)
177
	} else {
178
		// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.
179
		p = mallocgc(capmem, et, true)
180
		if !writeBarrier.enabled {
181 182 183 184 185
			memmove(p, old.array, lenmem)
		} else {
			for i := uintptr(0); i < lenmem; i += et.size {
				typedmemmove(et, add(p, i), add(old.array, i))
			}
186
		}
187 188
	}

189
	return slice{p, old.len, newcap}
190 191
}

192
func slicecopy(to, fm slice, width uintptr) int {
193
	if fm.len == 0 || to.len == 0 {
194 195 196 197 198 199 200 201
		return 0
	}

	n := fm.len
	if to.len < n {
		n = to.len
	}

202 203 204 205
	if width == 0 {
		return n
	}

206
	if raceenabled {
207
		callerpc := getcallerpc()
208
		pc := funcPC(slicecopy)
209 210
		racewriterangepc(to.array, uintptr(n*int(width)), callerpc, pc)
		racereadrangepc(fm.array, uintptr(n*int(width)), callerpc, pc)
211
	}
212 213 214 215
	if msanenabled {
		msanwrite(to.array, uintptr(n*int(width)))
		msanread(fm.array, uintptr(n*int(width)))
	}
216 217 218 219 220 221 222 223

	size := uintptr(n) * width
	if size == 1 { // common case worth about 2x to do here
		// TODO: is this still worth it with new memmove impl?
		*(*byte)(to.array) = *(*byte)(fm.array) // known to be a byte pointer
	} else {
		memmove(to.array, fm.array, size)
	}
224
	return n
225 226 227 228 229 230 231 232 233 234 235 236 237
}

func slicestringcopy(to []byte, fm string) int {
	if len(fm) == 0 || len(to) == 0 {
		return 0
	}

	n := len(fm)
	if len(to) < n {
		n = len(to)
	}

	if raceenabled {
238
		callerpc := getcallerpc()
239
		pc := funcPC(slicestringcopy)
240
		racewriterangepc(unsafe.Pointer(&to[0]), uintptr(n), callerpc, pc)
241
	}
242 243 244
	if msanenabled {
		msanwrite(unsafe.Pointer(&to[0]), uintptr(n))
	}
245

246
	memmove(unsafe.Pointer(&to[0]), stringStructOf(&fm).str, uintptr(n))
247 248
	return n
}