From 6a5463951f0aa11cbdd5575cc78e85cd2ed10b46 Mon Sep 17 00:00:00 2001 From: mlugg Date: Mon, 21 Aug 2023 02:07:40 +0100 Subject: [PATCH] Sema: disallow C pointer to slice coercion Resolves: #16719 --- src/Sema.zig | 1 + .../compile_errors/ptr_coerced_to_slice.zig | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 test/cases/compile_errors/ptr_coerced_to_slice.zig diff --git a/src/Sema.zig b/src/Sema.zig index b4dd9fbd66..504a335b53 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -27289,6 +27289,7 @@ fn coerceExtra( // coercion from C pointer if (inst_ty.isCPtr(mod)) src_c_ptr: { + if (dest_info.flags.size == .Slice) break :src_c_ptr; if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :src_c_ptr; // In this case we must add a safety check because the C pointer // could be null. diff --git a/test/cases/compile_errors/ptr_coerced_to_slice.zig b/test/cases/compile_errors/ptr_coerced_to_slice.zig new file mode 100644 index 0000000000..2b96f83064 --- /dev/null +++ b/test/cases/compile_errors/ptr_coerced_to_slice.zig @@ -0,0 +1,20 @@ +export fn foo() void { + const ptr: [*]const u8 = "abc"; + _ = @as([]const u8, ptr); +} +export fn bar() void { + const ptr: [*c]const u8 = "def"; + _ = @as([]const u8, ptr); +} +export fn baz() void { + const ptr: *const u8 = &@as(u8, 123); + _ = @as([]const u8, ptr); +} + +// error +// backend=stage2 +// target=native +// +// :3:25: error: expected type '[]const u8', found '[*]const u8' +// :7:25: error: expected type '[]const u8', found '[*c]const u8' +// :11:25: error: expected type '[]const u8', found '*const u8'