authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2023-08-21 02:07:40+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-08-21 11:31:22-07:00
log6a5463951f0aa11cbdd5575cc78e85cd2ed10b46
tree9cff18509ff5a08748755d5dd57cc015a1a304a1
parent82c8e45a7e7659146b2ecda2929f01027b0658e4

Sema: disallow C pointer to slice coercion

Resolves: #16719

2 files changed, 21 insertions(+), 0 deletions(-)

src/Sema.zig+1
...@@ -27289,6 +27289,7 @@ fn coerceExtra(...@@ -27289,6 +27289,7 @@ fn coerceExtra(
2728927289
27290 // coercion from C pointer27290 // coercion from C pointer
27291 if (inst_ty.isCPtr(mod)) src_c_ptr: {27291 if (inst_ty.isCPtr(mod)) src_c_ptr: {
27292 if (dest_info.flags.size == .Slice) break :src_c_ptr;
27292 if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :src_c_ptr;27293 if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :src_c_ptr;
27293 // In this case we must add a safety check because the C pointer27294 // In this case we must add a safety check because the C pointer
27294 // could be null.27295 // could be null.
test/cases/compile_errors/ptr_coerced_to_slice.zig created+20
...@@ -0,0 +1,20 @@
1export fn foo() void {
2 const ptr: [*]const u8 = "abc";
3 _ = @as([]const u8, ptr);
4}
5export fn bar() void {
6 const ptr: [*c]const u8 = "def";
7 _ = @as([]const u8, ptr);
8}
9export fn baz() void {
10 const ptr: *const u8 = &@as(u8, 123);
11 _ = @as([]const u8, ptr);
12}
13
14// error
15// backend=stage2
16// target=native
17//
18// :3:25: error: expected type '[]const u8', found '[*]const u8'
19// :7:25: error: expected type '[]const u8', found '[*c]const u8'
20// :11:25: error: expected type '[]const u8', found '*const u8'