github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/runtime/cgo/gcc_linux_amd64.c (about) 1 // Copyright 2009 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 #include <pthread.h> 6 #include <errno.h> 7 #include <string.h> // strerror 8 #include <signal.h> 9 #include <stdlib.h> 10 #include "libcgo.h" 11 #include "libcgo_unix.h" 12 13 static void* threadentry(void*); 14 static void (*setg_gcc)(void*); 15 16 // This will be set in gcc_android.c for android-specific customization. 17 void (*x_cgo_inittls)(void **tlsg, void **tlsbase) __attribute__((common)); 18 19 void 20 x_cgo_init(G *g, void (*setg)(void*), void **tlsg, void **tlsbase) 21 { 22 pthread_attr_t *attr; 23 size_t size; 24 25 /* The memory sanitizer distributed with versions of clang 26 before 3.8 has a bug: if you call mmap before malloc, mmap 27 may return an address that is later overwritten by the msan 28 library. Avoid this problem by forcing a call to malloc 29 here, before we ever call malloc. 30 31 This is only required for the memory sanitizer, so it's 32 unfortunate that we always run it. It should be possible 33 to remove this when we no longer care about versions of 34 clang before 3.8. The test for this is 35 misc/cgo/testsanitizers. 36 37 GCC works hard to eliminate a seemingly unnecessary call to 38 malloc, so we actually use the memory we allocate. */ 39 40 setg_gcc = setg; 41 attr = (pthread_attr_t*)malloc(sizeof *attr); 42 if (attr == NULL) { 43 fatalf("malloc failed: %s", strerror(errno)); 44 } 45 pthread_attr_init(attr); 46 pthread_attr_getstacksize(attr, &size); 47 g->stacklo = (uintptr)__builtin_frame_address(0) - size + 4096; 48 if (g->stacklo >= g->stackhi) 49 fatalf("bad stack bounds: lo=%p hi=%p\n", g->stacklo, g->stackhi); 50 pthread_attr_destroy(attr); 51 free(attr); 52 53 if (x_cgo_inittls) { 54 x_cgo_inittls(tlsg, tlsbase); 55 } 56 } 57 58 59 void 60 _cgo_sys_thread_start(ThreadStart *ts) 61 { 62 pthread_attr_t attr; 63 sigset_t ign, oset; 64 pthread_t p; 65 size_t size; 66 int err; 67 68 sigfillset(&ign); 69 pthread_sigmask(SIG_SETMASK, &ign, &oset); 70 71 pthread_attr_init(&attr); 72 pthread_attr_getstacksize(&attr, &size); 73 // Leave stacklo=0 and set stackhi=size; mstart will do the rest. 74 ts->g->stackhi = size; 75 err = _cgo_try_pthread_create(&p, &attr, threadentry, ts); 76 77 pthread_sigmask(SIG_SETMASK, &oset, nil); 78 79 if (err != 0) { 80 fatalf("pthread_create failed: %s", strerror(err)); 81 } 82 } 83 84 static void* 85 threadentry(void *v) 86 { 87 ThreadStart ts; 88 89 ts = *(ThreadStart*)v; 90 _cgo_tsan_acquire(); 91 free(v); 92 _cgo_tsan_release(); 93 94 crosscall_amd64(ts.fn, setg_gcc, (void*)ts.g); 95 return nil; 96 }