[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

x86_64 segmentation fault due to forgotten extern directive

Geert Fannes

3/9/2005 3:38:00 PM

Hello, I have been tracking down a segmentation fault that only appeared
on a x86_64 64 bit linux machine and was finally able to catch the
bastard. I'm not sure it is a bug (it looks more like bad coding
practice from my side), but it might be interesting for other people
experiencing the same problems.



I created a toy example that shows the essence: I have a ruby program
(test.rb) that calls a C function "cf_test" which was added to the class
String. This C function is defined in test.c and calls another C
function (localFunction) that is contained in another .c file (test2.c)
and thus also in another object file (test2.o). Finally, "compile"
contains the compilation instructions I used for compiling all this.



Ruby generates a segmentation fault when I omit the "extern" directive
on line 2 of test.c. I guess it is bad practice to omit this, but I got
no errors when I compiled test.c or linked test.o and test2.o together
to generate the shared object file test.so. For some strange reason,
this does not cause any problems on a 32 bit machine, I only found out
about it when I tried to port everything to a x86_64 machine



I hope this can be useful for someone,

Greetings,

Geert.



***test.rb***

require './test.so'



a='abc'.cf_test

puts a.class



***test.c***

#include "ruby.h"

extern VALUE localFunction(char*);//THIS IS A CRITICAL LINE ON x86_64

VALUE f_test(VALUE self)

{

return localFunction(RSTRING(self)->ptr);

}



VALUE cString;



void Init_test()

{

cString=rb_define_class("String",rb_cObject);

rb_define_method(cString,"cf_test",f_test,0);

}



***test2.c***

#include "ruby.h"



VALUE localFunction(char *pch)

{

return rb_str_new2(pch);

}



***compile***

#!/bin/bash



gcc -fpic -c test2.c -I/usr/local/lib/ruby/1.9/x86_64-linux



gcc -fpic -c test.c -I/usr/local/lib/ruby/1.9/x86_64-linux

gcc -shared test.o test2.o -o test.so



2 Answers

Ville Mattila

3/9/2005 5:02:00 PM

0

Hello,

This is easy to explain. On 32 bit system non introduced functions are
treated like they return int. This is 32 bit value on 32 and 64 bit systems.
The VALUE is actually a long type which 32 bit in 32 bit OS and 64 bit
on 64 bit OS. So you will have bad data as a return value if you don't
declare your functions correctly.

- Ville




ts

3/9/2005 5:23:00 PM

0

>>>>> "G" == Geert Fannes <Geert.Fannes@ikanconsulting.com> writes:

G> to generate the shared object file test.so. For some strange reason,
G> this does not cause any problems on a 32 bit machine, I only found out
G> about it when I tried to port everything to a x86_64 machine

Normal, on 32 bit machine sizeof(int) == sizeof(unsigned long). This is
not the case on x86_64




Guy Decoux