I'm porting a Ruby gem written in C to Ruby with FFI.
When I run the tests using MRI Ruby there aren't any seg-faults. When running in jRuby, I get a seg-fault.
This is the code in the test that I think is responsible:
if type == Date or type == DateTime then
assert_nil param.set_value(value.strftime("%F %T"));
else
assert_nil param.set_value(value);
end
@api.sqlany_bind_param(stmt, 0, param)
puts "\n#{param.inspect}"
#return if String === value or Date === value or DateTime === value
assert_succeeded @api.sqlany_execute(stmt)
The segmentation fault happens when running sqlany_execute, but only when the object passed to set_value is of the class String.
sqlany_execute just uses FFI's attach_function method.
param.set_value is more complicated. I'll focus just on the String specific part. Here is the original C code
case T_STRING:
s_bind->value.length = malloc(sizeof(size_t));
length = RSTRING_LEN(val);
*s_bind->value.length = length;
s_bind->value.buffer = malloc(length);
memcpy(s_bind->value.buffer, RSTRING_PTR(val), length);
s_bind->value.type = A_STRING;
break;
In my port, this became:
when String
self[:value][:length] = SQLAnywhere::LibC.malloc(FFI::Type::ULONG.size)
length = value.bytesize
self[:value][:length].write_int(length)
self[:value][:buffer] = SQLAnywhere::LibC.malloc(length + 1)
self[:value][:buffer_size] = length + 1
## Don't use put_string as that includes the terminating null
# value.each_byte.each_with_index do |byte, index|
# self[:value][:buffer].put_uchar(index, byte)
# end
self[:value][:buffer].put_string(0, value)
self[:value][:type] = :string
My question is: what's causing jRuby to seg fault and what can I do about it?