mirror of
https://github.com/par274/sharpemu.git
synced 2026-09-01 06:13:38 +08:00
[SourceGenerators] Compile-time SysAbi export registry, analyzers, and build-generated aerolib.bin (#204)
* [SourceGenerators] Add the SysAbi export generator and analyzers (phase 0) New SharpEmu.SourceGenerators Roslyn component, complete and tested but consumed by nothing yet — the emulator projects adopt it in the following commits. Ps5Nid ports the PS NID derivation (base64 of the byte-reversed first eight SHA1 bytes of name + fixed suffix) from scripts/generate_aerolib_binary.py to C#, so what has always been a manual, out-of-band computation becomes a compile-time capability. SysAbiExportGenerator emits a per-assembly SysAbiExportRegistry whose CreateExports(Generation) reproduces ModuleManager's reflection scan exactly — same generation inheritance and filtering, same method-name fallback, same libKernel default — with attribute-omitted NIDs derived algorithmically (equivalent to the runtime catalog lookup, which is built from the same computation). Parameterless handlers are adapted to the SysAbiFunction shape; invalid declarations are skipped here because the analyzer rejects them as build errors, so nothing drops silently. SysAbiExportAnalyzer turns the runtime failure modes into diagnostics: SHEM001 duplicate NID (across declared and derived forms), SHEM002 malformed NID, SHEM003 uncallable handler signature, SHEM004 NID contradicting its export name (the class of drift previously fixed by hand), SHEM005 unresolvable export, SHEM006 export name unknown to ps5_names.txt when the catalog is wired as an AdditionalFile, SHEM007 handler not reachable by generated code. The self-contained test suite drives both in-process against the real SharpEmu.HLE metadata: known catalog NID pairs pin the algorithm, the generated registry must itself compile, and each diagnostic has a triggering fixture. Fittingly, the NID pinning test caught a wrong pair in its own first draft — the exact mistake SHEM004 exists to stop. * [SourceGenerators] Adopt the generated export registry in the emulator (phase 1) SharpEmu.Libs consumes the generator and analyzers, with scripts/ps5_names.txt wired as the AdditionalFile catalog. The runtime now registers exports from the compile-time SysAbiExportRegistry instead of the boot-time reflection scan; RegisterFromAssembly is retained solely as the arbiter for a parity test that pins the two tables identical — same NIDs, names, libraries, targets, and handler methods — across Gen4, Gen5, and combined registration. First contact between the analyzer and all 715 existing exports surfaced real drift the old offline checker structurally missed (scripts/check_sysabi_aerolib.py skipped any NID absent from aerolib.bin): three exports whose friendly names collide with real catalog symbols of different NIDs, now suppressed at-site with reasons pending AGC API confirmation, alongside the established synthetic Unknown* labels for uncatalogued NIDs, which prompted a rule refinement — SHEM004 only hard-errors when the export name is a real catalog symbol, since synthetic labels cannot be validated by hashing and the NID is authoritative for them. The two allowlisted mismatches in the python checker no longer trigger anything, and the checker is deleted: the analyzer subsumes it with the semantic model instead of regex, and validates every declared pair rather than only catalog-known NIDs. * [SourceGenerators] Generate aerolib.bin at build time from ps5_names.txt The runtime NID -> name catalog is derived data and no longer lives in the repository: a Framework-only MSBuild task (GenerateAerolibBinaryTask, sharing the same Ps5Nid implementation the analyzers use) builds it into the intermediate directory from scripts/ps5_names.txt — now the single source of truth — and SharpEmu.HLE embeds it from there. The output is byte-identical to the previously committed binary, verified with cmp against git history; a new test pins that the embedded catalog loads and resolves a known symbol both directions. scripts/generate_aerolib_binary.py is deleted (its algorithm lives in Ps5Nid, its invocation in the build); the REUSE annotation for the binary goes with it. MSBuild's Inputs/Outputs check means the ~154k NID hashes only recompute when the names file actually changes. The task implements ITask against Microsoft.Build.Framework directly, keeping the vulnerable-flagged Utilities.Core package out and the analyzer project's file-IO ban suppressed only inside the task itself. * [SourceGenerators] Emit typed-signature register thunks (phase 2) [SysAbiExport] handlers can now be written with real signatures — a CpuContext followed by up to six int/uint/long/ulong parameters — and the generator emits the SysV unmarshalling thunk, mapping parameters positionally to RDI/RSI/RDX/RCX/R8/R9 with the same unchecked-cast idiom hand-written handlers use. SHEM003 accepts the new shape and rejects register overflow and non-register-representable types. Both shapes coexist, so migration is per-handler; sceKernelPollSema, sceKernelSignalSema, and sceKernelCancelSema migrate as the demonstration (the last showing raw ulong guest-address passthrough). The reflection scan cannot represent typed handlers, so it retires here: RegisterFromAssembly, its signature validation, and ResolveExportInfo are deleted, and the parity test that pinned the generated registry to the scan is replaced by content-invariant tests (duplicate-free, full 715-export surface, catalog identity). Deleting the scan surfaced a phase-1 latent regression — the pre-JIT warm sweep enumerated only reflection-scanned assemblies, so the generated registration path warmed nothing and re-exposed the guest-thread fail-fast risk; the warm set is now derived from the registered handler delegates themselves. * [SourceGenerators] Marshal guest strings declaratively with [GuestCString] (phase 3) A string parameter on a typed [SysAbiExport] handler, annotated [GuestCString(maxLength)], now makes the generated thunk read the null-terminated UTF-8 string from the argument register's guest address before the handler runs, returning ORBIS_GEN2_ERROR_MEMORY_FAULT to the guest when the read fails — the exact prologue nearly every string-taking handler writes by hand. The attribute lives in SharpEmu.HLE next to SysAbiExportAttribute; SHEM008 rejects misuse (non-string parameter, non-positive MaxLength) while a bare string parameter stays a SHEM003 signature error. _open, open, and sceKernelOpen migrate as the demonstration; they were chosen because their hand-written prologue faulted on a null pointer the same way the thunk does (handlers that return INVALID_ARGUMENT for null pointers, like sceKernelCreateSema, keep the raw shape so guest- visible semantics stay untouched). * [SourceGenerators] Apply review findings across the branch Behavior: the open/_open/sceKernelOpen [GuestCString] demo migration is reverted — the local compat reader falls back to host memory for paths in loader-mapped regions that ctx.Memory cannot see, so the generated thunk would have turned recoverable reads into MEMORY_FAULT. The marshalling infrastructure stays, proven by generator/analyzer tests; production migration waits for a handler whose semantics the thunk reproduces exactly. A comment on the handler records why. Build robustness: the aerolib target is skipped for design-time builds (the IDE resolves project references without compiling them, so on a fresh clone the task assembly does not exist yet), and the task/names paths are centralized in properties. The generator now emits no registry for export-free assemblies, so referencing the analyzer can never mint a colliding SharpEmu.Generated type. Cleanup and perf: the pragma-suppression sites left mis-indented by the phase-1 relocation are reformatted and the restores moved after the method body; the dead ExportsForTesting hook and its InternalsVisibleTo are deleted; the aerolib task reuses one SHA1 instance across ~150k names; the analyzer caches the parsed catalog per file snapshot instead of re-parsing 150k lines every compilation start, shares the attribute name constant with the generator, and computes the catalog-membership check once. * [CI] Run the test suites in the build workflow The workflow compiled the test projects (they are in SharpEmu.slnx) but never executed them. A solution-level dotnet test now runs between build and publish, so any test failure fails the build — including the AerolibCatalogTests/SysAbiRegistryTests that guard the build-generated aerolib.bin and the generated export registry. Generation failures of aerolib.bin itself already fail the build step: the MSBuild task logs an error event and returns false, and a missing task assembly or missing embedded output are hard MSBuild errors. The NuGet cache key now also tracks the test projects' lock files. * [SourceGenerators] Address review feedback Multi-diagnostic analyzer tests no longer assume a stable diagnostic order (analyzer execution is concurrent), and the aerolib task logs the full exception instead of only its message so build failures keep the type and stack trace. * [SourceGenerators] Address second review round Symbol-name comparisons in the shape rules and analyzer now pin an explicit SymbolDisplayFormat.FullyQualifiedFormat instead of relying on the display-format default, and the aerolib task fails loudly on a symbol name that would overflow the format's ushort length prefix instead of silently truncating it, with null-safe output-directory handling made explicit. * [SourceGenerators] Embed aerolib.bin via a target so design-time builds never reference it The static EmbeddedResource item referenced the generated file even in design-time builds, where the generation target is skipped — on a fresh clone the IDE would try to embed a file that never existed. The item is now created inside an EmbedAerolibBinary target gated on DesignTimeBuild, separate from the generation target so an up-to-date skip of GenerateAerolibBinary cannot drop the item with the rest of its body, and hooked before AssignTargetPaths since dynamic resource items added later miss the resource pipeline. Verified fresh build, incremental rebuild (embedded catalog test both times), and a simulated design-time compile with no artifacts present. * [SourceGenerators] Regenerate test lock file after rebase onto main Rebase fallout: main's package graph shifted under #200, so the SourceGenerators.Tests lock file is re-evaluated to keep --locked-mode restore green at the branch tip. * [Build] Drop NuGet lock files; rely on central package management Central package management was already in effect (ManagePackageVersionsCentrally with all versions in Directory.Packages.props and no inline PackageReference versions), so the per-project packages.lock.json files and the lock-mode workflow only added maintenance overhead. This removes all eleven lock files, drops RestorePackagesWithLockFile so restore no longer regenerates them, and takes --locked-mode off the CI restore steps (re-keying the NuGet cache on the central props files). Package versions remain centrally pinned in Directory.Packages.props.
This commit is contained in:
committed by
GitHub
parent
30fdd8d6ed
commit
320dbcacba
@@ -0,0 +1,99 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Text;
|
||||
using Microsoft.Build.Framework;
|
||||
|
||||
namespace SharpEmu.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// Builds aerolib.bin (the runtime NID -> name catalog) from scripts/ps5_names.txt at
|
||||
/// build time, replacing scripts/generate_aerolib_binary.py and the committed binary.
|
||||
/// Format matches the python script exactly: uint32 entry count, then per entry a
|
||||
/// byte-length-prefixed NID and a ushort-length-prefixed name, little-endian UTF-8.
|
||||
///
|
||||
/// Implements ITask directly (Framework-only reference) and is an MSBuild task, not an
|
||||
/// analyzer — the file-IO ban that RS1035 enforces for compiler-loaded code does not
|
||||
/// apply to build tasks, hence the targeted suppressions.
|
||||
/// </summary>
|
||||
public sealed class GenerateAerolibBinaryTask : ITask
|
||||
{
|
||||
public IBuildEngine? BuildEngine { get; set; }
|
||||
|
||||
public ITaskHost? HostObject { get; set; }
|
||||
|
||||
[Required]
|
||||
public string NamesFile { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string OutputFile { get; set; } = string.Empty;
|
||||
|
||||
#pragma warning disable RS1035 // File IO is the entire point of this build task.
|
||||
public bool Execute()
|
||||
{
|
||||
try
|
||||
{
|
||||
var names = new List<string>();
|
||||
foreach (var line in File.ReadAllLines(NamesFile))
|
||||
{
|
||||
var name = line.Trim();
|
||||
if (name.Length != 0)
|
||||
{
|
||||
names.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
var outputDirectory = Path.GetDirectoryName(OutputFile);
|
||||
if (!string.IsNullOrEmpty(outputDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(outputDirectory);
|
||||
}
|
||||
|
||||
using (var sha1 = System.Security.Cryptography.SHA1.Create())
|
||||
using (var stream = File.Create(OutputFile))
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
writer.Write((uint)names.Count);
|
||||
foreach (var name in names)
|
||||
{
|
||||
var nidBytes = Encoding.UTF8.GetBytes(Ps5Nid.Compute(name, sha1));
|
||||
var nameBytes = Encoding.UTF8.GetBytes(name);
|
||||
if (nameBytes.Length > ushort.MaxValue)
|
||||
{
|
||||
// A silent (ushort) truncation would corrupt the catalog.
|
||||
throw new InvalidDataException(
|
||||
$"Symbol name exceeds the format's ushort length prefix ({nameBytes.Length} bytes): '{name.Substring(0, 64)}...'");
|
||||
}
|
||||
|
||||
writer.Write((byte)nidBytes.Length);
|
||||
writer.Write(nidBytes);
|
||||
writer.Write((ushort)nameBytes.Length);
|
||||
writer.Write(nameBytes);
|
||||
}
|
||||
}
|
||||
|
||||
BuildEngine?.LogMessageEvent(new BuildMessageEventArgs(
|
||||
$"aerolib: {names.Count} symbols -> {OutputFile}",
|
||||
helpKeyword: null,
|
||||
senderName: nameof(GenerateAerolibBinaryTask),
|
||||
MessageImportance.Normal));
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
BuildEngine?.LogErrorEvent(new BuildErrorEventArgs(
|
||||
subcategory: null,
|
||||
code: "SHEMAERO",
|
||||
file: NamesFile,
|
||||
lineNumber: 0,
|
||||
columnNumber: 0,
|
||||
endLineNumber: 0,
|
||||
endColumnNumber: 0,
|
||||
message: exception.ToString(),
|
||||
helpKeyword: null,
|
||||
senderName: nameof(GenerateAerolibBinaryTask)));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#pragma warning restore RS1035
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace SharpEmu.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// The PS NID derivation: base64 (with the '+','-' alphabet, no padding) of the
|
||||
/// byte-reversed first eight bytes of SHA1(symbolName + fixed suffix). The same
|
||||
/// algorithm scripts/generate_aerolib_binary.py uses to build the runtime catalog,
|
||||
/// in C# so the analyzer and generator can validate and derive NIDs at compile time.
|
||||
/// </summary>
|
||||
public static class Ps5Nid
|
||||
{
|
||||
private static readonly byte[] Suffix =
|
||||
[
|
||||
0x51, 0x8D, 0x64, 0xA6, 0x35, 0xDE, 0xD8, 0xC1,
|
||||
0xE6, 0xB0, 0x39, 0xB1, 0xC3, 0xE5, 0x52, 0x30,
|
||||
];
|
||||
|
||||
public static string Compute(string symbolName)
|
||||
{
|
||||
using var sha1 = SHA1.Create();
|
||||
return Compute(symbolName, sha1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bulk-callable overload: the aerolib build task hashes every catalog name
|
||||
/// (~150k), so the caller owns one SHA1 instance instead of churning one per name.
|
||||
/// </summary>
|
||||
public static string Compute(string symbolName, SHA1 sha1)
|
||||
{
|
||||
var nameBytes = Encoding.UTF8.GetBytes(symbolName);
|
||||
var input = new byte[nameBytes.Length + Suffix.Length];
|
||||
nameBytes.CopyTo(input, 0);
|
||||
Suffix.CopyTo(input, nameBytes.Length);
|
||||
|
||||
var hash = sha1.ComputeHash(input);
|
||||
|
||||
// The script reads the first eight bytes as a little-endian integer and
|
||||
// formats it big-endian before encoding — a byte reversal.
|
||||
var reversed = new byte[8];
|
||||
for (var index = 0; index < 8; index++)
|
||||
{
|
||||
reversed[index] = hash[7 - index];
|
||||
}
|
||||
|
||||
return Convert.ToBase64String(reversed)
|
||||
.TrimEnd('=')
|
||||
.Replace('/', '-');
|
||||
}
|
||||
|
||||
/// <summary>Eleven characters of the '+','-' base64 alphabet.</summary>
|
||||
public static bool IsValidFormat(string nid)
|
||||
{
|
||||
if (nid.Length != 11)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var character in nid)
|
||||
{
|
||||
var valid = character is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or
|
||||
(>= '0' and <= '9') or '+' or '-';
|
||||
if (!valid)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<!--
|
||||
Copyright (C) 2026 SharpEmu Emulator Project
|
||||
SPDX-License-Identifier: GPL-2.0-or-later
|
||||
-->
|
||||
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Roslyn components (source generator + analyzers) for the SysAbi export system.
|
||||
Must target netstandard2.0 to load inside the compiler. Consumed by the emulator
|
||||
projects as an analyzer reference (OutputItemType="Analyzer"), never at runtime. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<!-- RS2008: analyzer release tracking files are overkill for an in-repo analyzer. -->
|
||||
<NoWarn>$(NoWarn);RS2008</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Build.Framework" PrivateAssets="all" ExcludeAssets="runtime" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace SharpEmu.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// Compile-time rules for [SysAbiExport] declarations. Everything here used to be a
|
||||
/// runtime discovery (console warning or InvalidOperationException at boot); the
|
||||
/// analyzer turns each one into a build failure.
|
||||
/// </summary>
|
||||
public static class SysAbiDiagnostics
|
||||
{
|
||||
private const string Category = "SharpEmu.SysAbi";
|
||||
|
||||
public static readonly DiagnosticDescriptor DuplicateNid = new(
|
||||
"SHEM001",
|
||||
"Duplicate SysAbi NID",
|
||||
"NID '{0}' is exported by both '{1}' and '{2}'",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor InvalidNidFormat = new(
|
||||
"SHEM002",
|
||||
"Invalid NID format",
|
||||
"NID '{0}' is not eleven characters of the PS base64 alphabet (A-Z a-z 0-9 + -)",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor InvalidHandlerSignature = new(
|
||||
"SHEM003",
|
||||
"Invalid SysAbi handler signature",
|
||||
"Method '{0}' must be a static, non-generic method returning int and taking no parameters, a single CpuContext parameter, or a CpuContext followed by up to six int/uint/long/ulong or [GuestCString] string parameters",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor NidNameMismatch = new(
|
||||
"SHEM004",
|
||||
"NID does not match export name",
|
||||
"NID '{0}' does not match export name '{1}' (computed NID is '{2}') — one of the two is wrong",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor UnresolvableExport = new(
|
||||
"SHEM005",
|
||||
"Export declares neither NID nor export name",
|
||||
"Method '{0}' must declare an ExportName (from which the NID is derived) or an explicit Nid",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor NameNotInCatalog = new(
|
||||
"SHEM006",
|
||||
"Export name not present in the PS5 symbol catalog",
|
||||
"Export name '{0}' is not in ps5_names.txt — likely a typo, or the catalog needs the new symbol",
|
||||
Category,
|
||||
DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor HandlerNotAccessible = new(
|
||||
"SHEM007",
|
||||
"SysAbi handler not accessible to generated registration",
|
||||
"Method '{0}' (or its containing type) must be at least internal so the generated registry can reference it",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
|
||||
public static readonly DiagnosticDescriptor InvalidGuestCString = new(
|
||||
"SHEM008",
|
||||
"Invalid [GuestCString] usage",
|
||||
"Method '{0}' misuses [GuestCString]: it applies only to string parameters and requires a positive MaxLength",
|
||||
Category,
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Immutable;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
|
||||
namespace SharpEmu.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// Build-time enforcement for [SysAbiExport] declarations: duplicate NIDs, malformed
|
||||
/// NIDs, NIDs that contradict their export name (checked with the PS NID computation),
|
||||
/// handler signatures the dispatcher cannot call, and — when scripts/ps5_names.txt is
|
||||
/// wired up as an AdditionalFile — export names unknown to the symbol catalog.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public sealed class SysAbiExportAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
private const string CatalogFileName = "ps5_names.txt";
|
||||
|
||||
// The catalog is ~150k lines; parse it once per file snapshot instead of on every
|
||||
// compilation start (the IDE creates one per keystroke). A changed file arrives as
|
||||
// a fresh AdditionalText instance, which naturally misses the cache.
|
||||
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<AdditionalText, CatalogHolder> _catalogCache = new();
|
||||
|
||||
private sealed class CatalogHolder
|
||||
{
|
||||
public CatalogHolder(HashSet<string>? names) => Names = names;
|
||||
|
||||
public HashSet<string>? Names { get; }
|
||||
}
|
||||
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
|
||||
[
|
||||
SysAbiDiagnostics.DuplicateNid,
|
||||
SysAbiDiagnostics.InvalidNidFormat,
|
||||
SysAbiDiagnostics.InvalidHandlerSignature,
|
||||
SysAbiDiagnostics.NidNameMismatch,
|
||||
SysAbiDiagnostics.UnresolvableExport,
|
||||
SysAbiDiagnostics.NameNotInCatalog,
|
||||
SysAbiDiagnostics.HandlerNotAccessible,
|
||||
SysAbiDiagnostics.InvalidGuestCString,
|
||||
];
|
||||
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.EnableConcurrentExecution();
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
context.RegisterCompilationStartAction(static startContext =>
|
||||
{
|
||||
var catalogNames = LoadCatalog(startContext.Options.AdditionalFiles, startContext.CancellationToken);
|
||||
var exportsByNid = new ConcurrentDictionary<string, IMethodSymbol>();
|
||||
|
||||
startContext.RegisterSymbolAction(
|
||||
symbolContext => AnalyzeMethod(symbolContext, catalogNames, exportsByNid),
|
||||
SymbolKind.Method);
|
||||
});
|
||||
}
|
||||
|
||||
private static HashSet<string>? LoadCatalog(
|
||||
ImmutableArray<AdditionalText> additionalFiles,
|
||||
System.Threading.CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var file in additionalFiles)
|
||||
{
|
||||
if (!file.Path.EndsWith(CatalogFileName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
return _catalogCache.GetValue(file, static f => new CatalogHolder(ParseCatalog(f))).Names;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static HashSet<string>? ParseCatalog(AdditionalText file)
|
||||
{
|
||||
var text = file.GetText();
|
||||
if (text is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var line in text.Lines)
|
||||
{
|
||||
var name = line.ToString().Trim();
|
||||
if (name.Length != 0)
|
||||
{
|
||||
names.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
private static void AnalyzeMethod(
|
||||
SymbolAnalysisContext context,
|
||||
HashSet<string>? catalogNames,
|
||||
ConcurrentDictionary<string, IMethodSymbol> exportsByNid)
|
||||
{
|
||||
var method = (IMethodSymbol)context.Symbol;
|
||||
AttributeData? exportAttribute = null;
|
||||
foreach (var attribute in method.GetAttributes())
|
||||
{
|
||||
if (SysAbiExportShape.IsSysAbiExportAttribute(attribute.AttributeClass))
|
||||
{
|
||||
exportAttribute = attribute;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (exportAttribute is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var location = method.Locations.Length != 0 ? method.Locations[0] : Location.None;
|
||||
var methodDisplay = $"{method.ContainingType.ToDisplayString()}.{method.Name}";
|
||||
|
||||
if (SysAbiExportShape.Classify(method, out _, out var invalidGuestCString) == SysAbiExportShape.HandlerShape.Invalid)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
invalidGuestCString ? SysAbiDiagnostics.InvalidGuestCString : SysAbiDiagnostics.InvalidHandlerSignature,
|
||||
location,
|
||||
methodDisplay));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!SysAbiExportShape.IsAccessibleFromGeneratedCode(method))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
SysAbiDiagnostics.HandlerNotAccessible, location, methodDisplay));
|
||||
}
|
||||
|
||||
var arguments = SysAbiExportShape.ReadArguments(exportAttribute);
|
||||
var hasNid = !string.IsNullOrWhiteSpace(arguments.Nid);
|
||||
var hasName = !string.IsNullOrWhiteSpace(arguments.ExportName);
|
||||
|
||||
if (!hasNid && !hasName)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
SysAbiDiagnostics.UnresolvableExport, location, methodDisplay));
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasNid && !Ps5Nid.IsValidFormat(arguments.Nid))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
SysAbiDiagnostics.InvalidNidFormat, location, arguments.Nid));
|
||||
return;
|
||||
}
|
||||
|
||||
var effectiveNid = arguments.Nid;
|
||||
if (hasName)
|
||||
{
|
||||
var computed = Ps5Nid.Compute(arguments.ExportName);
|
||||
|
||||
var nameInCatalog = catalogNames is not null && catalogNames.Contains(arguments.ExportName);
|
||||
|
||||
// A declared NID that contradicts its name is only provably wrong when the
|
||||
// name is a real catalog symbol. Names outside the catalog are synthetic
|
||||
// labels for NIDs whose true symbol is unknown (the "sceAgcUnknown..."
|
||||
// convention) — for those the NID is authoritative and only SHEM006 applies.
|
||||
// With no catalog wired, every name is validated (fail closed).
|
||||
var nameIsKnown = catalogNames is null || nameInCatalog;
|
||||
if (hasNid && nameIsKnown && !string.Equals(computed, arguments.Nid, StringComparison.Ordinal))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
SysAbiDiagnostics.NidNameMismatch,
|
||||
location,
|
||||
arguments.Nid,
|
||||
arguments.ExportName,
|
||||
computed));
|
||||
}
|
||||
|
||||
if (!hasNid)
|
||||
{
|
||||
effectiveNid = computed;
|
||||
}
|
||||
|
||||
if (catalogNames is not null && !nameInCatalog)
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
SysAbiDiagnostics.NameNotInCatalog, location, arguments.ExportName));
|
||||
}
|
||||
}
|
||||
|
||||
var existing = exportsByNid.GetOrAdd(effectiveNid, method);
|
||||
if (!SymbolEqualityComparer.Default.Equals(existing, method))
|
||||
{
|
||||
context.ReportDiagnostic(Diagnostic.Create(
|
||||
SysAbiDiagnostics.DuplicateNid,
|
||||
location,
|
||||
effectiveNid,
|
||||
$"{existing.ContainingType.ToDisplayString()}.{existing.Name}",
|
||||
methodDisplay));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Collections.Immutable;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace SharpEmu.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// Emits the SysAbi export registry at compile time: one static class per assembly whose
|
||||
/// CreateExports(Generation) lists every [SysAbiExport] handler — generation filtering,
|
||||
/// name fallback, and library default preserved from the retired reflection scan. NIDs
|
||||
/// omitted from attributes are derived from the export name with the PS NID algorithm
|
||||
/// (the same computation the runtime symbol catalog was built from). Handlers written
|
||||
/// with typed signatures get a SysV register-unmarshalling thunk emitted here.
|
||||
///
|
||||
/// Invalid declarations are skipped here and rejected by SysAbiExportAnalyzer as build
|
||||
/// errors, so nothing can be silently dropped.
|
||||
/// </summary>
|
||||
[Generator]
|
||||
public sealed class SysAbiExportGenerator : IIncrementalGenerator
|
||||
{
|
||||
private const string AttributeMetadataName = SysAbiExportShape.SysAbiExportAttributeName;
|
||||
|
||||
private sealed class ExportModel : IEquatable<ExportModel>
|
||||
{
|
||||
public ExportModel(string containingType, string methodName, SysAbiExportShape.HandlerShape shape, string typedParameterKinds, string libraryName, string nid, string exportName, int target)
|
||||
{
|
||||
ContainingType = containingType;
|
||||
MethodName = methodName;
|
||||
Shape = shape;
|
||||
TypedParameterKinds = typedParameterKinds;
|
||||
LibraryName = libraryName;
|
||||
Nid = nid;
|
||||
ExportName = exportName;
|
||||
Target = target;
|
||||
}
|
||||
|
||||
public string ContainingType { get; }
|
||||
public string MethodName { get; }
|
||||
public SysAbiExportShape.HandlerShape Shape { get; }
|
||||
|
||||
// Deliberately a comma-joined string ("uint,int,cstring:4096") rather than an
|
||||
// array: the model must be equatable for incremental-generator caching, and a
|
||||
// string gets that for free where an array would need a custom comparer.
|
||||
public string TypedParameterKinds { get; }
|
||||
public string LibraryName { get; }
|
||||
public string Nid { get; }
|
||||
public string ExportName { get; }
|
||||
public int Target { get; }
|
||||
|
||||
public bool Equals(ExportModel? other) =>
|
||||
other is not null &&
|
||||
ContainingType == other.ContainingType &&
|
||||
MethodName == other.MethodName &&
|
||||
Shape == other.Shape &&
|
||||
TypedParameterKinds == other.TypedParameterKinds &&
|
||||
LibraryName == other.LibraryName &&
|
||||
Nid == other.Nid &&
|
||||
ExportName == other.ExportName &&
|
||||
Target == other.Target;
|
||||
|
||||
public override bool Equals(object? obj) => Equals(obj as ExportModel);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
var hash = 17;
|
||||
hash = (hash * 31) + ContainingType.GetHashCode();
|
||||
hash = (hash * 31) + MethodName.GetHashCode();
|
||||
hash = (hash * 31) + Nid.GetHashCode();
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var exports = context.SyntaxProvider
|
||||
.ForAttributeWithMetadataName(
|
||||
AttributeMetadataName,
|
||||
static (node, _) => node is MethodDeclarationSyntax,
|
||||
static (attributeContext, _) => CreateModel(attributeContext))
|
||||
.Where(static model => model is not null)
|
||||
.Collect();
|
||||
|
||||
var assemblyName = context.CompilationProvider
|
||||
.Select(static (compilation, _) => compilation.AssemblyName ?? "Assembly");
|
||||
|
||||
context.RegisterSourceOutput(
|
||||
exports.Combine(assemblyName),
|
||||
static (productionContext, source) => Emit(productionContext, source.Left!, source.Right));
|
||||
}
|
||||
|
||||
private static ExportModel? CreateModel(GeneratorAttributeSyntaxContext context)
|
||||
{
|
||||
if (context.TargetSymbol is not IMethodSymbol method ||
|
||||
!SysAbiExportShape.IsAccessibleFromGeneratedCode(method))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var shape = SysAbiExportShape.Classify(method, out var typedParameterKinds);
|
||||
if (shape == SysAbiExportShape.HandlerShape.Invalid)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var attribute = context.Attributes[0];
|
||||
var arguments = SysAbiExportShape.ReadArguments(attribute);
|
||||
var nid = arguments.Nid;
|
||||
var exportName = arguments.ExportName;
|
||||
|
||||
// Mirror ModuleManager.ResolveExportInfo: a missing NID resolves from the export
|
||||
// name (algorithmically — equivalent to the runtime catalog lookup, which was
|
||||
// built with the same computation); a missing name falls back to the method name.
|
||||
if (string.IsNullOrWhiteSpace(nid) && !string.IsNullOrWhiteSpace(exportName))
|
||||
{
|
||||
nid = Ps5Nid.Compute(exportName);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(nid))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(exportName))
|
||||
{
|
||||
exportName = method.Name;
|
||||
}
|
||||
|
||||
var libraryName = string.IsNullOrWhiteSpace(arguments.LibraryName) ? "libKernel" : arguments.LibraryName;
|
||||
return new ExportModel(
|
||||
method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||
method.Name,
|
||||
shape,
|
||||
typedParameterKinds,
|
||||
libraryName,
|
||||
nid!,
|
||||
exportName!,
|
||||
arguments.Target);
|
||||
}
|
||||
|
||||
private static void Emit(
|
||||
SourceProductionContext context,
|
||||
ImmutableArray<ExportModel?> exports,
|
||||
string assemblyName)
|
||||
{
|
||||
// No exports, no registry: an assembly that merely references the analyzer
|
||||
// (e.g. SharpEmu.HLE itself) must not mint a colliding
|
||||
// SharpEmu.Generated.SysAbiExportRegistry type.
|
||||
if (exports.IsDefaultOrEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("// <auto-generated by SharpEmu.SourceGenerators/SysAbiExportGenerator />");
|
||||
builder.AppendLine("#nullable enable");
|
||||
builder.AppendLine();
|
||||
builder.AppendLine("namespace SharpEmu.Generated;");
|
||||
builder.AppendLine();
|
||||
builder.AppendLine("/// <summary>Compile-time SysAbi export registry for " + assemblyName + ".</summary>");
|
||||
builder.AppendLine("public static class SysAbiExportRegistry");
|
||||
builder.AppendLine("{");
|
||||
builder.AppendLine(" /// <summary>");
|
||||
builder.AppendLine(" /// Exports effective for the given registration generation, with the same");
|
||||
builder.AppendLine(" /// semantics as the reflection scan: an attribute Target of None inherits the");
|
||||
builder.AppendLine(" /// registration generation, and exports outside it are skipped.");
|
||||
builder.AppendLine(" /// </summary>");
|
||||
builder.AppendLine(" public static global::System.Collections.Generic.IReadOnlyList<global::SharpEmu.HLE.ExportedFunction> CreateExports(");
|
||||
builder.AppendLine(" global::SharpEmu.HLE.Generation registrationGeneration)");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine($" var exports = new global::System.Collections.Generic.List<global::SharpEmu.HLE.ExportedFunction>({exports.Length});");
|
||||
|
||||
foreach (var export in exports)
|
||||
{
|
||||
if (export is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var function = export.Shape switch
|
||||
{
|
||||
SysAbiExportShape.HandlerShape.ContextOnly => $"{export.ContainingType}.{export.MethodName}",
|
||||
SysAbiExportShape.HandlerShape.Parameterless => $"static _ => {export.ContainingType}.{export.MethodName}()",
|
||||
_ => TypedThunk(export),
|
||||
};
|
||||
builder.AppendLine(
|
||||
$" Add(exports, registrationGeneration, {Literal(export.LibraryName)}, {Literal(export.Nid)}, " +
|
||||
$"{Literal(export.ExportName)}, (global::SharpEmu.HLE.Generation){export.Target}, {function});");
|
||||
}
|
||||
|
||||
builder.AppendLine(" return exports;");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine();
|
||||
builder.AppendLine(" private static void Add(");
|
||||
builder.AppendLine(" global::System.Collections.Generic.List<global::SharpEmu.HLE.ExportedFunction> exports,");
|
||||
builder.AppendLine(" global::SharpEmu.HLE.Generation registrationGeneration,");
|
||||
builder.AppendLine(" string libraryName,");
|
||||
builder.AppendLine(" string nid,");
|
||||
builder.AppendLine(" string exportName,");
|
||||
builder.AppendLine(" global::SharpEmu.HLE.Generation attributeTarget,");
|
||||
builder.AppendLine(" global::SharpEmu.HLE.SysAbiFunction function)");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine(" var target = attributeTarget == global::SharpEmu.HLE.Generation.None ? registrationGeneration : attributeTarget;");
|
||||
builder.AppendLine(" if ((target & registrationGeneration) == 0)");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine(" return;");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine();
|
||||
builder.AppendLine(" exports.Add(new global::SharpEmu.HLE.ExportedFunction(libraryName, nid, exportName, target, function));");
|
||||
builder.AppendLine(" }");
|
||||
builder.AppendLine("}");
|
||||
|
||||
context.AddSource("SysAbiExportRegistry.g.cs", SourceText.From(builder.ToString(), Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SysV integer-register unmarshalling: parameter i reads argument register i as a
|
||||
/// raw ulong and reinterprets it with an unchecked cast, exactly the idiom
|
||||
/// hand-written handlers use today. [GuestCString] parameters read the register as
|
||||
/// a guest pointer and marshal the null-terminated UTF-8 string up front, failing
|
||||
/// the call with ORBIS_GEN2_ERROR_MEMORY_FAULT before the handler runs.
|
||||
/// </summary>
|
||||
private static string TypedThunk(ExportModel export)
|
||||
{
|
||||
var kinds = export.TypedParameterKinds.Split(',');
|
||||
var arguments = new string[kinds.Length];
|
||||
var reads = new StringBuilder();
|
||||
for (var index = 0; index < kinds.Length; index++)
|
||||
{
|
||||
var register = "ctx[global::SharpEmu.HLE.CpuRegister." + SysAbiExportShape.ArgumentRegisters[index] + "]";
|
||||
if (kinds[index].StartsWith("cstring:", StringComparison.Ordinal))
|
||||
{
|
||||
var maxLength = kinds[index].Substring("cstring:".Length);
|
||||
var variable = "guestString" + index;
|
||||
reads.AppendLine($" if (!ctx.TryReadNullTerminatedUtf8({register}, {maxLength}, out var {variable}))");
|
||||
reads.AppendLine(" {");
|
||||
reads.AppendLine(" return ctx.SetReturn(global::SharpEmu.HLE.OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);");
|
||||
reads.AppendLine(" }");
|
||||
reads.AppendLine();
|
||||
arguments[index] = variable;
|
||||
continue;
|
||||
}
|
||||
|
||||
arguments[index] = kinds[index] == "ulong"
|
||||
? register
|
||||
: "unchecked((" + kinds[index] + ")" + register + ")";
|
||||
}
|
||||
|
||||
var invocation = export.ContainingType + "." + export.MethodName + "(ctx, " + string.Join(", ", arguments) + ")";
|
||||
if (reads.Length == 0)
|
||||
{
|
||||
return "static ctx => " + invocation;
|
||||
}
|
||||
|
||||
var builder = new StringBuilder();
|
||||
builder.AppendLine("static ctx =>");
|
||||
builder.AppendLine(" {");
|
||||
builder.Append(reads);
|
||||
builder.AppendLine(" return " + invocation + ";");
|
||||
builder.Append(" }");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string Literal(string value) =>
|
||||
"\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace SharpEmu.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// Shared shape rules for [SysAbiExport] methods, used by both the generator (to decide
|
||||
/// what it can emit) and the analyzer (to reject everything else as build errors), so
|
||||
/// the two can never disagree about what a valid handler is.
|
||||
/// </summary>
|
||||
public static class SysAbiExportShape
|
||||
{
|
||||
/// <summary>Single source of truth so the generator and analyzer can never
|
||||
/// disagree about which attribute marks an export.</summary>
|
||||
public const string SysAbiExportAttributeName = "SharpEmu.HLE.SysAbiExportAttribute";
|
||||
|
||||
public readonly struct Arguments
|
||||
{
|
||||
public Arguments(string libraryName, string nid, string exportName, int target)
|
||||
{
|
||||
LibraryName = libraryName;
|
||||
Nid = nid;
|
||||
ExportName = exportName;
|
||||
Target = target;
|
||||
}
|
||||
|
||||
public string LibraryName { get; }
|
||||
public string Nid { get; }
|
||||
public string ExportName { get; }
|
||||
public int Target { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SysV integer argument registers in call order; typed handler parameters map to
|
||||
/// these positionally.
|
||||
/// </summary>
|
||||
public static readonly string[] ArgumentRegisters = ["Rdi", "Rsi", "Rdx", "Rcx", "R8", "R9"];
|
||||
|
||||
public enum HandlerShape
|
||||
{
|
||||
Invalid,
|
||||
/// <summary>int M(CpuContext) — the classic raw-register shape.</summary>
|
||||
ContextOnly,
|
||||
/// <summary>int M() — no guest state needed.</summary>
|
||||
Parameterless,
|
||||
/// <summary>int M(CpuContext, up to six int/uint/long/ulong args) — the
|
||||
/// generator emits the SysV register unmarshalling thunk.</summary>
|
||||
Typed,
|
||||
}
|
||||
|
||||
private const string GuestCStringAttributeName = "SharpEmu.HLE.GuestCStringAttribute";
|
||||
|
||||
/// <summary>Static, non-generic, returns int, takes one of the supported shapes.</summary>
|
||||
public static HandlerShape Classify(IMethodSymbol method, out string typedParameterKinds) =>
|
||||
Classify(method, out typedParameterKinds, out _);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="invalidGuestCString"/> distinguishes a misused [GuestCString]
|
||||
/// (wrong parameter type, non-positive MaxLength) from a plain signature mismatch,
|
||||
/// so the analyzer can point at the marshalling attribute instead of the shape.
|
||||
/// </summary>
|
||||
public static HandlerShape Classify(IMethodSymbol method, out string typedParameterKinds, out bool invalidGuestCString)
|
||||
{
|
||||
typedParameterKinds = string.Empty;
|
||||
invalidGuestCString = false;
|
||||
if (!method.IsStatic ||
|
||||
method.IsGenericMethod ||
|
||||
method.ReturnType.SpecialType != SpecialType.System_Int32)
|
||||
{
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
if (method.Parameters.Length == 0)
|
||||
{
|
||||
return HandlerShape.Parameterless;
|
||||
}
|
||||
|
||||
if (method.Parameters[0].RefKind != RefKind.None || !IsCpuContext(method.Parameters[0].Type))
|
||||
{
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
if (method.Parameters.Length == 1)
|
||||
{
|
||||
return HandlerShape.ContextOnly;
|
||||
}
|
||||
|
||||
if (method.Parameters.Length > 1 + ArgumentRegisters.Length)
|
||||
{
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
var kinds = new string[method.Parameters.Length - 1];
|
||||
for (var index = 1; index < method.Parameters.Length; index++)
|
||||
{
|
||||
var parameter = method.Parameters[index];
|
||||
if (parameter.RefKind != RefKind.None)
|
||||
{
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
var hasGuestCString = TryGetGuestCStringMaxLength(parameter, out var maxLength);
|
||||
if (parameter.Type.SpecialType == SpecialType.System_String)
|
||||
{
|
||||
if (!hasGuestCString)
|
||||
{
|
||||
// A bare string has no register representation; the guest pointer
|
||||
// must be marshalled explicitly via [GuestCString].
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
if (maxLength <= 0)
|
||||
{
|
||||
invalidGuestCString = true;
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
kinds[index - 1] = "cstring:" + maxLength.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hasGuestCString)
|
||||
{
|
||||
invalidGuestCString = true;
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
|
||||
kinds[index - 1] = parameter.Type.SpecialType switch
|
||||
{
|
||||
SpecialType.System_Int32 => "int",
|
||||
SpecialType.System_UInt32 => "uint",
|
||||
SpecialType.System_Int64 => "long",
|
||||
SpecialType.System_UInt64 => "ulong",
|
||||
_ => string.Empty,
|
||||
};
|
||||
if (kinds[index - 1].Length == 0)
|
||||
{
|
||||
return HandlerShape.Invalid;
|
||||
}
|
||||
}
|
||||
|
||||
typedParameterKinds = string.Join(",", kinds);
|
||||
return HandlerShape.Typed;
|
||||
}
|
||||
|
||||
// Symbol names are compared with an explicit fully-qualified format so
|
||||
// classification can never depend on a display-format default.
|
||||
private static bool IsCpuContext(ITypeSymbol type) =>
|
||||
type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "global::SharpEmu.HLE.CpuContext";
|
||||
|
||||
public static bool IsSysAbiExportAttribute(INamedTypeSymbol? attributeClass) =>
|
||||
attributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "global::" + SysAbiExportAttributeName;
|
||||
|
||||
private static bool TryGetGuestCStringMaxLength(IParameterSymbol parameter, out int maxLength)
|
||||
{
|
||||
maxLength = 0;
|
||||
foreach (var attribute in parameter.GetAttributes())
|
||||
{
|
||||
if (attribute.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) != "global::" + GuestCStringAttributeName)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attribute.ConstructorArguments.Length == 1 &&
|
||||
attribute.ConstructorArguments[0].Value is int value)
|
||||
{
|
||||
maxLength = value;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsValidHandler(IMethodSymbol method) =>
|
||||
Classify(method, out _) != HandlerShape.Invalid;
|
||||
|
||||
/// <summary>The generated registry lives in the same assembly: internal suffices.</summary>
|
||||
public static bool IsAccessibleFromGeneratedCode(IMethodSymbol method)
|
||||
{
|
||||
if (method.DeclaredAccessibility is Accessibility.Private or Accessibility.ProtectedOrInternal
|
||||
or Accessibility.Protected or Accessibility.ProtectedAndInternal)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var type = method.ContainingType; type is not null; type = type.ContainingType)
|
||||
{
|
||||
if (type.DeclaredAccessibility is Accessibility.Private or Accessibility.Protected
|
||||
or Accessibility.ProtectedOrInternal or Accessibility.ProtectedAndInternal)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Arguments ReadArguments(AttributeData attribute)
|
||||
{
|
||||
var libraryName = string.Empty;
|
||||
var nid = string.Empty;
|
||||
var exportName = string.Empty;
|
||||
var target = 0;
|
||||
foreach (var argument in attribute.NamedArguments)
|
||||
{
|
||||
switch (argument.Key)
|
||||
{
|
||||
case "LibraryName":
|
||||
libraryName = argument.Value.Value as string ?? string.Empty;
|
||||
break;
|
||||
case "Nid":
|
||||
nid = argument.Value.Value as string ?? string.Empty;
|
||||
break;
|
||||
case "ExportName":
|
||||
exportName = argument.Value.Value as string ?? string.Empty;
|
||||
break;
|
||||
case "Target":
|
||||
target = argument.Value.Value is int value ? value : 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new Arguments(libraryName, nid, exportName, target);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user