@setRuntimeSafety — 런타임 안전 검사 켜고 끄기

@setRuntimeSafety — 런타임 안전 검사 켜고 끄기

출처: Zig Documentation

본문

함수 호출이 들어 있는 그 스코프(범위)에서 런타임 안전 검사를 켤지 끌지를 정해드려요.

@setRuntimeSafety(comptime safety_on: bool) void

이 빌트인은 호출된 그 스코프에만 적용돼요. 그래서 여기서 정수 오버플로는 ReleaseFastReleaseSmall 모드에서 검출되지 않을 거예요:

test "@setRuntimeSafety" {
    // The builtin applies to the scope that it is called in. So here, integer overflow
    // will not be caught in ReleaseFast and ReleaseSmall modes:
    // var x: u8 = 255;
    // x += 1; // Unchecked Illegal Behavior in ReleaseFast/ReleaseSmall modes.
    {
        // However this block has safety enabled, so safety checks happen here,
        // even in ReleaseFast and ReleaseSmall modes.
        @setRuntimeSafety(true);
        var x: u8 = 255;
        x += 1;

        {
            // The value can be overridden at any scope. So here integer overflow
            // would not be caught in any build mode.
            @setRuntimeSafety(false);
            // var x: u8 = 255;
            // x += 1; // Unchecked Illegal Behavior in all build modes.
        }
    }
}

하지만 이 블록은 안전 검사가 켜져 있어서, ReleaseFastReleaseSmall 모드에서도 여기서는 안전 검사가 일어나요. 그리고 이 값은 어느 스코프에서든 다시 덮어쓸 수 있어서, 어떤 빌드 모드에서든 정수 오버플로가 검출되지 않게 할 수도 있어요.

$ zig test test_setRuntimeSafety_builtin.zig -Ofast
1/1 [email protected] 975313 panic: integer overflow
/home/ci/work/zig-bootstrap/out/zig-local-cache/tmp/15625dde49aa511e/../../../../zig/doc/langref/test_setRuntimeSafety_builtin.zig:11:11: 0x107c3c8 in test.@setRuntimeSafety (test)
        x += 1;
          ^
/home/ci/work/zig-bootstrap/out/host/lib/zig/compiler/test_runner.zig:295:25: 0x106eb62 in mainTerminal (test)
        if (test_fn.func()) |_| {
                        ^
/home/ci/work/zig-bootstrap/out/host/lib/zig/std/start.zig:789:88: 0x106d066 in callMain (test)
    if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
                                                                                       ^
/home/ci/work/zig-bootstrap/out/host/lib/zig/std/start.zig:248:5: 0x106ccfd in _start (test)
    asm volatile (switch (native_arch) {
    ^
error: the following test command terminated with signal ABRT:
/home/ci/work/zig-bootstrap/out/zig-local-cache/o/1053d260722683c1c582e293d115d193/test --seed=0xf0b4385

참고로 @setRuntimeSafety는 앞으로 @optimizeFor로 대체될 예정이에요.

더 알아보기 (Learn more)

  • @setRuntimeSafety는 빌트인 함수의 하나로, Builtin Functions 목록에서 확인할 수 있어요.
  • 빌드 모드별 안전 검사 동작은 Build Mode 항목에서 함께 보면 좋아요.