Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions ext/bson/write.c
Original file line number Diff line number Diff line change
Expand Up @@ -649,20 +649,26 @@ VALUE rb_bson_byte_buffer_put_array(VALUE self, VALUE array){
size_t new_position = 0;
int32_t new_length = 0;
size_t position = 0;
VALUE *array_element = NULL;
TypedData_Get_Struct(self, byte_buffer_t, &rb_byte_buffer_data_type, b);
Check_Type(array, T_ARRAY);

position = READ_SIZE(b);
/* insert length placeholder */
pvt_put_int32(b, 0);

array_element = RARRAY_PTR(array);
long original_len = RARRAY_LEN(array);
if (original_len > INT32_MAX) {
rb_raise(rb_eRangeError, "array too large for BSON serialization");
}

for(int32_t index=0; index < RARRAY_LEN(array); index++, array_element++){
pvt_put_type_byte(b, *array_element);
for (int32_t index = 0; index < (int32_t)original_len; index++) {
if (RARRAY_LEN(array) != original_len) {
rb_raise(rb_eRuntimeError, "array modified during BSON serialization");
}
volatile VALUE element = rb_ary_entry(array, index);
pvt_put_type_byte(b, element);
pvt_put_array_index(b, index);
pvt_put_field(b, self, *array_element);
pvt_put_field(b, self, element);
}
pvt_put_byte(b, 0);

Expand Down
24 changes: 24 additions & 0 deletions spec/bson/array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,30 @@
end
end

context 'when an array element mutates the array size during serialization',
if: BSON::ByteBuffer.new.respond_to?(:put_array) do
let(:array) { Array.new(10, 1) }

before do
evil = Class.new do
define_method(:initialize) { |a| @array = a; @mutated = false }
define_method(:bson_type) do
unless @mutated
@mutated = true
@array.replace(Array.new(200_000, 0))
end
BSON::Int32::BSON_TYPE
end
define_method(:to_bson) { |buffer| 123.to_bson(buffer) }
end
array[0] = evil.new(array)
end

it 'raises a RuntimeError' do
expect { array.to_bson }.to raise_error(RuntimeError, /array modified during BSON serialization/)
end
end

context 'when array contains value of an unserializable class' do
class ArraySpecUnserializableClass
end
Expand Down
Loading