1use std::{
15 io::{self, BufRead, BufReader, Write},
16 path::Path,
17 process::{Child, Command, Stdio},
18 sync::atomic::{AtomicI32, AtomicU32, Ordering},
19 time::Duration,
20};
21
22use crossbeam_channel::{Receiver, unbounded};
23use process_memory::{TryIntoProcessHandle, copy_address};
24
25pub const TARGET_ARGUMENT: &str = "--tutorial-target";
26pub const HEALTH_BAR_ARGUMENT: &str = "--health-bar";
28pub const MAX_HEALTH: i32 = 100;
29pub const MAX_BAR: f32 = 100.0;
30const BAR_DAMAGE: std::ops::RangeInclusive<i32> = 70..=230;
32const BAR_HEAL: std::ops::RangeInclusive<i32> = 100..=300;
33const MOVING_VALUES: usize = 64;
35const MOVING_INTERVAL: Duration = Duration::from_millis(100);
36const DAMAGE: std::ops::RangeInclusive<i32> = 7..=23;
37const HEAL: std::ops::RangeInclusive<i32> = 10..=30;
38const DECOYS: usize = 3 * MAX_HEALTH as usize;
40const RESPONSE_TIMEOUT: Duration = Duration::from_secs(3);
41
42struct Rng(u64);
43
44impl Rng {
45 fn seeded() -> Self {
46 let nanos = std::time::SystemTime::now()
47 .duration_since(std::time::UNIX_EPOCH)
48 .map_or(0, |duration| duration.as_nanos() as u64);
49 Self((nanos ^ u64::from(std::process::id()).rotate_left(32)) | 1)
50 }
51
52 fn range(&mut self, range: std::ops::RangeInclusive<i32>) -> i32 {
53 self.0 ^= self.0 << 13;
55 self.0 ^= self.0 >> 7;
56 self.0 ^= self.0 << 17;
57 let span = (range.end() - range.start() + 1) as u64;
58 range.start() + (self.0 % span) as i32
59 }
60}
61
62pub fn damaged(health: i32, amount: i32) -> i32 {
64 let health = health.saturating_sub(amount);
65 if health <= 0 { MAX_HEALTH } else { health }
66}
67
68pub fn healed(health: i32, amount: i32) -> i32 {
70 if health >= MAX_HEALTH { health } else { (health + amount).min(MAX_HEALTH) }
71}
72
73pub fn bar_damaged(health: f32, amount: f32) -> f32 {
76 let health = health - amount;
77 if !health.is_finite() || health <= 0.0 { MAX_BAR } else { health }
78}
79
80pub fn bar_healed(health: f32, amount: f32) -> f32 {
81 if !health.is_finite() {
82 MAX_BAR
83 } else if health >= MAX_BAR {
84 health
85 } else {
86 (health.max(0.0) + amount).min(MAX_BAR)
87 }
88}
89
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
91pub enum Lesson {
92 #[default]
94 KnownValue,
95 HealthBar,
97}
98
99struct Game {
100 health: AtomicI32,
101 hud: AtomicI32,
102 changes: u32,
103 rng: Rng,
104}
105
106impl Game {
107 #[inline(never)]
109 fn apply(&mut self, command: &str) -> bool {
110 let current = self.health.load(Ordering::SeqCst);
111 let next = match command {
112 "damage" => damaged(current, self.rng.range(DAMAGE)),
113 "heal" => healed(current, self.rng.range(HEAL)),
114 _ => return false,
115 };
116 if next != current {
117 self.health.store(next, Ordering::SeqCst);
118 self.changes += 1;
119 if self.changes % 2 == 1 {
121 self.hud.store(next, Ordering::SeqCst);
122 }
123 }
124 true
125 }
126}
127
128#[inline(never)]
131fn scrub_stack() {
132 std::hint::black_box(&mut [0_u8; 16 * 1024]);
133}
134
135struct Bar {
138 health: AtomicU32,
139}
140
141impl Bar {
142 #[inline(never)]
143 fn apply(&self, command: &str) -> bool {
144 let mut rng = Rng::seeded();
146 let current = f32::from_bits(self.health.load(Ordering::SeqCst));
147 let next = match command {
148 "damage" => bar_damaged(current, rng.range(BAR_DAMAGE) as f32 / 10.0),
149 "heal" => bar_healed(current, rng.range(BAR_HEAL) as f32 / 10.0),
150 _ => return false,
151 };
152 self.health.store(next.to_bits(), Ordering::SeqCst);
153 true
154 }
155}
156
157fn spawn_moving_values() {
160 let values: &'static [AtomicU32; MOVING_VALUES] = Box::leak(Box::new(std::array::from_fn(|index| {
161 let start = (index as f32 * 1.5) % MAX_BAR + 1.0;
162 AtomicU32::new(if index % 2 == 0 { start.to_bits() } else { start as u32 })
163 })));
164 std::thread::spawn(move || {
165 let mut rng = Rng::seeded();
166 loop {
167 for (index, value) in values.iter().enumerate() {
168 let step = rng.range(1..=40) * if rng.range(0..=1) == 0 { -1 } else { 1 };
169 let old = value.load(Ordering::Relaxed);
170 let new = if index % 2 == 0 {
171 let moved = f32::from_bits(old) + step as f32 / 8.0;
172 (if (1.0..MAX_BAR).contains(&moved) {
173 moved
174 } else {
175 f32::from_bits(old) - step as f32 / 8.0
176 })
177 .to_bits()
178 } else {
179 let moved = old as i32 + step;
180 (if (1..10_000).contains(&moved) { moved } else { old as i32 - step }) as u32
181 };
182 value.store(new, Ordering::Relaxed);
183 }
184 std::thread::sleep(MOVING_INTERVAL);
185 }
186 });
187}
188
189pub fn run_target(lesson: Lesson) -> io::Result<()> {
191 let mut output = io::stdout().lock();
192 match lesson {
193 Lesson::KnownValue => {
194 let mut game = Box::new(Game {
195 health: AtomicI32::new(MAX_HEALTH),
196 hud: AtomicI32::new(MAX_HEALTH),
197 changes: 0,
198 rng: Rng::seeded(),
199 });
200 let decoys = Box::new(std::array::from_fn::<_, DECOYS, _>(|index| AtomicI32::new(index as i32 % MAX_HEALTH + 1)));
201 writeln!(output, "{:X} {:X}", game.health.as_ptr() as usize, game.hud.as_ptr() as usize)?;
202 serve(&mut output, |command| game.apply(command))?;
203 std::hint::black_box(&decoys);
204 }
205 Lesson::HealthBar => {
206 let bar = Box::new(Bar {
207 health: AtomicU32::new(MAX_BAR.to_bits()),
208 });
209 spawn_moving_values();
210 writeln!(output, "{:X} 0", bar.health.as_ptr() as usize)?;
211 serve(&mut output, |command| bar.apply(command))?;
212 }
213 }
214 Ok(())
215}
216
217fn serve(output: &mut impl Write, mut apply: impl FnMut(&str) -> bool) -> io::Result<()> {
218 output.flush()?;
219 for line in io::stdin().lock().lines() {
220 let known = apply(&line?);
221 scrub_stack();
222 if !known {
223 return Err(io::Error::new(io::ErrorKind::InvalidInput, "Unknown tutorial command"));
224 }
225 writeln!(output, "ok")?;
226 output.flush()?;
227 }
228 Ok(())
229}
230
231fn rseq_disabled(tunables: &str) -> String {
232 let kept = tunables
233 .split(':')
234 .filter(|tunable| !tunable.is_empty() && !tunable.starts_with("glibc.pthread.rseq="));
235 kept.chain(["glibc.pthread.rseq=0"]).collect::<Vec<_>>().join(":")
236}
237
238pub struct TutorialProcess {
240 lesson: Lesson,
241 child: Child,
242 responses: Receiver<Result<String, String>>,
243 pid: process_memory::Pid,
244 health_address: usize,
245 hud_address: usize,
247}
248
249impl TutorialProcess {
250 pub fn spawn(executable: &Path, lesson: Lesson) -> Result<Self, String> {
251 let mut command = Command::new(executable);
252 command.arg(TARGET_ARGUMENT);
253 if lesson == Lesson::HealthBar {
254 command.arg(HEALTH_BAR_ARGUMENT);
255 }
256 if cfg!(target_os = "linux") {
260 let tunables = std::env::var("GLIBC_TUNABLES").unwrap_or_default();
261 command.env("GLIBC_TUNABLES", rseq_disabled(&tunables));
262 }
263 let mut child = command
264 .stdin(Stdio::piped())
265 .stdout(Stdio::piped())
266 .stderr(Stdio::inherit())
267 .spawn()
268 .map_err(|error| error.to_string())?;
269 let output = child.stdout.take().expect("piped tutorial stdout");
270 let (sender, responses) = unbounded();
271 std::thread::spawn(move || {
272 for line in BufReader::new(output).lines() {
273 if sender.send(line.map_err(|error| error.to_string())).is_err() {
274 break;
275 }
276 }
277 });
278 let mut target = Self {
280 lesson,
281 child,
282 responses,
283 pid: 0,
284 health_address: 0,
285 hud_address: 0,
286 };
287 target.pid = process_memory::Pid::try_from(target.child.id()).map_err(|error| error.to_string())?;
288 let response = target.response()?;
289 let mut addresses = response.split_whitespace().map(|text| usize::from_str_radix(text, 16));
290 match (addresses.next(), addresses.next()) {
291 (Some(Ok(health)), Some(Ok(hud))) if health != 0 && (hud != 0 || lesson == Lesson::HealthBar) => {
292 target.health_address = health;
293 target.hud_address = hud;
294 Ok(target)
295 }
296 _ => Err(format!("Unexpected tutorial handshake: {response}")),
297 }
298 }
299
300 fn response(&self) -> Result<String, String> {
301 self.responses.recv_timeout(RESPONSE_TIMEOUT).map_err(|error| error.to_string())?
302 }
303
304 pub fn lesson(&self) -> Lesson {
305 self.lesson
306 }
307
308 pub fn pid(&self) -> process_memory::Pid {
309 self.pid
310 }
311
312 pub fn health_address(&self) -> usize {
313 self.health_address
314 }
315
316 pub fn hud_address(&self) -> Option<usize> {
318 (self.hud_address != 0).then_some(self.hud_address)
319 }
320
321 fn read(&self, address: usize) -> Result<[u8; 4], String> {
322 let handle = self.pid.try_into_process_handle().map_err(|error| error.to_string())?;
323 let bytes = copy_address(address, 4, &crate::state::memory_reader::ExactProcessReader(&handle)).map_err(|error| error.to_string())?;
324 bytes.try_into().map_err(|_| "Incomplete tutorial read".to_owned())
325 }
326
327 pub fn health(&self) -> Result<f32, String> {
329 let bytes = self.read(self.health_address)?;
330 Ok(match self.lesson {
331 Lesson::KnownValue => i32::from_ne_bytes(bytes) as f32,
332 Lesson::HealthBar => f32::from_ne_bytes(bytes),
333 })
334 }
335
336 pub fn hud(&self) -> Result<Option<f32>, String> {
337 self.hud_address()
338 .map(|address| self.read(address).map(|bytes| i32::from_ne_bytes(bytes) as f32))
339 .transpose()
340 }
341
342 fn command(&mut self, command: &[u8]) -> Result<(), String> {
344 let input = self.child.stdin.as_mut().ok_or("Tutorial input is closed")?;
345 input.write_all(command).and_then(|()| input.flush()).map_err(|error| error.to_string())?;
346 if self.response()? != "ok" {
347 return Err("Unexpected tutorial response".into());
348 }
349 Ok(())
350 }
351
352 pub fn damage(&mut self) -> Result<(), String> {
353 self.command(b"damage\n")
354 }
355
356 pub fn heal(&mut self) -> Result<(), String> {
357 self.command(b"heal\n")
358 }
359}
360
361impl Drop for TutorialProcess {
362 fn drop(&mut self) {
363 match self.child.try_wait() {
364 Ok(Some(_)) => return,
365 Ok(None) => {
366 if let Err(error) = self.child.kill() {
367 eprintln!("Failed to stop tutorial target: {error}");
368 }
369 }
370 Err(error) => eprintln!("Failed to check tutorial target: {error}"),
371 }
372 if let Err(error) = self.child.wait() {
373 eprintln!("Failed to reap tutorial target: {error}");
374 }
375 }
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 #[test]
383 fn rseq_is_disabled_without_dropping_other_tunables() {
384 assert_eq!(rseq_disabled(""), "glibc.pthread.rseq=0");
385 assert_eq!(
386 rseq_disabled("glibc.malloc.check=3:glibc.pthread.rseq=1"),
387 "glibc.malloc.check=3:glibc.pthread.rseq=0"
388 );
389 }
390
391 #[test]
392 fn health_rules_always_change_damage_and_cap_potions() {
393 assert_eq!(damaged(100, 23), 77);
394 assert_eq!(damaged(5, 7), MAX_HEALTH, "an empty health bar respawns");
395 assert_eq!(healed(90, 30), MAX_HEALTH);
396 assert_eq!(healed(MAX_HEALTH, 10), MAX_HEALTH);
397 assert_eq!(healed(999, 10), 999, "potions never lower edited health");
398 let mut rng = Rng(1);
399 for _ in 0..1000 {
400 assert!(DAMAGE.contains(&rng.range(DAMAGE)));
401 assert!(HEAL.contains(&rng.range(HEAL)));
402 }
403 }
404
405 #[test]
406 fn bar_rules_repair_garbage_and_never_lower_boosted_health() {
407 assert_eq!(bar_damaged(50.5, 7.0), 43.5);
408 assert_eq!(bar_damaged(5.0, 7.0), MAX_BAR);
409 assert_eq!(bar_damaged(f32::NAN, 7.0), MAX_BAR);
410 assert_eq!(bar_healed(95.0, 10.0), MAX_BAR);
411 assert_eq!(bar_healed(500.0, 10.0), 500.0);
412 assert_eq!(bar_healed(f32::INFINITY, 10.0), MAX_BAR);
413 assert_eq!(bar_healed(-3.0, 10.0), 10.0);
414 }
415}