remove empty dir
[ghc-hetmet.git] / ghc / docs / comm / the-beast / fexport.html
1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
2 <html>
3   <head>
4     <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
5     <title>The GHC Commentary - foreign export</title>
6   </head>
7
8   <body BGCOLOR="FFFFFF">
9     <h1>The GHC Commentary - foreign export</h1>
10
11     The implementation scheme for foreign export, as of 27 Feb 02, is
12     as follows.  There are four cases, of which the first two are easy.
13     <p>
14     <b>(1) static export of an IO-typed function from some module <code>MMM</code></b>
15     <p>
16     <code>foreign export foo :: Int -> Int -> IO Int</code>
17     <p>
18     For this we generate no Haskell code.  However, a C stub is
19     generated, and it looks like this:
20     <p>
21     <pre>
22 extern StgClosure* MMM_foo_closure;
23
24 HsInt foo (HsInt a1, HsInt a2)
25 {
26    SchedulerStatus rc;
27    HaskellObj ret;
28    rc = rts_evalIO(
29            rts_apply(rts_apply(MMM_foo_closure,rts_mkInt(a1)),
30                      rts_mkInt(a2)
31                     ),
32            &ret
33         );
34    rts_checkSchedStatus("foo",rc);
35    return(rts_getInt(ret));
36 }
37 </pre>
38     <p>
39     This does the obvious thing: builds in the heap the expression
40     <code>(foo a1 a2)</code>, calls <code>rts_evalIO</code> to run it,
41     and uses <code>rts_getInt</code> to fish out the result.
42
43     <p>
44     <b>(2) static export of a non-IO-typed function from some module <code>MMM</code></b>
45     <p>
46     <code>foreign export foo :: Int -> Int -> Int</code>
47     <p>
48     This is identical to case (1), with the sole difference that the
49     stub calls <code>rts_eval</code> rather than
50     <code>rts_evalIO</code>.
51     <p>
52
53     <b>(3) dynamic export of an IO-typed function from some module <code>MMM</code></b>
54     <p>
55     <code>foreign export mkCallback :: (Int -> Int -> IO Int) -> IO (FunPtr a)</code>
56     <p>
57     Dynamic exports are a whole lot more complicated than their static
58     counterparts.
59     <p>
60     First of all, we get some Haskell code, which, when given a
61     function <code>callMe :: (Int -> Int -> IO Int)</code> to be made
62     C-callable, IO-returns a <code>FunPtr a</code>, which is the
63     address of the resulting C-callable code.  This address can now be
64     handed out to the C-world, and callers to it will get routed
65     through to <code>callMe</code>.
66     <p>
67     The generated Haskell function looks like this:
68     <p>
69 <pre>
70 mkCallback f
71   = do sp <- mkStablePtr f
72        r  <- ccall "createAdjustorThunk" sp (&"run_mkCallback")
73        return r
74 </pre>
75     <p>
76     <code>createAdjustorThunk</code> is a gruesome,
77     architecture-specific function in the RTS.  It takes a stable
78     pointer to the Haskell function to be run, and the address of the
79     associated C wrapper, and returns a piece of machine code,
80     which, when called from the outside (C) world, eventually calls
81     through to <code>f</code>.
82     <p>
83     This machine code fragment is called the "Adjustor Thunk" (don't
84     ask me why).  What it does is simply to call onwards to the C
85     helper
86     function <code>run_mkCallback</code>, passing all the args given
87     to it but also conveying <code>sp</code>, which is a stable
88     pointer
89     to the Haskell function to run.  So:
90     <p>
91 <pre>
92 createAdjustorThunk ( StablePtr sp, CCodeAddress addr_of_helper_C_fn ) 
93 {
94    create malloc'd piece of machine code "mc", behaving thusly:
95
96    mc ( args_to_mc ) 
97    { 
98       jump to addr_of_helper_C_fn, passing sp as an additional
99       argument
100    }
101 </pre>
102     <p>
103     This is a horrible hack, because there is no portable way, even at
104     the machine code level, to function which adds one argument and
105     then transfers onwards to another C function.  On x86s args are
106     pushed R to L onto the stack, so we can just push <code>sp</code>,
107     fiddle around with return addresses, and jump onwards to the
108     helper C function.  However, on architectures which use register
109     windows and/or pass args extensively in registers (Sparc, Alpha,
110     MIPS, IA64), this scheme borders on the unviable.  GHC has a
111     limited <code>createAdjustorThunk</code> implementation for Sparc
112     and Alpha, which handles only the cases where all args, including
113     the extra one, fit in registers.
114     <p>
115     Anyway: the other lump of code generated as a result of a
116     f-x-dynamic declaration is the C helper stub.  This is basically
117     the same as in the static case, except that it only ever gets
118     called from the adjustor thunk, and therefore must accept 
119     as an extra argument, a stable pointer to the Haskell function
120     to run, naturally enough, as this is not known until run-time.
121     It then dereferences the stable pointer and does the call in
122     the same way as the f-x-static case:
123 <pre>
124 HsInt Main_d1kv ( StgStablePtr the_stableptr, 
125                   void* original_return_addr, 
126                   HsInt a1, HsInt a2 )
127 {
128    SchedulerStatus rc;
129    HaskellObj ret;
130    rc = rts_evalIO(
131            rts_apply(rts_apply((StgClosure*)deRefStablePtr(the_stableptr),
132                                rts_mkInt(a1)
133                      ),
134                      rts_mkInt(a2)
135            ),
136            &ret
137         );
138    rts_checkSchedStatus("Main_d1kv",rc);
139    return(rts_getInt(ret));
140 }
141 </pre>
142     <p>
143     Note how this function has a purely made-up name
144     <code>Main_d1kv</code>, since unlike the f-x-static case, this
145     function is never called from user code, only from the adjustor
146     thunk.
147     <p>
148     Note also how the function takes a bogus parameter
149     <code>original_return_addr</code>, which is part of this extra-arg
150     hack.  The usual scheme is to leave the original caller's return
151     address in place and merely push the stable pointer above that,
152     hence the spare parameter.
153     <p>
154     Finally, there is some extra trickery, detailed in
155     <code>ghc/rts/Adjustor.c</code>, to get round the following
156     problem: the adjustor thunk lives in mallocville.  It is
157     quite possible that the Haskell code will actually
158     call <code>free()</code> on the adjustor thunk used to get to it
159     -- because otherwise there is no way to reclaim the space used
160     by the adjustor thunk.  That's all very well, but it means that
161     the C helper cannot return to the adjustor thunk in the obvious
162     way, since we've already given it back using <code>free()</code>.
163     So we leave, on the C stack, the address of whoever called the
164     adjustor thunk, and before calling the helper, mess with the stack
165     such that when the helper returns, it returns directly to the
166     adjustor thunk's caller.  
167     <p>
168     That's how the <code>stdcall</code> convention works.  If the
169     adjustor thunk has been called using the <code>ccall</code>
170     convention, we return indirectly, via a statically-allocated
171     yet-another-magic-piece-of-code, which takes care of removing the
172     extra argument that the adjustor thunk pushed onto the stack.
173     This is needed because in <code>ccall</code>-world, it is the
174     caller who removes args after the call, and the original caller of
175     the adjustor thunk has no way to know about the extra arg pushed
176     by the adjustor thunk.
177     <p>
178     You didn't really want to know all this stuff, did you?
179     <p>
180
181
182
183     <b>(4) dynamic export of an non-IO-typed function from some module <code>MMM</code></b>
184     <p>
185     <code>foreign export mkCallback :: (Int -> Int -> Int) -> IO (FunPtr a)</code>
186     <p>
187     (4) relates to (3) as (2) relates to (1), that is, it's identical,
188     except the C stub uses <code>rts_eval</code> instead of
189     <code>rts_evalIO</code>.
190     <p>
191
192
193    <h2>Some perspective on f-x-dynamic</h2>
194
195    The only really horrible problem with f-x-dynamic is how the
196    adjustor thunk should pass to the C helper the stable pointer to
197    use.  Ideally we would like this to be conveyed via some invisible
198    side channel, since then the adjustor thunk could simply jump
199    directly to the C helper, with no non-portable stack fiddling.
200    <p>
201    Unfortunately there is no obvious candidate for the invisible
202    side-channel.  We've chosen to pass it on the stack, with the
203    bad consequences detailed above.  Another possibility would be to
204    park it in a global variable, but this is non-reentrant and
205    non-(OS-)thread-safe.  A third idea is to put it into a callee-saves
206    register, but that has problems too: the C helper may not use that
207    register and therefore we will have trashed any value placed there
208    by the caller; and there is no C-level portable way to read from
209    the register inside the C helper.
210    <p>
211    In short, we can't think of a really satisfactory solution.  I'd
212    vote for introducing some kind of OS-thread-local-state and passing
213    it in there, but that introduces complications of its own.
214    <p>
215    <b>OS-thread-safety</b> is of concern in the C stubs, whilst
216    building up the expressions to run.  These need to have exclusive
217    access to the heap whilst allocating in it.  Also, there needs to
218    be some guarantee that no GC will happen in between the
219    <code>deRefStablePtr</code> call and when <code>rts_eval[IO]</code>
220    starts running.  At the moment there are no guarantees for
221    either property.  This needs to be sorted out before the
222    implementation can be regarded as fully safe to use.
223
224 <p><small>
225    
226 <!-- hhmts start -->
227 Last modified: Weds 27 Feb 02
228 <!-- hhmts end -->
229     </small>
230   </body>
231 </html>