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 <sys/types.h>
6 #include <errno.h>
7 #include <sys/signalvar.h>
8 #include <pthread.h>
9 #include <signal.h>
10 #include <string.h>
11 #include "libcgo.h"
12 #include "libcgo_unix.h"
13 
14 static void* threadentry(void*);
15 static void (*setg_gcc)(void*);
16 
17 void
x_cgo_init(G * g,void (* setg)(void *))18 x_cgo_init(G *g, void (*setg)(void*))
19 {
20 	uintptr *pbounds;
21 
22 	// Deal with memory sanitizer/clang interaction.
23 	// See gcc_linux_amd64.c for details.
24 	setg_gcc = setg;
25 	pbounds = (uintptr*)malloc(2 * sizeof(uintptr));
26 	if (pbounds == NULL) {
27 		fatalf("malloc failed: %s", strerror(errno));
28 	}
29 	_cgo_set_stacklo(g, pbounds);
30 	free(pbounds);
31 }
32 
33 void
_cgo_sys_thread_start(ThreadStart * ts)34 _cgo_sys_thread_start(ThreadStart *ts)
35 {
36 	pthread_attr_t attr;
37 	sigset_t ign, oset;
38 	pthread_t p;
39 	size_t size;
40 	int err;
41 
42 	SIGFILLSET(ign);
43 	pthread_sigmask(SIG_SETMASK, &ign, &oset);
44 
45 	pthread_attr_init(&attr);
46 	pthread_attr_getstacksize(&attr, &size);
47 	// Leave stacklo=0 and set stackhi=size; mstart will do the rest.
48 	ts->g->stackhi = size;
49 	err = _cgo_try_pthread_create(&p, &attr, threadentry, ts);
50 
51 	pthread_sigmask(SIG_SETMASK, &oset, nil);
52 
53 	if (err != 0) {
54 		fatalf("pthread_create failed: %s", strerror(err));
55 	}
56 }
57 
58 extern void crosscall1(void (*fn)(void), void (*setg_gcc)(void*), void *g);
59 static void*
threadentry(void * v)60 threadentry(void *v)
61 {
62 	ThreadStart ts;
63 
64 	ts = *(ThreadStart*)v;
65 	_cgo_tsan_acquire();
66 	free(v);
67 	_cgo_tsan_release();
68 
69 	crosscall1(ts.fn, setg_gcc, (void*)ts.g);
70 	return nil;
71 }
72