1 // Copyright 2011 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 //go:build !cgo
6 7 package fakecgo
8 9 import "unsafe"
10 11 //go:nosplit
12 func _cgo_sys_thread_start(ts *ThreadStart) {
13 var attr pthread_attr_t
14 var ign, oset sigset_t
15 var p pthread_t
16 var size size_t
17 var err int
18 19 sigfillset(&ign)
20 pthread_sigmask(SIG_SETMASK, &ign, &oset)
21 22 pthread_attr_init(&attr)
23 pthread_attr_getstacksize(&attr, &size)
24 // Leave stacklo=0 and set stackhi=size; mstart will do the rest.
25 ts.g.stackhi = uintptr(size)
26 27 err = _cgo_try_pthread_create(&p, &attr, unsafe.Pointer(threadentry_trampolineABI0), ts)
28 29 pthread_sigmask(SIG_SETMASK, &oset, nil)
30 31 if err != 0 {
32 print("fakecgo: pthread_create failed: ")
33 println(err)
34 abort()
35 }
36 }
37 38 // threadentry_trampolineABI0 maps the C ABI to Go ABI then calls the Go function
39 //
40 //go:linkname x_threadentry_trampoline threadentry_trampoline
41 var x_threadentry_trampoline byte
42 var threadentry_trampolineABI0 = &x_threadentry_trampoline
43 44 //go:nosplit
45 func threadentry(v unsafe.Pointer) unsafe.Pointer {
46 ts := *(*ThreadStart)(v)
47 free(v)
48 49 setg_trampoline(setg_func, uintptr(unsafe.Pointer(ts.g)))
50 51 // faking funcs in go is a bit a... involved - but the following works :)
52 fn := uintptr(unsafe.Pointer(&ts.fn))
53 (*(*func())(unsafe.Pointer(&fn)))()
54 55 return nil
56 }
57 58 // here we will store a pointer to the provided setg func
59 var setg_func uintptr
60 61 //go:nosplit
62 func x_cgo_init(g *G, setg uintptr) {
63 var size size_t
64 var attr *pthread_attr_t
65 66 /* The memory sanitizer distributed with versions of clang
67 before 3.8 has a bug: if you call mmap before malloc, mmap
68 may return an address that is later overwritten by the msan
69 library. Avoid this problem by forcing a call to malloc
70 here, before we ever call malloc.
71 72 This is only required for the memory sanitizer, so it's
73 unfortunate that we always run it. It should be possible
74 to remove this when we no longer care about versions of
75 clang before 3.8. The test for this is
76 misc/cgo/testsanitizers.
77 78 GCC works hard to eliminate a seemingly unnecessary call to
79 malloc, so we actually use the memory we allocate. */
80 81 setg_func = setg
82 attr = (*pthread_attr_t)(malloc(unsafe.Sizeof(*attr)))
83 if attr == nil {
84 println("fakecgo: malloc failed")
85 abort()
86 }
87 pthread_attr_init(attr)
88 pthread_attr_getstacksize(attr, &size)
89 g.stacklo = uintptr(unsafe.Pointer(&size)) - uintptr(size) + 4096
90 pthread_attr_destroy(attr)
91 free(unsafe.Pointer(attr))
92 }
93