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