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 <pthread.h>
7#include <signal.h>
8#include <string.h>
9#include "libcgo.h"
10#include "libcgo_unix.h"
11
12static void* threadentry(void*);
13static void (*setg_gcc)(void*);
14
15void
16x_cgo_init(G *g, void (*setg)(void*))
17{
18	pthread_attr_t attr;
19	size_t size;
20
21	setg_gcc = setg;
22	pthread_attr_init(&attr);
23	pthread_attr_getstacksize(&attr, &size);
24	g->stacklo = (uintptr)&attr - size + 4096;
25	pthread_attr_destroy(&attr);
26}
27
28void
29_cgo_sys_thread_start(ThreadStart *ts)
30{
31	pthread_attr_t attr;
32	sigset_t ign, oset;
33	pthread_t p;
34	size_t size;
35	int err;
36
37	sigfillset(&ign);
38	pthread_sigmask(SIG_SETMASK, &ign, &oset);
39
40	pthread_attr_init(&attr);
41	pthread_attr_getstacksize(&attr, &size);
42
43	// Leave stacklo=0 and set stackhi=size; mstart will do the rest.
44	ts->g->stackhi = size;
45	err = _cgo_try_pthread_create(&p, &attr, threadentry, ts);
46
47	pthread_sigmask(SIG_SETMASK, &oset, nil);
48
49	if (err != 0) {
50		fprintf(stderr, "runtime/cgo: pthread_create failed: %s\n", strerror(err));
51		abort();
52	}
53}
54
55static void*
56threadentry(void *v)
57{
58	ThreadStart ts;
59
60	ts = *(ThreadStart*)v;
61	free(v);
62
63	/*
64	 * Set specific keys.
65	 */
66	setg_gcc((void*)ts.g);
67
68	crosscall_amd64(ts.fn);
69	return nil;
70}
71