Home | History | Annotate | Download | only in cgo
      1 // Copyright 2015 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 <string.h>
      7 #include <signal.h>
      8 #include <ucontext.h>
      9 #include "libcgo.h"
     10 #include "libcgo_unix.h"
     11 
     12 static void* threadentry(void*);
     13 static void (*setg_gcc)(void*);
     14 
     15 void
     16 x_cgo_init(G *g, void (*setg)(void*))
     17 {
     18 	ucontext_t ctx;
     19 
     20 	setg_gcc = setg;
     21 	if (getcontext(&ctx) != 0)
     22 		perror("runtime/cgo: getcontext failed");
     23 	g->stacklo = (uintptr_t)ctx.uc_stack.ss_sp;
     24 
     25 	// Solaris processes report a tiny stack when run with "ulimit -s unlimited".
     26 	// Correct that as best we can: assume it's at least 1 MB.
     27 	// See golang.org/issue/12210.
     28 	if(ctx.uc_stack.ss_size < 1024*1024)
     29 		g->stacklo -= 1024*1024 - ctx.uc_stack.ss_size;
     30 }
     31 
     32 void
     33 _cgo_sys_thread_start(ThreadStart *ts)
     34 {
     35 	pthread_attr_t attr;
     36 	sigset_t ign, oset;
     37 	pthread_t p;
     38 	void *base;
     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 
     47 	if (pthread_attr_getstack(&attr, &base, &size) != 0)
     48 		perror("runtime/cgo: pthread_attr_getstack failed");
     49 	if (size == 0) {
     50 		ts->g->stackhi = 2 << 20;
     51 		if (pthread_attr_setstack(&attr, NULL, ts->g->stackhi) != 0)
     52 			perror("runtime/cgo: pthread_attr_setstack failed");
     53 	} else {
     54 		ts->g->stackhi = size;
     55 	}
     56 	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
     57 	err = _cgo_try_pthread_create(&p, &attr, threadentry, ts);
     58 
     59 	pthread_sigmask(SIG_SETMASK, &oset, nil);
     60 
     61 	if (err != 0) {
     62 		fprintf(stderr, "runtime/cgo: pthread_create failed: %s\n", strerror(err));
     63 		abort();
     64 	}
     65 }
     66 
     67 static void*
     68 threadentry(void *v)
     69 {
     70 	ThreadStart ts;
     71 
     72 	ts = *(ThreadStart*)v;
     73 	free(v);
     74 
     75 	/*
     76 	 * Set specific keys.
     77 	 */
     78 	setg_gcc((void*)ts.g);
     79 
     80 	crosscall_amd64(ts.fn);
     81 	return nil;
     82 }
     83