rocketmq_runtime/stack.rs
1// Copyright 2026 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Normalize before adding lifecycle/select/timeout wrappers. This bounds
16// inline state, not arbitrary user poll frames or recursive user destructors.
17//
18// Unoptimized builds give every by-value move its own stack slot, so each
19// wrapper and forwarding call below this boundary keeps another copy of an
20// inline future and submission can take many times the future's size. Such
21// builds use Tokio's debug boxing boundary instead.
22pub(crate) const MAX_INLINE_SIZE: usize = if cfg!(debug_assertions) { 2 * 1024 } else { 16 * 1024 };
23
24/// Builds a future directly in a heap allocation.
25///
26/// Unoptimized builds give every temporary its own stack slot, so an `async fn`
27/// that builds a large future keeps a copy of it in its poll frame for as long
28/// as it runs, even when it boxes the result itself. Calling `make` from here
29/// puts that copy in this short-lived frame instead and leaves only the box
30/// pointer in the caller's frame and state. Use it where a large future is
31/// built on a thread whose stack the runtime cannot size, such as the process
32/// main thread, which Windows limits to 1 MiB.
33pub fn heap_future<F, Fut>(make: F) -> std::pin::Pin<Box<Fut>>
34where
35 F: FnOnce() -> Fut,
36 Fut: std::future::Future,
37{
38 Box::pin(make())
39}
40
41/// Returns how many bytes of the calling thread's stack are committed.
42///
43/// Windows commits a thread stack one page at a time as it grows and keeps
44/// those pages until the thread exits, so the value is the deepest stack use
45/// of the thread so far, rounded up to whole pages. A process entrypoint can
46/// read it just before returning to measure the headroom left on the main
47/// thread, whose size the runtime cannot choose.
48///
49/// Returns `None` on other platforms, or if the stack layout cannot be read.
50pub fn current_thread_committed_stack_bytes() -> Option<usize> {
51 #[cfg(windows)]
52 {
53 win::committed_stack_bytes()
54 }
55 #[cfg(not(windows))]
56 {
57 None
58 }
59}
60
61#[cfg(windows)]
62mod win {
63 use std::ffi::c_void;
64 use std::mem::size_of;
65
66 use windows_sys::Win32::System::Memory::VirtualQuery;
67 use windows_sys::Win32::System::Memory::MEMORY_BASIC_INFORMATION;
68 use windows_sys::Win32::System::Memory::MEM_COMMIT;
69 use windows_sys::Win32::System::Memory::PAGE_GUARD;
70 use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits;
71
72 pub(super) fn committed_stack_bytes() -> Option<usize> {
73 let mut low = 0_usize;
74 let mut high = 0_usize;
75 // SAFETY: both arguments point to live, writable locals.
76 unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
77
78 // The reservation runs from `low` (never committed) through the guard
79 // pages to the committed pages that end at `high`. Walk it upward and
80 // stop at the first committed page that is not a guard page.
81 let mut address = low;
82 while address < high {
83 let mut region = MEMORY_BASIC_INFORMATION::default();
84 // SAFETY: `region` is a live, writable buffer of the length passed.
85 // VirtualQuery reads the page attributes only, never the page
86 // contents, so it cannot trip a guard page.
87 let written = unsafe {
88 VirtualQuery(
89 address as *const c_void,
90 &mut region,
91 size_of::<MEMORY_BASIC_INFORMATION>(),
92 )
93 };
94 if written == 0 || region.RegionSize == 0 {
95 return None;
96 }
97 let base = region.BaseAddress as usize;
98 if region.State == MEM_COMMIT && region.Protect & PAGE_GUARD == 0 {
99 return high.checked_sub(base);
100 }
101 address = base.checked_add(region.RegionSize)?;
102 }
103 None
104 }
105}
106
107#[cfg(test)]
108mod tests {
109 use super::current_thread_committed_stack_bytes;
110
111 #[test]
112 #[cfg(windows)]
113 fn committed_stack_grows_with_stack_use() {
114 let (before, after) = std::thread::Builder::new()
115 .stack_size(1024 * 1024)
116 .spawn(|| {
117 let before = current_thread_committed_stack_bytes().expect("committed stack before use");
118 (before, use_stack(256 * 1024))
119 })
120 .expect("spawn stack test thread")
121 .join()
122 .expect("stack test thread");
123 assert!(before > 0);
124 assert!(
125 after >= before + 200 * 1024,
126 "committed stack {after} did not grow past {before} after using 256 KiB"
127 );
128 }
129
130 #[cfg(windows)]
131 #[inline(never)]
132 fn use_stack(bytes: usize) -> usize {
133 const CHUNK: usize = 16 * 1024;
134 let mut frame = [0_u8; CHUNK];
135 std::hint::black_box(&mut frame);
136 let committed = if bytes > CHUNK {
137 use_stack(bytes - CHUNK)
138 } else {
139 current_thread_committed_stack_bytes().expect("committed stack after use")
140 };
141 // Keep this frame live across the call so it cannot become a tail call.
142 std::hint::black_box(&frame);
143 committed
144 }
145
146 #[test]
147 #[cfg(not(windows))]
148 fn other_platforms_do_not_report_a_committed_stack() {
149 assert_eq!(current_thread_committed_stack_bytes(), None);
150 }
151}