Merge branch 'master' into ebadf-error

This commit is contained in:
luna 2020-07-02 00:49:56 -03:00 committed by GitHub
commit e2cfc65909
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 479 additions and 188 deletions

View File

@ -49,11 +49,6 @@ pub fn build(b: *Builder) !void {
const fmt_build_zig = b.addFmt(&[_][]const u8{"build.zig"});
var exe = b.addExecutable("zig", "src-self-hosted/main.zig");
exe.setBuildMode(mode);
test_step.dependOn(&exe.step);
b.default_step.dependOn(&exe.step);
const skip_release = b.option(bool, "skip-release", "Main test suite skips release builds") orelse false;
const skip_release_small = b.option(bool, "skip-release-small", "Main test suite skips release-small builds") orelse skip_release;
const skip_release_fast = b.option(bool, "skip-release-fast", "Main test suite skips release-fast builds") orelse skip_release;
@ -63,29 +58,37 @@ pub fn build(b: *Builder) !void {
const only_install_lib_files = b.option(bool, "lib-files-only", "Only install library files") orelse false;
const enable_llvm = b.option(bool, "enable-llvm", "Build self-hosted compiler with LLVM backend enabled") orelse false;
if (enable_llvm) {
var ctx = parseConfigH(b, config_h_text);
ctx.llvm = try findLLVM(b, ctx.llvm_config_exe);
try configureStage2(b, exe, ctx);
}
if (!only_install_lib_files) {
exe.install();
}
const tracy = b.option([]const u8, "tracy", "Enable Tracy integration. Supply path to Tracy source");
const link_libc = b.option(bool, "force-link-libc", "Force self-hosted compiler to link libc") orelse false;
if (link_libc) exe.linkLibC();
var exe = b.addExecutable("zig", "src-self-hosted/main.zig");
exe.setBuildMode(mode);
test_step.dependOn(&exe.step);
b.default_step.dependOn(&exe.step);
exe.addBuildOption(bool, "enable_tracy", tracy != null);
if (tracy) |tracy_path| {
const client_cpp = fs.path.join(
b.allocator,
&[_][]const u8{ tracy_path, "TracyClient.cpp" },
) catch unreachable;
exe.addIncludeDir(tracy_path);
exe.addCSourceFile(client_cpp, &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" });
exe.linkSystemLibraryName("c++");
exe.linkLibC();
if (enable_llvm) {
var ctx = parseConfigH(b, config_h_text);
ctx.llvm = try findLLVM(b, ctx.llvm_config_exe);
try configureStage2(b, exe, ctx);
}
if (!only_install_lib_files) {
exe.install();
}
const tracy = b.option([]const u8, "tracy", "Enable Tracy integration. Supply path to Tracy source");
const link_libc = b.option(bool, "force-link-libc", "Force self-hosted compiler to link libc") orelse false;
if (link_libc) exe.linkLibC();
exe.addBuildOption(bool, "enable_tracy", tracy != null);
if (tracy) |tracy_path| {
const client_cpp = fs.path.join(
b.allocator,
&[_][]const u8{ tracy_path, "TracyClient.cpp" },
) catch unreachable;
exe.addIncludeDir(tracy_path);
exe.addCSourceFile(client_cpp, &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" });
exe.linkSystemLibraryName("c++");
exe.linkLibC();
}
}
b.installDirectory(InstallDirectoryOptions{

View File

@ -7530,7 +7530,7 @@ test "@hasDecl" {
source file than the one they are declared in.
</p>
<p>
{#syntax#}path{#endsyntax#} can be a relative or absolute path, or it can be the name of a package.
{#syntax#}path{#endsyntax#} can be a relative path or it can be the name of a package.
If it is a relative path, it is relative to the file that contains the {#syntax#}@import{#endsyntax#}
function call.
</p>
@ -8030,7 +8030,29 @@ test "vector @splat" {
</p>
{#see_also|Vectors|@shuffle#}
{#header_close#}
{#header_open|@src#}
<pre>{#syntax#}@src() std.builtin.SourceLocation{#endsyntax#}</pre>
<p>
Returns a {#syntax#}SourceLocation{#endsyntax#} struct representing the function's name and location in the source code. This must be called in a function.
</p>
{#code_begin|test#}
const std = @import("std");
const expect = std.testing.expect;
test "@src" {
doTheTest();
}
fn doTheTest() void {
const src = @src();
expect(src.line == 9);
expect(src.column == 17);
expect(std.mem.endsWith(u8, src.fn_name, "doTheTest"));
expect(std.mem.endsWith(u8, src.file, "test.zig"));
}
{#code_end#}
{#header_close#}
{#header_open|@sqrt#}
<pre>{#syntax#}@sqrt(value: var) @TypeOf(value){#endsyntax#}</pre>
<p>

View File

@ -552,6 +552,7 @@ fn preadNoEof(file: std.fs.File, buf: []u8, offset: u64) !void {
error.Unexpected => return error.Unexpected,
error.WouldBlock => return error.Unexpected,
error.NotOpenForReading => return error.Unexpected,
error.AccessDenied => return error.Unexpected,
};
if (len == 0) return error.UnexpectedEndOfFile;
i += len;

View File

@ -535,14 +535,15 @@ pub const Dir = struct {
w.EFAULT => unreachable,
w.ENOTDIR => unreachable,
w.EINVAL => unreachable,
w.ENOTCAPABLE => return error.AccessDenied,
else => |err| return os.unexpectedErrno(err),
}
if (bufused == 0) return null;
self.index = 0;
self.end_index = bufused;
}
const entry = @ptrCast(*align(1) os.wasi.dirent_t, &self.buf[self.index]);
const entry_size = @sizeOf(os.wasi.dirent_t);
const entry = @ptrCast(*align(1) w.dirent_t, &self.buf[self.index]);
const entry_size = @sizeOf(w.dirent_t);
const name_index = self.index + entry_size;
const name = mem.span(self.buf[name_index .. name_index + entry.d_namlen]);
@ -556,12 +557,12 @@ pub const Dir = struct {
}
const entry_kind = switch (entry.d_type) {
wasi.FILETYPE_BLOCK_DEVICE => Entry.Kind.BlockDevice,
wasi.FILETYPE_CHARACTER_DEVICE => Entry.Kind.CharacterDevice,
wasi.FILETYPE_DIRECTORY => Entry.Kind.Directory,
wasi.FILETYPE_SYMBOLIC_LINK => Entry.Kind.SymLink,
wasi.FILETYPE_REGULAR_FILE => Entry.Kind.File,
wasi.FILETYPE_SOCKET_STREAM, wasi.FILETYPE_SOCKET_DGRAM => Entry.Kind.UnixDomainSocket,
w.FILETYPE_BLOCK_DEVICE => Entry.Kind.BlockDevice,
w.FILETYPE_CHARACTER_DEVICE => Entry.Kind.CharacterDevice,
w.FILETYPE_DIRECTORY => Entry.Kind.Directory,
w.FILETYPE_SYMBOLIC_LINK => Entry.Kind.SymLink,
w.FILETYPE_REGULAR_FILE => Entry.Kind.File,
w.FILETYPE_SOCKET_STREAM, wasi.FILETYPE_SOCKET_DGRAM => Entry.Kind.UnixDomainSocket,
else => Entry.Kind.Unknown,
};
return Entry{
@ -1110,10 +1111,18 @@ pub const Dir = struct {
/// Delete a file name and possibly the file it refers to, based on an open directory handle.
/// Asserts that the path parameter has no null bytes.
pub fn deleteFile(self: Dir, sub_path: []const u8) DeleteFileError!void {
os.unlinkat(self.fd, sub_path, 0) catch |err| switch (err) {
error.DirNotEmpty => unreachable, // not passing AT_REMOVEDIR
else => |e| return e,
};
if (builtin.os.tag == .windows) {
const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);
return self.deleteFileW(sub_path_w.span().ptr);
} else if (builtin.os.tag == .wasi) {
os.unlinkatWasi(self.fd, sub_path, 0) catch |err| switch (err) {
error.DirNotEmpty => unreachable, // not passing AT_REMOVEDIR
else => |e| return e,
};
} else {
const sub_path_c = try os.toPosixPath(sub_path);
return self.deleteFileZ(&sub_path_c);
}
}
pub const deleteFileC = @compileError("deprecated: renamed to deleteFileZ");
@ -1122,6 +1131,17 @@ pub const Dir = struct {
pub fn deleteFileZ(self: Dir, sub_path_c: [*:0]const u8) DeleteFileError!void {
os.unlinkatZ(self.fd, sub_path_c, 0) catch |err| switch (err) {
error.DirNotEmpty => unreachable, // not passing AT_REMOVEDIR
error.AccessDenied => |e| switch (builtin.os.tag) {
// non-Linux POSIX systems return EPERM when trying to delete a directory, so
// we need to handle that case specifically and translate the error
.macosx, .ios, .freebsd, .netbsd, .dragonfly => {
// Don't follow symlinks to match unlinkat (which acts on symlinks rather than follows them)
const fstat = os.fstatatZ(self.fd, sub_path_c, os.AT_SYMLINK_NOFOLLOW) catch return e;
const is_dir = fstat.mode & os.S_IFMT == os.S_IFDIR;
return if (is_dir) error.IsDir else e;
},
else => return e,
},
else => |e| return e,
};
}

View File

@ -73,6 +73,43 @@ test "directory operations on files" {
file.close();
}
test "file operations on directories" {
var tmp_dir = tmpDir(.{});
defer tmp_dir.cleanup();
const test_dir_name = "test_dir";
try tmp_dir.dir.makeDir(test_dir_name);
testing.expectError(error.IsDir, tmp_dir.dir.createFile(test_dir_name, .{}));
testing.expectError(error.IsDir, tmp_dir.dir.deleteFile(test_dir_name));
// Currently, WASI will return error.Unexpected (via ENOTCAPABLE) when attempting fd_read on a directory handle.
// TODO: Re-enable on WASI once https://github.com/bytecodealliance/wasmtime/issues/1935 is resolved.
if (builtin.os.tag != .wasi) {
testing.expectError(error.IsDir, tmp_dir.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize)));
}
// Note: The `.write = true` is necessary to ensure the error occurs on all platforms.
// TODO: Add a read-only test as well, see https://github.com/ziglang/zig/issues/5732
testing.expectError(error.IsDir, tmp_dir.dir.openFile(test_dir_name, .{ .write = true }));
if (builtin.os.tag != .wasi) {
// TODO: use Dir's realpath function once that exists
const absolute_path = blk: {
const relative_path = try fs.path.join(testing.allocator, &[_][]const u8{ "zig-cache", "tmp", tmp_dir.sub_path[0..], test_dir_name });
defer testing.allocator.free(relative_path);
break :blk try fs.realpathAlloc(testing.allocator, relative_path);
};
defer testing.allocator.free(absolute_path);
testing.expectError(error.IsDir, fs.createFileAbsolute(absolute_path, .{}));
testing.expectError(error.IsDir, fs.deleteFileAbsolute(absolute_path));
}
// ensure the directory still exists as a sanity check
var dir = try tmp_dir.dir.openDir(test_dir_name, .{});
dir.close();
}
test "openSelfExe" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;

View File

@ -714,6 +714,11 @@ test "PageAllocator" {
slice[127] = 0x34;
allocator.free(slice);
}
{
var buf = try allocator.alloc(u8, mem.page_size + 1);
defer allocator.free(buf);
buf = try allocator.realloc(buf, 1); // shrink past the page boundary
}
}
test "HeapAllocator" {

View File

@ -49,9 +49,8 @@ pub const ArenaAllocator = struct {
const actual_min_size = minimum_size + (@sizeOf(BufNode) + 16);
const big_enough_len = prev_len + actual_min_size;
const len = big_enough_len + big_enough_len / 2;
const buf = try self.child_allocator.alignedAlloc(u8, @alignOf(BufNode), len);
const buf_node_slice = mem.bytesAsSlice(BufNode, buf[0..@sizeOf(BufNode)]);
const buf_node = &buf_node_slice[0];
const buf = try self.child_allocator.callAllocFn(len, @alignOf(BufNode), 1);
const buf_node = @ptrCast(*BufNode, @alignCast(@alignOf(BufNode), buf.ptr));
buf_node.* = BufNode{
.data = buf,
.next = null,

View File

@ -116,9 +116,6 @@ pub const Allocator = struct {
if (isAligned(@ptrToInt(old_mem.ptr), new_alignment)) {
if (new_byte_count <= old_mem.len) {
const shrunk_len = self.shrinkBytes(old_mem, new_byte_count, len_align);
if (shrunk_len < old_mem.len) {
@memset(old_mem.ptr + shrunk_len, undefined, old_mem.len - shrunk_len);
}
return old_mem.ptr[0..shrunk_len];
}
if (self.callResizeFn(old_mem, new_byte_count, len_align)) |resized_len| {
@ -723,8 +720,8 @@ pub fn zeroInit(comptime T: type, init: var) T {
@field(value, field.name) = @field(init, field.name);
},
}
} else if (field.default_value != null) {
@field(value, field.name) = field.default_value;
} else if (field.default_value) |default_value| {
@field(value, field.name) = default_value;
}
}
@ -751,7 +748,7 @@ test "zeroInit" {
b: ?bool,
c: I,
e: [3]u8,
f: i64,
f: i64 = -1,
};
const s = zeroInit(S, .{
@ -765,7 +762,7 @@ test "zeroInit" {
.d = 0,
},
.e = [3]u8{ 0, 0, 0 },
.f = 0,
.f = -1,
});
}

View File

@ -301,6 +301,10 @@ pub const ReadError = error{
/// This error occurs when no global event loop is configured,
/// and reading from the file descriptor would block.
WouldBlock,
/// In WASI, this error occurs when the file descriptor does
/// not hold the required rights to read from it.
AccessDenied,
} || UnexpectedError;
/// Returns the number of bytes that were read, which can be less than
@ -336,6 +340,7 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
wasi.ENOMEM => return error.SystemResources,
wasi.ECONNRESET => return error.ConnectionResetByPeer,
wasi.ETIMEDOUT => return error.ConnectionTimedOut,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -403,6 +408,7 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
wasi.EISDIR => return error.IsDir,
wasi.ENOBUFS => return error.SystemResources,
wasi.ENOMEM => return error.SystemResources,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -467,6 +473,7 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
wasi.ENXIO => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.EOVERFLOW => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -501,8 +508,11 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
pub const TruncateError = error{
FileTooBig,
InputOutput,
CannotTruncate,
FileBusy,
/// In WASI, this error occurs when the file descriptor does
/// not hold the required rights to call `ftruncate` on it.
AccessDenied,
} || UnexpectedError;
pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
@ -523,7 +533,7 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
switch (rc) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable, // Handle not open for writing
.ACCESS_DENIED => return error.CannotTruncate,
.ACCESS_DENIED => return error.AccessDenied,
else => return windows.unexpectedStatus(rc),
}
}
@ -533,10 +543,11 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
wasi.EINTR => unreachable,
wasi.EFBIG => return error.FileTooBig,
wasi.EIO => return error.InputOutput,
wasi.EPERM => return error.CannotTruncate,
wasi.EPERM => return error.AccessDenied,
wasi.ETXTBSY => return error.FileBusy,
wasi.EBADF => unreachable, // Handle not open for writing
wasi.EINVAL => unreachable, // Handle not open for writing
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -555,7 +566,7 @@ pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
EINTR => continue,
EFBIG => return error.FileTooBig,
EIO => return error.InputOutput,
EPERM => return error.CannotTruncate,
EPERM => return error.AccessDenied,
ETXTBSY => return error.FileBusy,
EBADF => unreachable, // Handle not open for writing
EINVAL => unreachable, // Handle not open for writing
@ -605,6 +616,7 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
wasi.ENXIO => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.EOVERFLOW => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -642,6 +654,9 @@ pub const WriteError = error{
FileTooBig,
InputOutput,
NoSpaceLeft,
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to write to it.
AccessDenied,
BrokenPipe,
SystemResources,
@ -699,6 +714,7 @@ pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
wasi.ENOSPC => return error.NoSpaceLeft,
wasi.EPERM => return error.AccessDenied,
wasi.EPIPE => return error.BrokenPipe,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -776,6 +792,7 @@ pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
wasi.ENOSPC => return error.NoSpaceLeft,
wasi.EPERM => return error.AccessDenied,
wasi.EPIPE => return error.BrokenPipe,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -858,6 +875,7 @@ pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
wasi.ENXIO => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.EOVERFLOW => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -951,6 +969,7 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz
wasi.ENXIO => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.EOVERFLOW => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -986,6 +1005,8 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usiz
}
pub const OpenError = error{
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to open a new resource relative to it.
AccessDenied,
SymLinkLoop,
ProcessFdQuotaExceeded,
@ -1115,6 +1136,7 @@ pub fn openatWasi(dir_fd: fd_t, file_path: []const u8, oflags: oflags_t, fdflags
wasi.EPERM => return error.AccessDenied,
wasi.EEXIST => return error.PathAlreadyExists,
wasi.EBUSY => return error.DeviceBusy,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -1501,6 +1523,8 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
}
pub const SymLinkError = error{
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to create a new symbolic link relative to it.
AccessDenied,
DiskQuota,
PathAlreadyExists,
@ -1606,13 +1630,14 @@ pub fn symlinkatWasi(target_path: []const u8, newdirfd: fd_t, sym_link_path: []c
wasi.ENOMEM => return error.SystemResources,
wasi.ENOSPC => return error.NoSpaceLeft,
wasi.EROFS => return error.ReadOnlyFileSystem,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
/// Windows-only. The same as `symlinkat` except the paths are null-terminated, WTF-16 encoded.
/// See also `symlinkat`.
pub fn symlinkatW(target_path: [*:0]const u16, newdirfd: fd_t, sym_link_path: [*:0]const u16) SymlinkError!void {
pub fn symlinkatW(target_path: [*:0]const u16, newdirfd: fd_t, sym_link_path: [*:0]const u16) SymLinkError!void {
@compileError("TODO implement on Windows");
}
@ -1646,6 +1671,9 @@ pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:
pub const UnlinkError = error{
FileNotFound,
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to unlink a resource by path relative to it.
AccessDenied,
FileBusy,
FileSystem,
@ -1749,6 +1777,7 @@ pub fn unlinkatWasi(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatErro
wasi.ENOMEM => return error.SystemResources,
wasi.EROFS => return error.ReadOnlyFileSystem,
wasi.ENOTEMPTY => return error.DirNotEmpty,
wasi.ENOTCAPABLE => return error.AccessDenied,
wasi.EINVAL => unreachable, // invalid flags, or pathname has . as last component
wasi.EBADF => unreachable, // always a race condition
@ -1851,6 +1880,8 @@ pub fn unlinkatW(dirfd: fd_t, sub_path_w: [*:0]const u16, flags: u32) UnlinkatEr
}
const RenameError = error{
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to rename a resource by path relative to it.
AccessDenied,
FileBusy,
DiskQuota,
@ -1970,6 +2001,7 @@ pub fn renameatWasi(old_dir_fd: fd_t, old_path: []const u8, new_dir_fd: fd_t, ne
wasi.ENOTEMPTY => return error.PathAlreadyExists,
wasi.EROFS => return error.ReadOnlyFileSystem,
wasi.EXDEV => return error.RenameAcrossMountPoints,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -2068,23 +2100,6 @@ pub fn renameatW(
}
}
pub const MakeDirError = error{
AccessDenied,
DiskQuota,
PathAlreadyExists,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
SystemResources,
NoSpaceLeft,
NotDir,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
NoDevice,
} || UnexpectedError;
pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const sub_dir_path_w = try windows.sliceToPrefixedFileW(sub_dir_path);
@ -2116,6 +2131,7 @@ pub fn mkdiratWasi(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirErr
wasi.ENOSPC => return error.NoSpaceLeft,
wasi.ENOTDIR => return error.NotDir,
wasi.EROFS => return error.ReadOnlyFileSystem,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -2150,6 +2166,25 @@ pub fn mkdiratW(dir_fd: fd_t, sub_path_w: [*:0]const u16, mode: u32) MakeDirErro
windows.CloseHandle(sub_dir_handle);
}
pub const MakeDirError = error{
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to create a new directory relative to it.
AccessDenied,
DiskQuota,
PathAlreadyExists,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
SystemResources,
NoSpaceLeft,
NotDir,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
NoDevice,
} || UnexpectedError;
/// Create a directory.
/// `mode` is ignored on Windows.
pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {
@ -2313,6 +2348,8 @@ pub fn fchdir(dirfd: fd_t) FchdirError!void {
}
pub const ReadLinkError = error{
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to read value of a symbolic link relative to it.
AccessDenied,
FileSystem,
SymLinkLoop,
@ -2398,6 +2435,7 @@ pub fn readlinkatWasi(dirfd: fd_t, file_path: []const u8, out_buffer: []u8) Read
wasi.ENOENT => return error.FileNotFound,
wasi.ENOMEM => return error.SystemResources,
wasi.ENOTDIR => return error.NotDir,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -3075,6 +3113,9 @@ pub fn waitpid(pid: i32, flags: u32) u32 {
pub const FStatError = error{
SystemResources,
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to get its filestat information.
AccessDenied,
} || UnexpectedError;
@ -3088,6 +3129,7 @@ pub fn fstat(fd: fd_t) FStatError!Stat {
wasi.EBADF => unreachable, // Always a race condition.
wasi.ENOMEM => return error.SystemResources,
wasi.EACCES => return error.AccessDenied,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -3138,6 +3180,7 @@ pub fn fstatatWasi(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!S
wasi.ENAMETOOLONG => return error.NameTooLong,
wasi.ENOENT => return error.FileNotFound,
wasi.ENOTDIR => return error.FileNotFound,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -3643,7 +3686,13 @@ pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) void {
}
}
pub const SeekError = error{Unseekable} || UnexpectedError;
pub const SeekError = error{
Unseekable,
/// In WASI, this error may occur when the file descriptor does
/// not hold the required rights to seek on it.
AccessDenied,
} || UnexpectedError;
/// Repositions read/write file offset relative to the beginning.
pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
@ -3671,6 +3720,7 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
wasi.EOVERFLOW => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.ENXIO => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -3712,6 +3762,7 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
wasi.EOVERFLOW => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.ENXIO => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -3752,6 +3803,7 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
wasi.EOVERFLOW => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.ENXIO => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
@ -3792,6 +3844,7 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
wasi.EOVERFLOW => return error.Unseekable,
wasi.ESPIPE => return error.Unseekable,
wasi.ENXIO => return error.Unseekable,
wasi.ENOTCAPABLE => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}

View File

@ -860,6 +860,7 @@ pub const NativeTargetInfo = struct {
error.ConnectionTimedOut => return error.UnableToReadElfFile,
error.Unexpected => return error.Unexpected,
error.InputOutput => return error.FileSystem,
error.AccessDenied => return error.Unexpected,
};
if (len == 0) return error.UnexpectedEndOfFile;
i += len;

View File

@ -37,6 +37,68 @@ pub fn generateSymbol(
.Fn => {
const module_fn = typed_value.val.cast(Value.Payload.Function).?.func;
const fn_type = module_fn.owner_decl.typed_value.most_recent.typed_value.ty;
const param_types = try bin_file.allocator.alloc(Type, fn_type.fnParamLen());
defer bin_file.allocator.free(param_types);
fn_type.fnParamTypes(param_types);
// A parameter may be broken into multiple machine code parameters, so we don't
// know the size up front.
var mc_args = try std.ArrayList(Function.MCValue).initCapacity(bin_file.allocator, param_types.len);
defer mc_args.deinit();
var next_stack_offset: u64 = 0;
switch (fn_type.fnCallingConvention()) {
.Naked => assert(mc_args.items.len == 0),
.Unspecified, .C => {
// Prepare the function parameters
switch (bin_file.options.target.cpu.arch) {
.x86_64 => {
const integer_registers = [_]Reg(.x86_64){ .rdi, .rsi, .rdx, .rcx, .r8, .r9 };
var next_int_reg: usize = 0;
for (param_types) |param_type, src_i| {
switch (param_type.zigTypeTag()) {
.Bool, .Int => {
if (next_int_reg >= integer_registers.len) {
try mc_args.append(.{ .stack_offset = next_stack_offset });
next_stack_offset += param_type.abiSize(bin_file.options.target);
} else {
try mc_args.append(.{ .register = @enumToInt(integer_registers[next_int_reg]) });
next_int_reg += 1;
}
},
else => return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement function parameters of type {}",
.{@tagName(param_type.zigTypeTag())},
),
},
}
}
},
else => return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement function parameters for {}",
.{bin_file.options.target.cpu.arch},
),
},
}
},
else => return Result{
.fail = try ErrorMsg.create(
bin_file.allocator,
src,
"TODO implement {} calling convention",
.{fn_type.fnCallingConvention()},
),
},
}
var function = Function{
.target = &bin_file.options.target,
.bin_file = bin_file,
@ -44,16 +106,14 @@ pub fn generateSymbol(
.code = code,
.inst_table = std.AutoHashMap(*ir.Inst, Function.MCValue).init(bin_file.allocator),
.err_msg = null,
.args = mc_args.items,
};
defer function.inst_table.deinit();
for (module_fn.analysis.success.instructions) |inst| {
const new_inst = function.genFuncInst(inst) catch |err| switch (err) {
error.CodegenFail => return Result{ .fail = function.err_msg.? },
else => |e| return e,
};
try function.inst_table.putNoClobber(inst, new_inst);
}
function.gen() catch |err| switch (err) {
error.CodegenFail => return Result{ .fail = function.err_msg.? },
else => |e| return e,
};
if (function.err_msg) |em| {
return Result{ .fail = em };
@ -157,6 +217,7 @@ const Function = struct {
code: *std.ArrayList(u8),
inst_table: std.AutoHashMap(*ir.Inst, MCValue),
err_msg: ?*ErrorMsg,
args: []MCValue,
const MCValue = union(enum) {
none,
@ -170,44 +231,119 @@ const Function = struct {
register: usize,
/// The value is in memory at a hard-coded address.
memory: u64,
/// The value is one of the stack variables.
stack_offset: u64,
};
fn genFuncInst(self: *Function, inst: *ir.Inst) !MCValue {
switch (inst.tag) {
.add => return self.genAdd(inst.cast(ir.Inst.Add).?),
.arg => return self.genArg(inst.src),
.block => return self.genBlock(inst.cast(ir.Inst.Block).?),
.breakpoint => return self.genBreakpoint(inst.src),
.call => return self.genCall(inst.cast(ir.Inst.Call).?),
.unreach => return MCValue{ .unreach = {} },
.constant => unreachable, // excluded from function bodies
.assembly => return self.genAsm(inst.cast(ir.Inst.Assembly).?),
.ptrtoint => return self.genPtrToInt(inst.cast(ir.Inst.PtrToInt).?),
.bitcast => return self.genBitCast(inst.cast(ir.Inst.BitCast).?),
.ret => return self.genRet(inst.cast(ir.Inst.Ret).?),
.retvoid => return self.genRetVoid(inst.cast(ir.Inst.RetVoid).?),
.cmp => return self.genCmp(inst.cast(ir.Inst.Cmp).?),
.condbr => return self.genCondBr(inst.cast(ir.Inst.CondBr).?),
.isnull => return self.genIsNull(inst.cast(ir.Inst.IsNull).?),
.isnonnull => return self.genIsNonNull(inst.cast(ir.Inst.IsNonNull).?),
fn gen(self: *Function) !void {
switch (self.target.cpu.arch) {
.arm => return self.genArch(.arm),
.armeb => return self.genArch(.armeb),
.aarch64 => return self.genArch(.aarch64),
.aarch64_be => return self.genArch(.aarch64_be),
.aarch64_32 => return self.genArch(.aarch64_32),
.arc => return self.genArch(.arc),
.avr => return self.genArch(.avr),
.bpfel => return self.genArch(.bpfel),
.bpfeb => return self.genArch(.bpfeb),
.hexagon => return self.genArch(.hexagon),
.mips => return self.genArch(.mips),
.mipsel => return self.genArch(.mipsel),
.mips64 => return self.genArch(.mips64),
.mips64el => return self.genArch(.mips64el),
.msp430 => return self.genArch(.msp430),
.powerpc => return self.genArch(.powerpc),
.powerpc64 => return self.genArch(.powerpc64),
.powerpc64le => return self.genArch(.powerpc64le),
.r600 => return self.genArch(.r600),
.amdgcn => return self.genArch(.amdgcn),
.riscv32 => return self.genArch(.riscv32),
.riscv64 => return self.genArch(.riscv64),
.sparc => return self.genArch(.sparc),
.sparcv9 => return self.genArch(.sparcv9),
.sparcel => return self.genArch(.sparcel),
.s390x => return self.genArch(.s390x),
.tce => return self.genArch(.tce),
.tcele => return self.genArch(.tcele),
.thumb => return self.genArch(.thumb),
.thumbeb => return self.genArch(.thumbeb),
.i386 => return self.genArch(.i386),
.x86_64 => return self.genArch(.x86_64),
.xcore => return self.genArch(.xcore),
.nvptx => return self.genArch(.nvptx),
.nvptx64 => return self.genArch(.nvptx64),
.le32 => return self.genArch(.le32),
.le64 => return self.genArch(.le64),
.amdil => return self.genArch(.amdil),
.amdil64 => return self.genArch(.amdil64),
.hsail => return self.genArch(.hsail),
.hsail64 => return self.genArch(.hsail64),
.spir => return self.genArch(.spir),
.spir64 => return self.genArch(.spir64),
.kalimba => return self.genArch(.kalimba),
.shave => return self.genArch(.shave),
.lanai => return self.genArch(.lanai),
.wasm32 => return self.genArch(.wasm32),
.wasm64 => return self.genArch(.wasm64),
.renderscript32 => return self.genArch(.renderscript32),
.renderscript64 => return self.genArch(.renderscript64),
.ve => return self.genArch(.ve),
}
}
fn genAdd(self: *Function, inst: *ir.Inst.Add) !MCValue {
switch (self.target.cpu.arch) {
fn genArch(self: *Function, comptime arch: std.Target.Cpu.Arch) !void {
for (self.mod_fn.analysis.success.instructions) |inst| {
const new_inst = try self.genFuncInst(inst, arch);
try self.inst_table.putNoClobber(inst, new_inst);
}
}
fn genFuncInst(self: *Function, inst: *ir.Inst, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (inst.tag) {
.add => return self.genAdd(inst.cast(ir.Inst.Add).?, arch),
.arg => return self.genArg(inst.cast(ir.Inst.Arg).?),
.block => return self.genBlock(inst.cast(ir.Inst.Block).?, arch),
.breakpoint => return self.genBreakpoint(inst.src, arch),
.call => return self.genCall(inst.cast(ir.Inst.Call).?, arch),
.unreach => return MCValue{ .unreach = {} },
.constant => unreachable, // excluded from function bodies
.assembly => return self.genAsm(inst.cast(ir.Inst.Assembly).?, arch),
.ptrtoint => return self.genPtrToInt(inst.cast(ir.Inst.PtrToInt).?),
.bitcast => return self.genBitCast(inst.cast(ir.Inst.BitCast).?),
.ret => return self.genRet(inst.cast(ir.Inst.Ret).?, arch),
.retvoid => return self.genRetVoid(inst.cast(ir.Inst.RetVoid).?, arch),
.cmp => return self.genCmp(inst.cast(ir.Inst.Cmp).?, arch),
.condbr => return self.genCondBr(inst.cast(ir.Inst.CondBr).?, arch),
.isnull => return self.genIsNull(inst.cast(ir.Inst.IsNull).?, arch),
.isnonnull => return self.genIsNonNull(inst.cast(ir.Inst.IsNonNull).?, arch),
}
}
fn genAdd(self: *Function, inst: *ir.Inst.Add, comptime arch: std.Target.Cpu.Arch) !MCValue {
const lhs = try self.resolveInst(inst.args.lhs);
const rhs = try self.resolveInst(inst.args.rhs);
switch (arch) {
.i386, .x86_64 => {
// const lhs_reg = try self.instAsReg(lhs);
// const rhs_reg = try self.instAsReg(rhs);
// const result = try self.allocateReg();
// try self.code.append(??);
// lhs_reg.release();
// rhs_reg.release();
return self.fail(inst.base.src, "TODO implement register allocation", .{});
},
else => return self.fail(inst.base.src, "TODO implement add for {}", .{self.target.cpu.arch}),
}
}
fn genArg(self: *Function, src: usize) !MCValue {
switch (self.target.cpu.arch) {
else => return self.fail(src, "TODO implement function parameters for {}", .{self.target.cpu.arch}),
}
return .none;
fn genArg(self: *Function, inst: *ir.Inst.Arg) !MCValue {
return self.args[inst.args.index];
}
fn genBreakpoint(self: *Function, src: usize) !MCValue {
switch (self.target.cpu.arch) {
fn genBreakpoint(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
.i386, .x86_64 => {
try self.code.append(0xcc); // int3
},
@ -216,8 +352,8 @@ const Function = struct {
return .none;
}
fn genCall(self: *Function, inst: *ir.Inst.Call) !MCValue {
switch (self.target.cpu.arch) {
fn genCall(self: *Function, inst: *ir.Inst.Call, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
.x86_64, .i386 => {
if (inst.args.func.cast(ir.Inst.Constant)) |func_inst| {
if (inst.args.args.len != 0) {
@ -251,11 +387,11 @@ const Function = struct {
}
}
fn ret(self: *Function, src: usize, mcv: MCValue) !MCValue {
fn ret(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch, mcv: MCValue) !MCValue {
if (mcv != .none) {
return self.fail(src, "TODO implement return with non-void operand", .{});
}
switch (self.target.cpu.arch) {
switch (arch) {
.i386, .x86_64 => {
try self.code.append(0xc3); // ret
},
@ -264,43 +400,43 @@ const Function = struct {
return .unreach;
}
fn genRet(self: *Function, inst: *ir.Inst.Ret) !MCValue {
fn genRet(self: *Function, inst: *ir.Inst.Ret, comptime arch: std.Target.Cpu.Arch) !MCValue {
const operand = try self.resolveInst(inst.args.operand);
return self.ret(inst.base.src, operand);
return self.ret(inst.base.src, arch, operand);
}
fn genRetVoid(self: *Function, inst: *ir.Inst.RetVoid) !MCValue {
return self.ret(inst.base.src, .none);
fn genRetVoid(self: *Function, inst: *ir.Inst.RetVoid, comptime arch: std.Target.Cpu.Arch) !MCValue {
return self.ret(inst.base.src, arch, .none);
}
fn genCmp(self: *Function, inst: *ir.Inst.Cmp) !MCValue {
switch (self.target.cpu.arch) {
fn genCmp(self: *Function, inst: *ir.Inst.Cmp, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement cmp for {}", .{self.target.cpu.arch}),
}
}
fn genCondBr(self: *Function, inst: *ir.Inst.CondBr) !MCValue {
switch (self.target.cpu.arch) {
fn genCondBr(self: *Function, inst: *ir.Inst.CondBr, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement condbr for {}", .{self.target.cpu.arch}),
}
}
fn genIsNull(self: *Function, inst: *ir.Inst.IsNull) !MCValue {
switch (self.target.cpu.arch) {
fn genIsNull(self: *Function, inst: *ir.Inst.IsNull, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement isnull for {}", .{self.target.cpu.arch}),
}
}
fn genIsNonNull(self: *Function, inst: *ir.Inst.IsNonNull) !MCValue {
fn genIsNonNull(self: *Function, inst: *ir.Inst.IsNonNull, comptime arch: std.Target.Cpu.Arch) !MCValue {
// Here you can specialize this instruction if it makes sense to, otherwise the default
// will call genIsNull and invert the result.
switch (self.target.cpu.arch) {
switch (arch) {
else => return self.fail(inst.base.src, "TODO call genIsNull and invert the result ", .{}),
}
}
fn genRelativeFwdJump(self: *Function, src: usize, amount: u32) !void {
switch (self.target.cpu.arch) {
fn genRelativeFwdJump(self: *Function, src: usize, comptime arch: std.Target.Cpu.Arch, amount: u32) !void {
switch (arch) {
.i386, .x86_64 => {
// TODO x86 treats the operands as signed
if (amount <= std.math.maxInt(u8)) {
@ -318,70 +454,13 @@ const Function = struct {
}
}
fn genBlock(self: *Function, inst: *ir.Inst.Block) !MCValue {
switch (self.target.cpu.arch) {
fn genBlock(self: *Function, inst: *ir.Inst.Block, comptime arch: std.Target.Cpu.Arch) !MCValue {
switch (arch) {
else => return self.fail(inst.base.src, "TODO implement codegen Block for {}", .{self.target.cpu.arch}),
}
}
fn genAsm(self: *Function, inst: *ir.Inst.Assembly) !MCValue {
// TODO convert to inline function
switch (self.target.cpu.arch) {
.arm => return self.genAsmArch(.arm, inst),
.armeb => return self.genAsmArch(.armeb, inst),
.aarch64 => return self.genAsmArch(.aarch64, inst),
.aarch64_be => return self.genAsmArch(.aarch64_be, inst),
.aarch64_32 => return self.genAsmArch(.aarch64_32, inst),
.arc => return self.genAsmArch(.arc, inst),
.avr => return self.genAsmArch(.avr, inst),
.bpfel => return self.genAsmArch(.bpfel, inst),
.bpfeb => return self.genAsmArch(.bpfeb, inst),
.hexagon => return self.genAsmArch(.hexagon, inst),
.mips => return self.genAsmArch(.mips, inst),
.mipsel => return self.genAsmArch(.mipsel, inst),
.mips64 => return self.genAsmArch(.mips64, inst),
.mips64el => return self.genAsmArch(.mips64el, inst),
.msp430 => return self.genAsmArch(.msp430, inst),
.powerpc => return self.genAsmArch(.powerpc, inst),
.powerpc64 => return self.genAsmArch(.powerpc64, inst),
.powerpc64le => return self.genAsmArch(.powerpc64le, inst),
.r600 => return self.genAsmArch(.r600, inst),
.amdgcn => return self.genAsmArch(.amdgcn, inst),
.riscv32 => return self.genAsmArch(.riscv32, inst),
.riscv64 => return self.genAsmArch(.riscv64, inst),
.sparc => return self.genAsmArch(.sparc, inst),
.sparcv9 => return self.genAsmArch(.sparcv9, inst),
.sparcel => return self.genAsmArch(.sparcel, inst),
.s390x => return self.genAsmArch(.s390x, inst),
.tce => return self.genAsmArch(.tce, inst),
.tcele => return self.genAsmArch(.tcele, inst),
.thumb => return self.genAsmArch(.thumb, inst),
.thumbeb => return self.genAsmArch(.thumbeb, inst),
.i386 => return self.genAsmArch(.i386, inst),
.x86_64 => return self.genAsmArch(.x86_64, inst),
.xcore => return self.genAsmArch(.xcore, inst),
.nvptx => return self.genAsmArch(.nvptx, inst),
.nvptx64 => return self.genAsmArch(.nvptx64, inst),
.le32 => return self.genAsmArch(.le32, inst),
.le64 => return self.genAsmArch(.le64, inst),
.amdil => return self.genAsmArch(.amdil, inst),
.amdil64 => return self.genAsmArch(.amdil64, inst),
.hsail => return self.genAsmArch(.hsail, inst),
.hsail64 => return self.genAsmArch(.hsail64, inst),
.spir => return self.genAsmArch(.spir, inst),
.spir64 => return self.genAsmArch(.spir64, inst),
.kalimba => return self.genAsmArch(.kalimba, inst),
.shave => return self.genAsmArch(.shave, inst),
.lanai => return self.genAsmArch(.lanai, inst),
.wasm32 => return self.genAsmArch(.wasm32, inst),
.wasm64 => return self.genAsmArch(.wasm64, inst),
.renderscript32 => return self.genAsmArch(.renderscript32, inst),
.renderscript64 => return self.genAsmArch(.renderscript64, inst),
.ve => return self.genAsmArch(.ve, inst),
}
}
fn genAsmArch(self: *Function, comptime arch: Target.Cpu.Arch, inst: *ir.Inst.Assembly) !MCValue {
fn genAsm(self: *Function, inst: *ir.Inst.Assembly, comptime arch: Target.Cpu.Arch) !MCValue {
if (arch != .x86_64 and arch != .i386) {
return self.fail(inst.base.src, "TODO implement inline asm support for more architectures", .{});
}
@ -607,6 +686,9 @@ const Function = struct {
}
}
},
.stack_offset => |off| {
return self.fail(src, "TODO implement genSetReg for stack variables", .{});
},
},
else => return self.fail(src, "TODO implement genSetReg for more architectures", .{}),
}

View File

@ -1,20 +1,21 @@
const Type = @import("../Type.zig");
// zig fmt: off
/// Definitions of all of the x64 registers. The order is very, very important.
/// Definitions of all of the x64 registers. The order is semantically meaningful.
/// The registers are defined such that IDs go in descending order of 64-bit,
/// 32-bit, 16-bit, and then 8-bit, and each set contains exactly sixteen
/// registers. This results in some very, very useful properties:
/// registers. This results in some useful properties:
///
/// Any 64-bit register can be turned into its 32-bit form by adding 16, and
/// vice versa. This also works between 32-bit and 16-bit forms. With 8-bit, it
/// works for all except for sp, bp, si, and di, which don't *have* an 8-bit
/// works for all except for sp, bp, si, and di, which do *not* have an 8-bit
/// form.
///
/// If (register & 8) is set, the register is extended.
///
/// The ID can be easily determined by figuring out what range the register is
/// in, and then subtracting the base.
///
pub const Register = enum(u8) {
// 0 through 15, 64-bit registers. 8-15 are extended.
// id is just the int value.
@ -66,4 +67,4 @@ pub const Register = enum(u8) {
}
};
// zig fmt: on
// zig fmt: on

View File

@ -535,6 +535,76 @@ pub const Type = extern union {
};
}
/// Asserts the type has the ABI size already resolved.
pub fn abiSize(self: Type, target: Target) u64 {
return switch (self.tag()) {
.fn_noreturn_no_args => unreachable, // represents machine code; not a pointer
.fn_void_no_args => unreachable, // represents machine code; not a pointer
.fn_naked_noreturn_no_args => unreachable, // represents machine code; not a pointer
.fn_ccc_void_no_args => unreachable, // represents machine code; not a pointer
.function => unreachable, // represents machine code; not a pointer
.c_void => unreachable,
.void => unreachable,
.type => unreachable,
.comptime_int => unreachable,
.comptime_float => unreachable,
.noreturn => unreachable,
.@"null" => unreachable,
.@"undefined" => unreachable,
.u8,
.i8,
.bool,
=> return 1,
.array_u8_sentinel_0 => @fieldParentPtr(Payload.Array_u8_Sentinel0, "base", self.ptr_otherwise).len,
.array => {
const payload = @fieldParentPtr(Payload.Array, "base", self.ptr_otherwise);
const elem_size = std.math.max(payload.elem_type.abiAlignment(target), payload.elem_type.abiSize(target));
return payload.len * elem_size;
},
.i16, .u16 => return 2,
.i32, .u32 => return 4,
.i64, .u64 => return 8,
.isize,
.usize,
.single_const_pointer_to_comptime_int,
.const_slice_u8,
.single_const_pointer,
=> return @divExact(target.cpu.arch.ptrBitWidth(), 8),
.c_short => return @divExact(CType.short.sizeInBits(target), 8),
.c_ushort => return @divExact(CType.ushort.sizeInBits(target), 8),
.c_int => return @divExact(CType.int.sizeInBits(target), 8),
.c_uint => return @divExact(CType.uint.sizeInBits(target), 8),
.c_long => return @divExact(CType.long.sizeInBits(target), 8),
.c_ulong => return @divExact(CType.ulong.sizeInBits(target), 8),
.c_longlong => return @divExact(CType.longlong.sizeInBits(target), 8),
.c_ulonglong => return @divExact(CType.ulonglong.sizeInBits(target), 8),
.f16 => return 2,
.f32 => return 4,
.f64 => return 8,
.f128 => return 16,
.c_longdouble => return 16,
.anyerror => return 2, // TODO revisit this when we have the concept of the error tag type
.int_signed, .int_unsigned => {
const bits: u16 = if (self.cast(Payload.IntSigned)) |pl|
pl.bits
else if (self.cast(Payload.IntUnsigned)) |pl|
pl.bits
else
unreachable;
return std.math.ceilPowerOfTwoPromote(u16, (bits + 7) / 8);
},
};
}
pub fn isSinglePointer(self: Type) bool {
return switch (self.tag()) {
.u8,