stage1: fix crash on accessing an array of size zero with runtime index

master
xackus 2020-04-23 03:06:41 +02:00 committed by Andrew Kelley
parent e6428f9401
commit a9eb4a6740
3 changed files with 19 additions and 1 deletions

View File

@ -3869,6 +3869,9 @@ static LLVMValueRef ir_render_elem_ptr(CodeGen *g, IrExecutableGen *executable,
assert(array_type->data.pointer.child_type->id == ZigTypeIdArray);
array_type = array_type->data.pointer.child_type;
}
assert(array_type->data.array.len != 0 || array_type->data.array.sentinel != nullptr);
if (safety_check_on) {
uint64_t extra_len_from_sentinel = (array_type->data.array.sentinel != nullptr) ? 1 : 0;
uint64_t full_len = array_type->data.array.len + extra_len_from_sentinel;

View File

@ -21199,6 +21199,11 @@ static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemP
}
if (array_type->id == ZigTypeIdArray) {
if(array_type->data.array.len == 0 && array_type->data.array.sentinel == nullptr){
ir_add_error(ira, &elem_ptr_instruction->base.base, buf_sprintf("accessing a zero length array is not allowed"));
return ira->codegen->invalid_inst_gen;
}
ZigType *child_type = array_type->data.array.child_type;
if (ptr_type->data.pointer.host_int_bytes == 0) {
return_type = get_pointer_to_type_extra(ira->codegen, child_type,

View File

@ -4552,7 +4552,17 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
\\ const pointer = &array[0];
\\}
, &[_][]const u8{
"tmp.zig:3:27: error: index 0 outside array of size 0",
"tmp.zig:3:27: error: accessing a zero length array is not allowed",
});
cases.add("indexing an array of size zero with runtime index",
\\const array = [_]u8{};
\\export fn foo() void {
\\ var index: usize = 0;
\\ const pointer = &array[index];
\\}
, &[_][]const u8{
"tmp.zig:4:27: error: accessing a zero length array is not allowed",
});
cases.add("compile time division by zero",