1#![deny(missing_docs)]
17
18use crate::ecosystem::{Ecosystem, GameProfile, InstanceType, LoaderKind};
19use crate::error::{Error, Result};
20use std::path::{Path, PathBuf};
21
22mod prepare;
23
24pub use prepare::{LaunchNotice, prepare_plan_from};
25#[cfg(feature = "io")]
26pub use prepare::{PreparedLaunch, prepare_launch};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum HostOs {
32 Windows,
34 Linux,
37 MacOs,
41}
42
43impl HostOs {
44 pub fn detect() -> Option<Self> {
50 if cfg!(target_os = "windows") {
51 Some(Self::Windows)
52 } else if cfg!(target_os = "linux") {
53 Some(Self::Linux)
54 } else if cfg!(target_os = "macos") {
55 Some(Self::MacOs)
56 } else {
57 None
58 }
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum StorePlatform {
66 Steam,
68 SteamDirect,
70 Other,
72}
73
74impl std::str::FromStr for StorePlatform {
75 type Err = Error;
76
77 fn from_str(value: &str) -> Result<Self> {
79 match value {
80 "steam" => Ok(Self::Steam),
81 "steam-direct" => Ok(Self::SteamDirect),
82 "other" => Ok(Self::Other),
83 other => Err(Error::Profile(format!(
84 "{other:?} is not a known store platform; expected steam, steam-direct, \
85 or other"
86 ))),
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum Runtime {
95 Native,
97 Proton,
100}
101
102impl std::str::FromStr for Runtime {
103 type Err = Error;
104
105 fn from_str(value: &str) -> Result<Self> {
107 match value {
108 "native" => Ok(Self::Native),
109 "proton" => Ok(Self::Proton),
110 other => Err(Error::Profile(format!(
111 "{other:?} is not a known runtime; expected native or proton"
112 ))),
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum LaunchMode {
121 Modded,
123 Vanilla,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum LaunchProgram {
137 GameExe {
140 exe_names: Vec<String>,
142 },
143 Steam {
145 steam_app_id: u32,
147 },
148 ProfileScript {
153 path: PathBuf,
155 exe_names: Vec<String>,
158 },
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
177#[non_exhaustive]
178pub struct SteamWrapper {
179 pub target_dir: PathBuf,
183 pub loader: LoaderKind,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq)]
195#[non_exhaustive]
196pub struct LaunchPlan {
197 pub program: LaunchProgram,
199 pub args: Vec<String>,
201 pub env: Vec<(String, String)>,
214 pub working_dir: Option<PathBuf>,
216 pub steam_wrapper: Option<SteamWrapper>,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub struct LaunchContext {
227 pub os: HostOs,
230 pub store: StorePlatform,
233 pub runtime: Runtime,
236 pub mode: LaunchMode,
238 pub extra_args: Vec<String>,
240}
241
242impl LaunchContext {
243 pub fn new(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> Self {
252 Self {
253 os,
254 store,
255 runtime,
256 mode,
257 extra_args: Vec::new(),
258 }
259 }
260
261 pub fn with_extra_args(self, extra_args: Vec<String>) -> Self {
263 Self { extra_args, ..self }
264 }
265}
266
267pub const PRELOADER_CANDIDATES: [&str; 5] = [
270 "BepInEx.Unity.Mono.Preloader.dll",
271 "BepInEx.Unity.IL2CPP.dll",
272 "BepInEx.Preloader.dll",
273 "BepInEx.IL2CPP.dll",
274 "BepInEx.NET.CoreCLR.dll",
275];
276
277pub const LOADER_SCRIPTS: [&str; 3] = [
287 "start_server_bepinex.sh",
288 "run_bepinex.sh",
289 "start_game_bepinex.sh",
290];
291
292const SERVER_SCRIPT: &str = LOADER_SCRIPTS[0];
294
295const MACOS_UNSUPPORTED: &str =
298 "macOS launch is not supported: the injection chain requires r2modman's closed-source proxy";
299
300#[derive(Debug, Clone, PartialEq, Eq)]
321#[non_exhaustive]
322pub struct LaunchFacts {
323 pub doorstop_version: u32,
327 pub preloader: Option<String>,
330 pub has_corlibs: bool,
333 pub loader_scripts: Vec<String>,
335 pub melonloader_assemblies: bool,
339 pub loaders: Vec<LoaderKind>,
342 pub recorded: Vec<String>,
345}
346
347impl Default for LaunchFacts {
348 fn default() -> Self {
349 Self {
350 doorstop_version: 3,
351 preloader: None,
352 has_corlibs: false,
353 loader_scripts: Vec::new(),
354 melonloader_assemblies: false,
355 loaders: Vec::new(),
356 recorded: Vec::new(),
357 }
358 }
359}
360
361const MELONLOADER_FILES: [&str; 4] = [
363 "MelonLoader/MelonLoader.dll",
364 "MelonLoader/net35/MelonLoader.dll",
365 "MelonLoader/net472/MelonLoader.dll",
366 "MelonLoader/net6/MelonLoader.dll",
367];
368
369pub const LOADER_FILES: [(LoaderKind, &[&str]); 7] = [
376 (LoaderKind::Umm, &["UMM/Core/UnityModManager.dll"]),
377 (LoaderKind::MelonLoader, &MELONLOADER_FILES),
378 (LoaderKind::RecursiveMelonLoader, &MELONLOADER_FILES),
379 (
380 LoaderKind::GdWeave,
381 &["GDWeave/core/GDWeave.dll", "winmm.dll"],
382 ),
383 (
384 LoaderKind::Northstar,
385 &["R2Northstar/Northstar.dll", "NorthstarLauncher.exe"],
386 ),
387 (LoaderKind::Rivet, &["Rivet/Loader.dll"]),
388 (LoaderKind::Shimloader, &["dwmapi.dll", "ue4ss.dll"]),
389];
390
391#[cfg(feature = "io")]
392impl LaunchFacts {
393 pub fn read(target_dir: &Path) -> Self {
396 let loader_scripts = LOADER_SCRIPTS
397 .iter()
398 .filter(|name| target_dir.join(name).is_file())
399 .map(|name| name.to_string())
400 .collect();
401 let melonloader_assemblies = target_dir
402 .join("MelonLoader/Managed/Assembly-CSharp.dll")
403 .is_file()
404 || target_dir
405 .join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll")
406 .is_file();
407 let loaders = LOADER_FILES
408 .iter()
409 .filter(|(_, files)| files.iter().any(|file| target_dir.join(file).is_file()))
410 .map(|(loader, _)| *loader)
411 .collect();
412 let recorded = crate::profile::modlist::read(target_dir)
413 .map(|mods| mods.into_iter().map(|entry| entry.name).collect())
414 .unwrap_or_default();
415
416 Self {
417 doorstop_version: doorstop_version(target_dir),
418 preloader: find_preloader(target_dir),
419 has_corlibs: has_corlibs(target_dir),
420 loader_scripts,
421 melonloader_assemblies,
422 loaders,
423 recorded,
424 }
425 }
426}
427
428#[cfg(feature = "io")]
435pub fn doorstop_version(target_dir: &Path) -> u32 {
436 let path = target_dir.join(".doorstop_version");
437
438 let text = match std::fs::read_to_string(&path) {
439 Ok(text) => text,
440 Err(_) => return 3,
441 };
442
443 let major = text
444 .trim()
445 .split('.')
446 .next()
447 .and_then(|part| part.parse::<u32>().ok());
448
449 match major {
450 Some(version) if version >= 3 => version,
451 _ => 3,
452 }
453}
454
455fn wine_path(path: &Path) -> String {
457 format!("Z:{}", path.to_string_lossy().replace('\\', "/"))
458}
459
460#[cfg(feature = "io")]
465pub fn bepinex_preloader(target_dir: &Path, runtime: Runtime) -> Result<String> {
466 render_preloader(target_dir, find_preloader(target_dir).as_deref(), runtime)
467}
468
469#[cfg(feature = "io")]
471fn find_preloader(target_dir: &Path) -> Option<String> {
472 let core = target_dir.join("BepInEx").join("core");
473
474 PRELOADER_CANDIDATES
475 .iter()
476 .find(|name| core.join(name).is_file())
477 .map(|name| name.to_string())
478}
479
480fn render_preloader(
483 target_dir: &Path,
484 preloader: Option<&str>,
485 runtime: Runtime,
486) -> Result<String> {
487 let core = target_dir.join("BepInEx").join("core");
488
489 let found = preloader
490 .map(|name| core.join(name))
491 .ok_or_else(|| Error::Profile(format!("no BepInEx preloader found in {}", core.display())))?;
492
493 let rendered = match runtime {
494 Runtime::Proton => wine_path(&found),
495 Runtime::Native => found.to_string_lossy().replace('\\', "/"),
496 };
497
498 Ok(rendered)
499}
500
501#[cfg(feature = "io")]
504pub fn has_corlibs(target_dir: &Path) -> bool {
505 target_dir.join("unstripped_corlib").is_dir()
506}
507
508fn arg_path(target_dir: &Path, relative: &str) -> String {
511 target_dir
512 .join(relative)
513 .to_string_lossy()
514 .replace('\\', "/")
515}
516
517#[cfg(feature = "io")]
523pub fn loader_args(
524 target_dir: &Path,
525 profile: &GameProfile,
526 ctx: &LaunchContext,
527) -> Result<Vec<String>> {
528 loader_args_from(target_dir, &LaunchFacts::read(target_dir), profile, ctx)
529}
530
531pub fn loader_args_from(
546 target_dir: &Path,
547 facts: &LaunchFacts,
548 profile: &GameProfile,
549 ctx: &LaunchContext,
550) -> Result<Vec<String>> {
551 let target = target_dir.to_string_lossy().replace('\\', "/");
552
553 let args = match profile.package_loader {
554 LoaderKind::BepInEx => {
555 let script_injected = is_script_injected(target_dir, facts, profile, ctx);
556
557 doorstop_args(
558 target_dir,
559 facts,
560 profile,
561 ctx,
562 DoorstopTarget::BepInEx,
563 script_injected,
564 )?
565 }
566 LoaderKind::BepisLoader => bepis_args(target_dir, facts, profile, ctx)?,
567 LoaderKind::Umm => {
568 let script_injected = is_script_injected(target_dir, facts, profile, ctx);
569
570 doorstop_args(
571 target_dir,
572 facts,
573 profile,
574 ctx,
575 DoorstopTarget::Umm,
576 script_injected,
577 )?
578 }
579 LoaderKind::MelonLoader | LoaderKind::RecursiveMelonLoader => {
580 melonloader_args(facts, ctx, &target)
581 }
582 LoaderKind::GdWeave => match ctx.mode {
583 LaunchMode::Modded => vec![format!(
584 "--gdweave-folder-override={}",
585 arg_path(target_dir, "GDWeave")
586 )],
587 LaunchMode::Vanilla => vec!["--gdweave-disable".to_string()],
588 },
589 LoaderKind::Lovely => match ctx.mode {
590 LaunchMode::Modded => vec!["--mod-dir".to_string(), arg_path(target_dir, "mods")],
591 LaunchMode::Vanilla => vec!["--vanilla".to_string()],
592 },
593 LoaderKind::Northstar => match ctx.mode {
594 LaunchMode::Modded => vec![
595 "-northstar".to_string(),
596 format!("-profile={}", arg_path(target_dir, "R2Northstar")),
597 ],
598 LaunchMode::Vanilla => vec!["-vanilla".to_string()],
599 },
600 LoaderKind::GodotMl => match ctx.mode {
601 LaunchMode::Modded => vec![
602 "--script".to_string(),
603 "res://addons/mod_loader/mod_loader_setup.gd".to_string(),
604 "--enable-mods".to_string(),
605 "--mods-path".to_string(),
606 arg_path(target_dir, "mods"),
607 ],
608 LaunchMode::Vanilla => Vec::new(),
609 },
610 LoaderKind::Shimloader => match ctx.mode {
611 LaunchMode::Modded => vec![
612 "--mod-dir".to_string(),
613 arg_path(target_dir, "shimloader/mod"),
614 "--pak-dir".to_string(),
615 arg_path(target_dir, "shimloader/pak"),
616 "--cfg-dir".to_string(),
617 arg_path(target_dir, "shimloader/cfg"),
618 "--overlay-dir".to_string(),
619 arg_path(target_dir, "shimloader/overlay"),
620 ],
621 LaunchMode::Vanilla => Vec::new(),
622 },
623 LoaderKind::ReturnOfModding => match ctx.mode {
624 LaunchMode::Modded => vec!["--rom_modding_root_folder".to_string(), target.clone()],
625 LaunchMode::Vanilla => vec!["--rom_enabled".to_string(), "false".to_string()],
626 },
627 LoaderKind::Rivet => match ctx.mode {
628 LaunchMode::Modded => vec![
629 "-rivetEnable".to_string(),
630 "true".to_string(),
631 "-rivetTarget".to_string(),
632 arg_path(target_dir, "Rivet/Loader.dll"),
633 "-rivetDirectory".to_string(),
634 arg_path(target_dir, "Rivet/Mods"),
635 ],
636 LaunchMode::Vanilla => vec!["-rivetEnable".to_string(), "false".to_string()],
637 },
638 _ => Vec::new(),
641 };
642
643 Ok(args)
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648enum DoorstopTarget {
649 BepInEx,
650 Umm,
651}
652
653fn doorstop_args(
677 target_dir: &Path,
678 facts: &LaunchFacts,
679 profile: &GameProfile,
680 ctx: &LaunchContext,
681 target: DoorstopTarget,
682 script_injected: bool,
683) -> Result<Vec<String>> {
684 let v4 = script_injected || facts.doorstop_version >= 4;
685
686 let (enable_flag, target_flag, search_flag) = if v4 {
687 (
688 "--doorstop-enabled",
689 "--doorstop-target-assembly",
690 "--doorstop-mono-dll-search-path-override",
691 )
692 } else {
693 (
694 "--doorstop-enable",
695 "--doorstop-target",
696 "--doorstop-dll-search-override",
697 )
698 };
699
700 if ctx.mode == LaunchMode::Vanilla {
701 return Ok(vec![enable_flag.to_string(), "false".to_string()]);
702 }
703
704 let assembly = match target {
705 DoorstopTarget::BepInEx => {
706 render_preloader(target_dir, facts.preloader.as_deref(), ctx.runtime)?
707 }
708 DoorstopTarget::Umm => arg_path(target_dir, "UMM/Core/UnityModManager.dll"),
709 };
710
711 let mut args = vec![
712 enable_flag.to_string(),
713 "true".to_string(),
714 target_flag.to_string(),
715 assembly,
716 ];
717
718 if target == DoorstopTarget::BepInEx && profile.instance_type == InstanceType::Server {
719 args.push("--server".to_string());
720 }
721
722 if facts.has_corlibs {
723 args.push(search_flag.to_string());
724 args.push(arg_path(target_dir, "unstripped_corlib"));
725 }
726
727 Ok(args)
728}
729
730fn bepis_args(
732 target_dir: &Path,
733 facts: &LaunchFacts,
734 profile: &GameProfile,
735 ctx: &LaunchContext,
736) -> Result<Vec<String>> {
737 if ctx.mode == LaunchMode::Vanilla {
738 return Ok(vec![
739 "--hookfxr-disable".to_string(),
740 "--doorstop-enabled".to_string(),
741 "false".to_string(),
742 ]);
743 }
744
745 let mut args = vec![
746 "--hookfxr-enable".to_string(),
747 "--bepinex-target".to_string(),
748 arg_path(target_dir, "BepInEx"),
749 "--doorstop-enabled".to_string(),
750 "true".to_string(),
751 "--doorstop-target-assembly".to_string(),
752 render_preloader(target_dir, facts.preloader.as_deref(), ctx.runtime)?,
753 ];
754
755 if profile.instance_type == InstanceType::Server {
756 args.push("--server".to_string());
757 }
758
759 if facts.has_corlibs {
760 args.push("--doorstop-mono-dll-search-path-override".to_string());
761 args.push(arg_path(target_dir, "unstripped_corlib"));
762 }
763
764 Ok(args)
765}
766
767fn melonloader_args(facts: &LaunchFacts, ctx: &LaunchContext, target: &str) -> Vec<String> {
770 if ctx.mode == LaunchMode::Vanilla {
771 return vec!["--no-mods".to_string()];
772 }
773
774 let mut args = vec!["--melonloader.basedir".to_string(), target.to_string()];
775
776 if !facts.melonloader_assemblies {
777 args.push("--melonloader.agfregenerate".to_string());
778 }
779
780 args
781}
782
783pub fn proxy_dll(loader: LoaderKind) -> &'static str {
785 match loader {
786 LoaderKind::GdWeave => "winmm",
787 _ => "winhttp",
788 }
789}
790
791#[derive(Debug, Clone, PartialEq, Eq)]
797enum ScriptInjection {
798 NotApplicable,
801 Found(PathBuf),
803 Missing,
805}
806
807impl ScriptInjection {
808 fn applies(&self) -> bool {
813 !matches!(self, Self::NotApplicable)
814 }
815}
816
817fn script_candidates(profile: &GameProfile) -> Vec<&'static str> {
819 match profile.instance_type {
820 InstanceType::Server => LOADER_SCRIPTS.to_vec(),
821 _ => LOADER_SCRIPTS
822 .iter()
823 .copied()
824 .filter(|name| *name != SERVER_SCRIPT)
825 .collect(),
826 }
827}
828
829fn script_injection(
837 target_dir: &Path,
838 facts: &LaunchFacts,
839 profile: &GameProfile,
840 ctx: &LaunchContext,
841) -> ScriptInjection {
842 if !script_injection_applies(profile, ctx) {
843 return ScriptInjection::NotApplicable;
844 }
845
846 let found = script_candidates(profile)
847 .into_iter()
848 .find(|name| facts.loader_scripts.iter().any(|present| present == name));
849
850 match found {
851 Some(name) => ScriptInjection::Found(target_dir.join(name)),
852 None => ScriptInjection::Missing,
853 }
854}
855
856fn script_injection_applies(profile: &GameProfile, ctx: &LaunchContext) -> bool {
859 let script_loader = matches!(
860 profile.package_loader,
861 LoaderKind::BepInEx | LoaderKind::BepisLoader
862 );
863
864 script_loader && ctx.os == HostOs::Linux && ctx.runtime == Runtime::Native
865}
866
867fn is_script_injected(
877 target_dir: &Path,
878 facts: &LaunchFacts,
879 profile: &GameProfile,
880 ctx: &LaunchContext,
881) -> bool {
882 matches!(
883 script_injection(target_dir, facts, profile, ctx),
884 ScriptInjection::Found(_)
885 )
886}
887
888#[cfg(feature = "io")]
947pub fn launch_plan_in(
948 target_dir: &Path,
949 eco: &Ecosystem,
950 game: &str,
951 ctx: &LaunchContext,
952) -> Result<LaunchPlan> {
953 launch_plan_from(target_dir, &LaunchFacts::read(target_dir), eco, game, ctx)
954}
955
956pub fn launch_plan_from(
991 target_dir: &Path,
992 facts: &LaunchFacts,
993 eco: &Ecosystem,
994 game: &str,
995 ctx: &LaunchContext,
996) -> Result<LaunchPlan> {
997 if ctx.os == HostOs::MacOs {
998 return Err(Error::Profile(MACOS_UNSUPPORTED.to_string()));
999 }
1000
1001 let profile = eco.require_profile(game)?;
1002
1003 let injection = script_injection(target_dir, facts, profile, ctx);
1007 let mut args = loader_args_from(target_dir, facts, profile, ctx)?;
1008
1009 args.extend(ctx.extra_args.iter().cloned());
1010
1011 let program = resolve_program(&injection, target_dir, profile, ctx)?;
1012 let needs_wrapper = injection.applies() && ctx.store == StorePlatform::Steam;
1013
1014 if needs_wrapper {
1019 args.extend(wrapper_target_args(target_dir));
1020 }
1021
1022 let steam_wrapper = needs_wrapper.then(|| SteamWrapper {
1023 target_dir: target_dir.to_path_buf(),
1024 loader: profile.package_loader,
1025 });
1026
1027 let mut env = Vec::new();
1028
1029 if ctx.runtime == Runtime::Proton {
1030 env.push((
1031 WINE_DLL_OVERRIDES.to_string(),
1032 format!("{}=n,b", proxy_dll(profile.package_loader)),
1033 ));
1034 }
1035
1036 Ok(LaunchPlan {
1037 program,
1038 args,
1039 env,
1040 working_dir: None,
1041 steam_wrapper,
1042 })
1043}
1044
1045fn resolve_program(
1051 injection: &ScriptInjection,
1052 target_dir: &Path,
1053 profile: &GameProfile,
1054 ctx: &LaunchContext,
1055) -> Result<LaunchProgram> {
1056 if *injection == ScriptInjection::Missing && ctx.mode == LaunchMode::Modded {
1057 return Err(Error::Profile(format!(
1058 "modded launch injects through a loader script, but none of {} exist in {}",
1059 script_candidates(profile).join(", "),
1060 target_dir.display(),
1061 )));
1062 }
1063
1064 if let ScriptInjection::Found(path) = injection
1065 && ctx.store != StorePlatform::Steam
1066 {
1067 return Ok(LaunchProgram::ProfileScript {
1068 path: path.clone(),
1069 exe_names: profile.exe_names.clone(),
1070 });
1071 }
1072
1073 if ctx.store == StorePlatform::Steam {
1074 let steam_app_id = profile.steam_app_id().ok_or_else(|| {
1075 Error::Profile("Steam launch requested but the game has no Steam app id".to_string())
1076 })?;
1077
1078 return Ok(LaunchProgram::Steam { steam_app_id });
1079 }
1080
1081 Ok(LaunchProgram::GameExe {
1082 exe_names: profile.exe_names.clone(),
1083 })
1084}
1085
1086#[cfg(feature = "io")]
1089pub fn launch_plan(
1090 base: &Path,
1091 game: &str,
1092 profile_name: &str,
1093 eco: &Ecosystem,
1094 ctx: &LaunchContext,
1095) -> Result<LaunchPlan> {
1096 launch_plan_in(
1097 &crate::profile::layout::profile_dir(base, game, profile_name),
1098 eco,
1099 game,
1100 ctx,
1101 )
1102}
1103
1104pub const WRAPPER_TARGET_FLAG: &str = "--ts-target";
1110
1111pub fn wrapper_target_args(target_dir: &Path) -> Vec<String> {
1118 vec![
1119 WRAPPER_TARGET_FLAG.to_string(),
1120 target_dir.to_string_lossy().replace('\\', "/"),
1121 ]
1122}
1123
1124pub fn wrapper_script_contents() -> String {
1158 let mut branches = String::new();
1159
1160 for (index, name) in LOADER_SCRIPTS.iter().enumerate() {
1161 let keyword = if index == 0 { "if" } else { "elif" };
1162 let server_gate = if *name == SERVER_SCRIPT {
1165 r#" && [ -n "$TS_START_SERVER" ]"#
1166 } else {
1167 ""
1168 };
1169
1170 branches.push_str(&format!(
1171 "{keyword} [ -f \"$TARGET/{name}\" ]{server_gate}; then\n exec \"$TARGET/{name}\" \"$@\"\n"
1172 ));
1173 }
1174
1175 format!(
1182 r#"#!/bin/sh
1183# Generated by thunderstore-engine. Chainloads the mod loader for a target.
1184#
1185# Paste this into Steam's launch options once; it never needs regenerating, and
1186# it names no profile. The target directory is read from
1187# `{WRAPPER_TARGET_FLAG} <dir>` when a manager appends it to the launch
1188# arguments. Without it — launching straight from Steam — the game starts
1189# unmodded. The flag is consumed here and never reaches the game.
1190TARGET=""
1191
1192remaining=$#
1193
1194while [ "$remaining" -gt 0 ]; do
1195 argument="$1"
1196 shift
1197 remaining=$((remaining - 1))
1198
1199 if [ "$argument" = "{WRAPPER_TARGET_FLAG}" ]; then
1200 if [ "$remaining" -gt 0 ]; then
1201 candidate="$1"
1202 shift
1203 remaining=$((remaining - 1))
1204
1205 if [ -d "$candidate" ]; then
1206 TARGET="$candidate"
1207 fi
1208 fi
1209
1210 continue
1211 fi
1212
1213 set -- "$@" "$argument"
1214done
1215
1216if [ -z "$TARGET" ]; then
1217 exec "$@"
1218fi
1219
1220{branches}else
1221 exec "$@"
1222fi
1223"#
1224 )
1225}
1226
1227#[cfg(feature = "io")]
1233pub fn write_wrapper_script(script_path: &Path) -> Result<()> {
1234 if let Some(parent) = script_path.parent() {
1235 std::fs::create_dir_all(parent)
1236 .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
1237 }
1238
1239 std::fs::write(script_path, wrapper_script_contents())
1240 .map_err(|e| Error::Profile(format!("writing {}: {}", script_path.display(), e)))?;
1241
1242 #[cfg(unix)]
1243 {
1244 use std::os::unix::fs::PermissionsExt;
1245
1246 let permissions = std::fs::Permissions::from_mode(0o755);
1247
1248 std::fs::set_permissions(script_path, permissions)
1249 .map_err(|e| Error::Profile(format!("chmod {}: {}", script_path.display(), e)))?;
1250 }
1251
1252 Ok(())
1253}
1254
1255#[cfg(feature = "io")]
1279pub fn ensure_loader_scripts_executable(target_dir: &Path) -> Result<Vec<PathBuf>> {
1280 let mut changed = Vec::new();
1281
1282 for name in LOADER_SCRIPTS {
1283 let path = target_dir.join(name);
1284
1285 if !path.is_file() {
1286 continue;
1287 }
1288
1289 if make_executable(&path)? {
1290 changed.push(path);
1291 }
1292 }
1293
1294 Ok(changed)
1295}
1296
1297#[cfg(feature = "io")]
1305fn make_executable(path: &Path) -> Result<bool> {
1306 #[cfg(unix)]
1307 {
1308 use std::os::unix::fs::PermissionsExt;
1309
1310 let metadata = std::fs::metadata(path)
1311 .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
1312 let mode = metadata.permissions().mode();
1313 let wanted = mode | ((mode & 0o444) >> 2);
1314
1315 if wanted == mode {
1316 return Ok(false);
1317 }
1318
1319 std::fs::set_permissions(path, std::fs::Permissions::from_mode(wanted))
1320 .map_err(|e| Error::Profile(format!("chmod {}: {}", path.display(), e)))?;
1321
1322 Ok(true)
1323 }
1324
1325 #[cfg(not(unix))]
1326 {
1327 let _ = path;
1328
1329 Ok(false)
1330 }
1331}
1332
1333const SHIMLOADER_STAGED: [&str; 3] = ["ue4ss.dll", "dwmapi.dll", "ue4ss-settings.ini"];
1335
1336pub fn stage_destination(
1339 loader: LoaderKind,
1340 file_name: &str,
1341 game_dir: &Path,
1342 data_folder: Option<&str>,
1343) -> Option<PathBuf> {
1344 let lowercased = file_name.to_ascii_lowercase();
1345
1346 if lowercased == "mods.yml" {
1347 return None;
1348 }
1349
1350 match loader {
1351 LoaderKind::Shimloader => {
1352 if !SHIMLOADER_STAGED.iter().any(|name| *name == lowercased) {
1353 return None;
1354 }
1355
1356 let data = data_folder?;
1357
1358 Some(
1359 game_dir
1360 .join(data)
1361 .join("Binaries")
1362 .join("Win64")
1363 .join(file_name),
1364 )
1365 }
1366 LoaderKind::Rivet => {
1367 if lowercased != "version.dll" {
1368 return None;
1369 }
1370
1371 Some(game_dir.join("Release").join(file_name))
1372 }
1373 _ => Some(game_dir.join(file_name)),
1374 }
1375}
1376
1377#[cfg(feature = "io")]
1420pub fn stage_for_launch_in(
1421 target_dir: &Path,
1422 eco: &Ecosystem,
1423 game: &str,
1424 game_dir: &Path,
1425 ctx: &LaunchContext,
1426) -> Result<Vec<PathBuf>> {
1427 let staged = stage_files_in(target_dir, eco, game, game_dir, ctx)?;
1428 let mut written = staged.created;
1429
1430 written.extend(staged.replaced);
1431 written.sort();
1432
1433 Ok(written)
1434}
1435
1436#[cfg(feature = "io")]
1443pub(crate) fn stage_files_in(
1444 target_dir: &Path,
1445 eco: &Ecosystem,
1446 game: &str,
1447 game_dir: &Path,
1448 ctx: &LaunchContext,
1449) -> Result<StagedFiles> {
1450 if ctx.os == HostOs::MacOs {
1451 return Err(Error::Profile(MACOS_UNSUPPORTED.to_string()));
1452 }
1453
1454 let profile = eco.require_profile(game)?;
1455
1456 if script_injection_applies(profile, ctx) {
1457 return Ok(StagedFiles::default());
1458 }
1459
1460 let mut copies = Vec::new();
1461
1462 for entry in std::fs::read_dir(target_dir)
1463 .map_err(|e| Error::Profile(format!("reading {}: {}", target_dir.display(), e)))?
1464 {
1465 let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
1466 let metadata = std::fs::symlink_metadata(entry.path())
1467 .map_err(|e| Error::Profile(format!("inspecting {}: {}", entry.path().display(), e)))?;
1468
1469 if !metadata.is_file() {
1470 continue;
1471 }
1472
1473 let file_name = match entry.file_name().to_str() {
1474 Some(name) => name.to_string(),
1475 None => continue,
1476 };
1477
1478 let dest = match stage_destination(
1479 profile.package_loader,
1480 &file_name,
1481 game_dir,
1482 profile.data_folder_name.as_deref(),
1483 ) {
1484 Some(dest) => dest,
1485 None => continue,
1486 };
1487
1488 copies.push((entry.path(), dest));
1489 }
1490
1491 copies.sort();
1492
1493 let mut staged = StagedFiles::default();
1494
1495 for (source, dest) in copies {
1496 match stage_one_file(&source, &dest) {
1497 Ok(StagedFile::InPlace) => {}
1498 Ok(StagedFile::Created) => staged.created.push(dest),
1499 Ok(StagedFile::Replaced) => staged.replaced.push(dest),
1500 Err(error) => {
1501 for created in &staged.created {
1502 let _ = std::fs::remove_file(created);
1503 }
1504
1505 return Err(error);
1506 }
1507 }
1508 }
1509
1510 staged.created.sort();
1511 staged.replaced.sort();
1512
1513 Ok(staged)
1514}
1515
1516#[cfg(feature = "io")]
1519pub fn stage_for_launch(
1520 base: &Path,
1521 game: &str,
1522 profile_name: &str,
1523 eco: &Ecosystem,
1524 game_dir: &Path,
1525 ctx: &LaunchContext,
1526) -> Result<Vec<PathBuf>> {
1527 stage_for_launch_in(
1528 &crate::profile::layout::profile_dir(base, game, profile_name),
1529 eco,
1530 game,
1531 game_dir,
1532 ctx,
1533 )
1534}
1535
1536#[cfg(feature = "io")]
1550fn stage_one_file(source: &Path, dest: &Path) -> Result<StagedFile> {
1551 let existing = std::fs::symlink_metadata(dest).ok();
1552
1553 if existing
1554 .as_ref()
1555 .is_some_and(|metadata| metadata.file_type().is_symlink())
1556 {
1557 return Err(Error::Profile(format!(
1558 "refusing to stage through a symlink at {}",
1559 dest.display()
1560 )));
1561 }
1562
1563 if crate::util::same_file(source, dest) {
1564 return Ok(StagedFile::InPlace);
1565 }
1566
1567 if let Some(parent) = dest.parent() {
1568 std::fs::create_dir_all(parent)
1569 .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
1570 }
1571
1572 std::fs::copy(source, dest)
1573 .map_err(|e| Error::Profile(format!("staging {}: {}", dest.display(), e)))?;
1574
1575 match existing {
1576 Some(_) => Ok(StagedFile::Replaced),
1577 None => Ok(StagedFile::Created),
1578 }
1579}
1580
1581#[cfg(feature = "io")]
1583enum StagedFile {
1584 InPlace,
1586 Created,
1588 Replaced,
1590}
1591
1592#[cfg(feature = "io")]
1595#[derive(Debug, Default)]
1596pub(crate) struct StagedFiles {
1597 pub(crate) created: Vec<PathBuf>,
1599 pub(crate) replaced: Vec<PathBuf>,
1601}
1602
1603pub fn steam_launch_options(script_path: &Path) -> String {
1622 format!(
1623 r#""{script}" %command%"#,
1624 script = script_path.to_string_lossy().replace('\\', "/"),
1625 )
1626}
1627
1628impl LaunchPlan {
1629 pub fn steam_launch_options(&self, wrapper_script: &Path) -> Option<String> {
1662 if self.steam_wrapper.is_some() {
1663 return Some(steam_launch_options(wrapper_script));
1664 }
1665
1666 if !matches!(self.program, LaunchProgram::Steam { .. }) {
1667 return None;
1668 }
1669
1670 self
1671 .env
1672 .iter()
1673 .find(|(key, _)| key == WINE_DLL_OVERRIDES)
1674 .map(|(key, value)| format!(r#"{key}="{value}" %command%"#))
1675 }
1676
1677 #[cfg(feature = "io")]
1680 pub(crate) fn steam_dll_override(&self) -> Option<&str> {
1681 if self.steam_wrapper.is_some() || !matches!(self.program, LaunchProgram::Steam { .. }) {
1682 return None;
1683 }
1684
1685 self
1686 .env
1687 .iter()
1688 .find(|(key, _)| key == WINE_DLL_OVERRIDES)
1689 .and_then(|(_, value)| value.split('=').next())
1690 }
1691}
1692
1693const WINE_DLL_OVERRIDES: &str = "WINEDLLOVERRIDES";
1695
1696#[cfg(feature = "io")]
1698pub fn resolve_game_exe(game_dir: &Path, exe_names: &[String]) -> Result<PathBuf> {
1699 exe_names
1700 .iter()
1701 .map(|name| game_dir.join(name))
1702 .find(|candidate| candidate.is_file())
1703 .ok_or_else(|| {
1704 Error::Profile(format!(
1705 "no game executable found in {}: none of {} exist",
1706 game_dir.display(),
1707 exe_names.join(", ")
1708 ))
1709 })
1710}
1711
1712pub fn wrapper_path(base: &Path, game: &str) -> PathBuf {
1719 base.join(game).join("steam-wrapper.sh")
1720}
1721
1722#[cfg(feature = "io")]
1733fn steam_command(program: &Path, steam_app_id: u32) -> std::process::Command {
1734 let mut command = std::process::Command::new(program);
1735
1736 command.arg("-applaunch").arg(steam_app_id.to_string());
1737
1738 command
1739}
1740
1741#[cfg(feature = "io")]
1742impl LaunchPlan {
1743 pub fn to_command(&self, game_dir: &Path) -> Result<std::process::Command> {
1765 let mut command = match &self.program {
1766 LaunchProgram::GameExe { exe_names } => {
1767 std::process::Command::new(resolve_game_exe(game_dir, exe_names)?)
1768 }
1769 LaunchProgram::Steam { steam_app_id } => {
1770 steam_command(&crate::steam::steam_exe(), *steam_app_id)
1771 }
1772 LaunchProgram::ProfileScript { path, exe_names } => {
1773 let mut command = std::process::Command::new(path);
1774
1775 command.arg(resolve_game_exe(game_dir, exe_names)?);
1776
1777 command
1778 }
1779 };
1780
1781 command.args(&self.args);
1782
1783 for (key, value) in &self.env {
1784 command.env(key, value);
1785 }
1786
1787 if let Some(dir) = &self.working_dir {
1788 command.current_dir(dir);
1789 }
1790
1791 Ok(command)
1792 }
1793}
1794
1795#[cfg(all(test, feature = "io"))]
1796mod tests {
1797 use super::*;
1798
1799 pub(super) fn assert_options_name_script(options: &str, script: &Path) {
1802 let quoted = options
1803 .strip_suffix(" %command%")
1804 .and_then(|rest| rest.strip_prefix('"'))
1805 .and_then(|rest| rest.strip_suffix('"'))
1806 .unwrap_or_else(|| panic!("not a quoted path then %command%: {options}"));
1807
1808 #[cfg(unix)]
1809 assert_eq!(quoted, script.to_str().unwrap());
1810
1811 #[cfg(not(unix))]
1812 {
1813 assert!(!quoted.contains('\\'), "{quoted}");
1814 assert_eq!(
1815 std::fs::canonicalize(quoted).unwrap(),
1816 std::fs::canonicalize(script).unwrap()
1817 );
1818 }
1819 }
1820
1821 #[test]
1822 fn doorstop_version_reads_major_and_defaults_to_three() {
1823 let dir = tempfile::tempdir().unwrap();
1824 let root = dir.path();
1825
1826 assert_eq!(doorstop_version(root), 3);
1828
1829 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1830 assert_eq!(doorstop_version(root), 4);
1831
1832 std::fs::write(root.join(".doorstop_version"), "3.7.1").unwrap();
1833 assert_eq!(doorstop_version(root), 3);
1834
1835 std::fs::write(root.join(".doorstop_version"), "5.1.0").unwrap();
1837 assert_eq!(doorstop_version(root), 5);
1838
1839 std::fs::write(root.join(".doorstop_version"), "garbage").unwrap();
1841 assert_eq!(doorstop_version(root), 3);
1842 }
1843
1844 #[test]
1845 fn bepinex_preloader_finds_candidate_and_prefixes_under_proton() {
1846 let dir = tempfile::tempdir().unwrap();
1847 let root = dir.path();
1848 let core = root.join("BepInEx/core");
1849
1850 std::fs::create_dir_all(&core).unwrap();
1851 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1852 std::fs::write(core.join("Unrelated.dll"), b"x").unwrap();
1853
1854 let native = bepinex_preloader(root, Runtime::Native).unwrap();
1855
1856 assert!(native.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1857 assert!(!native.starts_with("Z:"));
1858
1859 let proton = bepinex_preloader(root, Runtime::Proton).unwrap();
1860
1861 assert!(proton.starts_with("Z:"));
1862 assert!(proton.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1863 }
1864
1865 #[test]
1866 fn bepinex_preloader_errors_when_absent() {
1867 let dir = tempfile::tempdir().unwrap();
1868
1869 assert!(bepinex_preloader(dir.path(), Runtime::Native).is_err());
1870 }
1871
1872 #[test]
1873 fn has_corlibs_detects_the_directory() {
1874 let dir = tempfile::tempdir().unwrap();
1875 let root = dir.path();
1876
1877 assert!(!has_corlibs(root));
1878
1879 std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
1880
1881 assert!(has_corlibs(root));
1882 }
1883
1884 fn ctx(mode: LaunchMode) -> LaunchContext {
1885 LaunchContext {
1886 os: HostOs::Windows,
1887 store: StorePlatform::Steam,
1888 runtime: Runtime::Native,
1889 mode,
1890 extra_args: Vec::new(),
1891 }
1892 }
1893
1894 fn profile_with(loader: LoaderKind) -> GameProfile {
1895 let eco = Ecosystem::bundled();
1896 let mut profile = eco.game("valheim").unwrap().profile().unwrap().clone();
1897 profile.package_loader = loader;
1898
1899 profile
1900 }
1901
1902 #[test]
1903 fn bepinex_v3_and_v4_use_the_right_flag_spellings() {
1904 let dir = tempfile::tempdir().unwrap();
1905 let root = dir.path();
1906 let core = root.join("BepInEx/core");
1907
1908 std::fs::create_dir_all(&core).unwrap();
1909 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1910
1911 let profile = profile_with(LoaderKind::BepInEx);
1912
1913 let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1914
1915 assert_eq!(v3[0], "--doorstop-enable");
1916 assert_eq!(v3[1], "true");
1917 assert_eq!(v3[2], "--doorstop-target");
1918
1919 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1920
1921 let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1922
1923 assert_eq!(v4[0], "--doorstop-enabled");
1924 assert_eq!(v4[2], "--doorstop-target-assembly");
1925
1926 let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
1929
1930 assert_eq!(
1931 vanilla,
1932 vec!["--doorstop-enabled".to_string(), "false".to_string()]
1933 );
1934 }
1935
1936 #[test]
1937 fn melonloader_adds_regenerate_only_when_assemblies_are_absent() {
1938 let dir = tempfile::tempdir().unwrap();
1939 let root = dir.path();
1940 let profile = profile_with(LoaderKind::MelonLoader);
1941
1942 let bare = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1943
1944 assert_eq!(bare[0], "--melonloader.basedir");
1945 assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
1946
1947 let managed = root.join("MelonLoader/Managed");
1948 std::fs::create_dir_all(&managed).unwrap();
1949 std::fs::write(managed.join("Assembly-CSharp.dll"), b"x").unwrap();
1950
1951 let with_assembly = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1952
1953 assert!(!with_assembly.contains(&"--melonloader.agfregenerate".to_string()));
1954 assert_eq!(
1955 loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap(),
1956 vec!["--no-mods".to_string()]
1957 );
1958 }
1959
1960 #[test]
1961 fn single_element_flags_stay_single_elements() {
1962 let dir = tempfile::tempdir().unwrap();
1963 let root = dir.path();
1964
1965 let gdweave = loader_args(
1966 root,
1967 &profile_with(LoaderKind::GdWeave),
1968 &ctx(LaunchMode::Modded),
1969 )
1970 .unwrap();
1971
1972 assert_eq!(gdweave.len(), 1);
1973 assert!(gdweave[0].starts_with("--gdweave-folder-override="));
1974 assert!(gdweave[0].ends_with("/GDWeave"));
1975
1976 let northstar = loader_args(
1977 root,
1978 &profile_with(LoaderKind::Northstar),
1979 &ctx(LaunchMode::Modded),
1980 )
1981 .unwrap();
1982
1983 assert_eq!(northstar[0], "-northstar");
1984 assert!(northstar[1].starts_with("-profile="));
1985 }
1986
1987 #[test]
1988 fn shimloader_and_rivet_and_rom_shapes() {
1989 let dir = tempfile::tempdir().unwrap();
1990 let root = dir.path();
1991
1992 let shim = loader_args(
1993 root,
1994 &profile_with(LoaderKind::Shimloader),
1995 &ctx(LaunchMode::Modded),
1996 )
1997 .unwrap();
1998
1999 assert_eq!(shim.len(), 8);
2000 assert_eq!(shim[0], "--mod-dir");
2001 assert!(shim.contains(&"--overlay-dir".to_string()));
2002
2003 let rivet = loader_args(
2004 root,
2005 &profile_with(LoaderKind::Rivet),
2006 &ctx(LaunchMode::Modded),
2007 )
2008 .unwrap();
2009
2010 assert_eq!(rivet[0], "-rivetEnable");
2011 assert_eq!(rivet[1], "true");
2012 assert!(rivet.contains(&"-rivetDirectory".to_string()));
2013 assert_eq!(
2014 loader_args(
2015 root,
2016 &profile_with(LoaderKind::Rivet),
2017 &ctx(LaunchMode::Vanilla)
2018 )
2019 .unwrap(),
2020 vec!["-rivetEnable".to_string(), "false".to_string()]
2021 );
2022
2023 let rom = loader_args(
2024 root,
2025 &profile_with(LoaderKind::ReturnOfModding),
2026 &ctx(LaunchMode::Modded),
2027 )
2028 .unwrap();
2029
2030 assert_eq!(rom[0], "--rom_modding_root_folder");
2031 }
2032
2033 #[test]
2034 fn unknown_and_none_loaders_produce_no_args() {
2035 let dir = tempfile::tempdir().unwrap();
2036 let root = dir.path();
2037
2038 assert!(
2039 loader_args(
2040 root,
2041 &profile_with(LoaderKind::None),
2042 &ctx(LaunchMode::Modded)
2043 )
2044 .unwrap()
2045 .is_empty()
2046 );
2047 assert!(
2048 loader_args(
2049 root,
2050 &profile_with(LoaderKind::Other),
2051 &ctx(LaunchMode::Modded)
2052 )
2053 .unwrap()
2054 .is_empty()
2055 );
2056 }
2057
2058 #[test]
2059 fn server_instance_appends_server_flag_for_bepinex() {
2060 let dir = tempfile::tempdir().unwrap();
2061 let root = dir.path();
2062 let core = root.join("BepInEx/core");
2063
2064 std::fs::create_dir_all(&core).unwrap();
2065 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2066
2067 let mut profile = profile_with(LoaderKind::BepInEx);
2068 profile.instance_type = InstanceType::Server;
2069
2070 let args = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2071
2072 assert!(args.contains(&"--server".to_string()));
2073 }
2074
2075 #[test]
2076 fn umm_uses_doorstop_flags_and_never_gets_server_flag() {
2077 let dir = tempfile::tempdir().unwrap();
2078 let root = dir.path();
2079 let profile = profile_with(LoaderKind::Umm);
2080
2081 let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2082
2083 assert_eq!(v3[0], "--doorstop-enable");
2084 assert_eq!(v3[1], "true");
2085 assert_eq!(v3[2], "--doorstop-target");
2086 assert!(v3[3].ends_with("UMM/Core/UnityModManager.dll"));
2087
2088 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2089
2090 let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2091
2092 assert_eq!(v4[0], "--doorstop-enabled");
2093 assert_eq!(v4[2], "--doorstop-target-assembly");
2094 assert!(v4[3].ends_with("UMM/Core/UnityModManager.dll"));
2095
2096 let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2097
2098 assert_eq!(
2099 vanilla,
2100 vec!["--doorstop-enabled".to_string(), "false".to_string()]
2101 );
2102
2103 let mut server_profile = profile_with(LoaderKind::Umm);
2106 server_profile.instance_type = InstanceType::Server;
2107
2108 let server_args = loader_args(root, &server_profile, &ctx(LaunchMode::Modded)).unwrap();
2109
2110 assert!(!server_args.contains(&"--server".to_string()));
2111 }
2112
2113 #[test]
2114 fn bepis_loader_modded_and_vanilla_shapes() {
2115 let dir = tempfile::tempdir().unwrap();
2116 let root = dir.path();
2117 let core = root.join("BepInEx/core");
2118
2119 std::fs::create_dir_all(&core).unwrap();
2120 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2121
2122 let profile = profile_with(LoaderKind::BepisLoader);
2123
2124 let modded = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2125
2126 assert_eq!(modded[0], "--hookfxr-enable");
2127 assert_eq!(modded[1], "--bepinex-target");
2128 assert!(modded.contains(&"--doorstop-enabled".to_string()));
2129 assert!(modded.contains(&"--doorstop-target-assembly".to_string()));
2130
2131 let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2132
2133 assert_eq!(
2134 vanilla,
2135 vec![
2136 "--hookfxr-disable".to_string(),
2137 "--doorstop-enabled".to_string(),
2138 "false".to_string()
2139 ]
2140 );
2141 }
2142
2143 #[test]
2144 fn lovely_modded_and_vanilla_shapes() {
2145 let dir = tempfile::tempdir().unwrap();
2146 let root = dir.path();
2147
2148 let modded = loader_args(
2149 root,
2150 &profile_with(LoaderKind::Lovely),
2151 &ctx(LaunchMode::Modded),
2152 )
2153 .unwrap();
2154
2155 assert_eq!(modded[0], "--mod-dir");
2156 assert!(modded[1].ends_with("/mods"));
2157
2158 let vanilla = loader_args(
2159 root,
2160 &profile_with(LoaderKind::Lovely),
2161 &ctx(LaunchMode::Vanilla),
2162 )
2163 .unwrap();
2164
2165 assert_eq!(vanilla, vec!["--vanilla".to_string()]);
2166 }
2167
2168 #[test]
2169 fn godot_ml_modded_and_vanilla_shapes() {
2170 let dir = tempfile::tempdir().unwrap();
2171 let root = dir.path();
2172
2173 let modded = loader_args(
2174 root,
2175 &profile_with(LoaderKind::GodotMl),
2176 &ctx(LaunchMode::Modded),
2177 )
2178 .unwrap();
2179
2180 assert_eq!(modded[0], "--script");
2181 assert_eq!(modded[1], "res://addons/mod_loader/mod_loader_setup.gd");
2182 assert!(modded.contains(&"--mods-path".to_string()));
2183
2184 let vanilla = loader_args(
2185 root,
2186 &profile_with(LoaderKind::GodotMl),
2187 &ctx(LaunchMode::Vanilla),
2188 )
2189 .unwrap();
2190
2191 assert!(vanilla.is_empty());
2192 }
2193
2194 #[test]
2195 fn corlib_override_appends_search_flag_pair_matching_version() {
2196 let dir = tempfile::tempdir().unwrap();
2197 let root = dir.path();
2198 let core = root.join("BepInEx/core");
2199
2200 std::fs::create_dir_all(&core).unwrap();
2201 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2202 std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
2203
2204 let profile = profile_with(LoaderKind::BepInEx);
2205
2206 let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2207 let v3_idx = v3
2208 .iter()
2209 .position(|a| a == "--doorstop-dll-search-override")
2210 .unwrap();
2211
2212 assert!(v3[v3_idx + 1].ends_with("/unstripped_corlib"));
2213
2214 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2215
2216 let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2217 let v4_idx = v4
2218 .iter()
2219 .position(|a| a == "--doorstop-mono-dll-search-path-override")
2220 .unwrap();
2221
2222 assert!(v4[v4_idx + 1].ends_with("/unstripped_corlib"));
2223
2224 std::fs::remove_file(root.join(".doorstop_version")).unwrap();
2227
2228 let bepis = loader_args(
2229 root,
2230 &profile_with(LoaderKind::BepisLoader),
2231 &ctx(LaunchMode::Modded),
2232 )
2233 .unwrap();
2234 let bepis_idx = bepis
2235 .iter()
2236 .position(|a| a == "--doorstop-mono-dll-search-path-override")
2237 .unwrap();
2238
2239 assert!(bepis[bepis_idx + 1].ends_with("/unstripped_corlib"));
2240 }
2241
2242 #[test]
2243 fn windows_steam_plan_targets_steam_with_loader_args() {
2244 let dir = tempfile::tempdir().unwrap();
2245 let root = dir.path();
2246 let core = root.join("BepInEx/core");
2247
2248 std::fs::create_dir_all(&core).unwrap();
2249 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2250
2251 let eco = Ecosystem::bundled();
2252 let mut context = ctx(LaunchMode::Modded);
2253 context.extra_args = vec!["-nolog".to_string()];
2254
2255 let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2256
2257 match &plan.program {
2258 LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
2259 other => panic!("expected Steam, got {other:?}"),
2260 }
2261
2262 assert_eq!(plan.args[0], "--doorstop-enable");
2263 assert_eq!(plan.args.last().unwrap(), "-nolog");
2265 assert!(plan.env.is_empty());
2266 assert_eq!(plan.steam_wrapper, None);
2268 }
2269
2270 #[test]
2271 fn proton_sets_wine_dll_overrides_and_prefixes_the_preloader() {
2272 let dir = tempfile::tempdir().unwrap();
2273 let root = dir.path();
2274 let core = root.join("BepInEx/core");
2275
2276 std::fs::create_dir_all(&core).unwrap();
2277 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2278
2279 let eco = Ecosystem::bundled();
2280 let mut context = ctx(LaunchMode::Modded);
2281 context.os = HostOs::Linux;
2282 context.runtime = Runtime::Proton;
2283
2284 let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2285
2286 assert_eq!(
2287 plan.env,
2288 vec![("WINEDLLOVERRIDES".to_string(), "winhttp=n,b".to_string())]
2289 );
2290 assert!(plan.args.iter().any(|a| a.starts_with("Z:")));
2291 assert_eq!(plan.steam_wrapper, None);
2293 }
2294
2295 #[test]
2296 fn linux_native_bepinex_runs_the_profile_script() {
2297 let dir = tempfile::tempdir().unwrap();
2298 let root = dir.path();
2299 let core = root.join("BepInEx/core");
2300
2301 std::fs::create_dir_all(&core).unwrap();
2302 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2303 std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2304
2305 let eco = Ecosystem::bundled();
2306 let mut context = ctx(LaunchMode::Modded);
2307 context.os = HostOs::Linux;
2308 context.store = StorePlatform::SteamDirect;
2309 context.runtime = Runtime::Native;
2310
2311 let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2312
2313 match &plan.program {
2314 LaunchProgram::ProfileScript { path, exe_names } => {
2317 assert!(path.ends_with("run_bepinex.sh"));
2318 assert_eq!(
2319 *exe_names,
2320 eco.game("valheim").unwrap().profile().unwrap().exe_names
2321 );
2322 assert!(!exe_names.is_empty());
2323 }
2324 other => panic!("expected ProfileScript, got {other:?}"),
2325 }
2326
2327 assert_eq!(plan.steam_wrapper, None);
2329 }
2330
2331 #[test]
2332 fn macos_is_rejected() {
2333 let dir = tempfile::tempdir().unwrap();
2334 let root = dir.path();
2335 let core = root.join("BepInEx/core");
2336
2337 std::fs::create_dir_all(&core).unwrap();
2338 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2339
2340 let eco = Ecosystem::bundled();
2341 let mut context = ctx(LaunchMode::Modded);
2342 context.os = HostOs::MacOs;
2343
2344 let err = launch_plan_in(root, &eco, "valheim", &context).unwrap_err();
2345
2346 assert!(err.to_string().contains("macOS launch is not supported"));
2347
2348 context.os = HostOs::Windows;
2352
2353 assert!(launch_plan_in(root, &eco, "valheim", &context).is_ok());
2354 }
2355
2356 #[test]
2357 fn unknown_game_errors() {
2358 let dir = tempfile::tempdir().unwrap();
2359 let eco = Ecosystem::bundled();
2360
2361 let err = launch_plan_in(dir.path(), &eco, "not-a-game", &ctx(LaunchMode::Modded)).unwrap_err();
2362
2363 assert!(matches!(err, Error::UnknownGame { game } if game == "not-a-game"));
2364 }
2365
2366 #[test]
2367 fn proxy_dll_is_winmm_for_gdweave() {
2368 assert_eq!(proxy_dll(LoaderKind::GdWeave), "winmm");
2369 assert_eq!(proxy_dll(LoaderKind::BepInEx), "winhttp");
2370 }
2371
2372 #[test]
2373 fn wrapper_script_names_no_target_and_execs_the_loader() {
2374 let script = wrapper_script_contents();
2375
2376 assert!(script.starts_with("#!/bin/sh"));
2377
2378 assert!(script.contains(r#"TARGET="""#));
2382 assert!(script.contains(r#"[ -z "$TARGET" ]"#));
2383
2384 assert!(script.contains(&format!(r#"[ "$argument" = "{WRAPPER_TARGET_FLAG}" ]"#)));
2387 assert!(script.contains(r#"[ -d "$candidate" ]"#));
2388 assert!(!script.contains("eval"));
2389
2390 let pos_server = script
2392 .find("start_server_bepinex.sh")
2393 .expect("server branch missing");
2394 let pos_run = script.find("run_bepinex.sh").expect("run branch missing");
2395 let pos_game = script
2396 .find("start_game_bepinex.sh")
2397 .expect("game branch missing");
2398
2399 assert!(pos_server < pos_run, "server branch must come before run");
2400 assert!(pos_run < pos_game, "run branch must come before game");
2401
2402 assert!(script.contains("$TS_START_SERVER"));
2404
2405 assert!(script.contains("else"));
2407 assert!(script.contains("fi"));
2408
2409 assert!(script.contains("\"$@\""));
2411 }
2412
2413 #[test]
2414 fn write_wrapper_script_creates_an_executable_file() {
2415 let dir = tempfile::tempdir().unwrap();
2416 let root = dir.path();
2417 let script_path = root.join("launch_wrapper.sh");
2418
2419 write_wrapper_script(&script_path).unwrap();
2420
2421 assert!(script_path.is_file());
2422
2423 #[cfg(unix)]
2424 {
2425 use std::os::unix::fs::PermissionsExt;
2426
2427 let mode = std::fs::metadata(&script_path)
2428 .unwrap()
2429 .permissions()
2430 .mode();
2431
2432 assert_eq!(mode & 0o111, 0o111);
2433 }
2434 }
2435
2436 #[test]
2441 #[cfg(unix)]
2442 fn ensure_loader_scripts_executable_adds_the_bit_and_reports_what_changed() {
2443 use std::os::unix::fs::PermissionsExt;
2444
2445 let dir = tempfile::tempdir().unwrap();
2446 let root = dir.path();
2447
2448 let game = root.join("start_game_bepinex.sh");
2449 let server = root.join("start_server_bepinex.sh");
2450
2451 std::fs::write(&game, b"#!/bin/sh\n").unwrap();
2452 std::fs::write(&server, b"#!/bin/sh\n").unwrap();
2453
2454 std::fs::set_permissions(&game, std::fs::Permissions::from_mode(0o644)).unwrap();
2456 std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o644)).unwrap();
2457
2458 let changed = ensure_loader_scripts_executable(root).unwrap();
2459
2460 assert_eq!(changed.len(), 2, "got: {changed:?}");
2461
2462 for name in ["start_game_bepinex.sh", "start_server_bepinex.sh"] {
2463 let mode = std::fs::metadata(root.join(name))
2464 .unwrap()
2465 .permissions()
2466 .mode();
2467
2468 assert_eq!(mode & 0o777, 0o755, "{name} got mode {mode:o}");
2469 }
2470
2471 assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2474 }
2475
2476 #[test]
2479 #[cfg(not(unix))]
2480 fn ensure_loader_scripts_executable_changes_nothing_off_unix() {
2481 let dir = tempfile::tempdir().unwrap();
2482 let root = dir.path();
2483
2484 std::fs::write(root.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2485 std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2486
2487 assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2488 }
2489
2490 #[test]
2494 #[cfg(unix)]
2495 fn ensure_loader_scripts_executable_mirrors_read_access() {
2496 use std::os::unix::fs::PermissionsExt;
2497
2498 let dir = tempfile::tempdir().unwrap();
2499 let root = dir.path();
2500 let script = root.join("run_bepinex.sh");
2501
2502 std::fs::write(&script, b"#!/bin/sh\n").unwrap();
2503 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o640)).unwrap();
2504
2505 ensure_loader_scripts_executable(root).unwrap();
2506
2507 let mode = std::fs::metadata(&script).unwrap().permissions().mode();
2508
2509 assert_eq!(mode & 0o777, 0o750, "got mode {mode:o}");
2510 }
2511
2512 #[test]
2515 fn ensure_loader_scripts_executable_ignores_a_target_with_no_scripts() {
2516 let dir = tempfile::tempdir().unwrap();
2517
2518 assert!(
2519 ensure_loader_scripts_executable(dir.path())
2520 .unwrap()
2521 .is_empty()
2522 );
2523 }
2524
2525 #[test]
2526 fn wrapper_target_args_name_the_flag_and_the_directory() {
2527 assert_eq!(
2528 wrapper_target_args(Path::new("/data/profiles/Main")),
2529 vec![
2530 WRAPPER_TARGET_FLAG.to_string(),
2531 "/data/profiles/Main".to_string()
2532 ]
2533 );
2534 }
2535
2536 #[cfg(unix)]
2547 fn make_executable(path: &Path) {
2548 use std::os::unix::fs::PermissionsExt;
2549
2550 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
2551 }
2552
2553 #[cfg(unix)]
2560 fn recording_loader(path: &Path, log: &Path) {
2561 let contents = format!(
2562 "#!/bin/sh\nprintf '%s\\n' \"$0\" > \"{log}\"\nfor argument in \"$@\"; do\n printf '%s\\n' \"$argument\" >> \"{log}\"\ndone\n",
2563 log = log.display()
2564 );
2565
2566 std::fs::write(path, contents).unwrap();
2567 make_executable(path);
2568 }
2569
2570 #[cfg(unix)]
2573 fn recorded(log: &Path) -> Vec<String> {
2574 std::fs::read_to_string(log)
2575 .unwrap()
2576 .lines()
2577 .map(str::to_string)
2578 .collect()
2579 }
2580
2581 #[cfg(unix)]
2583 fn run_wrapper(wrapper: &Path, args: &[&str], server: bool) {
2584 let mut command = std::process::Command::new(wrapper);
2585
2586 command.args(args);
2587
2588 if server {
2589 command.env("TS_START_SERVER", "1");
2590 } else {
2591 command.env_remove("TS_START_SERVER");
2592 }
2593
2594 let output = command.output().unwrap();
2595
2596 assert!(
2597 output.status.success(),
2598 "wrapper failed: {}",
2599 String::from_utf8_lossy(&output.stderr)
2600 );
2601 }
2602
2603 #[cfg(unix)]
2604 #[test]
2605 fn wrapper_chainloads_the_target_given_at_run_time_and_consumes_only_the_flag() {
2606 let dir = tempfile::tempdir().unwrap();
2607 let fallback = dir.path().join("fallback");
2608 let selected = dir.path().join("My Profile 2");
2611 let log = dir.path().join("argv.log");
2612 let wrapper = dir.path().join("steam-wrapper.sh");
2613
2614 std::fs::create_dir_all(&fallback).unwrap();
2615 std::fs::create_dir_all(&selected).unwrap();
2616 recording_loader(&selected.join("run_bepinex.sh"), &log);
2617 write_wrapper_script(&wrapper).unwrap();
2618
2619 let target = selected.to_string_lossy().to_string();
2620
2621 run_wrapper(
2622 &wrapper,
2623 &[
2624 "/games/valheim/valheim.x86_64",
2625 "--doorstop-enabled",
2626 "true",
2627 WRAPPER_TARGET_FLAG,
2628 &target,
2629 "-name",
2630 "a server with spaces",
2631 ],
2632 false,
2633 );
2634
2635 let lines = recorded(&log);
2636
2637 assert_eq!(lines[0], selected.join("run_bepinex.sh").to_string_lossy());
2639 assert_eq!(
2642 &lines[1..],
2643 [
2644 "/games/valheim/valheim.x86_64",
2645 "--doorstop-enabled",
2646 "true",
2647 "-name",
2648 "a server with spaces",
2649 ]
2650 );
2651 }
2652
2653 #[cfg(unix)]
2654 #[test]
2655 fn wrapper_without_the_flag_launches_the_game_unmodded() {
2656 let dir = tempfile::tempdir().unwrap();
2657 let log = dir.path().join("argv.log");
2658 let wrapper = dir.path().join("steam-wrapper.sh");
2659 let game_exe = dir.path().join("valheim.x86_64");
2660 let unrequested = dir.path().join("profile");
2664 let unrequested_log = dir.path().join("must-not-run.log");
2665
2666 std::fs::create_dir_all(&unrequested).unwrap();
2667 recording_loader(&unrequested.join("run_bepinex.sh"), &unrequested_log);
2668 recording_loader(&game_exe, &log);
2669 write_wrapper_script(&wrapper).unwrap();
2670
2671 run_wrapper(&wrapper, &[&game_exe.to_string_lossy()], false);
2674
2675 assert!(
2676 !unrequested_log.exists(),
2677 "a bare launch must not load any profile's mods"
2678 );
2679
2680 let lines = recorded(&log);
2681
2682 assert_eq!(lines[0], game_exe.to_string_lossy());
2683 assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2684 }
2685
2686 #[cfg(unix)]
2687 #[test]
2688 fn wrapper_launches_unmodded_when_the_flags_value_is_not_a_directory() {
2689 let dir = tempfile::tempdir().unwrap();
2690 let log = dir.path().join("argv.log");
2691 let wrapper = dir.path().join("steam-wrapper.sh");
2692 let game_exe = dir.path().join("valheim.x86_64");
2693
2694 recording_loader(&game_exe, &log);
2695 write_wrapper_script(&wrapper).unwrap();
2696
2697 let missing = dir.path().join("deleted-profile");
2700
2701 run_wrapper(
2702 &wrapper,
2703 &[
2704 &game_exe.to_string_lossy(),
2705 WRAPPER_TARGET_FLAG,
2706 &missing.to_string_lossy(),
2707 ],
2708 false,
2709 );
2710
2711 let lines = recorded(&log);
2712
2713 assert_eq!(lines[0], game_exe.to_string_lossy());
2716 assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2717 }
2718
2719 #[cfg(unix)]
2720 #[test]
2721 fn wrapper_consumes_a_trailing_flag_that_has_no_value() {
2722 let dir = tempfile::tempdir().unwrap();
2723 let log = dir.path().join("argv.log");
2724 let wrapper = dir.path().join("steam-wrapper.sh");
2725 let game_exe = dir.path().join("valheim.x86_64");
2726
2727 recording_loader(&game_exe, &log);
2728 write_wrapper_script(&wrapper).unwrap();
2729
2730 run_wrapper(
2731 &wrapper,
2732 &[&game_exe.to_string_lossy(), WRAPPER_TARGET_FLAG],
2733 false,
2734 );
2735
2736 let lines = recorded(&log);
2737
2738 assert_eq!(lines[0], game_exe.to_string_lossy());
2741 assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2742 }
2743
2744 #[cfg(unix)]
2745 #[test]
2746 fn wrapper_execs_the_game_directly_when_the_target_ships_no_loader_script() {
2747 let dir = tempfile::tempdir().unwrap();
2748 let selected = dir.path().join("profile");
2749 let log = dir.path().join("argv.log");
2750 let wrapper = dir.path().join("steam-wrapper.sh");
2751 let game_exe = dir.path().join("valheim.x86_64");
2753
2754 std::fs::create_dir_all(&selected).unwrap();
2755 recording_loader(&game_exe, &log);
2756 write_wrapper_script(&wrapper).unwrap();
2757
2758 run_wrapper(
2759 &wrapper,
2760 &[
2761 &game_exe.to_string_lossy(),
2762 WRAPPER_TARGET_FLAG,
2763 &selected.to_string_lossy(),
2764 "-window-mode",
2765 ],
2766 false,
2767 );
2768
2769 let lines = recorded(&log);
2770
2771 assert_eq!(lines[0], game_exe.to_string_lossy());
2774 assert_eq!(&lines[1..], ["-window-mode"]);
2775 }
2776
2777 #[cfg(unix)]
2778 #[test]
2779 fn wrapper_selects_the_server_script_only_when_ts_start_server_is_set() {
2780 let dir = tempfile::tempdir().unwrap();
2781 let target = dir.path().join("target");
2782 let server_log = dir.path().join("server.log");
2783 let game_log = dir.path().join("game.log");
2784 let wrapper = dir.path().join("steam-wrapper.sh");
2785
2786 std::fs::create_dir_all(&target).unwrap();
2787 recording_loader(&target.join(SERVER_SCRIPT), &server_log);
2791 recording_loader(&target.join("run_bepinex.sh"), &game_log);
2792 write_wrapper_script(&wrapper).unwrap();
2793
2794 let selected = target.to_string_lossy().to_string();
2795 let argv = [
2796 "/games/valheim/valheim.x86_64",
2797 WRAPPER_TARGET_FLAG,
2798 &selected,
2799 ];
2800
2801 run_wrapper(&wrapper, &argv, false);
2802
2803 assert!(
2804 !server_log.exists(),
2805 "the server script must not run for a game instance"
2806 );
2807 assert_eq!(
2808 recorded(&game_log)[0],
2809 target.join("run_bepinex.sh").to_string_lossy()
2810 );
2811
2812 run_wrapper(&wrapper, &argv, true);
2813
2814 assert_eq!(
2815 recorded(&server_log)[0],
2816 target.join(SERVER_SCRIPT).to_string_lossy()
2817 );
2818 }
2819
2820 #[test]
2821 fn steam_launch_options_are_only_the_wrapper_and_command_placeholder() {
2822 let options = steam_launch_options(Path::new("/data/launch_wrapper.sh"));
2823
2824 assert_eq!(options, r#""/data/launch_wrapper.sh" %command%"#);
2827
2828 assert!(!options.contains("WINEDLLOVERRIDES"));
2832 assert!(!options.contains("winhttp"));
2833
2834 assert_eq!(
2836 steam_launch_options(Path::new("/data/My Games/wrapper.sh")),
2837 r#""/data/My Games/wrapper.sh" %command%"#
2838 );
2839
2840 assert_eq!(
2842 steam_launch_options(Path::new(r"C:\Users\me\launch_wrapper.sh")),
2843 r#""C:/Users/me/launch_wrapper.sh" %command%"#
2844 );
2845 }
2846
2847 #[test]
2848 fn stage_destination_routes_per_loader() {
2849 let game = Path::new("/game");
2850
2851 assert_eq!(
2852 stage_destination(LoaderKind::BepInEx, "winhttp.dll", game, None),
2853 Some(PathBuf::from("/game/winhttp.dll"))
2854 );
2855 assert_eq!(
2857 stage_destination(LoaderKind::BepInEx, "mods.yml", game, None),
2858 None
2859 );
2860
2861 assert_eq!(
2863 stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, Some("Palworld")),
2864 Some(PathBuf::from("/game/Palworld/Binaries/Win64/ue4ss.dll"))
2865 );
2866 assert_eq!(
2867 stage_destination(LoaderKind::Shimloader, "other.dll", game, Some("Palworld")),
2868 None
2869 );
2870 assert_eq!(
2872 stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, None),
2873 None
2874 );
2875
2876 assert_eq!(
2878 stage_destination(LoaderKind::Rivet, "version.dll", game, None),
2879 Some(PathBuf::from("/game/Release/version.dll"))
2880 );
2881 assert_eq!(
2882 stage_destination(LoaderKind::Rivet, "winhttp.dll", game, None),
2883 None
2884 );
2885 }
2886
2887 #[test]
2888 fn stage_for_launch_copies_root_files_only() {
2889 let dir = tempfile::tempdir().unwrap();
2890 let target = dir.path().join("target");
2891 let game_dir = dir.path().join("game");
2892
2893 std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
2894 std::fs::create_dir_all(&game_dir).unwrap();
2895 std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2896 std::fs::write(target.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
2897 std::fs::write(target.join("mods.yml"), b"[]").unwrap();
2898 std::fs::write(target.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
2899
2900 let eco = Ecosystem::bundled();
2901 let written = stage_for_launch_in(
2902 &target,
2903 &eco,
2904 "valheim",
2905 &game_dir,
2906 &ctx(LaunchMode::Modded),
2907 )
2908 .unwrap();
2909
2910 assert!(game_dir.join("winhttp.dll").exists());
2911 assert!(game_dir.join("doorstop_config.ini").exists());
2912 assert!(!game_dir.join("mods.yml").exists());
2914 assert!(!game_dir.join("BepInEx").exists());
2915 assert_eq!(written.len(), 2);
2916
2917 assert!(written.contains(&game_dir.join("winhttp.dll")));
2919 assert!(written.contains(&game_dir.join("doorstop_config.ini")));
2920
2921 let mut sorted = written.clone();
2922 sorted.sort();
2923
2924 assert_eq!(written, sorted);
2925 }
2926
2927 #[test]
2928 fn stage_for_launch_stages_shimloader_files_into_nested_binaries_dir() {
2929 let dir = tempfile::tempdir().unwrap();
2933 let target = dir.path().join("target");
2934 let game_dir = dir.path().join("game");
2935
2936 std::fs::create_dir_all(&target).unwrap();
2937 std::fs::create_dir_all(&game_dir).unwrap();
2938 std::fs::write(target.join("ue4ss.dll"), b"loader").unwrap();
2939 std::fs::write(target.join("dwmapi.dll"), b"proxy").unwrap();
2940 std::fs::write(target.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
2941 std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2942
2943 let eco = Ecosystem::bundled();
2944 let written = stage_for_launch_in(
2945 &target,
2946 &eco,
2947 "palworld",
2948 &game_dir,
2949 &ctx(LaunchMode::Modded),
2950 )
2951 .unwrap();
2952
2953 let nested = game_dir.join("Pal").join("Binaries").join("Win64");
2954
2955 assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
2956 assert!(nested.join("dwmapi.dll").exists());
2957 assert!(nested.join("ue4ss-settings.ini").exists());
2958 assert!(!game_dir.join("other.dll").exists());
2960 assert!(!nested.join("other.dll").exists());
2961
2962 assert_eq!(written.len(), 3);
2963 assert!(written.contains(&nested.join("ue4ss.dll")));
2964 assert!(written.contains(&nested.join("dwmapi.dll")));
2965 assert!(written.contains(&nested.join("ue4ss-settings.ini")));
2966
2967 let mut sorted = written.clone();
2968 sorted.sort();
2969
2970 assert_eq!(written, sorted);
2971 }
2972
2973 #[test]
2974 fn stage_for_launch_stages_rivet_version_dll_into_release_dir() {
2975 let dir = tempfile::tempdir().unwrap();
2979 let target = dir.path().join("target");
2980 let game_dir = dir.path().join("game");
2981
2982 std::fs::create_dir_all(&target).unwrap();
2983 std::fs::create_dir_all(&game_dir).unwrap();
2984 std::fs::write(target.join("version.dll"), b"rivet-loader").unwrap();
2985 std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2986
2987 let eco = Ecosystem::bundled();
2988 let written = stage_for_launch_in(
2989 &target,
2990 &eco,
2991 "scrap-mechanic",
2992 &game_dir,
2993 &ctx(LaunchMode::Modded),
2994 )
2995 .unwrap();
2996
2997 let dest = game_dir.join("Release").join("version.dll");
2998
2999 assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
3000 assert!(!game_dir.join("other.dll").exists());
3002 assert!(!game_dir.join("Release").join("other.dll").exists());
3003
3004 assert_eq!(written, vec![dest]);
3005 }
3006
3007 #[test]
3008 fn stage_for_launch_skips_linux_native_bepinex() {
3009 let dir = tempfile::tempdir().unwrap();
3010 let target = dir.path().join("target");
3011 let game_dir = dir.path().join("game");
3012
3013 std::fs::create_dir_all(&target).unwrap();
3014 std::fs::create_dir_all(&game_dir).unwrap();
3015 std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
3016
3017 let eco = Ecosystem::bundled();
3018 let mut context = ctx(LaunchMode::Modded);
3019 context.os = HostOs::Linux;
3020 context.runtime = Runtime::Native;
3021
3022 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3023
3024 assert!(written.is_empty());
3025 assert!(!game_dir.join("winhttp.dll").exists());
3026 }
3027
3028 #[cfg(unix)]
3029 #[test]
3030 fn stage_for_launch_refuses_to_write_through_a_symlink() {
3031 use std::os::unix::fs::symlink;
3032
3033 let dir = tempfile::tempdir().unwrap();
3034 let target = dir.path().join("target");
3035 let game_dir = dir.path().join("game");
3036 let outside = dir.path().join("secret.dll");
3037
3038 std::fs::create_dir_all(&target).unwrap();
3039 std::fs::create_dir_all(&game_dir).unwrap();
3040 std::fs::write(&outside, b"original").unwrap();
3041 std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
3042 symlink(&outside, game_dir.join("winhttp.dll")).unwrap();
3043
3044 let eco = Ecosystem::bundled();
3045
3046 assert!(
3047 stage_for_launch_in(
3048 &target,
3049 &eco,
3050 "valheim",
3051 &game_dir,
3052 &ctx(LaunchMode::Modded)
3053 )
3054 .is_err()
3055 );
3056 assert_eq!(std::fs::read(&outside).unwrap(), b"original");
3057 }
3058
3059 #[test]
3060 fn stage_for_launch_in_place_leaves_root_files_byte_for_byte_untouched() {
3061 let dir = tempfile::tempdir().unwrap();
3068 let root = dir.path().join("game");
3069
3070 std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
3071
3072 let winhttp_contents = b"MZ-fake-proxy-dll-18b";
3073 let ini_contents = b"[UnityDoorstop]\nenabled=true\n";
3074
3075 std::fs::write(root.join("winhttp.dll"), winhttp_contents).unwrap();
3076 std::fs::write(root.join("doorstop_config.ini"), ini_contents).unwrap();
3077 std::fs::write(root.join("mods.yml"), b"[]").unwrap();
3078 std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
3079
3080 let eco = Ecosystem::bundled();
3081 let written =
3082 stage_for_launch_in(&root, &eco, "valheim", &root, &ctx(LaunchMode::Modded)).unwrap();
3083
3084 assert_eq!(
3087 std::fs::read(root.join("winhttp.dll")).unwrap(),
3088 winhttp_contents
3089 );
3090 assert_eq!(
3091 std::fs::read(root.join("doorstop_config.ini")).unwrap(),
3092 ini_contents
3093 );
3094
3095 assert!(written.is_empty());
3101 }
3102
3103 #[test]
3104 fn stage_for_launch_in_place_survives_a_dot_dot_aliased_game_dir() {
3105 let dir = tempfile::tempdir().unwrap();
3110 let target = dir.path().join("target");
3111
3112 std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3113
3114 let contents = b"proxy-bytes-not-truncated";
3115
3116 std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3117
3118 let aliased_game_dir = target.join("BepInEx").join("..");
3119 let eco = Ecosystem::bundled();
3120
3121 let written = stage_for_launch_in(
3122 &target,
3123 &eco,
3124 "valheim",
3125 &aliased_game_dir,
3126 &ctx(LaunchMode::Modded),
3127 )
3128 .unwrap();
3129
3130 assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3131 assert!(written.is_empty());
3132 }
3133
3134 #[cfg(unix)]
3135 #[test]
3136 fn stage_for_launch_in_place_survives_a_symlinked_game_dir() {
3137 use std::os::unix::fs::symlink;
3138
3139 let dir = tempfile::tempdir().unwrap();
3143 let target = dir.path().join("target");
3144 let link = dir.path().join("game-link");
3145
3146 std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3147
3148 let contents = b"proxy-bytes-via-symlink";
3149
3150 std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3151 symlink(&target, &link).unwrap();
3152
3153 let eco = Ecosystem::bundled();
3154 let written =
3155 stage_for_launch_in(&target, &eco, "valheim", &link, &ctx(LaunchMode::Modded)).unwrap();
3156
3157 assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3158 assert!(written.is_empty());
3159 }
3160
3161 #[test]
3162 fn stage_for_launch_in_place_still_copies_shimloader_files_to_a_distinct_destination() {
3163 let dir = tempfile::tempdir().unwrap();
3169 let root = dir.path().join("game");
3170
3171 std::fs::create_dir_all(&root).unwrap();
3172 std::fs::write(root.join("ue4ss.dll"), b"loader").unwrap();
3173 std::fs::write(root.join("dwmapi.dll"), b"proxy").unwrap();
3174 std::fs::write(root.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
3175
3176 let eco = Ecosystem::bundled();
3177 let written =
3178 stage_for_launch_in(&root, &eco, "palworld", &root, &ctx(LaunchMode::Modded)).unwrap();
3179
3180 let nested = root.join("Pal").join("Binaries").join("Win64");
3181
3182 assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
3183 assert_eq!(std::fs::read(nested.join("dwmapi.dll")).unwrap(), b"proxy");
3184 assert_eq!(std::fs::read(root.join("ue4ss.dll")).unwrap(), b"loader");
3187
3188 assert_eq!(written.len(), 3);
3189 assert!(written.contains(&nested.join("ue4ss.dll")));
3190 assert!(written.contains(&nested.join("dwmapi.dll")));
3191 assert!(written.contains(&nested.join("ue4ss-settings.ini")));
3192 }
3193
3194 #[test]
3195 fn stage_for_launch_in_place_still_copies_rivet_version_dll_to_a_distinct_destination() {
3196 let dir = tempfile::tempdir().unwrap();
3200 let root = dir.path().join("game");
3201
3202 std::fs::create_dir_all(&root).unwrap();
3203 std::fs::write(root.join("version.dll"), b"rivet-loader").unwrap();
3204
3205 let eco = Ecosystem::bundled();
3206 let written = stage_for_launch_in(
3207 &root,
3208 &eco,
3209 "scrap-mechanic",
3210 &root,
3211 &ctx(LaunchMode::Modded),
3212 )
3213 .unwrap();
3214
3215 let dest = root.join("Release").join("version.dll");
3216
3217 assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
3218 assert_eq!(
3219 std::fs::read(root.join("version.dll")).unwrap(),
3220 b"rivet-loader"
3221 );
3222 assert_eq!(written, vec![dest]);
3223 }
3224
3225 #[test]
3226 fn stage_for_launch_wraps_stage_for_launch_in_over_a_layout_profile() {
3227 let dir = tempfile::tempdir().unwrap();
3228 let base = dir.path().join("base");
3229 let game_dir = dir.path().join("game");
3230
3231 let profile_dir = crate::profile::layout::create(&base, "valheim", "Main").unwrap();
3232 let core = profile_dir.join("BepInEx/core");
3233
3234 std::fs::create_dir_all(&core).unwrap();
3235 std::fs::create_dir_all(&game_dir).unwrap();
3236 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3237 std::fs::write(profile_dir.join("winhttp.dll"), b"proxy").unwrap();
3238 std::fs::write(profile_dir.join("mods.yml"), b"[]").unwrap();
3239
3240 let eco = Ecosystem::bundled();
3241 let written = stage_for_launch(
3242 &base,
3243 "valheim",
3244 "Main",
3245 &eco,
3246 &game_dir,
3247 &ctx(LaunchMode::Modded),
3248 )
3249 .unwrap();
3250
3251 assert!(game_dir.join("winhttp.dll").exists());
3252 assert!(!game_dir.join("mods.yml").exists());
3253 assert_eq!(written, vec![game_dir.join("winhttp.dll")]);
3254 }
3255
3256 fn linux_native(mode: LaunchMode) -> LaunchContext {
3258 let mut context = ctx(mode);
3259
3260 context.os = HostOs::Linux;
3261 context.store = StorePlatform::SteamDirect;
3262 context.runtime = Runtime::Native;
3263
3264 context
3265 }
3266
3267 fn linux_bepinex_target(root: &Path) {
3270 let core = root.join("BepInEx/core");
3271
3272 std::fs::create_dir_all(&core).unwrap();
3273 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3274 std::fs::write(root.join("winhttp.dll"), b"proxy").unwrap();
3275 std::fs::write(root.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
3276 }
3277
3278 #[test]
3279 fn linux_native_modded_selects_any_shipped_script_not_only_run_bepinex() {
3280 let dir = tempfile::tempdir().unwrap();
3281 let target = dir.path().join("target");
3282 let game_dir = dir.path().join("game");
3283
3284 linux_bepinex_target(&target);
3285 std::fs::create_dir_all(&game_dir).unwrap();
3286 std::fs::write(target.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3288
3289 let eco = Ecosystem::bundled();
3290 let context = linux_native(LaunchMode::Modded);
3291
3292 let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3293
3294 match &plan.program {
3295 LaunchProgram::ProfileScript { path, .. } => {
3296 assert!(path.ends_with("start_game_bepinex.sh"))
3297 }
3298 other => panic!("expected ProfileScript, got {other:?}"),
3301 }
3302
3303 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3305
3306 assert!(written.is_empty());
3307 assert!(!game_dir.join("winhttp.dll").exists());
3308 }
3309
3310 #[test]
3311 fn server_instance_prefers_the_server_script_and_a_game_instance_ignores_it() {
3312 let dir = tempfile::tempdir().unwrap();
3313 let all_three = dir.path().join("all-three");
3314 let server_only = dir.path().join("server-only");
3315
3316 linux_bepinex_target(&all_three);
3317 linux_bepinex_target(&server_only);
3318
3319 for name in LOADER_SCRIPTS {
3320 std::fs::write(all_three.join(name), b"#!/bin/sh\n").unwrap();
3321 }
3322
3323 std::fs::write(server_only.join(SERVER_SCRIPT), b"#!/bin/sh\n").unwrap();
3324
3325 let context = linux_native(LaunchMode::Modded);
3326 let game_profile = profile_with(LoaderKind::BepInEx);
3327 let mut server_profile = profile_with(LoaderKind::BepInEx);
3328
3329 server_profile.instance_type = InstanceType::Server;
3330
3331 let server = resolve_program(
3332 &script_injection(
3333 &all_three,
3334 &LaunchFacts::read(&all_three),
3335 &server_profile,
3336 &context,
3337 ),
3338 &all_three,
3339 &server_profile,
3340 &context,
3341 )
3342 .unwrap();
3343
3344 match &server {
3345 LaunchProgram::ProfileScript { path, .. } => {
3346 assert!(path.ends_with("start_server_bepinex.sh"))
3347 }
3348 other => panic!("expected ProfileScript, got {other:?}"),
3349 }
3350
3351 let game = resolve_program(
3354 &script_injection(
3355 &all_three,
3356 &LaunchFacts::read(&all_three),
3357 &game_profile,
3358 &context,
3359 ),
3360 &all_three,
3361 &game_profile,
3362 &context,
3363 )
3364 .unwrap();
3365
3366 match &game {
3367 LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3368 other => panic!("expected ProfileScript, got {other:?}"),
3369 }
3370
3371 let err = resolve_program(
3373 &script_injection(
3374 &server_only,
3375 &LaunchFacts::read(&server_only),
3376 &game_profile,
3377 &context,
3378 ),
3379 &server_only,
3380 &game_profile,
3381 &context,
3382 )
3383 .unwrap_err();
3384
3385 assert!(err.to_string().contains("run_bepinex.sh"));
3386 }
3387
3388 #[test]
3389 fn modded_script_injection_without_a_script_errors_but_vanilla_falls_through() {
3390 let dir = tempfile::tempdir().unwrap();
3391 let target = dir.path().join("target");
3392
3393 linux_bepinex_target(&target);
3394
3395 let eco = Ecosystem::bundled();
3396 let modded = linux_native(LaunchMode::Modded);
3397
3398 let err = launch_plan_in(&target, &eco, "valheim", &modded).unwrap_err();
3399 let message = err.to_string();
3400
3401 assert!(message.contains("run_bepinex.sh"), "{message}");
3402 assert!(message.contains("start_game_bepinex.sh"), "{message}");
3403 assert!(message.contains(&target.display().to_string()), "{message}");
3404
3405 let vanilla =
3408 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3409
3410 assert!(matches!(vanilla.program, LaunchProgram::GameExe { .. }));
3411 assert_eq!(
3412 vanilla.args,
3413 vec!["--doorstop-enable".to_string(), "false".to_string()]
3414 );
3415 }
3416
3417 #[test]
3418 fn linux_native_steam_launches_steam_and_reports_the_wrapper_requirement() {
3419 let dir = tempfile::tempdir().unwrap();
3420 let target = dir.path().join("target");
3421 let game_dir = dir.path().join("game");
3422 let script_path = dir.path().join("launch_wrapper.sh");
3423
3424 linux_bepinex_target(&target);
3425 std::fs::create_dir_all(&game_dir).unwrap();
3426 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3427
3428 let eco = Ecosystem::bundled();
3429 let mut context = linux_native(LaunchMode::Modded);
3430
3431 context.store = StorePlatform::Steam;
3432
3433 let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3434
3435 match &plan.program {
3437 LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
3438 other => panic!("expected Steam, got {other:?}"),
3439 }
3440
3441 let wrapper = plan.steam_wrapper.clone().expect("wrapper requirement");
3445
3446 assert_eq!(wrapper.target_dir, target);
3447 assert_eq!(wrapper.loader, LoaderKind::BepInEx);
3448
3449 write_wrapper_script(&script_path).unwrap();
3450
3451 let options = steam_launch_options(&script_path);
3452
3453 assert_options_name_script(&options, &script_path);
3454 assert!(!options.contains("WINEDLLOVERRIDES"));
3455 assert!(
3456 std::fs::read_to_string(&script_path)
3457 .unwrap()
3458 .contains("run_bepinex.sh")
3459 );
3460
3461 assert!(
3464 plan
3465 .args
3466 .windows(2)
3467 .any(|pair| pair == wrapper_target_args(&target).as_slice()),
3468 "plan args must carry the wrapper target flag: {:?}",
3469 plan.args
3470 );
3471
3472 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3474
3475 assert!(written.is_empty());
3476 assert!(!game_dir.join("winhttp.dll").exists());
3477 }
3478
3479 #[test]
3480 fn stage_for_launch_rejects_macos() {
3481 let dir = tempfile::tempdir().unwrap();
3482 let target = dir.path().join("target");
3483 let game_dir = dir.path().join("game");
3484
3485 linux_bepinex_target(&target);
3486 std::fs::create_dir_all(&game_dir).unwrap();
3487
3488 let eco = Ecosystem::bundled();
3489 let mut context = ctx(LaunchMode::Modded);
3490
3491 context.os = HostOs::MacOs;
3492
3493 let err = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap_err();
3494
3495 assert!(err.to_string().contains("macOS launch is not supported"));
3496 assert_eq!(std::fs::read_dir(&game_dir).unwrap().count(), 0);
3499
3500 context.os = HostOs::Windows;
3503
3504 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3505
3506 assert_eq!(written.len(), 2);
3507 assert!(game_dir.join("winhttp.dll").exists());
3508 }
3509
3510 #[test]
3511 fn only_a_wrapper_bound_plan_carries_the_target_flag() {
3512 let dir = tempfile::tempdir().unwrap();
3513 let target = dir.path().join("target");
3514
3515 linux_bepinex_target(&target);
3516 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3517
3518 let eco = Ecosystem::bundled();
3519
3520 let direct =
3524 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3525
3526 assert_eq!(direct.steam_wrapper, None);
3527 assert!(!direct.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3528
3529 let mut proton = linux_native(LaunchMode::Modded);
3532
3533 proton.store = StorePlatform::Steam;
3534 proton.runtime = Runtime::Proton;
3535
3536 let proton_plan = launch_plan_in(&target, &eco, "valheim", &proton).unwrap();
3537
3538 assert_eq!(proton_plan.steam_wrapper, None);
3539 assert!(!proton_plan.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3540 }
3541
3542 #[test]
3543 fn wrapper_branches_are_generated_from_the_shared_script_list() {
3544 let script = wrapper_script_contents();
3545
3546 let mut previous = 0;
3547
3548 for name in LOADER_SCRIPTS {
3549 let position = script
3550 .find(&format!("[ -f \"$TARGET/{name}\" ]"))
3551 .unwrap_or_else(|| panic!("wrapper is missing a branch for {name}"));
3552
3553 assert!(position >= previous, "{name} is out of precedence order");
3554
3555 previous = position;
3556 }
3557 }
3558
3559 #[test]
3564 fn linux_native_script_present_vanilla_runs_the_script_with_v4_enabled_spelling() {
3565 let dir = tempfile::tempdir().unwrap();
3566 let target = dir.path().join("target");
3567
3568 linux_bepinex_target(&target);
3569 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3570 let eco = Ecosystem::bundled();
3574 let plan =
3575 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3576
3577 match &plan.program {
3580 LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3581 other => panic!("expected ProfileScript, got {other:?}"),
3582 }
3583
3584 assert_eq!(
3585 plan.args,
3586 vec!["--doorstop-enabled".to_string(), "false".to_string()]
3587 );
3588 }
3589
3590 #[test]
3591 fn linux_native_script_present_modded_uses_v4_target_assembly_spelling() {
3592 let dir = tempfile::tempdir().unwrap();
3593 let target = dir.path().join("target");
3594
3595 linux_bepinex_target(&target);
3596 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3597 let eco = Ecosystem::bundled();
3601 let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3602
3603 assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3604 assert_eq!(plan.args[0], "--doorstop-enabled");
3605 assert_eq!(plan.args[1], "true");
3606 assert_eq!(plan.args[2], "--doorstop-target-assembly");
3607 assert!(plan.args[3].ends_with("BepInEx/core/BepInEx.Preloader.dll"));
3608 }
3609
3610 #[test]
3611 fn linux_native_script_present_v3_detected_corlib_override_uses_v4_search_flag_spelling() {
3612 let dir = tempfile::tempdir().unwrap();
3618 let target = dir.path().join("target");
3619
3620 linux_bepinex_target(&target);
3621 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3622 std::fs::create_dir_all(target.join("unstripped_corlib")).unwrap();
3623 let eco = Ecosystem::bundled();
3627 let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3628
3629 assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3630
3631 let idx = plan
3632 .args
3633 .iter()
3634 .position(|a| a == "--doorstop-mono-dll-search-path-override")
3635 .expect("v4 corlib search-path flag missing");
3636
3637 assert!(plan.args[idx + 1].ends_with("/unstripped_corlib"));
3638 assert!(
3639 !plan
3640 .args
3641 .iter()
3642 .any(|a| a == "--doorstop-dll-search-override"),
3643 "v3 corlib search-path spelling must not appear on the script-injected path: {:?}",
3644 plan.args
3645 );
3646 }
3647
3648 #[test]
3649 fn linux_native_script_present_v4_detected_target_is_unchanged() {
3650 let dir = tempfile::tempdir().unwrap();
3651 let target = dir.path().join("target");
3652
3653 linux_bepinex_target(&target);
3654 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3655 std::fs::write(target.join(".doorstop_version"), "4.0.0").unwrap();
3656
3657 let eco = Ecosystem::bundled();
3658
3659 let vanilla =
3660 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3661
3662 assert_eq!(
3663 vanilla.args,
3664 vec!["--doorstop-enabled".to_string(), "false".to_string()]
3665 );
3666
3667 let modded =
3668 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3669
3670 assert_eq!(modded.args[0], "--doorstop-enabled");
3671 assert_eq!(modded.args[2], "--doorstop-target-assembly");
3672 }
3673
3674 #[test]
3675 fn proton_v3_detected_target_still_uses_v3_spellings_even_with_a_script_on_disk() {
3676 let dir = tempfile::tempdir().unwrap();
3685 let target = dir.path().join("target");
3686
3687 linux_bepinex_target(&target);
3688 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3689
3690 let eco = Ecosystem::bundled();
3691 let mut context = linux_native(LaunchMode::Modded);
3692
3693 context.runtime = Runtime::Proton;
3694
3695 let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3696
3697 assert_eq!(plan.args[0], "--doorstop-enable");
3698 assert_eq!(plan.args[2], "--doorstop-target");
3699
3700 let mut vanilla_context = linux_native(LaunchMode::Vanilla);
3701
3702 vanilla_context.runtime = Runtime::Proton;
3703
3704 let vanilla = launch_plan_in(&target, &eco, "valheim", &vanilla_context).unwrap();
3705
3706 assert_eq!(
3707 vanilla.args,
3708 vec!["--doorstop-enable".to_string(), "false".to_string()]
3709 );
3710 }
3711
3712 #[test]
3713 fn windows_v3_detected_target_still_uses_v3_spellings_regression_guard() {
3714 let dir = tempfile::tempdir().unwrap();
3718 let root = dir.path();
3719 let core = root.join("BepInEx/core");
3720
3721 std::fs::create_dir_all(&core).unwrap();
3722 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3723
3724 let eco = Ecosystem::bundled();
3725 let plan = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Modded)).unwrap();
3726
3727 assert_eq!(plan.args[0], "--doorstop-enable");
3728 assert_eq!(plan.args[2], "--doorstop-target");
3729
3730 let vanilla = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Vanilla)).unwrap();
3731
3732 assert_eq!(
3733 vanilla.args,
3734 vec!["--doorstop-enable".to_string(), "false".to_string()]
3735 );
3736 }
3737
3738 #[test]
3739 fn store_and_runtime_parse_from_their_config_spellings() {
3740 assert_eq!(
3741 "steam".parse::<StorePlatform>().unwrap(),
3742 StorePlatform::Steam
3743 );
3744 assert_eq!(
3745 "steam-direct".parse::<StorePlatform>().unwrap(),
3746 StorePlatform::SteamDirect
3747 );
3748 assert_eq!(
3749 "other".parse::<StorePlatform>().unwrap(),
3750 StorePlatform::Other
3751 );
3752 assert_eq!("native".parse::<Runtime>().unwrap(), Runtime::Native);
3753 assert_eq!("proton".parse::<Runtime>().unwrap(), Runtime::Proton);
3754
3755 let error = "wat".parse::<StorePlatform>().unwrap_err().to_string();
3757
3758 assert!(error.contains("wat"), "got: {error}");
3759 }
3760
3761 #[test]
3762 fn resolve_game_exe_returns_the_first_present_candidate() {
3763 let dir = tempfile::tempdir().unwrap();
3764 let game_dir = dir.path();
3765
3766 std::fs::write(game_dir.join("second.x86_64"), b"elf").unwrap();
3767
3768 let names = vec!["first.exe".to_string(), "second.x86_64".to_string()];
3769 let found = resolve_game_exe(game_dir, &names).unwrap();
3770
3771 assert_eq!(found, game_dir.join("second.x86_64"));
3772
3773 let error = resolve_game_exe(game_dir, &["absent.exe".to_string()])
3775 .unwrap_err()
3776 .to_string();
3777
3778 assert!(error.contains("absent.exe"), "got: {error}");
3779 }
3780
3781 #[test]
3782 fn a_plan_becomes_a_spawnable_command() {
3783 let dir = tempfile::tempdir().unwrap();
3784 let game_dir = dir.path();
3785
3786 std::fs::write(game_dir.join("valheim.x86_64"), b"elf").unwrap();
3787
3788 let plan = LaunchPlan {
3792 program: LaunchProgram::GameExe {
3793 exe_names: vec!["valheim.x86_64".to_string()],
3794 },
3795 args: vec!["-console".to_string()],
3796 env: vec![("KEY".to_string(), "VALUE".to_string())],
3797 working_dir: Some(game_dir.to_path_buf()),
3798 steam_wrapper: None,
3799 };
3800
3801 let command = plan.to_command(game_dir).unwrap();
3802
3803 assert_eq!(command.get_program(), game_dir.join("valheim.x86_64"));
3804 assert_eq!(
3805 command.get_args().collect::<Vec<_>>(),
3806 vec![std::ffi::OsStr::new("-console")]
3807 );
3808 assert_eq!(command.get_current_dir(), Some(game_dir));
3809 assert!(
3810 command
3811 .get_envs()
3812 .any(|(key, value)| key == std::ffi::OsStr::new("KEY")
3813 && value == Some(std::ffi::OsStr::new("VALUE")))
3814 );
3815 }
3816
3817 #[test]
3821 fn a_steam_command_leads_with_applaunch_and_keeps_the_plan_argv_after_it() {
3822 let program = Path::new(r"C:\Program Files (x86)\Steam\steam.exe");
3823 let mut command = steam_command(program, 892970);
3824
3825 command.args(["-console".to_string(), "--ts-target".to_string()]);
3826
3827 assert_eq!(command.get_program(), program.as_os_str());
3828 assert_eq!(
3829 command.get_args().collect::<Vec<_>>(),
3830 vec![
3831 std::ffi::OsStr::new("-applaunch"),
3832 std::ffi::OsStr::new("892970"),
3833 std::ffi::OsStr::new("-console"),
3834 std::ffi::OsStr::new("--ts-target"),
3835 ]
3836 );
3837 }
3838
3839 #[test]
3847 fn a_steam_plan_spawns_the_resolved_steam_executable() {
3848 let dir = tempfile::tempdir().unwrap();
3849 let game_dir = dir.path();
3850
3851 let plan = LaunchPlan {
3852 program: LaunchProgram::Steam {
3853 steam_app_id: 892970,
3854 },
3855 args: vec!["-console".to_string()],
3856 env: vec![("KEY".to_string(), "VALUE".to_string())],
3857 working_dir: None,
3858 steam_wrapper: None,
3859 };
3860
3861 let command = plan.to_command(game_dir).unwrap();
3862
3863 assert_eq!(
3864 command.get_program(),
3865 crate::steam::steam_exe().as_os_str(),
3866 "the Steam arm must use the resolved executable"
3867 );
3868 assert_eq!(
3869 command.get_args().collect::<Vec<_>>(),
3870 vec![
3871 std::ffi::OsStr::new("-applaunch"),
3872 std::ffi::OsStr::new("892970"),
3873 std::ffi::OsStr::new("-console"),
3874 ]
3875 );
3876
3877 let envs = command.get_envs().collect::<Vec<_>>();
3878
3879 assert_eq!(
3880 envs,
3881 vec![(
3882 std::ffi::OsStr::new("KEY"),
3883 Some(std::ffi::OsStr::new("VALUE"))
3884 )],
3885 "the plan's env must reach the command unchanged, with nothing added"
3886 );
3887 }
3888}
3889
3890#[cfg(test)]
3891mod planning_tests {
3892 use super::*;
3893
3894 const TARGET: &str = "/profiles/main";
3895
3896 fn ctx(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> LaunchContext {
3897 LaunchContext::new(os, store, runtime, mode)
3898 }
3899
3900 fn with_preloader() -> LaunchFacts {
3901 LaunchFacts {
3902 preloader: Some("BepInEx.Preloader.dll".to_string()),
3903 ..LaunchFacts::default()
3904 }
3905 }
3906
3907 fn plan(facts: &LaunchFacts, context: &LaunchContext) -> Result<LaunchPlan> {
3908 launch_plan_from(
3909 Path::new(TARGET),
3910 facts,
3911 &Ecosystem::bundled(),
3912 "valheim",
3913 context,
3914 )
3915 }
3916
3917 #[test]
3918 fn doorstop_flags_follow_the_recorded_version() {
3919 let windows = ctx(
3920 HostOs::Windows,
3921 StorePlatform::SteamDirect,
3922 Runtime::Native,
3923 LaunchMode::Modded,
3924 );
3925 let mut facts = with_preloader();
3926
3927 let v3 = plan(&facts, &windows).unwrap();
3928
3929 facts.doorstop_version = 4;
3930
3931 let v4 = plan(&facts, &windows).unwrap();
3932
3933 assert_eq!(v3.args[0], "--doorstop-enable");
3934 assert_eq!(v4.args[0], "--doorstop-enabled");
3935 assert!(
3936 v3.args
3937 .contains(&format!("{TARGET}/BepInEx/core/BepInEx.Preloader.dll"))
3938 );
3939 }
3940
3941 #[test]
3942 fn a_modded_bepinex_launch_needs_a_preloader() {
3943 let windows = ctx(
3944 HostOs::Windows,
3945 StorePlatform::SteamDirect,
3946 Runtime::Native,
3947 LaunchMode::Modded,
3948 );
3949
3950 let result = plan(&LaunchFacts::default(), &windows);
3951
3952 assert!(
3953 matches!(result, Err(Error::Profile(message)) if message.contains("no BepInEx preloader"))
3954 );
3955 }
3956
3957 #[test]
3958 fn corlibs_add_the_search_path_override() {
3959 let windows = ctx(
3960 HostOs::Windows,
3961 StorePlatform::SteamDirect,
3962 Runtime::Native,
3963 LaunchMode::Modded,
3964 );
3965 let mut facts = with_preloader();
3966
3967 facts.has_corlibs = true;
3968
3969 let plan = plan(&facts, &windows).unwrap();
3970
3971 assert!(
3972 plan
3973 .args
3974 .contains(&"--doorstop-dll-search-override".to_string())
3975 );
3976 assert!(plan.args.contains(&format!("{TARGET}/unstripped_corlib")));
3977 }
3978
3979 #[test]
3980 fn a_listed_loader_script_is_run_on_linux_native() {
3981 let linux = ctx(
3982 HostOs::Linux,
3983 StorePlatform::SteamDirect,
3984 Runtime::Native,
3985 LaunchMode::Modded,
3986 );
3987 let mut facts = with_preloader();
3988
3989 facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
3990
3991 let plan = plan(&facts, &linux).unwrap();
3992
3993 assert!(matches!(
3994 plan.program,
3995 LaunchProgram::ProfileScript { ref path, .. }
3996 if path == &Path::new(TARGET).join("start_game_bepinex.sh")
3997 ));
3998 assert_eq!(plan.args[0], "--doorstop-enabled");
3999 }
4000
4001 #[test]
4002 fn a_proton_launch_through_steam_pastes_the_override_in_either_mode() {
4003 for mode in [LaunchMode::Modded, LaunchMode::Vanilla] {
4004 let proton = ctx(HostOs::Linux, StorePlatform::Steam, Runtime::Proton, mode);
4005 let plan = plan(&with_preloader(), &proton).unwrap();
4006
4007 assert_eq!(
4008 plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")),
4009 Some(r#"WINEDLLOVERRIDES="winhttp=n,b" %command%"#.to_string()),
4010 "{mode:?}"
4011 );
4012 }
4013 }
4014
4015 #[test]
4016 fn a_linux_native_launch_through_steam_pastes_the_wrapper_line() {
4017 let native = ctx(
4018 HostOs::Linux,
4019 StorePlatform::Steam,
4020 Runtime::Native,
4021 LaunchMode::Modded,
4022 );
4023 let mut facts = with_preloader();
4024
4025 facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
4026
4027 let plan = plan(&facts, &native).unwrap();
4028
4029 assert_eq!(
4030 plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")),
4031 Some(r#""/base/valheim/steam-wrapper.sh" %command%"#.to_string())
4032 );
4033 }
4034
4035 #[test]
4036 fn a_launch_steam_does_not_start_has_nothing_to_paste() {
4037 for (os, runtime) in [
4038 (HostOs::Windows, Runtime::Native),
4039 (HostOs::Linux, Runtime::Proton),
4040 ] {
4041 let direct = ctx(os, StorePlatform::SteamDirect, runtime, LaunchMode::Modded);
4042 let plan = plan(&with_preloader(), &direct).unwrap();
4043
4044 assert_eq!(
4045 plan.steam_launch_options(Path::new("/base/valheim/steam-wrapper.sh")),
4046 None,
4047 "{os:?} {runtime:?}"
4048 );
4049 }
4050 }
4051
4052 #[test]
4053 fn no_plan_needs_both_the_wrapper_and_the_proton_override() {
4054 let mut facts = with_preloader();
4055
4056 facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
4057
4058 for os in [HostOs::Windows, HostOs::Linux] {
4059 for store in [
4060 StorePlatform::Steam,
4061 StorePlatform::SteamDirect,
4062 StorePlatform::Other,
4063 ] {
4064 for runtime in [Runtime::Native, Runtime::Proton] {
4065 for mode in [LaunchMode::Modded, LaunchMode::Vanilla] {
4066 let Ok(plan) = plan(&facts, &ctx(os, store, runtime, mode)) else {
4067 continue;
4068 };
4069 let overrides = plan.env.iter().any(|(key, _)| key == "WINEDLLOVERRIDES");
4070
4071 assert!(
4072 !(plan.steam_wrapper.is_some() && overrides),
4073 "{os:?} {store:?} {runtime:?} {mode:?}"
4074 );
4075 }
4076 }
4077 }
4078 }
4079 }
4080
4081 #[test]
4082 fn linux_native_modded_without_a_loader_script_is_refused() {
4083 let linux = ctx(
4084 HostOs::Linux,
4085 StorePlatform::SteamDirect,
4086 Runtime::Native,
4087 LaunchMode::Modded,
4088 );
4089
4090 let result = plan(&with_preloader(), &linux);
4091
4092 assert!(matches!(result, Err(Error::Profile(message)) if message.contains("loader script")));
4093 }
4094
4095 #[test]
4096 fn the_server_script_is_ignored_for_a_game_instance() {
4097 let linux = ctx(
4098 HostOs::Linux,
4099 StorePlatform::SteamDirect,
4100 Runtime::Native,
4101 LaunchMode::Modded,
4102 );
4103 let mut facts = with_preloader();
4104
4105 facts.loader_scripts = vec!["start_server_bepinex.sh".to_string()];
4106
4107 assert!(plan(&facts, &linux).is_err());
4108 }
4109
4110 #[test]
4111 fn melonloader_regenerates_only_without_its_assemblies() {
4112 let eco = Ecosystem::bundled();
4113 let profile = eco
4114 .games()
4115 .filter_map(|game| game.profile())
4116 .find(|profile| profile.package_loader == LoaderKind::MelonLoader)
4117 .unwrap();
4118 let windows = ctx(
4119 HostOs::Windows,
4120 StorePlatform::SteamDirect,
4121 Runtime::Native,
4122 LaunchMode::Modded,
4123 );
4124 let mut facts = LaunchFacts::default();
4125
4126 let bare = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
4127
4128 facts.melonloader_assemblies = true;
4129
4130 let built = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
4131
4132 assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
4133 assert!(!built.contains(&"--melonloader.agfregenerate".to_string()));
4134 }
4135
4136 #[test]
4137 fn macos_is_refused_whatever_the_facts() {
4138 let mac = ctx(
4139 HostOs::MacOs,
4140 StorePlatform::SteamDirect,
4141 Runtime::Native,
4142 LaunchMode::Modded,
4143 );
4144
4145 assert!(plan(&with_preloader(), &mac).is_err());
4146 }
4147
4148 #[test]
4149 #[cfg(feature = "io")]
4150 fn launch_facts_read_what_the_target_holds() {
4151 let dir = tempfile::tempdir().unwrap();
4152 let root = dir.path();
4153
4154 std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
4155 std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
4156 std::fs::create_dir_all(root.join("MelonLoader/Il2CppAssemblies")).unwrap();
4157 std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"").unwrap();
4158 std::fs::write(root.join("run_bepinex.sh"), b"").unwrap();
4159 std::fs::write(root.join(".doorstop_version"), b"4.0.0").unwrap();
4160 std::fs::write(
4161 root.join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll"),
4162 b"",
4163 )
4164 .unwrap();
4165
4166 let facts = LaunchFacts::read(root);
4167
4168 assert_eq!(facts.doorstop_version, 4);
4169 assert_eq!(facts.preloader.as_deref(), Some("BepInEx.Preloader.dll"));
4170 assert!(facts.has_corlibs);
4171 assert_eq!(facts.loader_scripts, vec!["run_bepinex.sh".to_string()]);
4172 assert!(facts.melonloader_assemblies);
4173 assert_eq!(
4174 LaunchFacts::read(&root.join("missing")),
4175 LaunchFacts::default()
4176 );
4177 }
4178
4179 #[test]
4180 #[cfg(feature = "io")]
4181 fn launch_facts_read_the_loader_files_and_recorded_packages() {
4182 let dir = tempfile::tempdir().unwrap();
4183 let root = dir.path();
4184 let version: crate::models::Version = serde_json::from_str(
4185 r#"{"name":"GDWeave","full_name":"NotNet-GDWeave","description":"d","icon":"i",
4186 "version_number":"2.0.0","dependencies":[],"download_url":"u","downloads":1,
4187 "date_created":"2024-01-01T12:00:00Z","website_url":"w","is_active":true,
4188 "uuid4":"u","file_size":1}"#,
4189 )
4190 .unwrap();
4191
4192 std::fs::create_dir_all(root.join("GDWeave/core")).unwrap();
4193 std::fs::write(root.join("GDWeave/core/GDWeave.dll"), b"").unwrap();
4194 std::fs::create_dir_all(root.join("R2Northstar")).unwrap();
4195 std::fs::write(root.join("R2Northstar/Northstar.dll"), b"").unwrap();
4196 crate::profile::modlist::write(
4197 root,
4198 &[crate::profile::mod_entry_from_version(
4199 "NotNet-GDWeave",
4200 "NotNet",
4201 &version,
4202 1,
4203 )],
4204 )
4205 .unwrap();
4206
4207 let facts = LaunchFacts::read(root);
4208
4209 assert_eq!(
4210 facts.loaders,
4211 vec![LoaderKind::GdWeave, LoaderKind::Northstar]
4212 );
4213 assert_eq!(facts.recorded, vec!["NotNet-GDWeave".to_string()]);
4214 }
4215}