fix: Require only runtime packages on Linux, and check ICU and tzdata the way the runtime does (#2561)

## Why

ModernUO mandated `-dev` packages on production servers for exactly one reason: `DllImport` never
asks for a versioned SONAME, so `libdeflate.so.0` and `libargon2.so.1` sitting in `/usr/lib` went
unfound, and the `-dev` package's unversioned symlink was the only thing making resolution work.
The `-dev` packages ship no library of their own — operators were installing headers and a static
lib on machines that compile nothing.

Fixed in the binding packages (modernuo/LibDeflate.Bindings#4, modernuo/Argon2.Bindings#13), so
this picks them up and stops asking.

```
LibDeflate.Bindings 1.0.3  -> 1.0.4
Argon2.Bindings     1.17.0 -> 1.19.0
```

## zstd is dropped too, on every platform

ZstdNet bundles `libzstd` for `linux-x64`, `linux-arm64`, `osx-x64`, `osx-arm64` and win, and
nothing shells out to the CLI. Verified: the 15 `ManagedArchive` round-trip tests pass in a
container with no `zstd` package installed and `which zstd` empty. Removed from the README, the
macOS `brew install`, and CI — so the macOS runners now prove it rather than us assuming it.

## NativeLibraryChecker asks a different question

It asked *"is package X installed"* via `dpkg -l` / `rpm -q`. That is what forced `-dev`, and no
hardcoded name works for ICU anyway — its apt package is release-specific (`libicu70` on Ubuntu
22.04, `libicu76` on Debian 13). It now asks *"will the loader find this"*: `NativeLibrary.TryLoad`
on the unversioned name, then `libfoo.so.N` descending through the range the runtime accepts.

It deliberately does not consult a package database or `ldconfig -p`. Both answer a different
question than "will `dlopen` succeed" — see the ICU section below for how that bit.

## What was wrong with the ICU check

`libicuuc` was **inherited, not derived**. It came from translating the old package-name check into
a library probe, without establishing which library that should be. Reviewing it turned up three
defects, all of which could report ICU present on a host where the runtime then refuses to start:

- **`libicui18n` was never probed.** The only ICU names in `libSystem.Globalization.Native.so` are
  `libicuuc` and `libicui18n`. `libicudata` arrives as a dependency of `libicuuc`, and
  `libicuio`/`libicutu`/`libicutest` are never referenced — so that is the complete list, and both
  are checked now.
- **No version floor.** The runtime's `MinICUVersion` is 60, but the probe accepted down to
  `.so.0`. RHEL/CentOS 7 ships ICU 50, which passed and then aborted at startup.
- **The `ldconfig` fast path bypassed the range.** A cache line for `libicuuc.so.50` still matches a
  `libicuuc.so` prefix test, so the floor was unenforceable through it. It also trusts a stale
  cache — observed reporting a deleted `libdeflate` as present. Removed in favour of asking the
  loader directly, which reads the same cache but answers the real question, and which also deletes
  the musl special-case (`ldconfig -p` exits 0 on musl while producing nothing usable).

Worth knowing when this goes wrong in the field: **missing ICU does not throw, it `FailFast`s** —
SIGABRT, exit 134, uncatchable. The process starts cleanly and dies later at whatever line first
touches a culture, so the stack rarely implicates ICU.

## tzdata is a separate prerequisite, and nothing was checking it

The event scheduler resolves configured zone IDs through `TimeZoneInfo`, which reads
`/usr/share/zoneinfo`. It is data rather than a library, so no loader probe finds it, and slim
container images routinely omit it. Without it every lookup except `UTC` throws
`TimeZoneNotFoundException` and `GetSystemTimeZones()` returns 1 entry instead of ~419.

There is no per-zone packaging to opt into — it is ~2 MB for the whole set. The one split that does
exist is a trap rather than an optimization: Debian 12 and Ubuntu 24.04 move the legacy aliases into
`tzdata-legacy`, so plain `tzdata` has `America/New_York` and `EST5EDT` but is **missing
`US/Eastern` and `Asia/Calcutta`**. A shard configured with a legacy alias throws even though tzdata
is installed. Documented, with both fixes.

## Why `InvariantGlobalization` stays false

Dropping ICU entirely by turning on invariant mode looks tempting and is not safe. Because
`Directory.Build.props` also sets `PredefinedCulturesOnly=false`, invariant mode does **not** throw
`CultureNotFoundException` — it silently hands back invariant data. Measured on .NET 10:

| Behaviour | With ICU | Invariant mode |
|---|---|---|
| `new CultureInfo("de-DE")` | real culture | succeeds, returns invariant data |
| de-DE decimal separator | `,` | `.` |
| `1234.5` as de-DE | `1.234,5` | `1,234.5` |
| `string.Compare("a", "B", InvariantCulture)` | `-1` (linguistic) | `31` (ordinal) |
| sort `[b, A, a, B]` | `a, A, b, B` | `A, B, a, b` |
| `FindSystemTimeZoneById("Eastern Standard Time")` on Linux | resolves | `TimeZoneNotFoundException` |
| UTF-8 round-trip of non-ASCII | unaffected | unaffected |

Number parsing and formatting produce wrong values with no error, and culture-sensitive sort order
silently becomes ordinal. Encoding is not the mechanism — UTF-8 round-trips fine either way.

## Documentation

The rationale now lives in `dev-docs/platform-prerequisites.md` rather than in comments, so it is
discoverable without reading the build tool: what each dependency is for, what breaks without it,
per-distro package names, the ICU floor, the `tzdata-legacy` split, and why the check asks the
loader instead of the package manager.

README drops `libicu-dev`. Matching the runtime package by pattern (`'^libicu[0-9]+$'`) is
version-independent without pulling in headers, so **no `-dev` package is required on any supported
distribution** — which was the point of the whole change.

## CI now proves the claim instead of contradicting it

The dnf job already installed runtime packages only. The apt job installed `libicu-dev`, which ships
the unversioned `libicuuc.so` symlink — so every probe succeeded on the first attempt and the
versioned-SONAME fallback this PR depends on was never exercised. Switched to the pattern match,
verified to resolve exactly one package on jammy (70), bookworm (72), noble (74) and trixie (76).

Added an assertion that the unversioned symlinks are absent. Without it the suite silently stops
testing anything the moment a base image starts shipping one. Verified against all eight matrix
distributions — none ship them — and confirmed the step fails as intended when a symlink is planted.

## Audit of every other native entry point

Checked whether anything else has the same hazard. It does not:

| Import | Verdict |
|---|---|
| `ws2_32.dll` — `SocketHelper` | Always present on Windows |
| `libc` — `SocketHelper` | **Verified safe**, see below |
| ZstdNet → `libzstd` | Bundled for every RID |
| IORingGroup | No native library; raw syscalls |
| ICU | Loaded by the .NET runtime itself, which probes versioned suffixes |

`libc` deserved a hard look, because `libc.so` *is* a `libc6-dev` linker script while the real
library is `libc.so.6` — the same shape as the bug being fixed. It is not affected. Measured in a
container with no `libc6-dev`:

```
/usr/lib/x86_64-linux-gnu/libc.so   ABSENT
/lib/x86_64-linux-gnu/libc.so.6     present
TryLoad("libc")     LOADED      <- resolves where "libdeflate" would not
TryLoad("libc.so")  not found
getpid() -> DllImport("libc") WORKS
```

Confirmed on Alpine/musl as well. No code in this repo registers a `DllImportResolver`, and nothing
else P/Invokes.

## `--check-prereqs`

New flag. `Program.cs` only ran the SDK check in non-interactive mode — `NativeLibraryChecker` was
reachable only through the Spectre-driven guided flow, so there was no way to verify a deployment
target from a script or a container. It is what made the container verification below possible, and
it prints the exact ICU package for the running release via `apt-cache`.

It renders through the same `PrerequisiteChecker` the guided menu uses, rather than a second
hand-rolled table that could drift from it. Spectre drops ANSI styling on its own when stdout is not
a terminal, so redirected output stays clean; the console width is widened in that case so the
install hints, which are shell commands meant to be copied, do not gain a newline mid-command.

```
╭───────────────────────────╮
│ Checking native libraries │
╰───────────────────────────╯

  ✔ libicuuc (Found)
  ✔ libicui18n (Found)
   libdeflate (Not found)
   tzdata (Not found — every zone except UTC will throw)

  ⚠️ Install the missing dependencies. The -dev/-devel packages are not required:
   sudo apt-get install -y libicu74 libdeflate0 tzdata
```

Exit code carries the machine-readable half: 0 when everything resolves, 1 when anything is missing.

## Verification

Against 1.0.4 and 1.19.0: build plus **810 Server.Tests and 642 UOContent.Tests**, on Windows and
on Linux with **only** `libdeflate0` and `libargon2-1` installed — with the absence of the
unversioned symlink asserted first so the run could not pass for the wrong reason.

`--check-prereqs` verified in containers on Debian and Alpine across every state that matters: all
present, each dependency removed individually, tzdata removed, a deliberately stale `ldconfig`
cache, and ICU downgraded to `.so.50` to confirm the floor rejects it. Package resolution and the
absence of unversioned symlinks checked on all eight CI distributions.
This commit is contained in:
Kamron Batman 2026-08-07 15:03:08 -07:00 committed by GitHub
parent 246f077778
commit 23dc6649a0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 388 additions and 98 deletions

View file

@ -14,4 +14,11 @@ public sealed class BuildOptions
public string? Arch { get; set; }
public bool SkipPrereqs { get; set; }
public bool Interactive { get; set; }
/// <summary>
/// Report the native library prerequisites and exit. The interactive flow is the only other
/// path that runs these checks, so without this there is no way to verify a deployment target
/// from a script or a container.
/// </summary>
public bool CheckPrereqsOnly { get; set; }
}

View file

@ -1,3 +1,4 @@
using System.Runtime.InteropServices;
using BuildTool.Platform;
using BuildTool.Publishing;
@ -31,8 +32,10 @@ public static class NativeLibraryChecker
"Linux",
[
".NET 10 Runtime — https://dotnet.microsoft.com/download/dotnet/10.0",
"Debian/Ubuntu: sudo apt-get install -y libicu-dev libdeflate-dev zstd libargon2-dev",
"Fedora/RHEL: sudo dnf install -y libicu libdeflate-devel zstd libargon2-devel",
"Debian/Ubuntu: sudo apt-get install -y libdeflate0 libargon2-1 libicuNN tzdata",
" (libicuNN varies by release, e.g. libicu76 — run build-tool --check-prereqs there for the exact name)",
" (add tzdata-legacy if the shard is configured with an alias such as US/Eastern)",
"Fedora/RHEL: sudo dnf install -y libdeflate libargon2 libicu tzdata",
"CentOS: Also requires epel-release and CRB enabled"
]
),
@ -176,82 +179,59 @@ public static class NativeLibraryChecker
return results;
}
/// <summary>
/// Native libraries the server needs from the system on Linux, and the SONAME range to accept
/// for each. Rationale and per-distro package names: dev-docs/platform-prerequisites.md.
/// </summary>
private static readonly (string Name, int MinSoVersion, int MaxSoVersion)[] _linuxLibraries =
[
("libicuuc", 60, 120),
("libicui18n", 60, 120),
("libdeflate", 0, 9),
("libargon2", 0, 9)
];
private static List<PrerequisiteResult> CheckLinux(PlatformInfo platform)
{
return platform.PackageManager switch
{
PackageManager.Apt => CheckLinuxApt(),
PackageManager.Dnf => CheckLinuxDnf(platform),
_ => CheckLinuxGeneric(platform)
};
}
private static List<PrerequisiteResult> CheckLinuxApt()
{
var results = new List<PrerequisiteResult>();
var packages = new[] { "libicu-dev", "libdeflate-dev", "zstd", "libargon2-dev" };
var missing = new List<string>();
foreach (var package in packages)
foreach (var (name, minSoVersion, maxSoVersion) in _linuxLibraries)
{
var result = ProcessRunner.RunCaptured("dpkg", $"-l {package}");
var installed = result.Success && result.StandardOutput.Contains("ii");
var found = CanLoad(name, minSoVersion, maxSoVersion);
if (!installed)
if (!found)
{
missing.Add(package);
missing.Add(name);
}
results.Add(new PrerequisiteResult
{
Name = package,
Passed = installed,
Details = installed ? "Installed" : "Not installed"
Name = name,
Passed = found,
Details = found ? "Found" : "Not found"
});
}
if (missing.Count > 0)
var hasTimeZoneData = HasTimeZoneData();
if (!hasTimeZoneData)
{
results.Add(new PrerequisiteResult
{
Name = "Install all missing",
Passed = false,
IsWarning = true,
Details = "Run the following command to install all missing dependencies:",
InstallCommand = $"sudo apt-get install -y {string.Join(' ', missing)}"
});
missing.Add("tzdata");
}
return results;
}
private static List<PrerequisiteResult> CheckLinuxDnf(PlatformInfo platform)
{
var results = new List<PrerequisiteResult>();
var packages = new[] { "libicu", "libdeflate-devel", "zstd", "libargon2-devel" };
var missing = new List<string>();
foreach (var package in packages)
results.Add(new PrerequisiteResult
{
var result = ProcessRunner.RunCaptured("rpm", $"-q {package}");
var installed = result.Success;
Name = "tzdata",
Passed = hasTimeZoneData,
Details = hasTimeZoneData ? "Found" : "Not found — every zone except UTC will throw"
});
if (!installed)
{
missing.Add(package);
}
results.Add(new PrerequisiteResult
{
Name = package,
Passed = installed,
Details = installed ? "Installed" : "Not installed"
});
if (missing.Count == 0)
{
return results;
}
// Check if this is CentOS (needs EPEL)
var isCentOs = platform.DistroId?.Equals("centos", StringComparison.OrdinalIgnoreCase) == true;
if (isCentOs && missing.Count > 0)
if (platform.DistroId?.Equals("centos", StringComparison.OrdinalIgnoreCase) == true)
{
results.Add(new PrerequisiteResult
{
@ -263,48 +243,131 @@ public static class NativeLibraryChecker
});
}
if (missing.Count > 0)
results.Add(new PrerequisiteResult
{
results.Add(new PrerequisiteResult
{
Name = "Install all missing",
Passed = false,
IsWarning = true,
Details = "Run the following command to install all missing dependencies:",
InstallCommand = $"sudo dnf install -y {string.Join(' ', missing)}"
});
}
Name = "Install all missing",
Passed = false,
IsWarning = true,
Details = "Install the missing dependencies. The -dev/-devel packages are not required:",
InstallCommand = BuildInstallCommand(platform, missing)
});
return results;
}
private static List<PrerequisiteResult> CheckLinuxGeneric(PlatformInfo platform)
/// <summary>
/// tzdata is data, not a library, so no loader probe finds it. Asking the runtime rather than
/// stat'ing a path keeps TZDIR honoured, and the count is still accurate under
/// InvariantGlobalization, which this tool runs with — only display names degrade there.
/// </summary>
private static bool HasTimeZoneData()
{
var results = new List<PrerequisiteResult>();
// Use ldconfig to check for shared libraries
var ldResult = ProcessRunner.RunCaptured("ldconfig", "-p");
var ldOutput = ldResult.Success ? ldResult.StandardOutput : "";
var libraries = new Dictionary<string, string>
try
{
["libicu"] = "libicuuc",
["libdeflate"] = "libdeflate",
["zstd"] = "libzstd",
["libargon2"] = "libargon2"
};
foreach (var (name, soName) in libraries)
return TimeZoneInfo.GetSystemTimeZones().Count > 1;
}
catch
{
var found = ldOutput.Contains(soName, StringComparison.OrdinalIgnoreCase);
results.Add(new PrerequisiteResult
{
Name = name,
Passed = found,
Details = found ? "Found" : "Not found — install using your package manager"
});
return false;
}
}
/// <summary>
/// Asks the loader directly rather than querying a package database or scanning ldconfig's
/// cache, both of which answer a different question and can disagree with what dlopen will do.
/// Mirrors the binding packages' own probing: the unversioned name first, then libfoo.so.N
/// descending. Bare names go through the full loader search path, so LD_LIBRARY_PATH and
/// /etc/ld.so.conf.d still apply.
/// </summary>
private static bool CanLoad(string library, int minSoVersion, int maxSoVersion)
{
if (TryLoadAndFree($"{library}.so"))
{
return true;
}
return results;
for (var soVersion = maxSoVersion; soVersion >= minSoVersion; soVersion--)
{
if (TryLoadAndFree($"{library}.so.{soVersion}"))
{
return true;
}
}
return false;
}
private static bool TryLoadAndFree(string candidate)
{
if (!NativeLibrary.TryLoad(candidate, out var handle))
{
return false;
}
NativeLibrary.Free(handle);
return true;
}
private static string BuildInstallCommand(PlatformInfo platform, List<string> missing)
{
switch (platform.PackageManager)
{
case PackageManager.Apt:
{
// Distinct because the two ICU libraries resolve to the same package, and
// ResolveAptIcuPackage shells out, so it is memoized rather than called per name.
var packages = missing.Select(
library => library switch
{
"libdeflate" => "libdeflate0",
"libargon2" => "libargon2-1",
"tzdata" => "tzdata",
_ => _aptIcuPackage ??= ResolveAptIcuPackage()
}
).Distinct();
return $"sudo apt-get install -y {string.Join(' ', packages)}";
}
case PackageManager.Dnf:
{
var packages = missing.Select(
library => library switch
{
"libdeflate" => "libdeflate",
"libargon2" => "libargon2",
"tzdata" => "tzdata",
_ => "libicu"
}
).Distinct();
return $"sudo dnf install -y {string.Join(' ', packages)}";
}
default:
return $"Install your distribution's runtime packages for: {string.Join(", ", missing)}";
}
}
private static string _aptIcuPackage;
/// <summary>
/// ICU's apt package carries the ABI version in its name and there is no stable alias, so ask
/// apt which one this release actually ships instead of printing a name that rots.
/// </summary>
private static string ResolveAptIcuPackage()
{
var result = ProcessRunner.RunCaptured("apt-cache", "search --names-only ^libicu[0-9]+$");
if (!result.Success)
{
return "libicu";
}
var best = result.StandardOutput
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Split(' ', 2)[0].Trim())
.Where(name => name.StartsWith("libicu", StringComparison.Ordinal))
.OrderBy(name => int.TryParse(name.AsSpan(6), out var version) ? version : 0)
.LastOrDefault();
return best ?? "libicu";
}
}

