...

Text file src/runtime/cgo/gcc_linux_amd64.c

Documentation: runtime/cgo

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

View as plain text