From c0a446aabd966cd9080bfe2f50ae0355e9b73bef Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Wed, 25 Mar 2020 16:41:11 +0100 Subject: [PATCH] Add bounds checks for writing to an inline char[] * Raise IndexError if the written String is longer than the char[]. * Don't write a final \0 if we write as many characters as the char[] length. --- ext/ffi_c/StructLayout.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ext/ffi_c/StructLayout.c b/ext/ffi_c/StructLayout.c index 80749bbe8..9b748bd0c 100644 --- a/ext/ffi_c/StructLayout.c +++ b/ext/ffi_c/StructLayout.c @@ -350,8 +350,13 @@ array_field_put(VALUE self, VALUE pointer, VALUE value) argv[0] = INT2FIX(f->offset); argv[1] = value; - rb_funcall2(pointer, rb_intern("put_string"), 2, argv); - + if (RSTRING_LEN(value) < array->length) { + rb_funcall2(pointer, rb_intern("put_string"), 2, argv); + } else if (RSTRING_LEN(value) == array->length) { + rb_funcall2(pointer, rb_intern("put_bytes"), 2, argv); + } else { + rb_raise(rb_eIndexError, "String is longer (%ld bytes) than the char array (%d bytes)", RSTRING_LEN(value), array->length); + } } else { #ifdef notyet MemoryOp* op;