aboutsummaryrefslogtreecommitdiff
path: root/test/behavior/ptrfromint.zig
blob: 480c773c156af7d49087d25a03a781ad553e1601 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const std = @import("std");
const builtin = @import("builtin");
const expectEqual = std.testing.expectEqual;

test "casting integer address to function pointer" {
    if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest;

    addressToFunction();
    comptime addressToFunction();
}

fn addressToFunction() void {
    var addr: usize = 0xdeadbee0;
    _ = &addr;
    _ = @as(*const fn () void, @ptrFromInt(addr));
}

test "mutate through ptr initialized with constant ptrFromInt value" {
    if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
    if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
    if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest;

    forceCompilerAnalyzeBranchHardCodedPtrDereference(false);
}

fn forceCompilerAnalyzeBranchHardCodedPtrDereference(x: bool) void {
    const hardCodedP = @as(*volatile u8, @ptrFromInt(0xdeadbeef));
    if (x) {
        hardCodedP.* = hardCodedP.* | 10;
    } else {
        return;
    }
}

test "@ptrFromInt creates null pointer" {
    if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
    if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
    if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest;

    const ptr = @as(?*u32, @ptrFromInt(0));
    try expectEqual(@as(?*u32, null), ptr);
}

test "@ptrFromInt creates allowzero zero pointer" {
    if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest;
    if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
    if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest;

    const ptr = @as(*allowzero u32, @ptrFromInt(0));
    try expectEqual(@as(usize, 0), @intFromPtr(ptr));
}