Debian Codegraph @

libgo/go/runtime/string.go

raw
1 // Copyright 2014 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 package runtime
6
7 import (
8 "internal/abi"
9 "internal/bytealg"
10 "internal/goarch"
11 "unsafe"
12 )
13
14 // For gccgo, use go:linkname to export compiler-called functions.
15 //
16 //go:linkname concatstrings
17 //go:linkname slicebytetostring
18 //go:linkname slicebytetostringtmp
19 //go:linkname stringtoslicebyte
20 //go:linkname stringtoslicerune
21 //go:linkname slicerunetostring
22 //go:linkname intstring
23 // Temporary for C code to call:
24 //go:linkname gostringnocopy
25 //go:linkname findnull
26
27 // The constant is known to the compiler.
28 // There is no fundamental theory behind this number.
29 const tmpStringBufSize = 32
30
31 type tmpBuf [tmpStringBufSize]byte
32
33 // concatstrings implements a Go string concatenation x+y+z+...
34 // The operands are passed in the slice a.
35 // If buf != nil, the compiler has determined that the result does not
36 // escape the calling function, so the string data can be stored in buf
37 // if small enough.
38 func concatstrings(buf *tmpBuf, p *string, n int) string {
39 var a []string
40 *(*slice)(unsafe.Pointer(&a)) = slice{unsafe.Pointer(p), n, n}
41 // idx := 0
42 l := 0
43 count := 0
44 for _, x := range a {
45 n := len(x)
46 if n == 0 {
47 continue
48 }
49 if l+n < l {
50 throw("string concatenation too long")
51 }
52 l += n
53 count++
54 // idx = i
55 }
56 if count == 0 {
57 return ""
58 }
59
60 // If there is just one string and either it is not on the stack
61 // or our result does not escape the calling frame (buf != nil),
62 // then we can return that string directly.
63 // Commented out for gccgo--no implementation of stringDataOnStack.
64 // if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {
65 // return a[idx]
66 // }
67 s, b := rawstringtmp(buf, l)
68 for _, x := range a {
69 copy(b, x)
70 b = b[len(x):]
71 }
72 return s
73 }
74
75 // slicebytetostring converts a byte slice to a string.
76 // It is inserted by the compiler into generated code.
77 // ptr is a pointer to the first element of the slice;
78 // n is the length of the slice.
79 // Buf is a fixed-size buffer for the result,
80 // it is not nil if the result does not escape.
81 func slicebytetostring(buf *tmpBuf, ptr *byte, n int) (str string) {
82 if n == 0 {
83 // Turns out to be a relatively common case.
84 // Consider that you want to parse out data between parens in "foo()bar",
85 // you find the indices and convert the subslice to string.
86 return ""
87 }
88 if raceenabled {
89 racereadrangepc(unsafe.Pointer(ptr),
90 uintptr(n),
91 getcallerpc(),
92 abi.FuncPCABIInternal(slicebytetostring))
93 }
94 if msanenabled {
95 msanread(unsafe.Pointer(ptr), uintptr(n))
96 }
97 if asanenabled {
98 asanread(unsafe.Pointer(ptr), uintptr(n))
99 }
100 if n == 1 {
101 p := unsafe.Pointer(&staticuint64s[*ptr])
102 if goarch.BigEndian {
103 p = add(p, 7)
104 }
105 stringStructOf(&str).str = p
106 stringStructOf(&str).len = 1
107 return
108 }
109
110 var p unsafe.Pointer
111 if buf != nil && n <= len(buf) {
112 p = unsafe.Pointer(buf)
113 } else {
114 p = mallocgc(uintptr(n), nil, false)
115 }
116 stringStructOf(&str).str = p
117 stringStructOf(&str).len = n
118 memmove(p, unsafe.Pointer(ptr), uintptr(n))
119 return
120 }
121
122 func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
123 if buf != nil && l <= len(buf) {
124 b = buf[:l]
125 s = slicebytetostringtmp(&b[0], len(b))
126 } else {
127 s, b = rawstring(l)
128 }
129 return
130 }
131
132 // slicebytetostringtmp returns a "string" referring to the actual []byte bytes.
133 //
134 // Callers need to ensure that the returned string will not be used after
135 // the calling goroutine modifies the original slice or synchronizes with
136 // another goroutine.
137 //
138 // The function is only called when instrumenting
139 // and otherwise intrinsified by the compiler.
140 //
141 // Some internal compiler optimizations use this function.
142 // - Used for m[T1{... Tn{..., string(k), ...} ...}] and m[string(k)]
143 // where k is []byte, T1 to Tn is a nesting of struct and array literals.
144 // - Used for "<"+string(b)+">" concatenation where b is []byte.
145 // - Used for string(b)=="foo" comparison where b is []byte.
146 func slicebytetostringtmp(ptr *byte, n int) (str string) {
147 if raceenabled && n > 0 {
148 racereadrangepc(unsafe.Pointer(ptr),
149 uintptr(n),
150 getcallerpc(),
151 abi.FuncPCABIInternal(slicebytetostringtmp))
152 }
153 if msanenabled && n > 0 {
154 msanread(unsafe.Pointer(ptr), uintptr(n))
155 }
156 if asanenabled && n > 0 {
157 asanread(unsafe.Pointer(ptr), uintptr(n))
158 }
159 stringStructOf(&str).str = unsafe.Pointer(ptr)
160 stringStructOf(&str).len = n
161 return
162 }
163
164 func stringtoslicebyte(buf *tmpBuf, s string) []byte {
165 var b []byte
166 if buf != nil && len(s) <= len(buf) {
167 *buf = tmpBuf{}
168 b = buf[:len(s)]
169 } else {
170 b = rawbyteslice(len(s))
171 }
172 copy(b, s)
173 return b
174 }
175
176 func stringtoslicerune(buf *[tmpStringBufSize]rune, s string) []rune {
177 // two passes.
178 // unlike slicerunetostring, no race because strings are immutable.
179 n := 0
180 for range s {
181 n++
182 }
183
184 var a []rune
185 if buf != nil && n <= len(buf) {
186 *buf = [tmpStringBufSize]rune{}
187 a = buf[:n]
188 } else {
189 a = rawruneslice(n)
190 }
191
192 n = 0
193 for _, r := range s {
194 a[n] = r
195 n++
196 }
197 return a
198 }
199
200 func slicerunetostring(buf *tmpBuf, a []rune) string {
201 if raceenabled && len(a) > 0 {
202 racereadrangepc(unsafe.Pointer(&a[0]),
203 uintptr(len(a))*unsafe.Sizeof(a[0]),
204 getcallerpc(),
205 abi.FuncPCABIInternal(slicerunetostring))
206 }
207 if msanenabled && len(a) > 0 {
208 msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
209 }
210 if asanenabled && len(a) > 0 {
211 asanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
212 }
213 var dum [4]byte
214 size1 := 0
215 for _, r := range a {
216 size1 += encoderune(dum[:], r)
217 }
218 s, b := rawstringtmp(buf, size1+3)
219 size2 := 0
220 for _, r := range a {
221 // check for race
222 if size2 >= size1 {
223 break
224 }
225 size2 += encoderune(b[size2:], r)
226 }
227 return s[:size2]
228 }
229
230 type stringStruct struct {
231 str unsafe.Pointer
232 len int
233 }
234
235 // Variant with *byte pointer type for DWARF debugging.
236 type stringStructDWARF struct {
237 str *byte
238 len int
239 }
240
241 func stringStructOf(sp *string) *stringStruct {
242 return (*stringStruct)(unsafe.Pointer(sp))
243 }
244
245 func intstring(buf *[4]byte, v int64) (s string) {
246 var b []byte
247 if buf != nil {
248 b = buf[:]
249 s = slicebytetostringtmp(&b[0], len(b))
250 } else {
251 s, b = rawstring(4)
252 }
253 if int64(rune(v)) != v {
254 v = runeError
255 }
256 n := encoderune(b, rune(v))
257 return s[:n]
258 }
259
260 // rawstring allocates storage for a new string. The returned
261 // string and byte slice both refer to the same storage.
262 // The storage is not zeroed. Callers should use
263 // b to set the string contents and then drop b.
264 func rawstring(size int) (s string, b []byte) {
265 p := mallocgc(uintptr(size), nil, false)
266
267 stringStructOf(&s).str = p
268 stringStructOf(&s).len = size
269
270 *(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
271
272 return
273 }
274
275 // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
276 func rawbyteslice(size int) (b []byte) {
277 cap := roundupsize(uintptr(size))
278 p := mallocgc(cap, nil, false)
279 if cap != uintptr(size) {
280 memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size))
281 }
282
283 *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
284 return
285 }
286
287 // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
288 func rawruneslice(size int) (b []rune) {
289 if uintptr(size) > maxAlloc/4 {
290 throw("out of memory")
291 }
292 mem := roundupsize(uintptr(size) * 4)
293 p := mallocgc(mem, nil, false)
294 if mem != uintptr(size)*4 {
295 memclrNoHeapPointers(add(p, uintptr(size)*4), mem-uintptr(size)*4)
296 }
297
298 *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
299 return
300 }
301
302 // used by cmd/cgo
303 func gobytes(p *byte, n int) (b []byte) {
304 if n == 0 {
305 return make([]byte, 0)
306 }
307
308 if n < 0 || uintptr(n) > maxAlloc {
309 panic(errorString("gobytes: length out of range"))
310 }
311
312 bp := mallocgc(uintptr(n), nil, false)
313 memmove(bp, unsafe.Pointer(p), uintptr(n))
314
315 *(*slice)(unsafe.Pointer(&b)) = slice{bp, n, n}
316 return
317 }
318
319 // This is exported via linkname to assembly in syscall (for Plan9).
320 //go:linkname gostring
321 func gostring(p *byte) string {
322 l := findnull(p)
323 if l == 0 {
324 return ""
325 }
326 s, b := rawstring(l)
327 memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
328 return s
329 }
330
331 func gostringn(p *byte, l int) string {
332 if l == 0 {
333 return ""
334 }
335 s, b := rawstring(l)
336 memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
337 return s
338 }
339
340 func hasPrefix(s, prefix string) bool {
341 return len(s) >= len(prefix) && s[:len(prefix)] == prefix
342 }
343
344 func hasSuffix(s, suffix string) bool {
345 return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
346 }
347
348 const (
349 maxUint = ^uint(0)
350 maxInt = int(maxUint >> 1)
351 )
352
353 // atoi parses an int from a string s.
354 // The bool result reports whether s is a number
355 // representable by a value of type int.
356 func atoi(s string) (int, bool) {
357 if s == "" {
358 return 0, false
359 }
360
361 neg := false
362 if s[0] == '-' {
363 neg = true
364 s = s[1:]
365 }
366
367 un := uint(0)
368 for i := 0; i < len(s); i++ {
369 c := s[i]
370 if c < '0' || c > '9' {
371 return 0, false
372 }
373 if un > maxUint/10 {
374 // overflow
375 return 0, false
376 }
377 un *= 10
378 un1 := un + uint(c) - '0'
379 if un1 < un {
380 // overflow
381 return 0, false
382 }
383 un = un1
384 }
385
386 if !neg && un > uint(maxInt) {
387 return 0, false
388 }
389 if neg && un > uint(maxInt)+1 {
390 return 0, false
391 }
392
393 n := int(un)
394 if neg {
395 n = -n
396 }
397
398 return n, true
399 }
400
401 // atoi32 is like atoi but for integers
402 // that fit into an int32.
403 func atoi32(s string) (int32, bool) {
404 if n, ok := atoi(s); n == int(int32(n)) {
405 return int32(n), ok
406 }
407 return 0, false
408 }
409
410 //go:nosplit
411 func findnull(s *byte) int {
412 if s == nil {
413 return 0
414 }
415
416 // Avoid IndexByteString on Plan 9 because it uses SSE instructions
417 // on x86 machines, and those are classified as floating point instructions,
418 // which are illegal in a note handler.
419 if GOOS == "plan9" {
420 p := (*[maxAlloc/2 - 1]byte)(unsafe.Pointer(s))
421 l := 0
422 for p[l] != 0 {
423 l++
424 }
425 return l
426 }
427
428 // pageSize is the unit we scan at a time looking for NULL.
429 // It must be the minimum page size for any architecture Go
430 // runs on. It's okay (just a minor performance loss) if the
431 // actual system page size is larger than this value.
432 const pageSize = 4096
433
434 offset := 0
435 ptr := unsafe.Pointer(s)
436 // IndexByteString uses wide reads, so we need to be careful
437 // with page boundaries. Call IndexByteString on
438 // [ptr, endOfPage) interval.
439 safeLen := int(pageSize - uintptr(ptr)%pageSize)
440
441 for {
442 t := *(*string)(unsafe.Pointer(&stringStruct{ptr, safeLen}))
443 // Check one page at a time.
444 if i := bytealg.IndexByteString(t, 0); i != -1 {
445 return offset + i
446 }
447 // Move to next page
448 ptr = unsafe.Pointer(uintptr(ptr) + uintptr(safeLen))
449 offset += safeLen
450 safeLen = pageSize
451 }
452 }
453
454 func findnullw(s *uint16) int {
455 if s == nil {
456 return 0
457 }
458 p := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(s))
459 l := 0
460 for p[l] != 0 {
461 l++
462 }
463 return l
464 }
465
466 //go:nosplit
467 func gostringnocopy(str *byte) string {
468 ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
469 s := *(*string)(unsafe.Pointer(&ss))
470 return s
471 }
472
473 func gostringw(strw *uint16) string {
474 var buf [8]byte
475 str := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(strw))
476 n1 := 0
477 for i := 0; str[i] != 0; i++ {
478 n1 += encoderune(buf[:], rune(str[i]))
479 }
480 s, b := rawstring(n1 + 4)
481 n2 := 0
482 for i := 0; str[i] != 0; i++ {
483 // check for race
484 if n2 >= n1 {
485 break
486 }
487 n2 += encoderune(b[n2:], rune(str[i]))
488 }
489 b[n2] = 0 // for luck
490 return s[:n2]
491 }
492
493 // These two functions are called by code generated by cgo -gccgo.
494
495 //go:linkname __go_byte_array_to_string __go_byte_array_to_string
496 func __go_byte_array_to_string(p unsafe.Pointer, l int) string {
497 if l == 0 {
498 return ""
499 }
500 s, c := rawstringtmp(nil, l)
501 memmove(unsafe.Pointer(&c[0]), p, uintptr(l))
502 return s
503 }
504
505 //go:linkname __go_string_to_byte_array __go_string_to_byte_array
506 func __go_string_to_byte_array(s string) []byte {
507 return stringtoslicebyte(nil, s)
508 }