Home | History | Annotate | Download | only in cgo
      1 // Copyright 2014 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 <signal.h>
      7 #include <stdio.h>
      8 #include <sys/limits.h>
      9 #include "libcgo.h"
     10 
     11 #define magic1 (0x23581321U)
     12 
     13 // PTHREAD_KEYS_MAX has been added to sys/limits.h at head in bionic:
     14 // https://android.googlesource.com/platform/bionic/+/master/libc/include/sys/limits.h
     15 // TODO(crawshaw): remove this definition when NDK r10d is required.
     16 #ifndef PTHREAD_KEYS_MAX
     17 #define PTHREAD_KEYS_MAX 128
     18 #endif
     19 
     20 // inittls allocates a thread-local storage slot for g.
     21 //
     22 // It finds the first available slot using pthread_key_create and uses
     23 // it as the offset value for runtime.tlsg.
     24 static void
     25 inittls(void **tlsg, void **tlsbase)
     26 {
     27 	pthread_key_t k;
     28 	int i, err;
     29 
     30 	err = pthread_key_create(&k, nil);
     31 	if(err != 0) {
     32 		fatalf("pthread_key_create failed: %d", err);
     33 	}
     34 	pthread_setspecific(k, (void*)magic1);
     35 	for (i=0; i<PTHREAD_KEYS_MAX; i++) {
     36 		if (*(tlsbase+i) == (void*)magic1) {
     37 			*tlsg = (void*)(i*sizeof(void *));
     38 			pthread_setspecific(k, 0);
     39 			return;
     40 		}
     41 	}
     42 	fatalf("could not find pthread key");
     43 }
     44 
     45 void (*x_cgo_inittls)(void **tlsg, void **tlsbase) = inittls;
     46