diff --git a/source-rust/application/tests/loader_stack_supply.rs b/source-rust/application/tests/loader_stack_supply.rs new file mode 100644 index 000000000000..a8ba40d34a28 --- /dev/null +++ b/source-rust/application/tests/loader_stack_supply.rs @@ -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, + 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}" + ); +} diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/09_post-allocation-machine-to-framed-machine/entry-planning/src/hosted_program.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/09_post-allocation-machine-to-framed-machine/entry-planning/src/hosted_program.rs index 8c1fb3eefd69..6d32671e5acf 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/09_post-allocation-machine-to-framed-machine/entry-planning/src/hosted_program.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/09_post-allocation-machine-to-framed-machine/entry-planning/src/hosted_program.rs @@ -89,6 +89,7 @@ pub fn plan_hosted_program_entry( "hosted native entry: requires the exact free Unit hosted program entry", )); } + check_loader_stack_supply(&input.demand)?; HostedEntryMode::LoaderStack } else { HostedEntryMode::OwnedStack @@ -144,6 +145,38 @@ pub fn plan_hosted_program_entry( )) } +/// 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::>() + .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, diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-emission/src/image.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-emission/src/image.rs index b113d5e23610..a2a929d27bd3 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-emission/src/image.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-emission/src/image.rs @@ -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. @@ -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 { + 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, diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/headers.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/headers.rs index 79dc6ac090dc..77b6e796450a 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/headers.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/headers.rs @@ -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, @@ -78,7 +79,7 @@ pub(crate) fn write_pe_headers(bytes: &mut Vec, 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); diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/lib.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/lib.rs index 323b495e4b0c..1362b64cba44 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/lib.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/lib.rs @@ -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 }, } +/// `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 { - emit_pe(image, subsystem, PeImageKind::Executable) + emit_pe(image, subsystem, PeImageKind::Executable { stack_reserve }) } pub(crate) fn emit_pe( @@ -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)?; @@ -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, }; @@ -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, @@ -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 = @@ -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; @@ -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 @@ -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 @@ -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(); @@ -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 diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/unwind_tests.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/unwind_tests.rs index ad0314ad5cf6..19f8211fd17f 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/unwind_tests.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/src/unwind_tests.rs @@ -100,8 +100,12 @@ fn x64_rows_release_the_frame_and_reload_each_saved_register() { epilogue: Vec::new(), epilogue_offsets: vec![40], }; - let output = emit_pe_executable(image_with(NativeTarget::windows_x64(), 64, frame), 3) - .expect("emit image"); + let output = emit_pe_executable( + image_with(NativeTarget::windows_x64(), 64, frame), + 3, + target::WINDOWS_LOADER_STACK_RESERVE_BYTES, + ) + .expect("emit image"); assert_eq!( read_pe_function_frames(&output.bytes).unwrap(), [PeFunctionFrame { @@ -143,8 +147,12 @@ fn x64_prologue_past_255_bytes_continues_in_chained_rows() { epilogue: Vec::new(), epilogue_offsets: Vec::new(), }; - let output = emit_pe_executable(image_with(NativeTarget::windows_x64(), 800, frame), 3) - .expect("emit image"); + let output = emit_pe_executable( + image_with(NativeTarget::windows_x64(), 800, frame), + 3, + target::WINDOWS_LOADER_STACK_RESERVE_BYTES, + ) + .expect("emit image"); assert_eq!( exception_directory(&output.bytes).1, 3 * 12, @@ -184,8 +192,12 @@ fn arm64_rows_give_one_code_per_prologue_word_and_scope_each_epilogue() { epilogue, epilogue_offsets: vec![40, 76], }; - let output = emit_pe_executable(image_with(NativeTarget::windows_arm64(), 100, frame), 3) - .expect("emit image"); + let output = emit_pe_executable( + image_with(NativeTarget::windows_arm64(), 100, frame), + 3, + target::WINDOWS_LOADER_STACK_RESERVE_BYTES, + ) + .expect("emit image"); assert_eq!( read_pe_function_frames(&output.bytes).unwrap(), [PeFunctionFrame { @@ -232,8 +244,12 @@ fn arm64_refuses_a_save_its_codes_cannot_reach() { epilogue: Vec::new(), epilogue_offsets: Vec::new(), }; - let error = - emit_pe_executable(image_with(NativeTarget::windows_arm64(), 16, frame), 3).unwrap_err(); + let error = emit_pe_executable( + image_with(NativeTarget::windows_arm64(), 16, frame), + 3, + target::WINDOWS_LOADER_STACK_RESERVE_BYTES, + ) + .unwrap_err(); assert!(format!("{error:?}").contains("504 bytes"), "{error:?}"); } @@ -246,6 +262,7 @@ fn frameless_functions_get_no_row() { FunctionFrameUnwind::default(), ), 3, + target::WINDOWS_LOADER_STACK_RESERVE_BYTES, ) .expect("emit image"); assert_eq!(exception_directory(&output.bytes), (0, 0)); @@ -263,8 +280,12 @@ fn x64_rows_encode_and_decode_save_xmm128_and_far() { epilogue: Vec::new(), epilogue_offsets: vec![40], }; - let output = emit_pe_executable(image_with(NativeTarget::windows_x64(), 64, frame), 3) - .expect("emit image"); + let output = emit_pe_executable( + image_with(NativeTarget::windows_x64(), 64, frame), + 3, + target::WINDOWS_LOADER_STACK_RESERVE_BYTES, + ) + .expect("emit image"); assert_eq!( read_pe_function_frames(&output.bytes).unwrap(), [PeFunctionFrame { diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/tests/windows_unwinder.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/tests/windows_unwinder.rs index eec5a6b63929..d6b6355d7f73 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/tests/windows_unwinder.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/15_objects-to-image/image-pe/tests/windows_unwinder.rs @@ -10,8 +10,12 @@ use arena::Handle; use calling_conventions::MachineRegister; -use calling_conventions::frame_unwind::{FrameProtocolEffect, FrameProtocolStep, FunctionFrameUnwind}; -use image::{FinalFunctionUnwind, FinalImage, FinalImageMemory, FinalImageSection, FinalImageSymbol}; +use calling_conventions::frame_unwind::{ + FrameProtocolEffect, FrameProtocolStep, FunctionFrameUnwind, +}; +use image::{ + FinalFunctionUnwind, FinalImage, FinalImageMemory, FinalImageSection, FinalImageSymbol, +}; use object_file::SymbolKind; use target::NativeTarget; @@ -86,8 +90,12 @@ fn mapped(text: Vec, frame: FunctionFrameUnwind) -> (Vec, u32, u32) { ..Default::default() }); image.symbol_table.entry_symbol = symbol; - image.function_unwinds.push(FinalFunctionUnwind { symbol, frame }); - let bytes = image_pe::emit_pe_executable(image, 3).expect("emit image").bytes; + image + .function_unwinds + .push(FinalFunctionUnwind { symbol, frame }); + let bytes = image_pe::emit_pe_executable(image, 3, target::WINDOWS_LOADER_STACK_RESERVE_BYTES) + .expect("emit image") + .bytes; let pe = u32_at(&bytes, 0x3c) as usize; let optional = pe + 24; let size_of_image = u32_at(&bytes, optional + 56) as usize; @@ -104,7 +112,11 @@ fn mapped(text: Vec, frame: FunctionFrameUnwind) -> (Vec, u32, u32) { memory[rva..rva + raw_size].copy_from_slice(&bytes[raw..raw + raw_size]); } let directory = optional + 112 + 3 * 8; - (memory, u32_at(&bytes, directory), u32_at(&bytes, directory + 4)) + ( + memory, + u32_at(&bytes, directory), + u32_at(&bytes, directory + 4), + ) } struct Unwound { @@ -116,7 +128,13 @@ struct Unwound { /// Undo one frame at `pc_offset` into the function, whose stack pointer is /// `rsp_offset` bytes into `stack`. -fn unwind(memory: &[u8], directory: (u32, u32), pc_offset: u64, stack: &[u64], rsp_offset: usize) -> Unwound { +fn unwind( + memory: &[u8], + directory: (u32, u32), + pc_offset: u64, + stack: &[u64], + rsp_offset: usize, +) -> Unwound { let base = memory.as_ptr() as u64; let table = memory[directory.0 as usize..].as_ptr(); let mut context = Context([0; 0x4d0]); @@ -157,7 +175,9 @@ fn unwind(memory: &[u8], directory: (u32, u32), pc_offset: u64, stack: &[u64], r #[test] fn windows_unwinder_restores_the_caller_from_prologue_body_and_epilogue() { // sub rsp, 40; mov [rsp], rbx; mov [rsp+8], r12; body; epilogue at 0x20. - let mut text = vec![0x48, 0x83, 0xec, 40, 0x48, 0x89, 0x1c, 0x24, 0x4c, 0x89, 0x64, 0x24, 8]; + let mut text = vec![ + 0x48, 0x83, 0xec, 40, 0x48, 0x89, 0x1c, 0x24, 0x4c, 0x89, 0x64, 0x24, 8, + ]; text.resize(0x20, 0x90); text.extend_from_slice(&[0x4c, 0x8b, 0x64, 0x24, 8, 0x48, 0x8b, 0x1c, 0x24]); let epilogue_add = text.len() as u64; @@ -177,11 +197,17 @@ fn windows_unwinder_restores_the_caller_from_prologue_body_and_epilogue() { let caller = stack.as_ptr() as u64 + 48; let body = unwind(&memory, (directory, size), 0x18, &stack, 0); - assert_eq!((body.rip, body.rsp, body.rbx, body.r12), (0xcafe, caller, 0x5b5b, 0x1c1c)); + assert_eq!( + (body.rip, body.rsp, body.rbx, body.r12), + (0xcafe, caller, 0x5b5b, 0x1c1c) + ); // After `sub rsp` only: nothing saved yet, so registers keep their values. let early = unwind(&memory, (directory, size), 4, &stack, 0); - assert_eq!((early.rip, early.rsp, early.rbx, early.r12), (0xcafe, caller, 0xb0b0, 0x1212)); + assert_eq!( + (early.rip, early.rsp, early.rbx, early.r12), + (0xcafe, caller, 0xb0b0, 0x1212) + ); // At function entry the return address is at the stack pointer. let entry = unwind(&memory, (directory, size), 0, &stack, 40); @@ -203,12 +229,18 @@ fn windows_unwinder_follows_chained_rows_through_a_long_probed_prologue() { let mut prologue = Vec::new(); for _ in 0..64 { text.extend_from_slice(&[0x48, 0x81, 0xec, 0x00, 0x10, 0x00, 0x00]); - prologue.push(step(text.len() as u32, FrameProtocolEffect::AdjustStack { bytes: 4_096 })); + prologue.push(step( + text.len() as u32, + FrameProtocolEffect::AdjustStack { bytes: 4_096 }, + )); text.extend_from_slice(&[0x80, 0x3c, 0x24, 0x00]); prologue.push(step(text.len() as u32, FrameProtocolEffect::Unchanged)); } text.extend_from_slice(&[0x48, 0x89, 0xb4, 0x24, 0xf8, 0xff, 0x03, 0x00]); - prologue.push(step(text.len() as u32, saved(MachineRegister::X86Rsi, 0x3fff8))); + prologue.push(step( + text.len() as u32, + saved(MachineRegister::X86Rsi, 0x3fff8), + )); text.resize(text.len() + 32, 0x90); let frame = FunctionFrameUnwind { prologue, @@ -226,6 +258,12 @@ fn windows_unwinder_follows_chained_rows_through_a_long_probed_prologue() { assert_eq!((body.rip, body.rsp), (0xfeed, caller)); // In the second row's prologue after 27 pages: only those are undone. - let partial = unwind(&memory, (directory, size), 297, &stack, 0x40000 - 27 * 4_096); + let partial = unwind( + &memory, + (directory, size), + 297, + &stack, + 0x40000 - 27 * 4_096, + ); assert_eq!((partial.rip, partial.rsp), (0xfeed, caller)); } diff --git a/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/demand.rs b/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/demand.rs index c670b0a597c5..cf0ccc6e1b8b 100644 --- a/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/demand.rs +++ b/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/demand.rs @@ -32,6 +32,8 @@ type Error = StackDemandError; struct Composition { active: Vec, peaks: Vec>, + /// The internal callee whose composed demand set each function's peak. + peak_callees: Vec>, machines: BTreeSet, reports: BTreeSet, commitments: BTreeSet, @@ -58,6 +60,7 @@ pub fn derive_physical_stack_demand( let mut composition = Composition { active: vec![false; functions.len()], peaks: vec![None; functions.len()], + peak_callees: vec![None; functions.len()], machines: BTreeSet::new(), reports: BTreeSet::new(), commitments: BTreeSet::new(), @@ -65,6 +68,15 @@ pub fn derive_physical_stack_demand( compiler_imports: BTreeSet::new(), }; let ceiling_bytes = visit(root, &functions, &private_demands, &mut composition)?; + let mut peak_path = vec![functions[root].machine]; + let mut current = root; + while let Some(callee) = composition.peak_callees[current] { + if peak_path.len() > functions.len() { + return Err(Error::TerminalStackCycle(functions[callee].machine)); + } + peak_path.push(functions[callee].machine); + current = callee; + } if composition .compiler_imports .iter() @@ -83,6 +95,7 @@ pub fn derive_physical_stack_demand( admitted_contribution_commitments: composition.commitments, hosted_native_bindings: composition.hosted, compiler_imports: composition.compiler_imports, + peak_path, private_demands, }) } @@ -123,7 +136,10 @@ fn visit( caller: machine, owner: call.owner, })?; - peak = peak.max(composed); + if composed > peak { + peak = composed; + composition.peak_callees[index] = Some(callee); + } } for call in &function.foreign_calls { let foreign_bytes = match &call.extent { @@ -145,7 +161,10 @@ fn visit( .hosted .insert(receipt.ok_or(Error::InvalidPrivateFunctionIdentity)?); } - peak = peak.max(u64::from(call.caller_live_bytes)); + if u64::from(call.caller_live_bytes) > peak { + peak = u64::from(call.caller_live_bytes); + composition.peak_callees[index] = None; + } continue; } }; @@ -174,7 +193,10 @@ fn visit( caller: machine, owner: call.owner, })?; - peak = peak.max(composed); + if composed > peak { + peak = composed; + composition.peak_callees[index] = None; + } } composition.active[index] = false; composition.peaks[index] = Some(peak); @@ -195,6 +217,7 @@ pub struct StackDemand { std::collections::BTreeSet, hosted_native_bindings: std::collections::BTreeSet<[u8; 32]>, compiler_imports: BTreeSet, + peak_path: Vec, private_demands: Vec<(function_identity::MachineFunctionIdentity, StackDemand)>, } @@ -240,6 +263,12 @@ impl StackDemand { self.stack_alignment } + /// The internal call path, from the entry, whose frames compose the + /// known ceiling. A foreign call or the last frame ends it. + pub fn peak_path(&self) -> &[MachineId] { + &self.peak_path + } + pub const fn contributing_machines(&self) -> &std::collections::BTreeSet { &self.contributing_machines } diff --git a/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/tests.rs b/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/tests.rs index 013b98f7f7a1..97e8ecb54837 100644 --- a/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/tests.rs +++ b/source-rust/subsystems/compiler/psi-to-native/representations/machine-code/stack-demand/tests.rs @@ -150,3 +150,14 @@ fn a_foreign_stack_promise_is_bound_to_its_selected_execution_and_composes_with_ ) )); } + +#[test] +fn the_peak_path_follows_the_calls_that_set_the_ceiling() { + let mut program = program(); + let demand = derive_physical_stack_demand(&program, machine(1), vec![]).unwrap(); + assert_eq!(demand.peak_path(), [machine(1), machine(2)]); + program.functions[0].local = LocalStackExtent::Finite(4096); + let local = derive_physical_stack_demand(&program, machine(1), vec![]).unwrap(); + assert_eq!(local.ceiling_bytes(), Some(4096)); + assert_eq!(local.peak_path(), [machine(1)]); +} diff --git a/source-rust/subsystems/compiler/psi-to-native/targets/target/src/lib.rs b/source-rust/subsystems/compiler/psi-to-native/targets/target/src/lib.rs index 3957c459b770..a25195561e55 100644 --- a/source-rust/subsystems/compiler/psi-to-native/targets/target/src/lib.rs +++ b/source-rust/subsystems/compiler/psi-to-native/targets/target/src/lib.rs @@ -62,10 +62,11 @@ pub use foreign_locator::{ NormalizedForeignLocator, evaluated_syscall_identity_digest, normalize_foreign_locator, }; pub use target_profile::{ - Architecture, CASE_TAG_BYTE_ALIGNMENT, CASE_TAG_BYTE_SIZE, HostedIntrinsicBundle, NativeTarget, - ObjectFormat, ProgramEntryArgument, ProgramEntryCallingConvention, - ProgramEntryPhysicalContractPackage, ProgramEntrySchema, ProgramEntrySlotDeclaration, - ProgramEntrySlots, ProgramStorageEntryRootRole, TargetProfile, TargetWireIdentityError, + Architecture, CASE_TAG_BYTE_ALIGNMENT, CASE_TAG_BYTE_SIZE, HostedIntrinsicBundle, + LOADER_STACK_HEADROOM_BYTES, NativeTarget, ObjectFormat, ProgramEntryArgument, + ProgramEntryCallingConvention, ProgramEntryPhysicalContractPackage, ProgramEntrySchema, + ProgramEntrySlotDeclaration, ProgramEntrySlots, ProgramStorageEntryRootRole, TargetProfile, + TargetWireIdentityError, WINDOWS_LOADER_STACK_RESERVE_BYTES, }; pub use target_semantics::{ SymbolicTargetObservationApplication, TargetEntryStackGuarantee, TargetSemantics, UefiX86_64, diff --git a/source-rust/subsystems/compiler/psi-to-native/targets/target/src/target_profile.rs b/source-rust/subsystems/compiler/psi-to-native/targets/target/src/target_profile.rs index 716d5748c3ea..38f8e11f24ff 100644 --- a/source-rust/subsystems/compiler/psi-to-native/targets/target/src/target_profile.rs +++ b/source-rust/subsystems/compiler/psi-to-native/targets/target/src/target_profile.rs @@ -625,7 +625,34 @@ pub enum TargetWireIdentityError { LayoutOverflow, } +/// The smallest initial-thread stack reserve a Windows executable declares. +pub const WINDOWS_LOADER_STACK_RESERVE_BYTES: u64 = 0x10_0000; + +/// The default initial-thread stack limit on Linux and macOS. +pub const POSIX_LOADER_STACK_LIMIT_BYTES: u64 = 8 * 0x10_0000; + +/// Bytes of a loader stack kept for the loader's own frames, the entry +/// adapter, guard pages and host imports' frames, none of which the checked +/// Omega frames account for. +pub const LOADER_STACK_HEADROOM_BYTES: u64 = 64 * 1024; + impl NativeTarget { + /// Stack the operating-system loader gives the initial thread of a hosted + /// executable whose checked frames need `frame_bytes`. A Windows image + /// declares its own reserve, so it is sized to the frames plus headroom + /// and is never below 1 MiB. Linux and macOS give the main thread their + /// default limit, whatever the image holds. `None` means the reserve + /// overflows. + pub fn loader_stack_supply_bytes(&self, frame_bytes: u64) -> Option { + match self.object_format { + ObjectFormat::Coff => frame_bytes + .checked_add(LOADER_STACK_HEADROOM_BYTES)? + .checked_next_multiple_of(LOADER_STACK_HEADROOM_BYTES) + .map(|bytes| bytes.max(WINDOWS_LOADER_STACK_RESERVE_BYTES)), + ObjectFormat::Elf | ObjectFormat::MachO => Some(POSIX_LOADER_STACK_LIMIT_BYTES), + } + } + pub fn identity_bytes(&self) -> [u8; 18] { let mut bytes = [0u8; 18]; bytes[0] = match self.architecture {