Bus error interfacing with C function returning large struct
John Colvin
john.loughran.colvin at gmail.com
Tue Apr 16 16:03:43 PDT 2013
On Tuesday, 16 April 2013 at 19:26:09 UTC, Jacob Carlborg wrote:
> The following code will result in a bus error on Mac OS X
> 10.8.2 using DMD 2.062 compiled for 32bit (segfault on 64bit).
> A couple of notes:
>
> * This code runs fine on Mac OS X 10.6.3
> * It seems the struct has to be over 64 bits in size
> * "foo" need to take an argument
>
> Dissassembly at the bottom.
>
> I think this is the same problem I had with interfacing with
> the objc_msgSend_stret function, see other post:
>
> http://forum.dlang.org/thread/kkefk8$2663$1@digitalmars.com
>
> C code:
>
> struct Foo
> {
> int a;
> int b;
> int c;
> };
>
> typedef struct Foo Foo;
>
> Foo foo (int a)
> {
> Foo f;
> f.a = 1;
> f.b = 2;
> f.c = 3;
> return f;
> }
>
> D code:
>
> struct Foo
> {
> int a;
> int b;
> int c;
> }
>
> extern (C) Foo foo (int a);
>
> Foo bar ()
> {
> return foo(0);
> }
>
> extern (C) int printf(in char*, ...);
>
> void main ()
> {
> auto frame = bar();
> printf("a=%d b=%d c=%d\n".ptr, frame.a, frame.b, frame.c);
> }
>
> GDB session with dissassembly:
>
> http://pastebin.com/rguwXucR
>
> Dissassembly of the corresponding C program compiled with Clang:
>
> http://pastebin.com/MG8Tnkzp
>
> Dissassembly of "foo" on Mac OS X 10.8.2 using Clang 4.1:
>
> http://pastebin.com/0jKqksxx
>
> Dissassembly of "foo" on Mac OS X 10.6.3 using Clang 1.5:
>
> http://pastebin.com/kbdfuVcB
Some observations:
Assuming main is doing everything properly, it's passing a
pointer to 12 bytes of stack space to bar in eax (as per the D
ABI). bar then puts that pointer on the stack for foo (as per the
IA32 OS X ABI). However, it looks to me like it's in the wrong
place, because of this line:
0x00002673 <D4test3barFZS4test3Foo+11>: sub $0x8,%esp
This is just from a quick glance, I may have added my hexes
wrongly.
More information about the Digitalmars-d
mailing list