Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created August 13, 2012 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TooTallNate/3342783 to your computer and use it in GitHub Desktop.
Save TooTallNate/3342783 to your computer and use it in GitHub Desktop.
libffi closures not working on OS X 10.8 Mountain Lion?
#include <stdio.h>
#include <ffi.h>
/* Acts like puts with the file given at time of enclosure. */
void puts_binding(ffi_cif *cif, unsigned int *ret, void* args[],
FILE *stream)
{
*ret = fputs(*(char **)args[0], stream);
}
int main()
{
ffi_cif cif;
ffi_type *args[1];
ffi_closure *closure;
int (*bound_puts)(char *);
int rc;
/* Allocate closure and bound_puts */
closure = ffi_closure_alloc(sizeof(ffi_closure), &bound_puts);
if (closure)
{
/* Initialize the argument info vectors */
args[0] = &ffi_type_pointer;
/* Initialize the cif */
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
&ffi_type_uint, args) == FFI_OK)
{
/* Initialize the closure, setting stream to stdout */
if (ffi_prep_closure_loc(closure, &cif, puts_binding,
stdout, bound_puts) == FFI_OK)
{
rc = bound_puts("Hello World!");
/* rc now holds the result of the call to fputs */
}
}
}
/* Deallocate both closure, and bound_puts */
ffi_closure_free(closure);
return 0;
}
# first build libffi
$ cd libffi
$ ./configure --enable-static --disable-shared --disable-builddir --with-pic
$ make

# now compile the closure test case
$ curl -O https://raw.github.com/gist/3342783/2bebffb034f528e035549b27c0d8aa3e019068e2/closure.c
$ gcc -Iinclude closure.c .libs/libffi.a -o closure-test

# now run the "closure-test" program and get a Bus Error
$ ./closure-test
Bus error: 10

# what gdb says
$ gdb --args ./closure-test
GNU gdb 6.3.50-20050815 (Apple version gdb-1820) (Sat Jun 16 02:40:11 UTC 2012)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries .. done

(gdb) run
Starting program: /Users/nrajlich/node-ffi/deps/libffi/closure-test 
Reading symbols for shared libraries +............................. done

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x0000000100103a30
0x0000000100103a30 in ?? ()
(gdb) bt full
#0  0x0000000100103a30 in ?? ()
No symbol table info available.
#1  0x00007fff923517e1 in start ()
No symbol table info available.
(gdb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment