Changes between Version 4 and Version 5 of Commentary/Rts/FFI

Oct 5, 2009 10:15:57 PM (6 years ago)



  • Commentary/Rts/FFI

    v4 v5  
    33= GHC Commentary: Runtime aspects of the FFI =
    5 [[GhcFile(rts/Adjustor.c)]]
     6== Foreign Import "wrapper" ==
     7Files [[GhcFile(rts/Adjustor.c)]]  [[GhcFile(rts/AdjustorAsm.S)]].
     9Occasionally, it is convenient to treat Haskell closures as C function pointers.
     10This is useful, for example, if we want to install Haskell callbacks in an existing C library.
     11This functionality is implemented with the aid of adjustor thunks.
     13An adjustor thunk is a dynamically allocated code snippet that allows
     14Haskell closures to be viewed as C function pointers.
     16Stable pointers provide a way for the outside world to get access to,
     17and evaluate, Haskell heap objects, with the RTS providing a small
     18range of ops for doing so. So, assuming we've got a stable pointer in
     19our hand in C, we can jump into the Haskell world and evaluate a callback
     20procedure, say. This works OK in some cases where callbacks are used, but
     21does require the external code to know about stable pointers and how to deal
     22with them. We'd like to hide the Haskell-nature of a callback and have it
     23be invoked just like any other C function pointer.
     25Enter adjustor thunks. An adjustor thunk is a little piece of code
     26that's generated on-the-fly (one per Haskell closure being exported)
     27that, when entered using some 'universal' calling convention (e.g., the
     28C calling convention on platform X), pushes an implicit stable pointer
     29(to the Haskell callback) before calling another (static) C function stub
     30which takes care of entering the Haskell code via its stable pointer.
     32An adjustor thunk is allocated on the C heap, and is called from within
     33Haskell just before handing out the function pointer to the Haskell (IO)
     34action. User code should never have to invoke it explicitly.
     36An adjustor thunk differs from a C function pointer in one respect: when
     37the code is through with it, it has to be freed in order to release Haskell
     38and C resources. Failure to do so will result in memory leaks on both the C and
     39Haskell side.