Commit e218b7ea0c

InKryption <inkryption07@gmail.com>
2022-08-10 17:09:27
stage2: add compile error for invalid null/undefined pointer cast
1 parent 0e118ed
Changed files (3)
src/Sema.zig
@@ -17272,6 +17272,15 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
     else
         operand;
 
+    if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |operand_val| {
+        if (!dest_ty.ptrAllowsZero() and operand_val.isUndef()) {
+            return sema.failWithUseOfUndef(block, operand_src);
+        }
+        if (!dest_ty.ptrAllowsZero() and operand_val.isNull()) {
+            return sema.fail(block, operand_src, "null pointer casted to type {}", .{dest_ty.fmt(sema.mod)});
+        }
+    }
+
     const dest_elem_ty = dest_ty.elemType2();
     try sema.resolveTypeLayout(block, dest_ty_src, dest_elem_ty);
     const dest_align = dest_ty.ptrAlignment(target);
test/cases/compile_errors/compile_time_null_ptr_cast.zig
@@ -0,0 +1,11 @@
+comptime {
+    var opt_ptr: ?*i32 = null;
+    const ptr = @ptrCast(*i32, opt_ptr);
+    _ = ptr;
+}
+
+// error
+// backend=llvm
+// target=native
+//
+// :3:32: error: null pointer casted to type *i32
test/cases/compile_errors/compile_time_undef_ptr_cast.zig
@@ -0,0 +1,11 @@
+comptime {
+    var undef_ptr: *i32 = undefined;
+    const ptr = @ptrCast(*i32, undef_ptr);
+    _ = ptr;
+}
+
+// error
+// backend=llvm
+// target=native
+//
+// :3:32: error: use of undefined value here causes undefined behavior