Commit f8cd981c04

Andrew Kelley <andrew@ziglang.org>
2019-10-31 22:24:22
use -fsanitize=undefined for C code in safe build modes
closes #3569
1 parent cb5a5eb
Changed files (2)
lib/std/debug.zig
@@ -2404,6 +2404,7 @@ pub fn attachSegfaultHandler() void {
     };
 
     os.sigaction(os.SIGSEGV, &act, null);
+    os.sigaction(os.SIGILL, &act, null);
 }
 
 fn resetSegfaultHandler() void {
@@ -2420,6 +2421,7 @@ fn resetSegfaultHandler() void {
         .flags = 0,
     };
     os.sigaction(os.SIGSEGV, &act, null);
+    os.sigaction(os.SIGILL, &act, null);
 }
 
 extern fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *const c_void) noreturn {
@@ -2429,8 +2431,11 @@ extern fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *con
     resetSegfaultHandler();
 
     const addr = @ptrToInt(info.fields.sigfault.addr);
-    std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr});
-
+    switch (sig) {
+        os.SIGSEGV => std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr}),
+        os.SIGILL => std.debug.warn("Illegal instruction at address 0x{x}\n", .{addr}),
+        else => unreachable,
+    }
     switch (builtin.arch) {
         .i386 => {
             const ctx = @ptrCast(*const os.ucontext_t, @alignCast(@alignOf(os.ucontext_t), ctx_ptr));
src/codegen.cpp
@@ -8973,6 +8973,9 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa
 
     switch (g->build_mode) {
         case BuildModeDebug:
+            args.append("-fsanitize=undefined");
+            args.append("-fsanitize-trap=undefined");
+
             // windows c runtime requires -D_DEBUG if using debug libraries
             args.append("-D_DEBUG");
 
@@ -8985,6 +8988,9 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa
             }
             break;
         case BuildModeSafeRelease:
+            args.append("-fsanitize=undefined");
+            args.append("-fsanitize-trap=undefined");
+
             // See the comment in the BuildModeFastRelease case for why we pass -O2 rather
             // than -O3 here.
             args.append("-O2");