Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
100 changes: 100 additions & 0 deletions source-rust/application/tests/loader_stack_supply.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! A program that writes to the console runs its Omega frames on the loader's
//! stack. On Windows a local record holding a 2 MB array used to compile and
//! then die with STATUS_STACK_OVERFLOW, because the image always reserved
//! 1 MiB. The image now reserves enough for the checked frames. macOS gives
//! the main thread a fixed 8 MiB, so a larger frame there is refused at build
//! time with its call path.
//!
//! The spec rule: `wiki/spec/build/entry_roots.md`, the WCSU paragraph
//! (insufficient fixed supply reports the responsible call path), with
//! `wiki/spec/resources/storage.md`, "Stack demand and backing".

#[path = "support/project.rs"]
mod project;
mod support;

/// Build `main` for `target` with a local record of `bytes` bytes and a
/// console write, and return the exit status, everything printed and the
/// staged project.
fn build(
name: &str,
target: &str,
bytes: u32,
) -> (
Option<i32>,
String,
platform_custody::temporary_directory::TemporaryDirectory,
) {
let library = support::repository_root().join("source/library/system");
let library = library.to_string_lossy().replace('\\', "/");
let application = name.replace('-', "_");
let build = format!(
"use main.omg as app;
use {{omega}}/build/dependency.omg;
use {{omega}}/language/core/process_authority.omg as streams;
machine build(builder: @mutable BuildPlan) {{
builder.product = BuildProduct::Application {{ name: \"{application}\" }};
let allowed: [BoundaryServiceReference; 1] = [Build::service::<|streams|::StandardOutput>(builder)];
let system: DependencyDescription = |dependency|::from_source(Source::Path {{ location: \"{library}\" }});
_ = |dependency|::add(builder, system, @allowed[..]);
Build::bind(builder, {target}::ProgramEntry, |app|::main);
}}
"
);
let main = format!(
"use {{omega}}/language/core/process_authority.omg;
use {{system}}/console.omg;
data Buffers {{
input: [u8; {bytes}];
count: u64;
}}
public machine main() reaches |process_authority|::StandardOutput {{
let mutable buffers: Buffers;
buffers.count = 3u64;
buffers.input[{last}] = 7u8;
|console|::Console::write_line(\"ok\");
}}
",
last = bytes - 1
);
let scratch = project::stage(name, &[("build.omg", &build), ("main.omg", &main)]);
let output = project::omega(
scratch.path(),
&["--target", target, "--build-dir", "out", "build.omg"],
);
let report = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
eprintln!("{report}");
(output.status.code(), report, scratch)
}

/// The PE32+ optional header's `SizeOfStackReserve`.
fn stack_reserve(image: &[u8]) -> u64 {
let header = u32::from_le_bytes(image[0x3c..0x40].try_into().unwrap()) as usize;
let field = header + 24 + 72;
u64::from_le_bytes(image[field..field + 8].try_into().unwrap())
}

#[test]
fn a_windows_image_reserves_the_stack_its_frames_need() {
for (bytes, reserve) in [(2_000_000, 2_097_152), (512_000, 1_048_576)] {
let (status, report, scratch) = build("loader-stack-reserve", "windows_x86_64", bytes);
assert_eq!(status, Some(0), "{report}");
let image = std::fs::read(scratch.path().join("out/omega-program.exe")).unwrap();
assert_eq!(stack_reserve(&image), reserve, "{report}");
}
}

#[test]
fn a_frame_larger_than_the_macos_main_thread_stack_is_refused() {
let (status, report, _) = build("loader-stack-overflow", "macos_arm64", 9_000_000);
assert_ne!(status, Some(0), "{report}");
assert!(
report.contains("stack frames on call path machine ")
&& report.contains("the macos_arm64 loader stack supplies 8388608 bytes"),
"{report}"
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub fn plan_hosted_program_entry<R: HostedReceiverCustody>(
"hosted native entry: requires the exact free Unit hosted program entry",
));
}
check_loader_stack_supply(&input.demand)?;
HostedEntryMode::LoaderStack
} else {
HostedEntryMode::OwnedStack
Expand Down Expand Up @@ -144,6 +145,38 @@ pub fn plan_hosted_program_entry<R: HostedReceiverCustody>(
))
}

/// A hosted import runs on the loader's stack, so the checked Omega frames
/// must fit in it with headroom for the frames they cannot see.
fn check_loader_stack_supply(demand: &StackDemand) -> Result<(), Diagnostic> {
use target::LOADER_STACK_HEADROOM_BYTES as HEADROOM;
let target = demand.target();
let needed = demand.known_stack_bytes();
let supply = target.loader_stack_supply_bytes(needed);
if supply.is_some_and(|supply| needed <= supply.saturating_sub(HEADROOM)) {
return Ok(());
}
let path = demand
.peak_path()
.iter()
.map(|machine| format!("machine {machine}"))
.collect::<Vec<_>>()
.join(" -> ");
let target = target::TargetProfile::ALL
.into_iter()
.find(|profile| {
*profile != target::TargetProfile::UefiX64
&& profile.native_realization() == Some(target)
})
.map_or("hosted", |profile| profile.target_name());
let supply = supply.map_or_else(|| "no".to_owned(), |bytes| bytes.to_string());
Err(Diagnostic::error(format!(
"hosted native entry: the stack frames on call path {path} need {needed} bytes, but \
the {target} loader stack supplies {supply} bytes and keeps {HEADROOM} of them for \
loader and host-call frames; shrink the large locals on that path, because the \
build cannot choose a larger stack"
)))
}

fn plan_storage(
target: target::NativeTarget,
finite_stack_bytes: Option<u64>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1735,7 +1735,9 @@ pub(crate) mod image_output {
Some(identifier) => image_macho::emit_macho_executable_signed(image, identifier),
None => image_macho::emit_macho_executable(image),
},
ObjectFormat::Coff => image_pe::emit_pe_executable(image, subsystem),
ObjectFormat::Coff => {
image_pe::emit_pe_executable(image, subsystem, pe_stack_reserve(artifact)?)
}
}?;
// Writers resolve fixups and place emitted regions. Independent replay
// belongs to retained-artifact receiving checks and backend tests.
Expand All @@ -1757,6 +1759,25 @@ pub(crate) mod image_output {
})
}

/// A hosted entry on the loader's stack gets a reserve that fits its
/// checked frames; any other entry runs on its own stack.
fn pe_stack_reserve(artifact: &ObjectArtifact) -> Result<u64, Diagnostic> {
let Some(entry) = artifact.hosted_entry.as_ref() else {
return Ok(target::WINDOWS_LOADER_STACK_RESERVE_BYTES);
};
let context = entry.context();
if !matches!(
context.backing,
physical_recipes::hosted_program::HostedStackBacking::Loader
) {
return Ok(target::WINDOWS_LOADER_STACK_RESERVE_BYTES);
}
artifact
.target
.loader_stack_supply_bytes(context.demand.known_stack_bytes())
.ok_or_else(|| Diagnostic::error("hosted loader-stack entry: stack reserve overflows"))
}

pub fn validate_direct_executable_image(
artifact: &ObjectArtifact,
image: &ExecutableImage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub(crate) struct PeHeaderInput {
pub(crate) has_reloc: bool,
pub(crate) subsystem: u16,
pub(crate) file_characteristics: u16,
pub(crate) stack_reserve: u64,
pub(crate) export_directory_rva: u32,
pub(crate) export_directory_size: usize,
pub(crate) exception_directory_rva: u32,
Expand Down Expand Up @@ -78,7 +79,7 @@ pub(crate) fn write_pe_headers(bytes: &mut Vec<u8>, input: PeHeaderInput) {
let dynamic_base = input.has_reloc || input.isa == PeIsa::Aarch64;
let dll_characteristics: u16 = 0x0100 | if dynamic_base { 0x0040 } else { 0 };
write_u16(bytes, dll_characteristics);
write_u64(bytes, 0x100000);
write_u64(bytes, input.stack_reserve);
write_u64(bytes, 0x1000);
write_u64(bytes, 0x100000);
write_u64(bytes, 0x1000);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,18 @@ use imports::{
use sections::{plan_pe_sections, rdata_rva_after_text};

pub(crate) enum PeImageKind {
Executable,
Executable { stack_reserve: u64 },
SharedComponent { exports: Vec<PeComponentExport> },
}

/// `stack_reserve` is the initial thread's stack reserve, which hosted entry
/// planning sizes to the checked frames that run on it.
pub fn emit_pe_executable(
image: FinalImage,
subsystem: u16,
stack_reserve: u64,
) -> Result<ExecutableImageOutput, Diagnostic> {
emit_pe(image, subsystem, PeImageKind::Executable)
emit_pe(image, subsystem, PeImageKind::Executable { stack_reserve })
}

pub(crate) fn emit_pe(
Expand All @@ -121,7 +124,7 @@ pub(crate) fn emit_pe(
let rdata_rva = rdata_rva_after_text(&image)?;
let import_table = build_import_table(&import_thunks, rdata_rva);
let (export_bytes, export_directory_rva, export_directory_size) = match &kind {
PeImageKind::Executable => (Vec::new(), 0, 0),
PeImageKind::Executable { .. } => (Vec::new(), 0, 0),
PeImageKind::SharedComponent { exports } => {
let aligned = align_to(import_table.bytes.len(), 4);
let directory_rva = shared_component::directory_rva_of(rdata_rva, aligned)?;
Expand Down Expand Up @@ -182,13 +185,13 @@ pub(crate) fn emit_pe(
};

let entry_rva = match &kind {
PeImageKind::Executable => {
PeImageKind::Executable { .. } => {
TEXT_RVA + image::final_image_entry_symbol(&image, "PE")?.offset as u32
}
PeImageKind::SharedComponent { .. } => 0,
};
let file_characteristics = match &kind {
PeImageKind::Executable => 0x0022,
PeImageKind::Executable { .. } => 0x0022,
PeImageKind::SharedComponent { .. } => 0x2022,
};

Expand Down Expand Up @@ -219,6 +222,10 @@ pub(crate) fn emit_pe(
has_reloc: sections.has_reloc,
subsystem,
file_characteristics,
stack_reserve: match &kind {
PeImageKind::Executable { stack_reserve } => *stack_reserve,
PeImageKind::SharedComponent { .. } => target::WINDOWS_LOADER_STACK_RESERVE_BYTES,
},
export_directory_rva,
export_directory_size,
exception_directory_rva,
Expand Down Expand Up @@ -353,7 +360,12 @@ mod tests {

#[test]
fn import_free_image_omits_empty_read_only_section() {
let output = emit_pe_executable(returning_image(), 3).expect("emit image");
let output = emit_pe_executable(
returning_image(),
3,
target::WINDOWS_LOADER_STACK_RESERVE_BYTES,
)
.expect("emit image");
let bytes = &output.bytes;
let pe_offset = u32::from_le_bytes(bytes[0x3c..0x40].try_into().unwrap()) as usize;
let section_count =
Expand All @@ -368,7 +380,12 @@ mod tests {

#[test]
fn efi_application_image_is_an_import_free_subsystem_10_pe32_plus() {
let output = emit_pe_executable(returning_image(), 10).expect("emit image");
let output = emit_pe_executable(
returning_image(),
10,
target::WINDOWS_LOADER_STACK_RESERVE_BYTES,
)
.expect("emit image");
let bytes = &output.bytes;
let pe_offset = u32::from_le_bytes(bytes[0x3c..0x40].try_into().unwrap()) as usize;
let optional_header = pe_offset + 4 + 20;
Expand Down Expand Up @@ -420,7 +437,9 @@ mod tests {
image.memory.bss_size = ZERO_FILL_BYTES;
names.push(b".bss\0\0\0\0");
}
let output = emit_pe_executable(image, 3).expect("emit image");
let output =
emit_pe_executable(image, 3, target::WINDOWS_LOADER_STACK_RESERVE_BYTES)
.expect("emit image");
let bytes = &output.bytes;
let read_u32 = |offset| {
u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize
Expand Down Expand Up @@ -476,20 +495,22 @@ mod tests {
};
let mut probe = returning_image();
probe.memory.bss_size = 1;
let probe = emit_pe_executable(probe, 3).expect("emit image");
let probe = emit_pe_executable(probe, 3, target::WINDOWS_LOADER_STACK_RESERVE_BYTES)
.expect("emit image");
let bss_rva = usize::try_from(probe.final_image_layout.bss_address - IMAGE_BASE).unwrap();
let last_page_end = 0xffff_f000usize;

let mut largest = returning_image();
largest.memory.bss_size = last_page_end - bss_rva;
let largest = emit_pe_executable(largest, 3).expect("largest addressable .bss");
let largest = emit_pe_executable(largest, 3, target::WINDOWS_LOADER_STACK_RESERVE_BYTES)
.expect("largest addressable .bss");
assert_eq!(size_of_image(&largest.bytes), 0xffff_f000);
assert_eq!(largest.bss_bytes, last_page_end - bss_rva);

for bss_size in [last_page_end - bss_rva + 1, 1usize << 32] {
let mut image = returning_image();
image.memory.bss_size = bss_size;
let error = emit_pe_executable(image, 3)
let error = emit_pe_executable(image, 3, target::WINDOWS_LOADER_STACK_RESERVE_BYTES)
.expect_err("a .bss past the 32-bit RVA space must be refused");
assert!(
error
Expand All @@ -507,7 +528,12 @@ mod tests {
eprintln!("SKIP: requires an x86-64 Windows loader");
return;
}
let output = emit_pe_executable(returning_image(), 3).expect("emit image");
let output = emit_pe_executable(
returning_image(),
3,
target::WINDOWS_LOADER_STACK_RESERVE_BYTES,
)
.expect("emit image");
let path = std::env::temp_dir().join(format!("omega-pe-return-{}.exe", std::process::id()));
std::fs::write(&path, &output.bytes).expect("write executable");
let result = std::process::Command::new(&path).output();
Expand Down Expand Up @@ -535,7 +561,8 @@ mod tests {
kind: RelocationKind::Absolute64,
});

let output = emit_pe_executable(image, 3).expect("emit image");
let output = emit_pe_executable(image, 3, target::WINDOWS_LOADER_STACK_RESERVE_BYTES)
.expect("emit image");
let bytes = &output.bytes;
let u32_at = |offset: usize| {
u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize
Expand Down
Loading
Loading