Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 49 additions & 25 deletions src/runtime/api/BunObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1249,36 +1249,64 @@ pub(crate) fn mmap(cx: &mut JsScope<'_>, path: &[u8], options: &MMapOptions) ->
{
use core::ffi::c_void;

if path.len() > MAX_PATH_BYTES {
if path.len() >= MAX_PATH_BYTES {
return Err(global_this.throw_invalid_arguments(format_args!("Path too long")));
}
Comment thread
robobun marked this conversation as resolved.
Resolved
node::types::Valid::path_null_bytes(path, global_this)?;
let throw = |err: sys::Error| {
use bun_jsc::SysErrorJsc as _;
// The error names the path as the caller wrote it.
let written = node::types::join_onto_working_directory_in_executable(path);
let err = node::fs::error_for_caller([written.as_ref(), None], err);
global_this.throw_value(err.to_js(global_this))
};
let mut buf = bun_paths::path_buffer_pool::get();
let buf_len = buf.len();
let Some(joined) = bun_paths::resolve_path::join_abs_string_buf_checked::<
bun_paths::resolve_path::platform::Auto,
>(
bun_core::working_directory_in_executable()
.unwrap_or_else(|| bun_paths::fs::FileSystem::instance().top_level_dir()),
&mut buf[..buf_len - 1],
&[path],
) else {
return Err(global_this.throw_invalid_arguments(format_args!("Path too long")));
};
let graph = bun_standalone_graph::Graph::get_ref()
.filter(|_| bun_standalone_graph::is_bun_standalone_file_path(joined));
let embedded = graph.and_then(|graph| graph.find_ref(joined));
if graph.is_some_and(|graph| graph.find_dir(joined)) {
use bun_jsc::SysErrorJsc as _;
let err = sys::Error::from_code(bun_sys::E::EISDIR, sys::Tag::open).with_path(joined);
return Err(global_this.throw_value(err.to_js(global_this)));
// The system gets the path as written: the joined text drops `link/..`, and names only what the executable holds.
let in_executable = bun_core::working_directory_in_executable();
let starts_in_executable = in_executable.is_some() && !bun_paths::is_absolute(path);
let mut graph = None;
let mut joined_len = None;
if let Some(standalone) = bun_standalone_graph::Graph::get_ref()
&& !path.is_empty()
{
match bun_paths::resolve_path::join_abs_string_buf_checked::<
bun_paths::resolve_path::platform::Auto,
>(
in_executable
.unwrap_or_else(|| bun_paths::fs::FileSystem::instance().top_level_dir()),
&mut buf[..buf_len - 1],
&[path],
) {
Some(joined) => {
if bun_standalone_graph::is_bun_standalone_file_path(joined) {
graph = Some(standalone);
}
if graph.is_some() || starts_in_executable {
joined_len = Some(joined.len());
}
}
// The system has no working directory in the executable to start from.
None if starts_in_executable => {
let err = sys::Error::from_code(bun_sys::E::ENAMETOOLONG, sys::Tag::open);
return Err(throw(err.with_path(path)));
}
None => {}
}
}

let path_len = joined.len();
let path_len = joined_len.unwrap_or_else(|| {
buf[..path.len()].copy_from_slice(path);
path.len()
});
buf[path_len] = 0;

// SAFETY: buf[path_len] == 0 written above
let buf_z = bun_core::ZStr::from_buf(&buf[..], path_len);
let embedded = graph.and_then(|graph| graph.find_ref(buf_z.as_bytes()));
if graph.is_some_and(|graph| graph.find_dir(buf_z.as_bytes())) {
let err = sys::Error::from_code(bun_sys::E::EISDIR, sys::Tag::open);
return Err(throw(err.with_path(buf_z.as_bytes())));
}

// Conforming applications must specify either MAP_PRIVATE or MAP_SHARED.
let flags = if options.shared {
Expand Down Expand Up @@ -1319,11 +1347,7 @@ pub(crate) fn mmap(cx: &mut JsScope<'_>, path: &[u8], options: &MMapOptions) ->

let (map, delta) = match bun_sys::mmap_file(buf_z, flags, map_size, offset) {
Ok(result) => result,
Err(err) => {
use bun_jsc::SysErrorJsc as _;
let err = node::fs::error_for_caller([None, None], err);
return Err(global_this.throw_value(err.to_js(global_this)));
}
Err(err) => return Err(throw(err)),
Comment thread
robobun marked this conversation as resolved.
Resolved
};

extern "C" fn munmap_dealloc(ptr: *mut c_void, size: *mut c_void) {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1200,7 +1200,7 @@ pub(crate) enum RelativePaths {
}

/// The system resolves a relative path against its own working directory, which is never a folder of the executable.
fn join_onto_working_directory_in_executable(path: &[u8]) -> Option<PathLike<'static>> {
pub(crate) fn join_onto_working_directory_in_executable(path: &[u8]) -> Option<PathLike<'static>> {
use bun_paths::resolve_path::{self, platform};
let directory = bun_core::working_directory_in_executable()?;
if path.is_empty() || bun_paths::is_absolute(path) || strings::contains_char(path, 0) {
Expand Down
220 changes: 208 additions & 12 deletions test/js/bun/util/mmap.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterAll, describe, expect, it } from "bun:test";
import { bunEnv, bunExe, gcTick, isWindows, tempDir, tmpdirSync } from "harness";
import { statSync, truncateSync, writeFileSync } from "node:fs";
import { bunEnv, bunExe, gcTick, isRoot, isWindows, tempDir, tmpdirSync } from "harness";
import { chmodSync, mkdirSync, readFileSync, statSync, symlinkSync, truncateSync, writeFileSync } from "node:fs";
import { join } from "path";

// TODO: We do not support mmap() on Windows. Maybe we can add it later.
Expand Down Expand Up @@ -130,26 +130,222 @@ describe.skipIf(isWindows)("Bun.mmap", async () => {
expect(() => Bun.mmap(file, { offset: 1, size: 0 })).toThrow("EINVAL");
});

it("mmap throws a catchable error when the resolved path does not fit", async () => {
// `deep + "/f.txt"` is one byte shorter than the longest path the system takes, so no working directory fits in front of it.
const deepPath = `const max = process.platform === "linux" ? 4096 : 1024;
let deep = "";
while (deep.length < max - 1 - "/f.txt".length) {
const separator = deep === "" ? "" : "/";
deep += separator + Buffer.alloc(Math.min(200, max - 1 - "/f.txt".length - deep.length - separator.length), "d");
}`;

it("mmap throws a catchable error for a path that is too long", async () => {
Comment thread
robobun marked this conversation as resolved.
Resolved
using dir = tempDir("mmap-long-path", {});
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`const max = process.platform === "linux" ? 4096 : 1024;
const rel = Buffer.alloc(max - 1, "a").toString();
try {
Bun.mmap(rel);
console.log("no throw");
} catch (e) {
console.log(e.message);
}`,
// The system gets every path that is shorter than its limit, however long the working directory is.
`import fs from "node:fs";
const answer = path => {
try {
return Buffer.from(Bun.mmap(path)).toString();
} catch (e) {
return e.syscall === "open" ? e.code : e.message;
}
};
${deepPath}
fs.mkdirSync(deep, { recursive: true });
fs.writeFileSync(deep + "/f.txt", "deep");
const out = {
oneNameBelowTheLimit: answer(Buffer.alloc(max - 1, "a").toString()),
nestedBelowTheLimit: answer(deep + "/f.txt"),
atTheLimit: answer("/" + deep + "/f.txt"),
};
fs.rmSync(deep.slice(0, deep.indexOf("/")), { recursive: true });
console.log(JSON.stringify(out));`,
],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stdout).toBe("Path too long\n");
expect({ out: JSON.parse(stdout.trim() || "null"), stderr }).toEqual({
out: { oneNameBelowTheLimit: "ENAMETOOLONG", nestedBelowTheLimit: "deep", atTheLimit: "Path too long" },
stderr: "",
});
expect(exitCode).toBe(0);
});

// `app/cur` links to `releases/v2`, so the system reads `app/cur/..` as `releases`. As text it is `app`.
function linkedTree(prefix) {
const dir = tempDir(prefix, {
"app/config.json": "STALE",
"app/a/b.txt": "in a folder",
"releases/config.json": "LIVE!",
"releases/v2/keep": "",
});
symlinkSync("../releases/v2", join(String(dir), "app", "cur"));
return dir;
}

it("mmap maps the file that the system resolves `link/..` to", () => {
using dir = linkedTree("mmap-link-dotdot");
const file = `${dir}/app/cur/../config.json`;
expect(readFileSync(file, "utf8")).toBe("LIVE!");

const map = Bun.mmap(file);
expect(Buffer.from(map).toString()).toBe("LIVE!");
// A write through the shared mapping reaches that file and no other.
map[0] = "D".charCodeAt(0);
expect({
releases: readFileSync(`${dir}/releases/config.json`, "utf8"),
app: readFileSync(`${dir}/app/config.json`, "utf8"),
}).toEqual({ releases: "DIVE!", app: "STALE" });
});

it("mmap gives the system a relative path as written, and an error names it so", async () => {
using dir = linkedTree("mmap-as-written");
writeFileSync(join(String(dir), "app", "a\\b.txt"), "a backslash in its name");
symlinkSync("loop", join(String(dir), "loop"));
const sealed = join(String(dir), "sealed");
mkdirSync(sealed, { mode: 0o000 });
// The directory is removed with the tree, which takes a mode that lets it be listed.
using _ = { [Symbol.dispose]: () => chmodSync(sealed, 0o700) };
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`import fs from "node:fs";
const answer = call => {
try {
return call();
} catch (e) {
return { code: e.code, syscall: e.syscall, path: e.path };
}
};
const open = path => {
const fd = fs.openSync(path, "r+");
try {
return fs.readFileSync(fd, "utf8");
} finally {
fs.closeSync(fd);
}
};
const out = {};
for (const path of process.argv.slice(1)) {
out[path] = { mmap: answer(() => Buffer.from(Bun.mmap(path)).toString()), open: answer(() => open(path)) };
}
console.log(JSON.stringify(out));`,
"app/cur/../config.json",
"app/absent/../config.json",
"app/config.json/../config.json",
"app/config.json/.",
"loop/../app/config.json",
"sealed/../app/config.json",
"app/absent.json",
"app/a\\b.txt",
"",
],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const both = answer => ({ mmap: answer, open: answer });
const fails = (code, path) => both({ code, syscall: "open", path });
expect({ out: JSON.parse(stdout.trim() || "null"), stderr }).toEqual({
out: {
"app/cur/../config.json": both("LIVE!"),
"app/absent/../config.json": fails("ENOENT", "app/absent/../config.json"),
"app/config.json/../config.json": fails("ENOTDIR", "app/config.json/../config.json"),
Comment thread
robobun marked this conversation as resolved.
Resolved
"app/config.json/.": fails("ENOTDIR", "app/config.json/."),
"loop/../app/config.json": fails("ELOOP", "loop/../app/config.json"),
// The mode of a directory does not stop root.
"sealed/../app/config.json": isRoot ? both("STALE") : fails("EACCES", "sealed/../app/config.json"),
"app/absent.json": fails("ENOENT", "app/absent.json"),
"app/a\\b.txt": both("a backslash in its name"),
"": both({ code: "ENOENT", syscall: "open" }),
},
stderr: "",
});
expect(exitCode).toBe(0);
});

it("mmap in a compiled executable names its own files by text and gives the system every other path", async () => {
using dir = linkedTree("mmap-compiled");
writeFileSync(join(String(dir), "note.txt"), "a note");
writeFileSync(
join(String(dir), "main.js"),
`import fs from "node:fs";
import path from "node:path";
import note from "./note.txt" with { type: "file" };
const root = import.meta.dir;
const disk = process.cwd();
${deepPath}
const shown = text => text.replaceAll(deep, "<deep>").replaceAll(root, "<root>").replaceAll(disk, "<disk>");
const answer = call => {
try {
return Buffer.from(call()).toString();
} catch (e) {
return { code: e.code, syscall: e.syscall, path: e.path === undefined ? undefined : shown(e.path) };
}
};
fs.mkdirSync(deep, { recursive: true });
fs.writeFileSync(deep + "/f.txt", "deep");
const out = {
"embedded file": answer(() => Bun.mmap(note)),
"embedded file behind ..": answer(() => Bun.mmap(root + "/absent/../" + path.basename(note))),
"embedded folder": answer(() => Bun.mmap(root)),
"link/.. on the disk": answer(() => Bun.mmap("app/cur/../config.json")),
"link/.. on the disk, absolute": answer(() => Bun.mmap(disk + "/app/cur/../config.json")),
"disk file behind the embedded folder": answer(() => Bun.mmap(root + "/../.." + disk + "/app/config.json")),
"long relative path": answer(() => Bun.mmap(deep + "/f.txt")),
"empty path": answer(() => Bun.mmap("")),
};
fs.rmSync(deep.slice(0, deep.indexOf("/")), { recursive: true });
process.chdir(root);
Object.assign(out, {
"in the embedded folder: file": answer(() => Bun.mmap(path.basename(note))),
"in the embedded folder: the folder": answer(() => Bun.mmap(".")),
"in the embedded folder: absent file": answer(() => Bun.mmap("absent.txt")),
"in the embedded folder: long relative path": answer(() => Bun.mmap(deep + "/f.txt")),
"in the embedded folder: empty path": answer(() => Bun.mmap("")),
});
console.log(JSON.stringify(out));`,
);
const executable = join(String(dir), "main");
await using build = Bun.spawn({
cmd: [bunExe(), "build", "--compile", "main.js", "--outfile", executable],
env: bunEnv,
cwd: String(dir),
stdout: "pipe",
stderr: "pipe",
});
expect({ stderr: await build.stderr.text(), exitCode: await build.exited }).toMatchObject({ exitCode: 0 });
await using proc = Bun.spawn({ cmd: [executable], env: bunEnv, cwd: String(dir), stdout: "pipe", stderr: "pipe" });
Comment thread
robobun marked this conversation as resolved.
Resolved
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const fails = (code, path) => ({ code, syscall: "open", path });
expect({ out: JSON.parse(stdout.trim() || "null"), stderr }).toEqual({
out: {
"embedded file": "a note",
"embedded file behind ..": "a note",
"embedded folder": fails("EISDIR", "<root>"),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"link/.. on the disk": "LIVE!",
"link/.. on the disk, absolute": "LIVE!",
// As for node:fs, the system does not know the embedded folder.
"disk file behind the embedded folder": fails("ENOENT", "<root>/../..<disk>/app/config.json"),
"long relative path": "deep",
"empty path": { code: "ENOENT", syscall: "open" },
"in the embedded folder: file": "a note",
"in the embedded folder: the folder": fails("EISDIR", "."),
"in the embedded folder: absent file": fails("ENOENT", "absent.txt"),
Comment thread
robobun marked this conversation as resolved.
Resolved
"in the embedded folder: long relative path": fails("ENAMETOOLONG", "<deep>/f.txt"),
"in the embedded folder: empty path": { code: "ENOENT", syscall: "open" },
},
stderr: "",
});
expect(exitCode).toBe(0);
});

Expand Down
Loading