Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
10 changes: 10 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4081,14 +4081,24 @@ declare module "bun" {
*/
aotHarden?: string | string[];
/**
* Lay the executable out by the order in which a run of it entered its functions. Requires `aot: true`.
*
* Run an executable built with `aotRecordOrder: true` with `BUN_AOT_ORDER_OUT=<path>` to record a
* start, then build again with that file. A file from an older build of the app still applies.
*
* With several files, list the most important one first. A function lies where the first file that
* lists it places it.
*
* Equivalent CLI flag: `--aot-order <file>[,<file>...]`
*
* @see https://bun.com/docs/compiler/aot#order-the-executable-by-a-recorded-start
*/
aotOrder?: string | string[];
/**
* Build an executable that writes what `aotOrder` takes when it runs with `BUN_AOT_ORDER_OUT=<path>`.
* Other executables have no recorder. Requires `aot: true`.
*
* Equivalent CLI flag: `--aot-record-order`
*/
aotRecordOrder?: boolean;
/**
Expand Down
2 changes: 1 addition & 1 deletion scripts/build/deps/webkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* for local mode. Override via `--webkit-version=<hash>` to test a branch.
* From https://github.com/oven-sh/WebKit releases.
*/
export const WEBKIT_VERSION = "ed67c459b78a45320c138dbedad0ec89cd77ee8f";
export const WEBKIT_VERSION = "autobuild-preview-pr-1063-f47af2a5";

/**
* WebKit (JavaScriptCore) — the JS engine, with WTF and bmalloc.
Expand Down
16 changes: 9 additions & 7 deletions src/aot/builtins/resolve/module_objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,16 +439,18 @@ impl Resolver<'_, '_> {
fn stores_method_that_may_read_receiver(&self, member: ExprId, holder: BuiltinId) -> bool {
let (hir, bound) = (self.input.hir, self.input.bound);
let stored_to = self.outermost_assertion_of(member);
let is_process = holder == BuiltinId::Process;
let asks_every_function = matches!(holder, BuiltinId::Process | BuiltinId::ModuleRequire);
let Parent::Expr(store) = bound.parent_of_expr(stored_to) else {
return is_process;
return asks_every_function;
};
match hir[store].kind {
ExprKind::Assign { target, value, .. } if target == stored_to => match is_process {
true => self.may_read_this(value),
false => self.is_function_reading_this(value),
},
_ => is_process,
ExprKind::Assign { target, value, .. } if target == stored_to => {
match asks_every_function {
true => self.may_read_this(value),
false => self.is_function_reading_this(value),
}
}
_ => asks_every_function,
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/aot/builtins/resolve/tests/module_objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,15 @@ fn the_main_module_without_its_name() {
] {
assert_mentions(source, &[]);
}
for source in [
"require.resolve = function () { 'use strict'; return this; };",
"let f = () => {}; f = function () { 'use strict'; return this; }; require.resolve = f;",
"function f() {} f = function () { 'use strict'; return this; }; require.resolve = f;",
"require.resolve = replaced;",
] {
assert_mentions(source, &[("require.resolve", EntryPoint, Escaped)]);
}
assert_mentions("require.resolve = () => {};", &[]);
for source in [
"f(globalThis);",
"const [root] = [globalThis];",
Expand Down
2 changes: 1 addition & 1 deletion src/codegen/builtins/host/web-values.builtins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ const storesInForm = [
},
implementation: b.hostCall,
},
...takingStrings(["name", "value"], [], { ...stateChanged, throws: true }),
...takingStrings(["name", "value"], ["filename"], { ...stateChanged, throws: true }),
] satisfies b.FunctionField[];

const otherReceiverIgnored = {
Expand Down
103 changes: 99 additions & 4 deletions src/exe_format/elf_payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,9 +785,10 @@ mod tests {
use bun_core::slice_to_nul;

use super::*;
use crate::elf_ranges::reserve_payload_segments;
use crate::elf_ranges::tests::toy_elf;
use crate::image::{AddressRange, Architecture, ImageEditor};
use crate::cut_model::{CutCapacity, RemovableBytes};
use crate::elf_ranges::tests::{HEADERS_WITH_ONE_CUT, limit_header_room, toy_elf};
use crate::elf_ranges::{cut_model, remove_ranges, reserve_payload_segments};
use crate::image::{AddressRange, Architecture, ImageEditor, ImageError};

const ARCHITECTURES: [Architecture; 2] = [Architecture::X86_64, Architecture::Aarch64];
const PHDR_SIZE: usize = size_of::<Elf64_Phdr>();
Expand Down Expand Up @@ -862,7 +863,10 @@ mod tests {
let page = page_size(elf);
let start = align_up(find_section(elf, b".text").sh_addr, page);
let end = start + 4 * page;
let cut = AddressRange { start, end };
remove(elf, AddressRange { start, end })
}

fn remove(elf: &mut Vec<u8>, cut: AddressRange) -> AddressRange {
let mut editor = ImageEditor::open(elf).unwrap();
editor.remove_ranges(&[cut]).unwrap();
cut
Expand Down Expand Up @@ -1181,6 +1185,97 @@ mod tests {
}
}

#[test]
fn payload_with_code_is_replaced_after_another_cut() {
for architecture in ARCHITECTURES {
let mut trimmed = template(architecture);
let first_cut = remove_text_pages(&mut trimmed);
let page = page_size(&trimmed);
let second_cut = AddressRange {
start: first_cut.end,
end: first_cut.end + page,
};
let mut cut_once = template(architecture);
let both_cuts = AddressRange {
start: first_cut.start,
end: second_cut.end,
};
remove(&mut cut_once, both_cuts);

let free_slots = |elf: &[u8]| cut_model(elf).free_slots();
let payloads = [
(4 * page, page - 8..3 * page - 8),
(2 * page - 8, page - 8..2 * page - 8),
(6 * page, 2 * page - 8..5 * page - 8),
];
for (length, code) in payloads.clone() {
let first = write_with_code(&trimmed, &create_payload(length), code);
assert_eq!(free_slots(&first), free_slots(&trimmed));

let mut cut_twice = first.clone();
remove(&mut cut_twice, second_cut);
assert_eq!(find_reserved_segment(&cut_twice), None);
assert_eq!(free_slots(&cut_twice), free_slots(&first));

for (length, code) in payloads.clone() {
let payload = create_payload(length);
let built = write_with_code(&cut_twice, &payload, code.clone());
assert!(built == write_with_code(&cut_once, &payload, code));
}
let payload = create_payload(3 * page);
let without_code = write_in_pieces(&cut_twice, &payload).0;
assert!(without_code == write_in_pieces(&cut_once, &payload).0);
}
}
}

#[test]
fn full_table_holds_the_empty_piece_of_a_payload() {
for architecture in ARCHITECTURES {
let mut trimmed = template(architecture);
limit_header_room(&mut trimmed, HEADERS_WITH_ONE_CUT);
let first_cut = remove_text_pages(&mut trimmed);
let page = page_size(&trimmed);
let [beside, apart] = [0, 2].map(|pages| AddressRange {
start: first_cut.end + pages * page,
end: first_cut.end + (pages + 1) * page,
});

let code_to_the_end = (2 * page - 8, page - 8..2 * page - 8);
let code_in_the_middle = (4 * page, page - 8..3 * page - 8);
for (length, code) in [code_to_the_end, code_in_the_middle.clone()] {
let first = write_with_code(&trimmed, &create_payload(length), code);
assert_eq!(usize::from(read_ehdr(&first).e_phnum), HEADERS_WITH_ONE_CUT);
assert_eq!(cut_model(&first).capacity, CutCapacity::Cuts(0));
let mut refused = first.clone();
let result = remove_ranges(&mut refused, &[apart]);
assert_eq!(result, Err(ImageError::HeaderRoomExhausted));
assert!(refused == first);

let removable = [beside, apart].map(|range| RemovableBytes {
range,
is_code: true,
can_be_cut: true,
can_be_filled: true,
});
let plan = cut_model(&first).choose(&removable);
assert_eq!(plan.cuts, [beside]);
let mut cut_twice = first;
remove(&mut cut_twice, beside);
let (length, code) = code_in_the_middle.clone();
let built = write_with_code(&cut_twice, &create_payload(length), code);
assert_eq!(
payload_segments(&built),
[
(PF_R, 0, page),
(PF_R | PF_X, page, 2 * page),
(PF_R, 3 * page, 2 * page),
]
);
}
}
}

#[test]
fn payload_with_code_replaces_plain_one() {
for architecture in ARCHITECTURES {
Expand Down
107 changes: 72 additions & 35 deletions src/exe_format/elf_ranges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use core::ops::Range;

use bun_sys::elf::PT_LOAD;

use crate::cut_model::{CutCapacity, CutModel, NoCutReason};
use crate::cut_model::{CutCapacity, CutModel, NoCutReason, SlotCosts};
use crate::elf::{
EM_AARCH64, EM_X86_64, Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, ElfFile, SHF_ALLOC, SHN_LORESERVE,
SHT_NOBITS, SHT_PROGBITS, read_ehdr,
Expand All @@ -22,6 +22,7 @@ const SHT_NULL: u32 = 0;
const SECTION_HEADER_SIZE: usize = size_of::<Elf64_Shdr>();
const SECTION_TABLE_ALIGNMENT: u64 = 8;
const UNREADABLE_FILE_ALIGNMENT: u64 = 0x1000;
const PROGRAM_HEADERS_FOR_A_CUT: usize = 1;

pub(crate) fn architecture(ehdr: &Elf64_Ehdr) -> Result<Architecture, ImageError> {
match ehdr.e_machine {
Expand Down Expand Up @@ -57,20 +58,25 @@ pub(crate) fn cut_model(elf: &[u8]) -> CutModel {
let Ok(table) = ProgramHeaderTable::read(elf, &ehdr) else {
return without_cuts(NoCutReason::HeadersUnreadable);
};
let capacity = compute_capacity(&ehdr, &table, alignment);
if let CutCapacity::NoCuts(reason) = capacity {
return without_cuts(reason);
}
match find_cuttable_spans(elf, &ehdr, &table) {
Ok(cuttable_spans) => CutModel {
format,
alignment,
capacity,
cuttable_spans,
spans_cut_only_at_end: Vec::new(),
slot_costs: None,
},
Err(_) => without_cuts(NoCutReason::HeadersUnreadable),
let free_slots = match count_free_slots(&ehdr, &table, alignment) {
Ok(free_slots) => free_slots,
Err(reason) => return without_cuts(reason),
};
let Ok(spans) = find_cuttable_spans(elf, &ehdr, &table) else {
return without_cuts(NoCutReason::HeadersUnreadable);
};
let (cuttable_spans, saved_at_ends) = spans.into_iter().unzip();
CutModel {
format,
alignment,
capacity: CutCapacity::Cuts(free_slots),
cuttable_spans,
spans_cut_only_at_end: Vec::new(),
slot_costs: Some(SlotCosts {
free_slots,
slots_for_a_cut: PROGRAM_HEADERS_FOR_A_CUT,
saved_at_ends,
}),
}
}

Expand All @@ -91,10 +97,11 @@ pub(crate) fn remove_ranges(
// Read before the cuts: one at the end of the highest segment lowers where the mapped addresses end.
let image_end = find_image_end(&table.headers)?;
table.headers = removal.update_program_headers(&table.headers)?;
if table.capacity().saturating_sub(table.headers.len()) < PAYLOAD_SEGMENT_COUNT {
let reserved_count = count_headers_to_reserve(&table.headers);
if table.headers.len() + reserved_count > table.capacity() {
return Err(ImageError::HeaderRoomExhausted);
}
for _ in 0..PAYLOAD_SEGMENT_COUNT {
for _ in 0..reserved_count {
table.insert_by_address(create_reserved_header(image_end, removal.alignment)?);
}
let section_table = removal.plan_section_table(elf, &ehdr)?;
Expand Down Expand Up @@ -130,27 +137,53 @@ fn compute_headers_end(table: &ProgramHeaderTable) -> u64 {
table.end_file_offset().max(size_of::<Elf64_Ehdr>() as u64)
}

fn compute_capacity(ehdr: &Elf64_Ehdr, table: &ProgramHeaderTable, alignment: u64) -> CutCapacity {
fn find_payload_headers(headers: &[Elf64_Phdr]) -> Option<Range<usize>> {
let start = headers
.iter()
.position(|header| header.p_type == PT_BUN_PAYLOAD)?;
Some(start..start + PAYLOAD_SEGMENT_COUNT)
}

fn headers_in_use(headers: &[Elf64_Phdr]) -> impl Iterator<Item = &Elf64_Phdr> {
let payload = find_payload_headers(headers).unwrap_or(0..0);
headers
.iter()
.enumerate()
.filter(move |(index, header)| match header.p_type {
PT_BUN_RESERVED => false,
PT_NULL => payload.contains(index),
_ => true,
})
.map(|(_, header)| header)
}

fn count_headers_to_reserve(headers: &[Elf64_Phdr]) -> usize {
match find_payload_headers(headers) {
Some(_) => 0,
None => PAYLOAD_SEGMENT_COUNT,
}
}

fn count_free_slots(
ehdr: &Elf64_Ehdr,
table: &ProgramHeaderTable,
alignment: u64,
) -> Result<usize, NoCutReason> {
if !has_section_headers(ehdr) {
return CutCapacity::NoCuts(NoCutReason::SectionHeadersMissing);
return Err(NoCutReason::SectionHeadersMissing);
}
let mut loads = table
.headers
.iter()
.filter(|header| header.p_type == PT_LOAD);
if !loads.all(|load| is_congruent(load, alignment)) {
return CutCapacity::NoCuts(NoCutReason::SegmentsNotCongruent);
return Err(NoCutReason::SegmentsNotCongruent);
}
let used = table
.headers
.iter()
.filter(|header| !matches!(header.p_type, PT_NULL | PT_BUN_RESERVED))
.count();
CutCapacity::from_free_slots(
table
.capacity()
.saturating_sub(used + PAYLOAD_SEGMENT_COUNT),
)
let used = headers_in_use(&table.headers).count();
table
.capacity()
.checked_sub(used + count_headers_to_reserve(&table.headers))
.ok_or(NoCutReason::HeaderRoomExhausted)
}

fn find_required_ranges(
Expand Down Expand Up @@ -183,15 +216,20 @@ fn find_cuttable_spans(
elf: &[u8],
ehdr: &Elf64_Ehdr,
table: &ProgramHeaderTable,
) -> Result<Vec<AddressRange>, ImageError> {
) -> Result<Vec<(AddressRange, [usize; 2])>, ImageError> {
let required = find_required_ranges(elf, ehdr, table)?;
let mut spans = Vec::new();
for load in &table.headers {
if load.p_type != PT_LOAD || load.p_filesz == 0 || load.p_flags & PF_W != 0 {
continue;
}
let addresses = AddressRange::from_size(load.p_vaddr, load.p_filesz)?;
spans.extend(subtract_cuts(addresses, &required));
let mapped_end = AddressRange::from_size(load.p_vaddr, load.p_memsz)?.end;
let saved_at_ends = |span: AddressRange| {
[span.start == addresses.start, span.end == mapped_end].map(usize::from)
};
let of_segment = subtract_cuts(addresses, &required).into_iter();
spans.extend(of_segment.map(|span| (span, saved_at_ends(span))));
}
Ok(spans)
}
Expand Down Expand Up @@ -348,11 +386,10 @@ impl Removal<'_> {
) -> Result<Vec<Elf64_Phdr>, ImageError> {
let mut updated =
Vec::with_capacity(headers.len() + self.cuts.len() + PAYLOAD_SEGMENT_COUNT);
for header in headers {
for header in headers_in_use(headers) {
match header.p_type {
PT_NULL | PT_BUN_RESERVED => {}
PT_LOAD => updated.extend(self.split_load_segment(header)?),
PT_PHDR => updated.push(*header),
PT_NULL | PT_PHDR => updated.push(*header),
_ => {
let p_offset = self
.compute_moved_offset(header.p_offset, header.p_filesz)
Expand Down
Loading
Loading