From 9964f1c160acd0bf994708333cd69bc070d6c77e Mon Sep 17 00:00:00 2001 From: InKryption Date: Thu, 16 Mar 2023 01:02:10 +0100 Subject: [PATCH] Add error for bad cast from `*T` to `*[n]T` Casting `*T` to `*[1]T` should still work, but every other length will now be a compiler error instead of a potential OOB access. --- src/Sema.zig | 1 + ..._implicit_cast_from_T_to_long_array_ptr.zig | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 test/cases/compile_errors/attempted_implicit_cast_from_T_to_long_array_ptr.zig diff --git a/src/Sema.zig b/src/Sema.zig index fc39fbb9fc..8b476d4542 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -24853,6 +24853,7 @@ fn coerceExtra( const array_ty = dest_info.pointee_type; if (array_ty.zigTypeTag() != .Array) break :single_item; const array_elem_ty = array_ty.childType(); + if (array_ty.arrayLen() != 1) break :single_item; const dest_is_mut = dest_info.mutable; switch (try sema.coerceInMemoryAllowed(block, array_elem_ty, ptr_elem_ty, dest_is_mut, target, dest_ty_src, inst_src)) { .ok => {}, diff --git a/test/cases/compile_errors/attempted_implicit_cast_from_T_to_long_array_ptr.zig b/test/cases/compile_errors/attempted_implicit_cast_from_T_to_long_array_ptr.zig new file mode 100644 index 0000000000..135081c15c --- /dev/null +++ b/test/cases/compile_errors/attempted_implicit_cast_from_T_to_long_array_ptr.zig @@ -0,0 +1,18 @@ +export fn entry0(single: *u32) void { + _ = @as(*const [0]u32, single); +} +export fn entry1(single: *u32) void { + _ = @as(*const [1]u32, single); +} +export fn entry2(single: *u32) void { + _ = @as(*const [2]u32, single); +} + +// error +// backend=stage2 +// target=native +// +// :2:28: error: expected type '*const [0]u32', found '*u32' +// :2:28: note: pointer type child 'u32' cannot cast into pointer type child '[0]u32' +// :8:28: error: expected type '*const [2]u32', found '*u32' +// :8:28: note: pointer type child 'u32' cannot cast into pointer type child '[2]u32'