Skip to content

remove realpath() from the standard library #19353

Open

Description

@andrewrk

This function is not portable, relies on a legacy permissions model, cannot handle arbitrarily nested file system paths, and is therefore typically a bug to call. Yet, many programmers reach for this function out of naivety. To prevent it from cropping up in various codebases, and causing an overall degradation of software quality, omit it from the Zig Standard Library.

diff --git a/lib/std/fs/Dir.zig b/lib/std/fs/Dir.zig
index 11fbc13c41..65922d3a0a 100644
--- a/lib/std/fs/Dir.zig
+++ b/lib/std/fs/Dir.zig
@@ -1201,126 +1201,21 @@ pub fn makeOpenPath(self: Dir, sub_path: []const u8, open_dir_options: OpenDirOp
     };
 }
 
-pub const RealPathError = posix.RealPathError;
-
-///  This function returns the canonicalized absolute pathname of
-/// `pathname` relative to this `Dir`. If `pathname` is absolute, ignores this
-/// `Dir` handle and returns the canonicalized absolute pathname of `pathname`
-/// argument.
-/// On Windows, `sub_path` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// On other platforms, `sub_path` is an opaque sequence of bytes with no particular encoding.
-/// On Windows, the result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// On other platforms, the result is an opaque sequence of bytes with no particular encoding.
-/// This function is not universally supported by all platforms.
-/// Currently supported hosts are: Linux, macOS, and Windows.
-/// See also `Dir.realpathZ`, `Dir.realpathW`, and `Dir.realpathAlloc`.
-pub fn realpath(self: Dir, pathname: []const u8, out_buffer: []u8) RealPathError![]u8 {
-    if (builtin.os.tag == .wasi) {
-        @compileError("realpath is not available on WASI");
-    }
-    if (builtin.os.tag == .windows) {
-        const pathname_w = try std.os.windows.sliceToPrefixedFileW(self.fd, pathname);
-        return self.realpathW(pathname_w.span(), out_buffer);
-    }
-    const pathname_c = try posix.toPosixPath(pathname);
-    return self.realpathZ(&pathname_c, out_buffer);
-}
-
-/// Same as `Dir.realpath` except `pathname` is null-terminated.
-/// See also `Dir.realpath`, `realpathZ`.
-pub fn realpathZ(self: Dir, pathname: [*:0]const u8, out_buffer: []u8) RealPathError![]u8 {
-    if (builtin.os.tag == .windows) {
-        const pathname_w = try posix.windows.cStrToPrefixedFileW(self.fd, pathname);
-        return self.realpathW(pathname_w.span(), out_buffer);
-    }
-
-    const flags: posix.O = switch (builtin.os.tag) {
-        .linux => .{
-            .NONBLOCK = true,
-            .CLOEXEC = true,
-            .PATH = true,
-        },
-        else => .{
-            .NONBLOCK = true,
-            .CLOEXEC = true,
-        },
-    };
-
-    const fd = posix.openatZ(self.fd, pathname, flags, 0) catch |err| switch (err) {
-        error.FileLocksNotSupported => return error.Unexpected,
-        error.FileBusy => return error.Unexpected,
-        error.WouldBlock => return error.Unexpected,
-        error.InvalidUtf8 => unreachable, // WASI-only
-        else => |e| return e,
-    };
-    defer posix.close(fd);
-
-    // Use of MAX_PATH_BYTES here is valid as the realpath function does not
-    // have a variant that takes an arbitrary-size buffer.
-    // TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008
-    // NULL out parameter (GNU's canonicalize_file_name) to handle overelong
-    // paths. musl supports passing NULL but restricts the output to PATH_MAX
-    // anyway.
-    var buffer: [fs.MAX_PATH_BYTES]u8 = undefined;
-    const out_path = try posix.getFdPath(fd, &buffer);
-
-    if (out_path.len > out_buffer.len) {
-        return error.NameTooLong;
-    }
-
-    const result = out_buffer[0..out_path.len];
-    @memcpy(result, out_path);
-    return result;
-}
-
-/// Windows-only. Same as `Dir.realpath` except `pathname` is WTF16 LE encoded.
-/// The result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// See also `Dir.realpath`, `realpathW`.
-pub fn realpathW(self: Dir, pathname: []const u16, out_buffer: []u8) RealPathError![]u8 {
-    const w = std.os.windows;
-
-    const access_mask = w.GENERIC_READ | w.SYNCHRONIZE;
-    const share_access = w.FILE_SHARE_READ;
-    const creation = w.FILE_OPEN;
-    const h_file = blk: {
-        const res = w.OpenFile(pathname, .{
-            .dir = self.fd,
-            .access_mask = access_mask,
-            .share_access = share_access,
-            .creation = creation,
-            .filter = .any,
-        }) catch |err| switch (err) {
-            error.WouldBlock => unreachable,
-            else => |e| return e,
-        };
-        break :blk res;
-    };
-    defer w.CloseHandle(h_file);
-
-    var wide_buf: [w.PATH_MAX_WIDE]u16 = undefined;
-    const wide_slice = try w.GetFinalPathNameByHandle(h_file, .{}, &wide_buf);
-    var big_out_buf: [fs.MAX_PATH_BYTES]u8 = undefined;
-    const end_index = std.unicode.wtf16LeToWtf8(&big_out_buf, wide_slice);
-    if (end_index > out_buffer.len)
-        return error.NameTooLong;
-    const result = out_buffer[0..end_index];
-    @memcpy(result, big_out_buf[0..end_index]);
-    return result;
-}
-
-pub const RealPathAllocError = RealPathError || Allocator.Error;
-
-/// Same as `Dir.realpath` except caller must free the returned memory.
-/// See also `Dir.realpath`.
-pub fn realpathAlloc(self: Dir, allocator: Allocator, pathname: []const u8) RealPathAllocError![]u8 {
-    // Use of MAX_PATH_BYTES here is valid as the realpath function does not
-    // have a variant that takes an arbitrary-size buffer.
-    // TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008
-    // NULL out parameter (GNU's canonicalize_file_name) to handle overelong
-    // paths. musl supports passing NULL but restricts the output to PATH_MAX
-    // anyway.
-    var buf: [fs.MAX_PATH_BYTES]u8 = undefined;
-    return allocator.dupe(u8, try self.realpath(pathname, buf[0..]));
+/// Returns the canonicalized absolute path of `pathname` relative to this `Dir`.
+///
+/// If `pathname` is absolute, ignores this `Dir` handle and returns the
+/// canonicalized absolute pathname of `pathname` argument.
+///
+/// This function is not portable, relies on a legacy permissions model, cannot
+/// handle arbitrarily nested file system paths, and is therefore typically a
+/// bug to call. Yet, many programmers reach for this function out of naivety.
+/// To prevent it from cropping up in various codebases, and causing an overall
+/// degradation of software quality, it is omitted from the Zig Standard
+/// Library.
+pub fn realpath(dir: Dir, pathname: []const u8) []const u8 {
+    _ = dir;
+    _ = pathname;
+    @compileError("zig strongly recommends not using realpath");
 }
 
 /// Changes the current working directory to the open directory handle.
diff --git a/lib/std/os.zig b/lib/std/os.zig
index 2138f5cd20..bc9a4fdfea 100644
--- a/lib/std/os.zig
+++ b/lib/std/os.zig
@@ -5483,310 +5483,6 @@ pub fn flock(fd: fd_t, operation: i32) FlockError!void {
     }
 }
 