View file

@ -4,6 +4,7 @@ using BuildTool.Interactive;
using BuildTool.Platform;
using BuildTool.Prerequisites;
using BuildTool.Publishing;
using Spectre.Console;
Console.OutputEncoding = Encoding.UTF8;
@ -36,6 +37,22 @@ options.Os ??= detectedPlatform.OsRid;
options.Arch ??= detectedPlatform.ArchRid;
var rid = $"{options.Os}-{options.Arch}";
if (options.CheckPrereqsOnly)
{
// Same renderer the guided menu uses, so the two cannot drift. Spectre drops ANSI styling by
// itself when stdout is not a terminal, which is the case this flag exists for, but it also
// falls back to an 80 column width and folds anything longer. The install hints we print are
// shell commands — the CentOS one is 95 characters — and a fold puts a newline in the middle of
// a command that someone is meant to copy. Widen the profile so they stay on one line.
if (Console.IsOutputRedirected)
{
AnsiConsole.Profile.Width = 200;
}
// Exit code is the machine-readable half: 0 when everything resolves, 1 when anything is missing.
return PrerequisiteChecker.CheckNativeLibraries(detectedPlatform, interactive: false) ? 0 : 1;
}
// Run prerequisite checks unless skipped
if (!options.SkipPrereqs)
{
@ -108,6 +125,12 @@ static BuildOptions ParseArguments(string[] args)
hasNamedArgs = true;
break;
}
case "--check-prereqs":
{
options.CheckPrereqsOnly = true;
hasNamedArgs = true;
break;
}
case "--interactive":
{
options.Interactive = true;

View file

@ -36,7 +36,7 @@
<ProjectReference Include="..\Logger\Logger.csproj" />
<PackageReference Include="IORingGroup" Version="1.0.9" />
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.4.2" />
<PackageReference Include="LibDeflate.Bindings" Version="1.0.3" />
<PackageReference Include="LibDeflate.Bindings" Version="1.0.4" />
<PackageReference Include="System.IO.Hashing" Version="10.0.10" />
<PackageReference Include="ModernUO.Serialization.Annotations" Version="2.14.2" />

View file

@ -40,12 +40,12 @@
<ProjectReference Include="..\Server\Server.csproj" Private="false" PrivateAssets="All" IncludeAssets="None">
<IncludeInPackage>false</IncludeInPackage>
</ProjectReference>
<PackageReference Include="LibDeflate.Bindings" Version="1.0.3" />
<PackageReference Include="LibDeflate.Bindings" Version="1.0.4" />
<PackageReference Include="System.IO.Hashing" Version="10.0.10" />
<PackageReference Include="MailKit" Version="4.17.0" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="10.0.10" />
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.4.2" />
<PackageReference Include="Argon2.Bindings" Version="1.17.0" />
<PackageReference Include="Argon2.Bindings" Version="1.19.0" />
<PackageReference Include="ModernUO.CodeGeneratedEvents.Annotations" Version="1.0.0" />
<PackageReference Include="ModernUO.CodeGeneratedEvents.Generator" Version="1.0.3.2" PrivateAssets="all" />
<PackageReference Include="ZstdNet" Version="1.5.7" />