tracing segfaults with FFI

Hello,
I have these two functions:
freezeNode node = do
ptr <- newStablePtr node
new (castPtr $ castStablePtrToPtr ptr)
thawNode nodePtr = do
deRefStablePtr (castPtrToStablePtr nodePtr)
I use the first to pack a Haskell structure and hand it over to a c
library with FFI. It calls me back (traces show I do get the original
address) but deRefStablePtr causes a segfault.
What am I doing wrong? More generally, how do I approach this kind of
problem? What tools exist that can help me debug FFI code?
--
Gaal Yahas

Gaal Yahas wrote:
I have these two functions:
freezeNode node = do ptr <- newStablePtr node new (castPtr $ castStablePtrToPtr ptr)
thawNode nodePtr = do deRefStablePtr (castPtrToStablePtr nodePtr)
You're attempting to deref the StablePtr, and also run it as an IO action! I bet the original value wasn't an IO action, right? You probably want something like thawNode nodePtr = do node <- deRefStablePtr (castPtrToStablePtr nodePtr) -- and do something with node here in general, try to keep as much type information as possible. That is, avoid the use of castPtrToStablePtr and its inverse, by giving correct types to your FFI functions (you haven't shown more of the code so I don't know if this applies in your case).
What am I doing wrong? More generally, how do I approach this kind of problem? What tools exist that can help me debug FFI code?
Tools are a bit thin on the ground. gdb can help you debug crashes that happen in C code, for for Haskell code your best tool is still putStr/printf/trace. Gurus can use gdb on Haskell code, and I'm happy to help out (there should probably be a wiki page on how to do this, actually), but it's definitely not for the faint hearted. Cheers, Simon

On Wed, Jan 04, 2006 at 12:36:35PM +0000, Simon Marlow wrote:
thawNode nodePtr = do deRefStablePtr (castPtrToStablePtr nodePtr)
You're attempting to deref the StablePtr, and also run it as an IO action! I bet the original value wasn't an IO action, right?
You probably want something like
thawNode nodePtr = do node <- deRefStablePtr (castPtrToStablePtr nodePtr) -- and do something with node here
in general, try to keep as much type information as possible. That is, avoid the use of castPtrToStablePtr and its inverse, by giving correct types to your FFI functions (you haven't shown more of the code so I don't know if this applies in your case).
The code is at http://svn.openfoundry.org/pugs/src/Data/Yaml/Syck.hsc .
parseYaml works, as does its usage of freezeNode. readNode is slightly
different than thawNode; it gets its pointer from an out variable in
syck_lookup_sym.
Note that readNode also returns an IO YamlNode. How is it correct to do
so there?
--
Gaal Yahas
participants (2)
-
Gaal Yahas
-
Simon Marlow