-pub const RealPathError = error{
-    FileNotFound,
-    AccessDenied,
-    NameTooLong,
-    NotSupported,
-    NotDir,
-    SymLinkLoop,
-    InputOutput,
-    FileTooBig,
-    IsDir,
-    ProcessFdQuotaExceeded,
-    SystemFdQuotaExceeded,
-    NoDevice,
-    SystemResources,
-    NoSpaceLeft,
-    FileSystem,
-    BadPathName,
-    DeviceBusy,
-
-    SharingViolation,
-    PipeBusy,
-
-    /// Windows-only; file paths provided by the user must be valid WTF-8.
-    /// https://simonsapin.github.io/wtf-8/
-    InvalidWtf8,
-
-    /// On Windows, `\\server` or `\\server\share` was not found.
-    NetworkNotFound,
-
-    PathAlreadyExists,
-
-    /// On Windows, antivirus software is enabled by default. It can be
-    /// disabled, but Windows Update sometimes ignores the user's preference
-    /// and re-enables it. When enabled, antivirus software on Windows
-    /// intercepts file system operations and makes them significantly slower
-    /// in addition to possibly failing with this error code.
-    AntivirusInterference,
-
-    /// On Windows, the volume does not contain a recognized file system. File
-    /// system drivers might not be loaded, or the volume may be corrupt.
-    UnrecognizedVolume,
-} || UnexpectedError;
-
-/// Return the canonicalized absolute pathname.
-/// Expands all symbolic links and resolves references to `.`, `..`, and
-/// extra `/` characters in `pathname`.
-/// On Windows, `pathname` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// On other platforms, `pathname` is an opaque sequence of bytes with no particular encoding.
-/// The return value is a slice of `out_buffer`, but not necessarily from the beginning.
-/// See also `realpathZ` and `realpathW`.
-/// On Windows, the result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// On other platforms, the result is an opaque sequence of bytes with no particular encoding.
-/// Calling this function is usually a bug.
-pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
-    if (builtin.os.tag == .windows) {
-        const pathname_w = try windows.sliceToPrefixedFileW(null, pathname);
-        return realpathW(pathname_w.span(), out_buffer);
-    } else if (builtin.os.tag == .wasi and !builtin.link_libc) {
-        @compileError("WASI does not support os.realpath");
-    }
-    const pathname_c = try toPosixPath(pathname);
-    return realpathZ(&pathname_c, out_buffer);
-}
-
-/// Same as `realpath` except `pathname` is null-terminated.
-/// Calling this function is usually a bug.
-pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
-    if (builtin.os.tag == .windows) {
-        const pathname_w = try windows.cStrToPrefixedFileW(null, pathname);
-        return realpathW(pathname_w.span(), out_buffer);
-    } else if (builtin.os.tag == .wasi and !builtin.link_libc) {
-        return realpath(mem.sliceTo(pathname, 0), out_buffer);
-    }
-    if (!builtin.link_libc) {
-        const flags: O = switch (builtin.os.tag) {
-            .linux => .{
-                .NONBLOCK = true,
-                .CLOEXEC = true,
-                .PATH = true,
-            },
-            else => .{
-                .NONBLOCK = true,
-                .CLOEXEC = true,
-            },
-        };
-        const fd = openZ(pathname, flags, 0) catch |err| switch (err) {
-            error.FileLocksNotSupported => unreachable,
-            error.WouldBlock => unreachable,
-            error.FileBusy => unreachable, // not asking for write permissions
-            error.InvalidUtf8 => unreachable, // WASI-only
-            else => |e| return e,
-        };
-        defer close(fd);
-
-        return getFdPath(fd, out_buffer);
-    }
-    const result_path = std.c.realpath(pathname, out_buffer) orelse switch (@as(E, @enumFromInt(std.c._errno().*))) {
-        .SUCCESS => unreachable,
-        .INVAL => unreachable,
-        .BADF => unreachable,
-        .FAULT => unreachable,
-        .ACCES => return error.AccessDenied,
-        .NOENT => return error.FileNotFound,
-        .OPNOTSUPP => return error.NotSupported,
-        .NOTDIR => return error.NotDir,
-        .NAMETOOLONG => return error.NameTooLong,
-        .LOOP => return error.SymLinkLoop,
-        .IO => return error.InputOutput,
-        else => |err| return unexpectedErrno(err),
-    };
-    return mem.sliceTo(result_path, 0);
-}
-
-/// Same as `realpath` except `pathname` is WTF16LE-encoded.
-/// The result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// Calling this function is usually a bug.
-pub fn realpathW(pathname: []const u16, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
-    const w = windows;
-
-    const dir = std.fs.cwd().fd;
-    const access_mask = w.GENERIC_READ | w.SYNCHRONIZE;
-    const share_access = w.FILE_SHARE_READ;
-    const creation = w.FILE_OPEN;
-    const h_file = blk: {
-        const res = w.OpenFile(pathname, .{
-            .dir = dir,
-            .access_mask = access_mask,
-            .share_access = share_access,
-            .creation = creation,
-            .filter = .any,
-        }) catch |err| switch (err) {
-            error.WouldBlock => unreachable,
-            else => |e| return e,
-        };
-        break :blk res;
-    };
-    defer w.CloseHandle(h_file);
-
-    return getFdPath(h_file, out_buffer);
-}
-
-pub fn isGetFdPathSupportedOnTarget(os: std.Target.Os) bool {
-    return switch (os.tag) {
-        .windows,
-        .macos,
-        .ios,
-        .watchos,
-        .tvos,
-        .linux,
-        .solaris,
-        .illumos,
-        .freebsd,
-        => true,
-
-        .dragonfly => os.version_range.semver.max.order(.{ .major = 6, .minor = 0, .patch = 0 }) != .lt,
-        .netbsd => os.version_range.semver.max.order(.{ .major = 10, .minor = 0, .patch = 0 }) != .lt,
-        else => false,
-    };
-}
-
-/// Return canonical path of handle `fd`.
-/// This function is very host-specific and is not universally supported by all hosts.
-/// For example, while it generally works on Linux, macOS, FreeBSD or Windows, it is
-/// unsupported on WASI.
-/// On Windows, the result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
-/// On other platforms, the result is an opaque sequence of bytes with no particular encoding.
-/// Calling this function is usually a bug.
-pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
-    if (!comptime isGetFdPathSupportedOnTarget(builtin.os)) {
-        @compileError("querying for canonical path of a handle is unsupported on this host");
-    }
-    switch (builtin.os.tag) {
-        .windows => {
-            var wide_buf: [windows.PATH_MAX_WIDE]u16 = undefined;
-            const wide_slice = try windows.GetFinalPathNameByHandle(fd, .{}, wide_buf[0..]);
-
-            const end_index = std.unicode.wtf16LeToWtf8(out_buffer, wide_slice);
-            return out_buffer[0..end_index];
-        },
-        .macos, .ios, .watchos, .tvos => {
-            // On macOS, we can use F.GETPATH fcntl command to query the OS for
-            // the path to the file descriptor.
-            @memset(out_buffer[0..MAX_PATH_BYTES], 0);
-            switch (errno(system.fcntl(fd, F.GETPATH, out_buffer))) {
-                .SUCCESS => {},
-                .BADF => return error.FileNotFound,
-                .NOSPC => return error.NameTooLong,
-                // TODO man pages for fcntl on macOS don't really tell you what
-                // errno values to expect when command is F.GETPATH...
-                else => |err| return unexpectedErrno(err),
-            }
-            const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse MAX_PATH_BYTES;
-            return out_buffer[0..len];
-        },
-        .linux => {
-            var procfs_buf: ["/proc/self/fd/-2147483648\x00".len]u8 = undefined;
-            const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/fd/{d}", .{fd}) catch unreachable;
-
-            const target = readlinkZ(proc_path, out_buffer) catch |err| {
-                switch (err) {
-                    error.NotLink => unreachable,
-                    error.BadPathName => unreachable,
-                    error.InvalidUtf8 => unreachable, // WASI-only
-                    error.InvalidWtf8 => unreachable, // Windows-only
-                    error.UnsupportedReparsePointType => unreachable, // Windows-only
-                    error.NetworkNotFound => unreachable, // Windows-only
-                    else => |e| return e,
-                }
-            };
-            return target;
-        },
-        .solaris, .illumos => {
-            var procfs_buf: ["/proc/self/path/-2147483648\x00".len]u8 = undefined;
-            const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/path/{d}", .{fd}) catch unreachable;
-
-            const target = readlinkZ(proc_path, out_buffer) catch |err| switch (err) {
-                error.UnsupportedReparsePointType => unreachable,
-                error.NotLink => unreachable,
-                else => |e| return e,
-            };
-            return target;
-        },
-        .freebsd => {
-            if (comptime builtin.os.isAtLeast(.freebsd, .{ .major = 13, .minor = 0, .patch = 0 }) orelse false) {
-                var kfile: system.kinfo_file = undefined;
-                kfile.structsize = system.KINFO_FILE_SIZE;
-                switch (errno(system.fcntl(fd, system.F.KINFO, @intFromPtr(&kfile)))) {
-                    .SUCCESS => {},
-                    .BADF => return error.FileNotFound,
-                    else => |err| return unexpectedErrno(err),
-                }
-                const len = mem.indexOfScalar(u8, &kfile.path, 0) orelse MAX_PATH_BYTES;
-                if (len == 0) return error.NameTooLong;
-                const result = out_buffer[0..len];
-                @memcpy(result, kfile.path[0..len]);
-                return result;
-            } else {
-                // This fallback implementation reimplements libutil's `kinfo_getfile()`.
-                // The motivation is to avoid linking -lutil when building zig or general
-                // user executables.
-                var mib = [4]c_int{ CTL.KERN, KERN.PROC, KERN.PROC_FILEDESC, system.getpid() };
-                var len: usize = undefined;
-                sysctl(&mib, null, &len, null, 0) catch |err| switch (err) {
-                    error.PermissionDenied => unreachable,
-                    error.SystemResources => return error.SystemResources,
-                    error.NameTooLong => unreachable,
-                    error.UnknownName => unreachable,
-                    else => return error.Unexpected,
-                };
-                len = len * 4 / 3;
-                const buf = std.heap.c_allocator.alloc(u8, len) catch return error.SystemResources;
-                defer std.heap.c_allocator.free(buf);
-                len = buf.len;
-                sysctl(&mib, &buf[0], &len, null, 0) catch |err| switch (err) {
-                    error.PermissionDenied => unreachable,
-                    error.SystemResources => return error.SystemResources,
-                    error.NameTooLong => unreachable,
-                    error.UnknownName => unreachable,
-                    else => return error.Unexpected,
-                };
-                var i: usize = 0;
-                while (i < len) {
-                    const kf: *align(1) system.kinfo_file = @ptrCast(&buf[i]);
-                    if (kf.fd == fd) {
-                        len = mem.indexOfScalar(u8, &kf.path, 0) orelse MAX_PATH_BYTES;
-                        if (len == 0) return error.NameTooLong;
-                        const result = out_buffer[0..len];
-                        @memcpy(result, kf.path[0..len]);
-                        return result;
-                    }
-                    i += @intCast(kf.structsize);
-                }
-                return error.FileNotFound;
-            }
-        },
-        .dragonfly => {
-            @memset(out_buffer[0..MAX_PATH_BYTES], 0);
-            switch (errno(system.fcntl(fd, F.GETPATH, out_buffer))) {
-                .SUCCESS => {},
-                .BADF => return error.FileNotFound,
-                .RANGE => return error.NameTooLong,
-                else => |err| return unexpectedErrno(err),
-            }
-            const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse MAX_PATH_BYTES;
-            return out_buffer[0..len];
-        },
-        .netbsd => {
-            @memset(out_buffer[0..MAX_PATH_BYTES], 0);
-            switch (errno(system.fcntl(fd, F.GETPATH, out_buffer))) {
-                .SUCCESS => {},
-                .ACCES => return error.AccessDenied,
-                .BADF => return error.FileNotFound,
-                .NOENT => return error.FileNotFound,
-                .NOMEM => return error.SystemResources,
-                .RANGE => return error.NameTooLong,
-                else => |err| return unexpectedErrno(err),
-            }
-            const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse MAX_PATH_BYTES;
-            return out_buffer[0..len];
-        },
-        else => unreachable, // made unreachable by isGetFdPathSupportedOnTarget above
-    }
-}
-
 /// Spurious wakeups are possible and no precision of timing is guaranteed.
 pub fn nanosleep(seconds: u64, nanoseconds: u64) void {
     var req = timespec{

Currently used by the zig compiler in several places:

../src/link/Elf.zig:                if (fs.realpath(scr_obj.path, &buffer)) |path| {
../src/link/Dwarf.zig:    const realpath = if (std.fs.path.isAbsolute(root_dir_path)) r: {
../src/link/Dwarf.zig:    } else std.fs.realpath(root_dir_path, buffer) catch return root_dir_path;
../src/link/Dwarf.zig:    const len = realpath.len + 1 + sub_path.len;
../src/link/Dwarf.zig:    buffer[realpath.len] = '/';
../src/link/Dwarf.zig:    @memcpy(buffer[realpath.len + 1 ..][0..sub_path.len], sub_path);
../src/link/Dwarf.zig:        // TODO re-investigate if realpath is needed here
../src/link/Dwarf.zig:            std.os.realpath(dir_path, &buffer) catch dir_path
../src/link/MachO.zig:                        const full_path = std.fs.realpath(rel_path, &buffer) catch continue;
../src/link/MachO.zig:                if (std.fs.realpath(id.name, &buffer)) |full_path| {
../src/link/Wasm/Archive.zig:        const path = try std.os.realpath(archive.name, &buffer);
../src/codegen/llvm.zig:                    break :blk std.fs.realpathAlloc(arena, d) catch break :blk d;
../src/codegen/llvm.zig:                const abs_path = std.fs.realpath(dir_path, &abs_buffer) catch
../src/Sema.zig:        // The compiler must not call realpath anywhere.

All of these instances have to do with debug info, except for the last line which I kept for the humor value. They are indeed all bugs. The problem is that the debug info in an executable needs to refer to the file paths of source locations, and if it uses relative paths, then a debugger looking at a moved executable will not be able to find the source files.

However, it is still incorrect to attempt a transformation of a relative path to an absolute path. Instead, the compiler needs to take note of the file paths passed in by the user. These strings must be retained whether absolute or relative, and used, rather than trying to resolve the path based on the file descriptor.

This pushes the problem back into the build system which constructs the CLI for the compiler. But that's precisely how to solve this problem - push it as far back as possible, until there is exactly one realpath() transformation done at the very beginning of the software, ideally by the user themselves.

I expect this to be a controversal proposal.

Activity

  1. added
    breaking
    standard library
    proposal
    on Mar 19, 2024
  2. added this to the 0.13.0 milestone on Mar 19, 2024
  3. matklad commented on Mar 19, 2024

    @matklad
    Contributor

    +1

    Using this function is almost always a bug, but it is not a common knowledge (someone needs to write "realpath considered harmful" blog post). At the same time, this function lies on the path of the least resistance for a lot of problems, and routinely sneaks into all kinds of places where it is completely inappropriate.

    I like that the function is preserved in the source code as compileError with an explnanatory comment. I think the comment could be better though: I'd remove the bit about "naivety", as knowing that realpath is not good is expert knowledge: in my career, I've seen this clearly articulated only twice: once in an off-hand remark by alexcrichton, and the second time in the Zig community. And I would include a bit of positive guidance here, which can be lifted straight out of the PR description. So, something along the lines of

    This function is not portable, relies on a legacy permissions model, cannot
    handle arbitrarily nested file system paths, and is therefore typically a
    bug to call.

    The correct behavior is usually to take note of the file paths passed in by the user. These strings
    must be retained whether absolute or relative, and used, rather than trying to resolve the path
    based on the file descriptor.

    To improve software quality, Zig Standard Library omits this function and provides this educational
    note instead.

    If we remove this function, I'd love to see #5190 fixed, as it is one of the cases where realpath is needed as a work-around for an unrelated bug.

  4. RossComputerGuy commented on Mar 19, 2024

    @RossComputerGuy
    Contributor

    Using this function is almost always a bug, but it is not a common knowledge (someone needs to write "realpath considered harmful" blog post).

    I could certainly write a blog post but I'd need some sources lol. On another note, I don't really understand what makes realpath not portable and a problem. Is it mainly a Windows issue?

  5. nektro commented on Mar 19, 2024

    @nektro
    Contributor

    on the portability, my guess is openbsd because windows can do it and #6718 exists; so it wouldn't surprise me if there was also difficulty in inspecting arbitrary fd's

  6. squeek502 commented on Mar 19, 2024

    @squeek502
    Member

    I have no real opinion on removing the API from std.fs, but want to note that the std.os implementation (std.os.getFdPath in particular) is used for testing absolute paths in std/fs/test.zig, see #16847 for context.

    There's also std.fs.selfExePath which relies on some realpath-like functionality for certain platforms (MacOS/OpenBSD/Haiku call std.os.realpathZ, Windows calls std.fs.Dir.realpathW).

  7. GalaxySnail commented on Mar 20, 2024

    @GalaxySnail

    How to prevent path traversal attack without realpath?

  8. silversquirl commented on Mar 20, 2024

    @silversquirl
    Contributor

    @GalaxySnail std.fs.path.resolve and check for ../ at the beginning of the result

  9. ikskuh commented on Mar 22, 2024

    @ikskuh
    Contributor

    What would be an alternative to realpath when talking to foreign code like C libraries or other executables without changing cwd?

    Assuming i only have a std.fs.Dir and a relative path available, and i want to call into a foreign function that only takes char const * path, what is the Zig way to do that then?
    The only way i know of right now would be using ´setAsCwd()` and then pass the relative path, but there might be some secret knowledge here.

    I guess if we deprecate that function, we should provide the users with a set of better alternatives instead of just claiming why it's a bug and that we do not support it.

  10. nektro commented on Mar 22, 2024

    @nektro
    Contributor

    I interpreted the messaging as that the use cases that still need it should use a 3rd party module

  11. castholm commented on Mar 23, 2024

    @castholm
    Contributor

    Assuming i only have a std.fs.Dir and a relative path available, and i want to call into a foreign function that only takes char const * path, what is the Zig way to do that then?

    My understanding of how a "proper" program is supposed to handle this situation (please correct me if I'm mistaken) is that because you have a std.fs.Dir handle, you presumably know where it came from. Either it's the cwd, or you opened it from a path (either relative to the cwd, or absolute). If it's the latter, the idea is that you keep the original path string in memory for as long as you need to do these kinds of operations.

    If the path you want to pass to the C library function is absolute, just pass that path verbatim.

    If the path you want to pass is relative, if your dir handle is the cwd you pass that path verbatim, otherwise, you pass the result of try std.fs.path.join(allocator, &.{ original_dir_path, rel_path }) where original_dir_path is the path string the directory was opened from. If you don't need to be cautious of symlinks you could also use fs.path.resolve.

    This should work for well-behaving external libraries. If the external library is poorly designed and only accepts absolute paths or paths relative to some hard-coded but unknown directory, you have to implement the required path transformation logic yourself in a way that makes the most sense for the OSes you're targeting.

  12. ikskuh commented on Mar 23, 2024

    @ikskuh
    Contributor

    My understanding of how a "proper" program is supposed to handle this situation (please correct me if I'm mistaken) is that because you have a std.fs.Dir handle, you presumably know where it came from.

    That's exactly the point. If i'm writing a library, i don't. I just receive a dirhandle+path, but no information if it's cwd-relative, root or anything, so the only two options are the ones i stated, at least to my knowledge. I cannot work on a "string" level of paths, because i don't know the root

  13. 12 remaining items

  14. charlesrocket commented on Sep 19, 2025

    @charlesrocket
    Contributor

    @squeek502 docs for 0.14.0 already state that this is a bug, but I just cannot find any other function in std that would produce similar results. Fixing the deprecation with cwd() feels like a workaround because it's technically not a refactoring change. I am not arguing that this should remain in std, just want to figure out where I should get absolute paths from now on when I need them.

  15. jcollie commented on Sep 19, 2025

    @jcollie

    realpath is absolutely necessary in certain instances. For example, say that you need to communicate the location of a file between two processes on the same system (say a client and a daemon). You can't guarantee that they both have the same CWD so passing a relative path is not possible. Other methods like passing an open file handle between processes are tricky to use and may not be available if you don't control the implementation on both sides.

  16. squeek502 commented on Sep 19, 2025

    @squeek502
    Member

    @charlesrocket "Calling this function is usually a bug" does not mean the function is deprecated.

    If you're using realpath/realpathAlloc/etc in a case where you don't need to, like in the case where you do realpath(relative_path) just to be able to call std.fs.*Absolute, then removing the realpath usage is a strict improvement, as it reduces the number of syscalls with no change in functionality:

    realpath -> openFileAbsolute
    const std = @import("std");
    
    pub fn main() !void {
        var debug_allocator = std.heap.DebugAllocator(.{}){};
        defer std.debug.assert(debug_allocator.deinit() == .ok);
        const allocator = debug_allocator.allocator();
    
        const some_path = "foo";
        const abs_path = try std.fs.realpathAlloc(allocator, some_path);
        defer allocator.free(abs_path);
    
        const file = try std.fs.openFileAbsolute(abs_path, .{});
        defer file.close();
    }

    On Linux, running with strace gives:

    open("foo", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_PATH) = 3
    readlink("/proc/self/fd/3", "/home/ryan/Programming/zig/tmp/f"..., 4096) = 34
    close(3)                                = 0
    openat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/foo", O_RDONLY|O_NOCTTY|O_CLOEXEC) = 3
    close(3)
    
    openFile
    const std = @import("std");
    
    pub fn main() !void {
        const some_path = "foo";
    
        const file = try std.fs.cwd().openFile(some_path, .{});
        defer file.close();
    }

    On Linux, running with strace gives:

    openat(AT_FDCWD, "foo", O_RDONLY|O_NOCTTY|O_CLOEXEC) = 3
    close(3)                                = 0
    
  17. charlesrocket commented on Sep 19, 2025

    @charlesrocket
    Contributor

    @squeek502 maybe I am too rush on that label, but from what i've read its pretty much deprecated and will be gone (why keep a buggy function, that's just "silly", right?).

    My usage of realpath() is more of a secure OCD call—I feel pretty shitty about forcing a user to expose absolute paths in the config (which might be a public asset), so I want to support relative paths as well. To do it right, I just treat all paths as absolute since cwd() in this case is unreliable (it is definitely silly to assume users's cwd within any CLI application). But without realpath or an alternative, I cannot see how I could make this work.

  18. squeek502 commented on Sep 19, 2025

    @squeek502
    Member

    This proposal will be marked as accepted if it will be gone. As of now, it may be gone in the future. The function is not buggy, the note in the docs is just to make people really think about whether or not they should be using it (with a strong emphasis on not using it).

    I feel we're veering off-topic, would probably be better to take this discussion to one of the community spaces (i.e. either continuing in this thread or creating a new one).

  19. ikskuh commented on Sep 20, 2025

    @ikskuh
    Contributor

    This function is not portable, relies on a legacy permissions model, cannot handle arbitrarily nested file system paths, and is therefore typically a bug to call. Yet, many programmers reach for this function out of naivety.

    Now that i've understood the true nature of realpath and it's friends, i despise it. It does not do what people want to do, and it does so in weird ways. It's also incredibly slow.

    Some datapoints:

    • We have a large, Python-written buildsystem at work. It used realpath everywhere in the assumption it was doing this: realpath("../foo/bar/../baz") == "../foo/baz". I was at this fault as well. When i measured the perf of the buildsystem itself, realpath took around 30% of the total execution time and i was stunned. After reading the docs i realized that realpath actually walks the filesystem tree in order to figure out which parts of the path are symlinks and which are not, then follows these symlinks. The performance improvement were close to half an order of magnitue when i replaced os.path.realpath with os.path.normpath.
    • You cannot use realpath on a filesystem provided by WinFsp due to Windows design constraints. This means that any application (including Zig apps) will fail to access any files that are realpathd on these file systems.
    • Due to the symlink following nature of realpath, the following can be legit:
      realpath("C:\\Foo\\Bar\\Bam") == "D:\\Wherever\\I\\May\\Go\\Bar\\Bam"
      which is most likely not what the programmer had in mind.

    So, in short:

    realpath must die.

    So what we really need in Zig is a normpath or abspath, but not a realpath.

    The problem here is, as stated above, that this must somehow work with directory handles, but i think for this, an equivalent for realpathat(dir.handle, ".") is fine, even though i'm not sure what this should return as even that might be ambigious (Enter NTFS directory junctions)

  20. squeek502 commented on Sep 20, 2025

    @squeek502
    Member

    @ikskuh For normpath, I think the closest analog in Zig is std.fs.path.resolve.

    For abspath, you could call std.process.getCwd() and then use that as the first path in std.fs.path.resolve (this used to be implicit)


    Note, though, that currently Zig doesn't always have that filesystem walking behavior you mentioned (unless you use posix.realpath and link libc since the libc implementations do it [or at least GNU libc and musl on Linux do]).

    Test setup:

    mkdir original_dir
    ln -s original_dir dir_link
    cd dir_link
    touch final
    ln -s intermediate initial
    ln -s /home/ryan/Programming/zig/tmp/realpath/dir_link/final intermediate
    

    So that creates this structure:

    /home/Programming/zig/tmp/realpath
    lrwxrwxrwx  dir_link -> original_dir
    drwxrwxr-x  original_dir
    
    /home/Programming/zig/tmp/realpath/dir_link
    lrwxrwxrwx  initial -> intermediate
    lrwxrwxrwx  intermediate -> /home/ryan/Programming/zig/tmp/realpath/dir_link/final
    -rw-rw-r--  final
    

    The intermediate -> final symlink uses an absolute path to re-trigger the filesystem walking behavior, and it goes through dir_link to ensure that a symlink in the middle of a path is resolved.

    On Linux when not linking libc, the Zig implementation of realpath always uses exactly three syscalls (open with O_PATH, readlink, close):

    const std = @import("std");
    
    pub fn main() !void {
        var buf: [std.fs.max_path_bytes]u8 = undefined;
        const path = try std.posix.realpath("dir_link/initial", &buf);
        std.debug.print("{s}\n", .{path});
    }

    output for me (same resulting path as the realpath command, the libc version, and the python version):

    /home/ryan/Programming/zig/tmp/realpath/original_dir/final
    

    strace:

    open("dir_link/initial", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_PATH) = 3
    readlink("/proc/self/fd/3", "/home/ryan/Programming/zig/tmp/r"..., 4096) = 58
    close(3)                                = 0
    

    (so essentially, Zig lets the kernel to figure it out, and is able to assume it can use O_PATH which requires kernel version >= 2.6.39)

    On Windows it'll use Zig's reimplementation of GetFinalPathNameByHandle which I believe (at worst) would involve a NtCreateFile + NtQueryObject + NtCreateFile + NtDeviceIoControlFile + maybe another NtDeviceIoControlFile if it's on a volume that has no associated drive letter

    Zig linking GNU libc on Linux strace

    Same code as above, but compiled with -lc (gnu/musl libc have the roughly same behavior)

    getcwd("/home/ryan/Programming/zig/tmp/realpath", 1024) = 40
    readlink("/home/ryan/Programming/zig/tmp/realpath/dir_link", "original_dir", 1023) = 12
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir/initial", "intermediate", 1023) = 12
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir/intermediate", "/home/ryan/Programming/zig/tmp/r"..., 1023) = 54
    readlink("/home", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming/zig", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming/zig/tmp", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming/zig/tmp/realpath", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming/zig/tmp/realpath/dir_link", "original_dir", 1023) = 12
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir/final", 0x7fffffff8bc0, 1023) = -1 EINVAL (Invalid argument)
    
    Python strace
    import os;
    
    print(os.path.realpath("/home/ryan/.local/bin/zig"))
    newfstatat(AT_FDCWD, "dir_link", {st_mode=S_IFLNK|0777, st_size=12, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("dir_link", "original_dir", 4096) = 12
    newfstatat(AT_FDCWD, "original_dir", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "original_dir/initial", {st_mode=S_IFLNK|0777, st_size=12, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("original_dir/initial", "intermediate", 4096) = 12
    newfstatat(AT_FDCWD, "original_dir/intermediate", {st_mode=S_IFLNK|0777, st_size=54, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("original_dir/intermediate", "/home/ryan/Programming/zig/tmp/r"..., 4096) = 54
    newfstatat(AT_FDCWD, "/home", {st_mode=S_IFDIR|0755, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan", {st_mode=S_IFDIR|0755, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp", {st_mode=S_IFDIR|0775, st_size=20480, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/dir_link", {st_mode=S_IFLNK|0777, st_size=12, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("/home/ryan/Programming/zig/tmp/realpath/dir_link", "original_dir", 4096) = 12
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir/final", {st_mode=S_IFREG|0664, st_size=0, ...}, AT_SYMLINK_NOFOLLOW) = 0
    
    realpath command strace
    realpath dir_link/initial
    
    getcwd("/home/ryan/Programming/zig/tmp/realpath", 4096) = 40
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/dir_link", {st_mode=S_IFLNK|0777, st_size=12, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("/home/ryan/Programming/zig/tmp/realpath/dir_link", "original_dir", 13) = 12
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir/initial", {st_mode=S_IFLNK|0777, st_size=12, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir/initial", "intermediate", 13) = 12
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir/intermediate", {st_mode=S_IFLNK|0777, st_size=54, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("/home/ryan/Programming/zig/tmp/realpath/original_dir/intermediate", "/home/ryan/Programming/zig/tmp/r"..., 55) = 54
    newfstatat(AT_FDCWD, "/home", {st_mode=S_IFDIR|0755, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan", {st_mode=S_IFDIR|0755, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp", {st_mode=S_IFDIR|0775, st_size=20480, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/dir_link", {st_mode=S_IFLNK|0777, st_size=12, ...}, AT_SYMLINK_NOFOLLOW) = 0
    readlink("/home/ryan/Programming/zig/tmp/realpath/dir_link", "original_dir", 13) = 12
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir", {st_mode=S_IFDIR|0775, st_size=4096, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(AT_FDCWD, "/home/ryan/Programming/zig/tmp/realpath/original_dir/final", {st_mode=S_IFREG|0664, st_size=0, ...}, AT_SYMLINK_NOFOLLOW) = 0
    newfstatat(1, "", {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0x3), ...}, AT_EMPTY_PATH) = 0
    
    Performance comparison

    Zig implementation vs GNU libc implementation vs realpath command

    Benchmark 1 (10000 runs): ./test
      measurement          mean ± σ            min … max           outliers         delta
      wall_time           458us ± 32.2us     368us …  631us       1334 (13%)        0%
      peak_rss            918KB ±    0       918KB …  918KB          0 ( 0%)        0%
      cpu_cycles         50.0K  ± 2.78K     44.7K  … 99.5K        1485 (15%)        0%
      instructions       8.96K  ± 0.11      8.96K  … 8.97K         125 ( 1%)        0%
      cache_references   3.93K  ±  192      3.22K  … 4.67K        1085 (11%)        0%
      cache_misses       1.69K  ± 77.4      1.30K  … 2.17K        1518 (15%)        0%
      branch_misses       220   ± 9.41       172   …  233         2000 (20%)        0%
    Benchmark 2 (5389 runs): ./test-lc
      measurement          mean ± σ            min … max           outliers         delta
      wall_time           889us ± 53.1us     747us … 1.27ms       1009 (19%)        💩+ 94.3% ±  0.3%
      peak_rss           2.75MB ± 1.79KB    2.62MB … 2.75MB          1 ( 0%)        💩+200.0% ±  0.0%
      cpu_cycles          229K  ± 23.0K      203K  …  565K         514 (10%)        💩+358.2% ±  0.9%
      instructions        196K  ± 0.28       196K  …  196K         409 ( 8%)        💩+2082.2% ±  0.0%
      cache_references   20.6K  ±  499      17.8K  … 23.9K         492 ( 9%)        💩+423.0% ±  0.3%
      cache_misses       7.50K  ±  267      6.15K  … 9.32K         346 ( 6%)        💩+343.7% ±  0.3%
      branch_misses      2.33K  ±  121      1.82K  … 3.26K         209 ( 4%)        💩+962.5% ±  1.1%
    Benchmark 3 (5710 runs): realpath dir_link/initial
      measurement          mean ± σ            min … max           outliers         delta
      wall_time           838us ± 51.3us     741us … 1.21ms        217 ( 4%)        💩+ 83.2% ±  0.3%
      peak_rss           2.10MB ± 1.73KB    1.97MB … 2.10MB          1 ( 0%)        💩+128.6% ±  0.0%
      cpu_cycles          223K  ± 31.6K      202K  …  547K         412 ( 7%)        💩+346.6% ±  1.2%
      instructions        238K  ± 2.56       238K  …  238K         646 (11%)        💩+2556.6% ±  0.0%
      cache_references   20.5K  ±  651      17.9K  … 24.5K          95 ( 2%)        💩+422.7% ±  0.3%
      cache_misses       7.25K  ±  307      6.26K  … 9.28K         213 ( 4%)        💩+328.9% ±  0.4%
      branch_misses      2.43K  ±  195      2.09K  … 3.20K           7 ( 0%)        💩+1008.0% ±  1.7%
    
  21. ikskuh commented on Sep 21, 2025

    @ikskuh
    Contributor

    Note, though, that currently Zig doesn't always have that filesystem walking behavior you mentioned

    I wasn't talking about an explicitly coded behaviour but about the underlying properties of the operation.

    The kernel will also have to do the walk, but it's probably way faster than doing it through syscalls.

    And yeah, the GetFinalPathNameByHandle bit me hard on Windows+ WinFsp which is why i'm working on removing all traces of realpath at work to be able to use our tooling on a special-purpose virtual file system

  22. loftafi commented on Sep 22, 2025

    @loftafi

    Perhaps the documentation for realpath needs to be improved. It is certainly true that usage of realpath in some situations is not the best technical solution. But when you need to interact with operating system components that expect the full path and filename, then you do end up needing realpath (unless there is another way to get_physical_file_path_as_understood_by_os() that I don't know about.

  23. ikskuh commented on Sep 22, 2025

    @ikskuh
    Contributor

    But when you need to interact with operating system components that expect the full path and filename, then you do end up needing realpath

    That might work as long as the actual path doesn't matter, as realpath is the wrong tool for this job.

    Imagine this simple scenario:

    1. You want to build a project with make
    2. Your user invokes your tool in /home/dude/projects/awesome-game and passes ./Makefile to your application.
    3. You invoke realpath, strip the last component and invoke make -C $realpathResultDir
    4. The build fails as /usr/share/makefile-templates contains no file called Makefile

    What happened? The user is a smart person who uses a OS vendored collection of makefiles for different tasks, and just symlinks them into their project to keep them updated with the OS updates.

    This means that /home/dude/projects/awesome-game/Makefile is a symlink to /usr/share/makefile-templates/Game.SDL3.Makefile.

    This means that the call to realpath yields /usr/share/makefile-templates/Game.SDL3.Makefile instead of the expected /home/dude/projects/awesome-game/Makefile.

    This means as soon as you use realpath your program will have weird consequences when obtaining full paths.

  24. SrekelDGG commented on Sep 22, 2025

    @SrekelDGG

    Just to be clear, is realpath the only way to get a "full" path, so on windows something like C:\lol\hello.txt ?

    If so I've used the Python counterpart a lot of times in various Python scripts to get clarity (e.g. something like "where the £$€%! is this file it's trying to find but isn't able to"). This is on inhouse projects where we know the setup.

    So it A) isn't in a public library that people on the internets would use for their own purposes and B) it's for where we had control over the environment (no symlinks) and C) there weren't any performance issues.

    In these cases it was quite helpful.

    Please give users autonomy over their choices and please believe they are competent developers who are working under custom circumstances.

  25. KilianHanich commented on Sep 23, 2025

    @KilianHanich
    const std = @import("std");
    
    pub fn main() !void {
        var buf: [std.fs.max_path_bytes]u8 = undefined;
        const path = try std.posix.realpath("dir_link/initial", &buf);
        std.debug.print("{s}\n", .{path});
    }

    On a different note, expecting something like std.fs.max_path_bytes/MAX_PATH or something along those lines to be useful is wrong on all operating systems these days.

    On Linux for example they even explicitly state that they just took a random value to not break the compilation of existing programs.

    Operating systems don't have an actual path limit (anymore), be it a UNIX or Windows.

    Zig defines std.fs.max_path_bytes as 4096 for some reason, but try to run this bash script which creates a directory named tmp, steps into it and does this in a loop 4096 times (beware, could take a while):

    i=0
    while [[ i -lt 4096 ]]; do mkdir tmp; cd tmp; i=$((i+1)); done
    pwd

    You are WAY past 4096 bytes path size at that point.

  26. GalaxySnail commented on Sep 23, 2025

    @GalaxySnail

    On a different note, expecting something like std.fs.max_path_bytes/MAX_PATH or something along those lines to be useful is wrong on all operating systems these days.

    On Linux for example they even explicitly state that they just took a random value to not break the compilation of existing programs.

    Actually, the limit is still there. You can't pass a path longer than PATH_MAX to a syscall on Linux, otherwise you'll get an ENAMETOOLONG. However, you can bypass this limit with something like openat(2), which allows you to pass a shorter path relative to a dirfd. Anyway, the buffer that contains the path can't be larger than PATH_MAX.

  27. KilianHanich commented on Sep 24, 2025

    @KilianHanich

    On a different note, expecting something like std.fs.max_path_bytes/MAX_PATH or something along those lines to be useful is wrong on all operating systems these days.
    On Linux for example they even explicitly state that they just took a random value to not break the compilation of existing programs.

    Actually, the limit is still there. You can't pass a path longer than PATH_MAX to a syscall on Linux, otherwise you'll get an ENAMETOOLONG. However, you can bypass this limit with something like openat(2), which allows you to pass a shorter path relative to a dirfd. Anyway, the buffer that contains the path can't be larger than PATH_MAX.

    Apparently.

    And glibc does a good job at hiding that often from you.

    On a different note, this also goes for the getcwd syscall. So if your cwd path is longer than that, it fails too.

    This means that you have to search your own path with the help of openat and the like.

    At the very least any libc which can error with ENAMETOOLONG is not POSIX compliant, so your libc does this search for you on POSIX systems (theoretically, muslc for example doesn't). This info could be of interest to the people who want to use Zig to build a libc.

  28. removed
    proposal
    on Apr 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    breakingstandard library

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions