Skip to content

Commit

Permalink
runtime: Don't hardcode PATH_MAX on POSIX
Browse files Browse the repository at this point in the history
There's still one usage of magic number 4096 in fn current_directory,
but only as an initial guess at the path length.
  • Loading branch information
Nopey committed Oct 13, 2023
1 parent 50eed97 commit 77d0520
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 21 deletions.
6 changes: 6 additions & 0 deletions runtime/jaktlib/platform/posix_errno.jakt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,9 @@ fn errno_value() -> i32 {
return *__errno_location()
}
}

fn erange_value() -> i32 {
mut erange: i32 = 0
unsafe { cpp { "erange = ERANGE;" } }
return erange
}
49 changes: 28 additions & 21 deletions runtime/jaktlib/platform/posix_fs.jakt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import jakt::path { Path }
import jakt::platform { platform_module, platform_errno }
import platform_errno() { errno_value }
import platform_errno() { errno_value, erange_value }
import utility { allocate, null }

import extern c "sys/stat.h" {
Expand Down Expand Up @@ -37,36 +37,43 @@ fn make_directory(path: String) throws {
}

fn current_directory() throws -> String {
let buffer_size : usize = 4096; // Roughly PATH_MAX
mut buffer = allocate<c_char>(count: buffer_size + 1)
defer {
unsafe { cpp { "free(buffer);" } }
}
// Initial guess at path length, resembles PATH_MAX and the page-size of some systems
mut buffer_size : usize = 4096;
loop {
mut buffer = allocate<c_char>(count: buffer_size)
defer {
unsafe { cpp { "free(buffer);" } }
}

let buf = getcwd(buffer, buffer_size)
if buf == null<c_char>() {
throw Error::from_errno(errno_value())
}
let buf = getcwd(buffer, buffer_size)
if buf == null<c_char>() {
let getcwd_errno = errno_value()
if getcwd_errno == erange_value() {
// grow buffer and try again
buffer_size *= 2
continue
} else {
throw Error::from_errno(getcwd_errno)
}
}

mut b = StringBuilder::create()
b.append_c_string(buf)
return b.to_string()
mut b = StringBuilder::create()
b.append_c_string(buf)
return b.to_string()
}
}

fn real_path(anon path: String) throws -> String {
let buffer_size : usize = 4096; // Roughly PATH_MAX
mut buffer = allocate<c_char>(count: buffer_size + 1)
let buffer = realpath(path: path.c_string(), resolved_path: null<c_char>())
if buffer == null<c_char>() {
throw Error::from_errno(errno_value())
}
defer {
unsafe { cpp { "free(buffer);" } }
}

let buf = realpath(path: path.c_string(), resolved_path: buffer)
if buf == null<c_char>() {
throw Error::from_errno(errno_value())
}

mut b = StringBuilder::create()
b.append_c_string(buf)
b.append_c_string(buffer)
return b.to_string()
}

Expand Down

0 comments on commit 77d0520

Please sign in to comment.