blob: 28f553c4463ee691a160365d7edb1e597149f0aa [file] [log] [blame]
Dan Willemsen38f2dba2016-07-08 14:54:35 -07001// 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 <string.h> /* for strerror */
6#include <pthread.h>
7#include <signal.h>
8#include "libcgo.h"
9
10static void* threadentry(void*);
11static pthread_key_t k1;
12
13#define magic1 (0x23581321U)
14
15static void
16inittls(void)
17{
18 uint32 x;
19 pthread_key_t tofree[128], k;
20 int i, ntofree;
21
22 /*
23 * Same logic, code as gcc_android_amd64.c:/inittls.
24 * Note that this is a temporary hack that should be fixed soon.
25 *
26 * TODO: fix this.
27 *
28 * The linker and runtime hard-code this constant offset
29 * from %gs where we expect to find g. Disgusting.
30 *
31 * Known to src/cmd/link/internal/ld/sym.go:/0xf8
32 * and to src/runtime/sys_linux_386.s:/0xf8 or /GOOS_android.
33 * TODO(hyangah): check 0xb0 works with API23+
34 *
35 * As disgusting as on the darwin/386, darwin/amd64.
36 */
37 ntofree = 0;
38 for(;;) {
Dan Willemsena3223282018-02-27 19:41:43 -080039 if(pthread_key_create(&k, nil) != 0) {
Dan Willemsen38f2dba2016-07-08 14:54:35 -070040 fprintf(stderr, "runtime/cgo: pthread_key_create failed\n");
41 abort();
42 }
43 pthread_setspecific(k, (void*)magic1);
44 asm volatile("movl %%gs:0xf8, %0" : "=r"(x));
45 pthread_setspecific(k, 0);
46 if (x == magic1) {
47 k1 = k;
48 break;
49 }
50 if(ntofree >= nelem(tofree)) {
51 fprintf(stderr, "runtime/cgo: could not obtain pthread_keys\n");
52 fprintf(stderr, "\ttried");
53 for(i=0; i<ntofree; i++)
54 fprintf(stderr, " %#x", (unsigned)tofree[i]);
55 fprintf(stderr, "\n");
56 abort();
57 }
58 tofree[ntofree++] = k;
59 }
60 // TODO: output to stderr is not useful for apps.
61 // Can we fall back to Android's log library?
62
63 /*
64 * We got the key we wanted. Free the others.
65 */
66 for(i=0; i<ntofree; i++) {
67 pthread_key_delete(tofree[i]);
68 }
69}
70
71
72static void*
73threadentry(void *v)
74{
75 ThreadStart ts;
76
77 ts = *(ThreadStart*)v;
78 free(v);
79
Dan Willemsena3223282018-02-27 19:41:43 -080080 if (pthread_setspecific(k1, (void*)ts.g) != 0) {
81 fprintf(stderr, "runtime/cgo: pthread_setspecific failed\n");
82 abort();
83 }
Dan Willemsen38f2dba2016-07-08 14:54:35 -070084
85 crosscall_386(ts.fn);
86 return nil;
87}
88
89void (*x_cgo_inittls)(void) = inittls;
90void* (*x_cgo_threadentry)(void*) = threadentry;