Repository navigation
Description
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
matklad commentedon Mar 19, 2024
+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
If we remove this function, I'd love to see #5190 fixed, as it is one of the cases where
realpathis needed as a work-around for an unrelated bug.RossComputerGuy commentedon Mar 19, 2024
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?
nektro commentedon Mar 19, 2024
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
squeek502 commentedon Mar 19, 2024
I have no real opinion on removing the API from
std.fs, but want to note that thestd.osimplementation (std.os.getFdPathin particular) is used for testing absolute paths instd/fs/test.zig, see #16847 for context.There's also
std.fs.selfExePathwhich relies on some realpath-like functionality for certain platforms (MacOS/OpenBSD/Haiku callstd.os.realpathZ, Windows callsstd.fs.Dir.realpathW).GalaxySnail commentedon Mar 20, 2024
How to prevent path traversal attack without
realpath?silversquirl commentedon Mar 20, 2024
@GalaxySnail
std.fs.path.resolveand check for../at the beginning of the resultikskuh commentedon Mar 22, 2024
What would be an alternative to
realpathwhen talking to foreign code like C libraries or other executables without changingcwd?Assuming i only have a
std.fs.Dirand a relative path available, and i want to call into a foreign function that only takeschar 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.
nektro commentedon Mar 22, 2024
I interpreted the messaging as that the use cases that still need it should use a 3rd party module
castholm commentedon Mar 23, 2024
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.Dirhandle, 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 })whereoriginal_dir_pathis the path string the directory was opened from. If you don't need to be cautious of symlinks you could also usefs.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.
ikskuh commentedon Mar 23, 2024
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
Apply patch and build for WASM-WASI
12 remaining items
charlesrocket commentedon Sep 19, 2025
@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.jcollie commentedon Sep 19, 2025
realpathis 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.squeek502 commentedon Sep 19, 2025
@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 dorealpath(relative_path)just to be able to callstd.fs.*Absolute, then removing therealpathusage is a strict improvement, as it reduces the number of syscalls with no change in functionality:realpath -> openFileAbsolute
On Linux, running with strace gives:
openFile
On Linux, running with strace gives:
charlesrocket commentedon Sep 19, 2025
@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 sincecwd()in this case is unreliable (it is definitely silly to assume users'scwdwithin any CLI application). But withoutrealpathor an alternative, I cannot see how I could make this work.squeek502 commentedon Sep 19, 2025
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).
ikskuh commentedon Sep 20, 2025
Now that i've understood the true nature of
realpathand 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:
realpatheverywhere 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,realpathtook around 30% of the total execution time and i was stunned. After reading the docs i realized thatrealpathactually 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 replacedos.path.realpathwithos.path.normpath.realpathon 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 arerealpathd on these file systems.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:
realpathmust die.So what we really need in Zig is a
normpathorabspath, but not arealpath.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)squeek502 commentedon Sep 20, 2025
@ikskuh For
normpath, I think the closest analog in Zig isstd.fs.path.resolve.For
abspath, you could callstd.process.getCwd()and then use that as the first path instd.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.realpathand link libc since the libc implementations do it [or at least GNU libc and musl on Linux do]).Test setup:
So that creates this structure:
The intermediate -> final symlink uses an absolute path to re-trigger the filesystem walking behavior, and it goes through
dir_linkto ensure that a symlink in the middle of a path is resolved.On Linux when not linking libc, the Zig implementation of
realpathalways uses exactly three syscalls (open withO_PATH, readlink, close):output for me (same resulting path as the
realpathcommand, the libc version, and the python version):strace:
(so essentially, Zig lets the kernel to figure it out, and is able to assume it can use
O_PATHwhich requires kernel version >= 2.6.39)On Windows it'll use Zig's reimplementation of
GetFinalPathNameByHandlewhich I believe (at worst) would involve aNtCreateFile+NtQueryObject+NtCreateFile+NtDeviceIoControlFile+ maybe anotherNtDeviceIoControlFileif it's on a volume that has no associated drive letterZig linking GNU libc on Linux strace
Same code as above, but compiled with
-lc(gnu/musl libc have the roughly same behavior)Python strace
realpath command strace
Performance comparison
Zig implementation vs GNU libc implementation vs
realpathcommandikskuh commentedon Sep 21, 2025
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
GetFinalPathNameByHandlebit me hard on Windows+ WinFsp which is why i'm working on removing all traces ofrealpathat work to be able to use our tooling on a special-purpose virtual file systemloftafi commentedon Sep 22, 2025
Perhaps the documentation for
realpathneeds to be improved. It is certainly true that usage ofrealpathin 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 needingrealpath(unless there is another way toget_physical_file_path_as_understood_by_os()that I don't know about.ikskuh commentedon Sep 22, 2025
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:
make/home/dude/projects/awesome-gameand passes./Makefileto your application.realpath, strip the last component and invokemake -C $realpathResultDir/usr/share/makefile-templatescontains no file calledMakefileWhat 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/Makefileis a symlink to/usr/share/makefile-templates/Game.SDL3.Makefile.This means that the call to realpath yields
/usr/share/makefile-templates/Game.SDL3.Makefileinstead of the expected/home/dude/projects/awesome-game/Makefile.This means as soon as you use
realpathyour program will have weird consequences when obtaining full paths.SrekelDGG commentedon Sep 22, 2025
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.
KilianHanich commentedon Sep 23, 2025
On a different note, expecting something like
std.fs.max_path_bytes/MAX_PATHor 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_bytesas 4096 for some reason, but try to run this bash script which creates a directory namedtmp, steps into it and does this in a loop 4096 times (beware, could take a while):You are WAY past 4096 bytes path size at that point.
GalaxySnail commentedon Sep 23, 2025
Actually, the limit is still there. You can't pass a path longer than
PATH_MAXto a syscall on Linux, otherwise you'll get anENAMETOOLONG. However, you can bypass this limit with something likeopenat(2), which allows you to pass a shorter path relative to a dirfd. Anyway, the buffer that contains the path can't be larger thanPATH_MAX.KilianHanich commentedon Sep 24, 2025
Apparently.
And glibc does a good job at hiding that often from you.
On a different note, this also goes for the
getcwdsyscall. 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
openatand the like.At the very least any libc which can error with
ENAMETOOLONGis 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.