authorgravatar for inkryption07@gmail.comInKryption <inkryption07@gmail.com> 2022-08-10 17:09:27+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-08-10 16:39:46-04:00
loge218b7ea0c2a907c5728006b38e7ca492e19ccb6
tree636e5a1fc5fbe220cf29060c657b8719de78764f
parent0e118ed0aca3d852d2499fa37d04adef62b03ead

stage2: add compile error for invalid null/undefined pointer cast


3 files changed, 31 insertions(+), 0 deletions(-)

src/Sema.zig+9
...@@ -17272,6 +17272,15 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air...@@ -17272,6 +17272,15 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
17272 else17272 else
17273 operand;17273 operand;
1727417274
17275 if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |operand_val| {
17276 if (!dest_ty.ptrAllowsZero() and operand_val.isUndef()) {
17277 return sema.failWithUseOfUndef(block, operand_src);
17278 }
17279 if (!dest_ty.ptrAllowsZero() and operand_val.isNull()) {
17280 return sema.fail(block, operand_src, "null pointer casted to type {}", .{dest_ty.fmt(sema.mod)});
17281 }
17282 }
17283
17275 const dest_elem_ty = dest_ty.elemType2();17284 const dest_elem_ty = dest_ty.elemType2();
17276 try sema.resolveTypeLayout(block, dest_ty_src, dest_elem_ty);17285 try sema.resolveTypeLayout(block, dest_ty_src, dest_elem_ty);
17277 const dest_align = dest_ty.ptrAlignment(target);17286 const dest_align = dest_ty.ptrAlignment(target);
test/cases/compile_errors/compile_time_null_ptr_cast.zig created+11
...@@ -0,0 +1,11 @@
1comptime {
2 var opt_ptr: ?*i32 = null;
3 const ptr = @ptrCast(*i32, opt_ptr);
4 _ = ptr;
5}
6
7// error
8// backend=llvm
9// target=native
10//
11// :3:32: error: null pointer casted to type *i32
test/cases/compile_errors/compile_time_undef_ptr_cast.zig created+11
...@@ -0,0 +1,11 @@
1comptime {
2 var undef_ptr: *i32 = undefined;
3 const ptr = @ptrCast(*i32, undef_ptr);
4 _ = ptr;
5}
6
7// error
8// backend=llvm
9// target=native
10//
11// :3:32: error: use of undefined value here causes undefined behavior