summaryrefslogtreecommitdiff
path: root/src/pkg/runtime/cgocall.c
blob: f673d1b6ecce535e1cf2d177d89a9c6fb87605d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "runtime.h"
#include "cgocall.h"

void *initcgo;	/* filled in by dynamic linker when Cgo is available */
int64 ncgocall;
void ·entersyscall(void);
void ·exitsyscall(void);

void
cgocall(void (*fn)(void*), void *arg)
{
	G *oldlock;

	if(initcgo == nil)
		throw("cgocall unavailable");

	ncgocall++;

	/*
	 * Lock g to m to ensure we stay on the same stack if we do a
	 * cgo callback.
	 */
	oldlock = m->lockedg;
	m->lockedg = g;
	g->lockedm = m;

	/*
	 * Announce we are entering a system call
	 * so that the scheduler knows to create another
	 * M to run goroutines while we are in the
	 * foreign code.
	 */
	·entersyscall();
	runcgo(fn, arg);
	·exitsyscall();

	m->lockedg = oldlock;
	if(oldlock == nil)
		g->lockedm = nil;

	return;
}

// When a C function calls back into Go, the wrapper function will
// call this.  This switches to a Go stack, copies the arguments
// (arg/argsize) on to the stack, calls the function, copies the
// arguments back where they came from, and finally returns to the old
// stack.
void
cgocallback(void (*fn)(void), void *arg, int32 argsize)
{
	Gobuf oldsched;
	G *g1;
	void *sp;

	if(g != m->g0)
		throw("bad g in cgocallback");

	oldsched = m->sched;

	g1 = m->curg;

	startcgocallback(g1);

	sp = g1->sched.sp - argsize;
	if(sp < g1->stackguard)
		throw("g stack overflow in cgocallback");
	mcpy(sp, arg, argsize);

	runcgocallback(g1, sp, fn);

	mcpy(arg, sp, argsize);

	endcgocallback(g1);

	m->sched = oldsched;
}

void
·Cgocalls(int64 ret)
{
	ret = ncgocall;
	FLUSH(&ret);
}

void (*_cgo_malloc)(void*);
void (*_cgo_free)(void*);

void*
cmalloc(uintptr n)
{
	struct a {
		uint64 n;
		void *ret;
	} a;

	a.n = n;
	a.ret = nil;
	cgocall(_cgo_malloc, &a);
	return a.ret;
}

void
cfree(void *p)
{
	cgocall(_cgo_free, p);
}