chore(all): resolve lint findings, update example plugin, refine docs and add LGPL licenses
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../PackageMetadata.props" />
|
||||
<PropertyGroup>
|
||||
<RootNamespace>BD2.GameSdk</RootNamespace>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
one line to give the library's name and an idea of what it does.
|
||||
Copyright (C) year name of author
|
||||
|
||||
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in
|
||||
the library `Frob' (a library for tweaking knobs) written
|
||||
by James Random Hacker.
|
||||
|
||||
signature of Ty Coon, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
That's all there is to it!
|
||||
@@ -1,60 +0,0 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)] [string]$GameDir,
|
||||
[string]$VersionConfig,
|
||||
[string]$PackageVersion,
|
||||
[string]$OutputDirectory
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $VersionConfig) { $VersionConfig = Join-Path $PSScriptRoot '..\..\versions.json' }
|
||||
if (-not $OutputDirectory) { $OutputDirectory = Join-Path $PSScriptRoot '..\..\.build\nuget' }
|
||||
$repository = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))
|
||||
$versions = Get-Content -LiteralPath $VersionConfig -Raw | ConvertFrom-Json
|
||||
if (-not $PackageVersion) {
|
||||
[xml]$metadata = Get-Content -LiteralPath (Join-Path $PSScriptRoot '..\PackageMetadata.props') -Raw
|
||||
$PackageVersion = "$($metadata.Project.PropertyGroup.BD2PackageVersion)-game.$($versions.game_version)"
|
||||
}
|
||||
if ($PackageVersion -notmatch '^\d+\.\d+\.\d+-game\.\d+\.\d+\.\d+(?:\.[A-Za-z0-9-]+)*$') {
|
||||
throw 'PackageVersion must be SemVer with game version, for example 0.2.1-game.2.35.10.'
|
||||
}
|
||||
if ($PackageVersion -notmatch ('-game\.' + [regex]::Escape([string]$versions.game_version) + '(?:\.|$)')) {
|
||||
throw 'PackageVersion game suffix must match VersionConfig game_version.'
|
||||
}
|
||||
$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
|
||||
$staging = Join-Path $repository ".build\nuget-staging\$PackageVersion"
|
||||
$sdk = Join-Path $staging 'sdk'
|
||||
$tool = Join-Path $staging 'tool'
|
||||
$runtimeObj = Join-Path $staging 'runtime-obj'
|
||||
$runtimeBin = Join-Path $staging 'runtime-bin'
|
||||
$packageObj = Join-Path $staging 'package-obj'
|
||||
$packageBin = Join-Path $staging 'package-bin'
|
||||
New-Item -ItemType Directory -Force -Path $OutputDirectory, $staging | Out-Null
|
||||
function Invoke-Dotnet([string[]]$Arguments) {
|
||||
& dotnet @Arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
$toolVersion = $PackageVersion.Split('-')[0]
|
||||
Invoke-Dotnet @('publish', (Join-Path $PSScriptRoot 'GameSdk.csproj'), '-c', 'Release', '--nologo', '-o', $tool, "-p:Version=$toolVersion", '-p:UseAppHost=false')
|
||||
$assembly = Join-Path $GameDir 'BrownDust II_Data\Managed\Assembly-CSharp.dll'
|
||||
$toolDll = Join-Path $tool 'GameSdk.dll'
|
||||
$previousSdkCache = $env:BD2_GAME_SDK_CACHE
|
||||
try {
|
||||
if (-not $env:BD2_GAME_SDK_CACHE) { $env:BD2_GAME_SDK_CACHE = Join-Path $repository '.build/game-sdk' }
|
||||
Invoke-Dotnet @($toolDll, 'prepare-embedded', $assembly, $sdk, $VersionConfig)
|
||||
} finally { $env:BD2_GAME_SDK_CACHE = $previousSdkCache }
|
||||
$sharedSdk = [IO.File]::ReadAllText((Join-Path $sdk 'shared-sdk.txt')).Trim()
|
||||
$table = Join-Path $sharedSdk 'names.json'
|
||||
$runtimeProject = Join-Path $PSScriptRoot '..\GameNames\GameNames.csproj'
|
||||
Invoke-Dotnet @('pack', $runtimeProject, '-c', 'Release', '--nologo', '-o', $OutputDirectory,
|
||||
"-p:Version=$PackageVersion", "-p:GameNamesTable=$table", "-p:BaseIntermediateOutputPath=$runtimeObj/", "-p:OutputPath=$runtimeBin/")
|
||||
Invoke-Dotnet @($toolDll, 'verify-runtime', $table, (Join-Path $runtimeBin 'BD2.GameNames.dll'))
|
||||
$packageProject = Join-Path $PSScriptRoot 'Package\BD2.GameSdk.Package.csproj'
|
||||
$nugetConfig = Join-Path $staging 'NuGet.Config'
|
||||
$escapedSource = [Security.SecurityElement]::Escape($OutputDirectory)
|
||||
[IO.File]::WriteAllText($nugetConfig, "<configuration><packageSources><clear/><add key=`"bd2-local`" value=`"$escapedSource`"/><add key=`"nuget.org`" value=`"https://api.nuget.org/v3/index.json`"/></packageSources></configuration>")
|
||||
Invoke-Dotnet @('restore', $packageProject, '--configfile', $nugetConfig, "-p:Version=$PackageVersion",
|
||||
'-p:BD2Packaging=true', "-p:BaseIntermediateOutputPath=$packageObj/", "-p:OutputPath=$packageBin/")
|
||||
Invoke-Dotnet @('pack', $packageProject, '-c', 'Release', '--no-restore', '--nologo', '-o', $OutputDirectory,
|
||||
"-p:Version=$PackageVersion", "-p:BD2ToolPublishDir=$tool", '-p:BD2Packaging=true',
|
||||
"-p:BaseIntermediateOutputPath=$packageObj/", "-p:OutputPath=$packageBin/")
|
||||
Write-Host "Created BD2.GameNames and BD2.GameSdk $PackageVersion in $OutputDirectory"
|
||||
@@ -13,13 +13,14 @@
|
||||
<ProjectReference Include="../../GameNames/GameNames.csproj" Condition="'$(BD2Packaging)' != 'true'" />
|
||||
<PackageReference Include="BD2.GameNames" Version="[$(Version)]" Condition="'$(BD2Packaging)' == 'true'" />
|
||||
<None Include="../README.md" Pack="true" PackagePath="README.md" />
|
||||
<None Include="../LICENSE" Pack="true" PackagePath="" />
|
||||
<None Include="../THIRD-PARTY-NOTICES.txt" Pack="true" PackagePath="" />
|
||||
<None Include="build/*" Pack="true" PackagePath="build/" />
|
||||
<None Include="_._" Pack="true" PackagePath="lib/netstandard2.0/" />
|
||||
<None Include="$(BD2ToolPublishDir)/**/*" Exclude="$(BD2ToolPublishDir)/**/*.exe;$(BD2ToolPublishDir)/**/*.pdb" Condition="'$(BD2ToolPublishDir)' != ''" Pack="true" PackagePath="tools/net8.0/%(RecursiveDir)%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
<Target Name="RequirePackageInputs" BeforeTargets="GenerateNuspec">
|
||||
<Error Condition="'$(BD2Packaging)' != 'true'" Text="Pack with ../Pack.ps1; BD2Packaging=true is required for the version-locked runtime dependency." />
|
||||
<Error Condition="!Exists('$(BD2ToolPublishDir)/GameSdk.dll')" Text="Pack with ../Pack.ps1: published tool missing." />
|
||||
<Error Condition="'$(BD2Packaging)' != 'true'" Text="Pack with bd2w sdk pack; BD2Packaging=true is required for the version-locked runtime dependency." />
|
||||
<Error Condition="!Exists('$(BD2ToolPublishDir)/GameSdk.dll')" Text="Pack with bd2w sdk pack: published tool missing." />
|
||||
</Target>
|
||||
</Project>
|
||||
|
||||
+107
-108
@@ -19,18 +19,9 @@ internal static class Program
|
||||
switch (args.FirstOrDefault())
|
||||
{
|
||||
case "prepare" when args.Length == 5: Prepare(args[1], args[2], args[3], args[4]); break;
|
||||
case "prepare-embedded" when args.Length is >= 3 and <= 6:
|
||||
var prepareOptions = args.Skip(3).ToList();
|
||||
string expectedGameVersion = null;
|
||||
int versionOption = prepareOptions.IndexOf("--game-version");
|
||||
if (versionOption >= 0)
|
||||
{
|
||||
if (versionOption + 1 >= prepareOptions.Count) throw new ArgumentException("--game-version requires a version");
|
||||
expectedGameVersion = prepareOptions[versionOption + 1];
|
||||
prepareOptions.RemoveRange(versionOption, 2);
|
||||
}
|
||||
if (prepareOptions.Count > 1) throw new ArgumentException("Invalid prepare-embedded options");
|
||||
PrepareEmbedded(args[1], args[2], prepareOptions.FirstOrDefault(), expectedGameVersion); break;
|
||||
case "prepare-embedded" when args.Length is 3 or 5:
|
||||
if (args.Length == 5 && args[3] != "--game-version") throw new ArgumentException("Invalid prepare-embedded options");
|
||||
PrepareEmbedded(args[1], args[2], args.Length == 5 ? args[4] : null); break;
|
||||
case "export-names" when args.Length == 2: ExportNames(args[1]); break;
|
||||
case "names" when args.Length == 5: GenerateNames(args[1], args[2], args[3], args[4]); break;
|
||||
case "shell" when args.Length == 4: GenerateShell(args[1], args[2], args[3]); break;
|
||||
@@ -40,7 +31,7 @@ internal static class Program
|
||||
case "verify" when args.Length is 3 or 4: Verify(args[1], args[2], args.Length == 4 ? args[3] : null); break;
|
||||
case "verify-runtime" when args.Length == 3: SelfTest.VerifyRuntime(args[1], args[2]); break;
|
||||
case "self-test": SelfTest.Run(); break;
|
||||
default: throw new ArgumentException("Usage: prepare-embedded <Assembly-CSharp.dll> <output-dir> [versions.json] | export-names <names.json> | names <Assembly-CSharp.dll> <mapping.obfuscate> <versions.json> <names.json> | shell <names.json> <Assembly-CSharp.dll> <output.dll> | source-navigation <readable-implementation.dll> <dependency-directory> | verify-navigation <sdk-directory> | reobf <names.json> <input.dll> <output.dll> [Assembly-CSharp.dll] [dependency-directory] | verify <names.json> <plugin.dll> [Assembly-CSharp.dll] | verify-runtime <names.json> <BD2.GameNames.dll> | self-test");
|
||||
default: throw new ArgumentException("Usage: prepare-embedded <Assembly-CSharp.dll> <output-dir> [--game-version version] | export-names <names.json> | names <Assembly-CSharp.dll> <mapping.obfuscate> <versions.json> <names.json> | shell <names.json> <Assembly-CSharp.dll> <output.dll> | source-navigation <readable-implementation.dll> <dependency-directory> | verify-navigation <sdk-directory> | reobf <names.json> <input.dll> <output.dll> [Assembly-CSharp.dll] [dependency-directory] | verify <names.json> <plugin.dll> [Assembly-CSharp.dll] | verify-runtime <names.json> <BD2.GameNames.dll> | self-test");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -58,7 +49,7 @@ internal static class Program
|
||||
|
||||
internal static byte[] EmbeddedNames()
|
||||
{
|
||||
using var stream = typeof(Program).Assembly.GetManifestResourceStream("BD2.GameNames.names.json.gz")
|
||||
using Stream stream = typeof(Program).Assembly.GetManifestResourceStream("BD2.GameNames.names.json.gz")
|
||||
?? throw new InvalidDataException("SDK embedded names table is missing; rebuild the SDK");
|
||||
using var output = new MemoryStream();
|
||||
stream.CopyTo(output);
|
||||
@@ -71,7 +62,7 @@ internal static class Program
|
||||
byte[] compressed = EmbeddedNames();
|
||||
File.WriteAllBytes(tablePath + ".gz", compressed);
|
||||
using var gzip = new GZipStream(new MemoryStream(compressed), CompressionMode.Decompress);
|
||||
using var destination = File.Create(tablePath);
|
||||
using FileStream destination = File.Create(tablePath);
|
||||
gzip.CopyTo(destination);
|
||||
}
|
||||
|
||||
@@ -81,17 +72,17 @@ internal static class Program
|
||||
return File.Exists(pointer) ? File.ReadAllText(pointer).Trim() : Path.GetFullPath(directory);
|
||||
}
|
||||
|
||||
internal static void PrepareEmbedded(string assembly, string output, string versions = null, string expectedGameVersion = null) =>
|
||||
PrepareShared(EmbeddedNames(), assembly, output, versions, expectedGameVersion);
|
||||
internal static void PrepareEmbedded(string assembly, string output, string expectedGameVersion = null) =>
|
||||
PrepareShared(EmbeddedNames(), assembly, output, expectedGameVersion);
|
||||
|
||||
internal static void PreparePackage(string compressedTable, string assembly, string output) =>
|
||||
PrepareShared(File.ReadAllBytes(compressedTable), assembly, output, null, null);
|
||||
PrepareShared(File.ReadAllBytes(compressedTable), assembly, output, null);
|
||||
|
||||
private static void PrepareShared(byte[] compressed, string assembly, string output, string versions, string expectedGameVersion)
|
||||
private static void PrepareShared(byte[] compressed, string assembly, string output, string expectedGameVersion)
|
||||
{
|
||||
output = Path.GetFullPath(output);
|
||||
Directory.CreateDirectory(output);
|
||||
using var outputLock = AcquireCacheLock(Path.Combine(output, "prepare.lock"), "Waiting for this project's game SDK preparation to finish...");
|
||||
using FileStream outputLock = AcquireCacheLock(Path.Combine(output, "prepare.lock"), "Waiting for this project's game SDK preparation to finish...");
|
||||
NameTable table;
|
||||
using (var gzip = new GZipStream(new MemoryStream(compressed), CompressionMode.Decompress))
|
||||
table = JsonSerializer.Deserialize<NameTable>(gzip, Json);
|
||||
@@ -102,12 +93,6 @@ internal static class Program
|
||||
throw new InvalidDataException($"Plugin requires game {expectedGameVersion}, but SDK names target game {gameVersion}. Install the matching SDK package.");
|
||||
if (Hash(assembly) != table.assembly_sha256)
|
||||
throw new InvalidDataException("Game DLL does not match SDK names for game " + gameVersion);
|
||||
if (versions != null)
|
||||
{
|
||||
using var config = JsonDocument.Parse(File.ReadAllText(versions));
|
||||
string expected = config.RootElement.GetProperty("game_version").GetString();
|
||||
if (expected != gameVersion) throw new InvalidDataException($"Repository game_version {expected} does not match SDK embedded names {gameVersion}");
|
||||
}
|
||||
string cacheRoot = Environment.GetEnvironmentVariable("BD2_GAME_SDK_CACHE");
|
||||
if (string.IsNullOrEmpty(cacheRoot)) cacheRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "BD2", "GameSdk", "navigation");
|
||||
string tableHash = Convert.ToHexString(SHA256.HashData(compressed)).ToLowerInvariant();
|
||||
@@ -120,8 +105,8 @@ internal static class Program
|
||||
using (AcquireCacheLock(Path.Combine(shared, "generation.lock")))
|
||||
{
|
||||
string tablePath = Path.Combine(shared, "names.json"), ready = Path.Combine(shared, "ready.txt");
|
||||
string[] relativeFiles = { "names.json", "names.json.gz", ShellName + ".dll", ShellName + ".xml", "navigation.json",
|
||||
"ref/" + ShellName + ".dll", "ref/" + ShellName + ".xml", "lib/" + ShellName + ".dll", "lib/" + ShellName + ".pdb", "lib/" + ShellName + ".xml", "lib/navigation.json" };
|
||||
string[] relativeFiles = [ "names.json", "names.json.gz", ShellName + ".dll", ShellName + ".xml", "navigation.json",
|
||||
"ref/" + ShellName + ".dll", "ref/" + ShellName + ".xml", "lib/" + ShellName + ".dll", "lib/" + ShellName + ".pdb", "lib/" + ShellName + ".xml", "lib/navigation.json" ];
|
||||
string[] files = relativeFiles.Select(p => Path.Combine(shared, p)).ToArray();
|
||||
string StampFiles() => inputs + "|" + string.Join("|", files.Select(Hash));
|
||||
if (!File.Exists(ready) || !files.All(File.Exists) || File.ReadAllText(ready) != StampFiles())
|
||||
@@ -129,7 +114,7 @@ internal static class Program
|
||||
File.Delete(ready);
|
||||
File.WriteAllBytes(tablePath + ".gz", compressed);
|
||||
using (var gzip = new GZipStream(new MemoryStream(compressed), CompressionMode.Decompress))
|
||||
using (var destination = File.Create(tablePath)) gzip.CopyTo(destination);
|
||||
using (FileStream destination = File.Create(tablePath)) gzip.CopyTo(destination);
|
||||
GenerateShell(tablePath, assembly, Path.Combine(shared, ShellName + ".dll"));
|
||||
File.WriteAllText(ready, StampFiles());
|
||||
}
|
||||
@@ -176,11 +161,11 @@ internal static class Program
|
||||
|
||||
private static void WriteNavigationItems(string output)
|
||||
{
|
||||
var manifest = JsonSerializer.Deserialize<SourceNavigation.Manifest>(File.ReadAllText(Path.Combine(output, "navigation.json")));
|
||||
SourceNavigation.Manifest manifest = JsonSerializer.Deserialize<SourceNavigation.Manifest>(File.ReadAllText(Path.Combine(output, "navigation.json")));
|
||||
if (!Directory.Exists(manifest.SourceRoot) || Directory.EnumerateFiles(manifest.SourceRoot, "*.cs", SearchOption.AllDirectories).Count() != manifest.Documents)
|
||||
SourceNavigation.RestoreSources(output);
|
||||
var items = new System.Xml.Linq.XElement("ItemGroup");
|
||||
foreach (var path in Directory.EnumerateFiles(manifest.SourceRoot, "*.cs", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal))
|
||||
foreach (string path in Directory.EnumerateFiles(manifest.SourceRoot, "*.cs", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal))
|
||||
items.Add(new System.Xml.Linq.XElement("None", new System.Xml.Linq.XAttribute("Include", path),
|
||||
new System.Xml.Linq.XElement("Link", "Game Sources/" + Path.GetRelativePath(manifest.SourceRoot, path)),
|
||||
new System.Xml.Linq.XElement("CopyToOutputDirectory", "Never")));
|
||||
@@ -235,7 +220,7 @@ internal static class Program
|
||||
|
||||
internal static void Prepare(string assembly, string mapping, string versions, string output)
|
||||
{
|
||||
var version = JsonDocument.Parse(File.ReadAllText(versions)).RootElement.GetProperty("game_version").GetString();
|
||||
string version = JsonDocument.Parse(File.ReadAllText(versions)).RootElement.GetProperty("game_version").GetString();
|
||||
if (!Path.GetFileName(mapping).Contains(version, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("Mapping filename must identify game_version " + version);
|
||||
Directory.CreateDirectory(output);
|
||||
@@ -263,24 +248,24 @@ internal static class Program
|
||||
if (string.IsNullOrWhiteSpace(version) || !Path.GetFileName(mapping).Contains(version, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("Mapping filename must identify game_version " + version);
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var raw in File.ReadLines(mapping))
|
||||
foreach (string raw in File.ReadLines(mapping))
|
||||
{
|
||||
string line = raw.Trim().TrimStart('\ufeff');
|
||||
if (line.Length == 0 || line.StartsWith('#') || line.StartsWith("//")) continue;
|
||||
var parts = line.Split('⇨');
|
||||
if (line.Length == 0 || line.StartsWith('#') || line.StartsWith("//", StringComparison.Ordinal)) continue;
|
||||
string[] parts = line.Split('⇨');
|
||||
if (parts.Length != 2 || string.IsNullOrWhiteSpace(parts[0]) || string.IsNullOrWhiteSpace(parts[1]))
|
||||
throw new InvalidDataException("Invalid mapping row: " + line);
|
||||
string key = parts[0].Trim(), value = parts[1].Trim();
|
||||
if (map.TryGetValue(key, out var old) && old != value) throw new InvalidDataException("Ambiguous mapping: " + key);
|
||||
if (map.TryGetValue(key, out string old) && old != value) throw new InvalidDataException("Ambiguous mapping: " + key);
|
||||
map[key] = value;
|
||||
}
|
||||
string Translate(string name)
|
||||
{
|
||||
// Dots in explicit interface members are part of the CLR name, not a scope prefix.
|
||||
if (map.TryGetValue(name, out var value)) return value.Split('/').Last();
|
||||
if (map.TryGetValue(name, out string value)) return value.Split('/').Last();
|
||||
// Accessors can retain their CLR prefix while the property/event is renamed.
|
||||
foreach (string prefix in new[] { "get_", "set_", "add_", "remove_" })
|
||||
if (name.StartsWith(prefix) && map.TryGetValue(name[prefix.Length..], out value))
|
||||
if (name.StartsWith(prefix, StringComparison.Ordinal) && map.TryGetValue(name[prefix.Length..], out value))
|
||||
{
|
||||
string property = value.Split('/').Last();
|
||||
int dot = property.LastIndexOf('.');
|
||||
@@ -288,11 +273,18 @@ internal static class Program
|
||||
}
|
||||
return name;
|
||||
}
|
||||
using var module = ReadModule(assembly);
|
||||
using ModuleDefinition module = ReadModule(assembly);
|
||||
if (module.Assembly.Name.Name != "Assembly-CSharp") throw new InvalidDataException("Expected Assembly-CSharp");
|
||||
var table = new NameTable { game_version = version, assembly_name = module.Assembly.Name.Name,
|
||||
assembly_mvid = module.Mvid.ToString(), assembly_sha256 = Hash(assembly), mapping_sha256 = Hash(mapping), generator_sha256 = Hash(typeof(Program).Assembly.Location) };
|
||||
var definitions = Types(module).ToArray();
|
||||
var table = new NameTable
|
||||
{
|
||||
game_version = version,
|
||||
assembly_name = module.Assembly.Name.Name,
|
||||
assembly_mvid = module.Mvid.ToString(),
|
||||
assembly_sha256 = Hash(assembly),
|
||||
mapping_sha256 = Hash(mapping),
|
||||
generator_sha256 = Hash(typeof(Program).Assembly.Location)
|
||||
};
|
||||
TypeDefinition[] definitions = Types(module).ToArray();
|
||||
var originalTypes = definitions.ToDictionary(t => t, TypeKey);
|
||||
string ReadableType(TypeDefinition t)
|
||||
{
|
||||
@@ -300,27 +292,34 @@ internal static class Program
|
||||
if (map.TryGetValue(t.Name, out string full)) return full.Replace('/', '+');
|
||||
return string.IsNullOrEmpty(t.Namespace) ? Translate(t.Name) : t.Namespace + "." + Translate(t.Name);
|
||||
}
|
||||
foreach (var type in definitions)
|
||||
foreach (TypeDefinition type in definitions)
|
||||
table.types.Add(new TypeName { token = type.MetadataToken.ToInt32(), original = originalTypes[type], readable = ReadableType(type) });
|
||||
if (table.types.GroupBy(t => t.readable).Any(g => g.Count() > 1)) throw new InvalidDataException("Readable type collision");
|
||||
var memberKeys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var type in definitions)
|
||||
foreach (TypeDefinition type in definitions)
|
||||
{
|
||||
void Add(IMemberDefinition member, string kind, string signature = null, MethodDefinition method = null)
|
||||
{
|
||||
var entry = new MemberName { token = member.MetadataToken.ToInt32(), kind = kind,
|
||||
declaring_type = originalTypes[type], original = member.Name, readable = Translate(member.Name), signature = signature };
|
||||
var entry = new MemberName
|
||||
{
|
||||
token = member.MetadataToken.ToInt32(),
|
||||
kind = kind,
|
||||
declaring_type = originalTypes[type],
|
||||
original = member.Name,
|
||||
readable = Translate(member.Name),
|
||||
signature = signature
|
||||
};
|
||||
if (!memberKeys.Add(originalTypes[type] + "|" + kind + "|" + entry.readable + "|" + signature))
|
||||
throw new InvalidDataException("Readable member collision: " + originalTypes[type] + "." + entry.readable + " " + signature);
|
||||
if (method != null)
|
||||
foreach (var p in method.Parameters)
|
||||
foreach (ParameterDefinition p in method.Parameters)
|
||||
if (Translate(p.Name) != p.Name) entry.parameters.Add(new ParameterName { position = p.Index, original = p.Name, readable = Translate(p.Name) });
|
||||
table.members.Add(entry);
|
||||
}
|
||||
foreach (var m in type.Methods) Add(m, "method", Signature(m), m);
|
||||
foreach (var f in type.Fields) Add(f, "field", Signature(f));
|
||||
foreach (var p in type.Properties) Add(p, "property", TypeKey(p.PropertyType) + "(" + string.Join(",", p.Parameters.Select(a => TypeKey(a.ParameterType))) + ")");
|
||||
foreach (var e in type.Events) Add(e, "event", TypeKey(e.EventType));
|
||||
foreach (MethodDefinition m in type.Methods) Add(m, "method", Signature(m), m);
|
||||
foreach (FieldDefinition f in type.Fields) Add(f, "field", Signature(f));
|
||||
foreach (PropertyDefinition p in type.Properties) Add(p, "property", TypeKey(p.PropertyType) + "(" + string.Join(",", p.Parameters.Select(a => TypeKey(a.ParameterType))) + ")");
|
||||
foreach (EventDefinition e in type.Events) Add(e, "event", TypeKey(e.EventType));
|
||||
}
|
||||
// Keep unrenamed overloads that share a readable name with a renamed member.
|
||||
// Otherwise runtime lookup would accidentally omit the literal overload.
|
||||
@@ -336,23 +335,23 @@ internal static class Program
|
||||
|
||||
internal static void GenerateShell(string tablePath, string assembly, string shellPath)
|
||||
{
|
||||
var table = ReadTable(tablePath);
|
||||
NameTable table = ReadTable(tablePath);
|
||||
if (Hash(assembly) != table.assembly_sha256) throw new InvalidDataException($"Assembly-CSharp does not match SDK names for game {table.game_version}; install the matching client or update the SDK names table");
|
||||
using var module = ReadModule(assembly);
|
||||
var definitions = Types(module).ToArray();
|
||||
using ModuleDefinition module = ReadModule(assembly);
|
||||
TypeDefinition[] definitions = Types(module).ToArray();
|
||||
// Rename references while their declaring types still have original names.
|
||||
Rewrite(module, table, toReadable: true);
|
||||
var membersByToken = table.members.ToDictionary(m => m.token);
|
||||
var typesByToken = table.types.ToDictionary(t => t.token);
|
||||
foreach (var type in definitions)
|
||||
foreach (TypeDefinition type in definitions)
|
||||
{
|
||||
foreach (var member in type.Methods.Cast<IMemberDefinition>().Concat(type.Fields).Concat(type.Properties).Concat(type.Events))
|
||||
foreach (IMemberDefinition member in type.Methods.Cast<IMemberDefinition>().Concat(type.Fields).Concat(type.Properties).Concat(type.Events))
|
||||
{
|
||||
membersByToken.TryGetValue(member.MetadataToken.ToInt32(), out var entry);
|
||||
membersByToken.TryGetValue(member.MetadataToken.ToInt32(), out MemberName entry);
|
||||
if (entry != null) member.Name = entry.readable;
|
||||
if (member is MethodDefinition m)
|
||||
{
|
||||
if (entry != null) foreach (var p in entry.parameters) m.Parameters[p.position].Name = p.readable;
|
||||
if (entry != null) foreach (ParameterName p in entry.parameters) m.Parameters[p.position].Name = p.readable;
|
||||
// Retain IL only for offline source navigation/decompilation.
|
||||
// ReferenceAssemblyAttribute prevents this assembly from executing.
|
||||
}
|
||||
@@ -387,7 +386,7 @@ internal static class Program
|
||||
{
|
||||
var resolver = new DefaultAssemblyResolver();
|
||||
resolver.AddSearchDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
|
||||
foreach (var directory in searchDirectories) resolver.AddSearchDirectory(directory);
|
||||
foreach (string directory in searchDirectories) resolver.AddSearchDirectory(directory);
|
||||
return ModuleDefinition.ReadModule(path, new ReaderParameters { InMemory = true, AssemblyResolver = resolver });
|
||||
}
|
||||
|
||||
@@ -406,7 +405,7 @@ internal static class Program
|
||||
string TranslateSignature(string sig)
|
||||
{
|
||||
// Type references in signatures are tokenized, so substring collisions are avoided.
|
||||
return System.Text.RegularExpressions.Regex.Replace(sig, @"[^,:()\[\]&*<>\s]+", m => readableByOriginal.TryGetValue(m.Value, out var v) ? v : m.Value);
|
||||
return System.Text.RegularExpressions.Regex.Replace(sig, @"[^,:()\[\]&*<>\s]+", m => readableByOriginal.TryGetValue(m.Value, out string v) ? v : m.Value);
|
||||
}
|
||||
var members = table.members.Where(m => m.kind is "method" or "field").ToDictionary(
|
||||
m => (toReadable ? m.declaring_type : readableByOriginal[m.declaring_type]) + "|" + m.kind + "|" + (toReadable ? m.original : m.readable) + "|" + (toReadable ? m.signature : TranslateSignature(m.signature)));
|
||||
@@ -425,38 +424,38 @@ internal static class Program
|
||||
if (provider.HasCustomAttributes) attributes.AddRange(provider.CustomAttributes);
|
||||
}
|
||||
Attributes(module); Attributes(module.Assembly);
|
||||
foreach (var t in Types(module))
|
||||
foreach (TypeDefinition t in Types(module))
|
||||
{
|
||||
Attributes(t);
|
||||
foreach (var gp in t.GenericParameters) Attributes(gp);
|
||||
foreach (var i in t.Interfaces) Attributes(i);
|
||||
foreach (var f in t.Fields) Attributes(f);
|
||||
foreach (var p in t.Properties) Attributes(p);
|
||||
foreach (var e in t.Events) Attributes(e);
|
||||
foreach (var m in t.Methods)
|
||||
foreach (GenericParameter gp in t.GenericParameters) Attributes(gp);
|
||||
foreach (InterfaceImplementation i in t.Interfaces) Attributes(i);
|
||||
foreach (FieldDefinition f in t.Fields) Attributes(f);
|
||||
foreach (PropertyDefinition p in t.Properties) Attributes(p);
|
||||
foreach (EventDefinition e in t.Events) Attributes(e);
|
||||
foreach (MethodDefinition m in t.Methods)
|
||||
{
|
||||
Attributes(m); Attributes(m.MethodReturnType);
|
||||
foreach (var p in m.Parameters) Attributes(p);
|
||||
foreach (var gp in m.GenericParameters) Attributes(gp);
|
||||
foreach (ParameterDefinition p in m.Parameters) Attributes(p);
|
||||
foreach (GenericParameter gp in m.GenericParameters) Attributes(gp);
|
||||
}
|
||||
}
|
||||
foreach (var attribute in attributes) memberRefs.Add(attribute.Constructor);
|
||||
foreach (var type in Types(module))
|
||||
foreach (var method in type.Methods)
|
||||
foreach (CustomAttribute attribute in attributes) memberRefs.Add(attribute.Constructor);
|
||||
foreach (TypeDefinition type in Types(module))
|
||||
foreach (MethodDefinition method in type.Methods)
|
||||
{
|
||||
foreach (var ov in method.Overrides) memberRefs.Add(ov);
|
||||
if (method.HasBody) foreach (var instruction in method.Body.Instructions)
|
||||
if (instruction.Operand is MemberReference mr) memberRefs.Add(mr);
|
||||
foreach (MethodReference ov in method.Overrides) memberRefs.Add(ov);
|
||||
if (method.HasBody) foreach (Instruction instruction in method.Body.Instructions)
|
||||
if (instruction.Operand is MemberReference mr) memberRefs.Add(mr);
|
||||
}
|
||||
foreach (var reference in memberRefs.Distinct())
|
||||
foreach (MemberReference reference in memberRefs.Distinct())
|
||||
{
|
||||
MemberReference member = reference is GenericInstanceMethod gm ? gm.ElementMethod : reference;
|
||||
if (member is not MethodReference && member is not FieldReference || member is IMemberDefinition || !IsGame(member.DeclaringType)) continue;
|
||||
var declaring = member.DeclaringType is GenericInstanceType gi ? gi.ElementType : member.DeclaringType;
|
||||
TypeReference declaring = member.DeclaringType is GenericInstanceType gi ? gi.ElementType : member.DeclaringType;
|
||||
// CLR array Get/Set/Address pseudo-methods have no metadata definitions.
|
||||
if (declaring is ArrayType) continue;
|
||||
string key = TypeKey(declaring) + "|" + (member is MethodReference ? "method" : "field") + "|" + member.Name + "|" + Signature(member);
|
||||
if (members.TryGetValue(key, out var entry)) member.Name = toReadable ? entry.readable : entry.original;
|
||||
if (members.TryGetValue(key, out MemberName entry)) member.Name = toReadable ? entry.readable : entry.original;
|
||||
else if (namedMembers.Contains(key[..key.LastIndexOf('|')])) throw new InvalidDataException("Game member signature does not match the names table: " + key);
|
||||
}
|
||||
// Snapshot names before renaming a parent of a nested type.
|
||||
@@ -464,17 +463,17 @@ internal static class Program
|
||||
void Visit(TypeReference type)
|
||||
{
|
||||
if (type == null || type is GenericParameter) return;
|
||||
if (type is FunctionPointerType fp) { Visit(fp.ReturnType); foreach (var p in fp.Parameters) Visit(p.ParameterType); return; }
|
||||
if (type is FunctionPointerType fp) { Visit(fp.ReturnType); foreach (ParameterDefinition p in fp.Parameters) Visit(p.ParameterType); return; }
|
||||
if (type is TypeSpecification spec)
|
||||
{
|
||||
Visit(spec.ElementType);
|
||||
if (type is GenericInstanceType gi) foreach (var a in gi.GenericArguments) Visit(a);
|
||||
if (type is GenericInstanceType gi) foreach (TypeReference a in gi.GenericArguments) Visit(a);
|
||||
if (type is IModifierType modifier) Visit(modifier.ModifierType);
|
||||
return;
|
||||
}
|
||||
if (!renames.ContainsKey(type) && IsGame(type))
|
||||
{
|
||||
if (!types.TryGetValue(TypeKey(type), out var entry)) throw new InvalidDataException("Unmapped game type: " + TypeKey(type));
|
||||
if (!types.TryGetValue(TypeKey(type), out TypeName entry)) throw new InvalidDataException("Unmapped game type: " + TypeKey(type));
|
||||
renames[type] = toReadable ? entry.readable : entry.original;
|
||||
}
|
||||
Visit(type.DeclaringType);
|
||||
@@ -484,21 +483,21 @@ internal static class Program
|
||||
Visit(argument.Type);
|
||||
if (argument.Value is TypeReference type) Visit(type);
|
||||
if (argument.Value is CustomAttributeArgument boxed) VisitArgument(boxed);
|
||||
if (argument.Value is CustomAttributeArgument[] array) foreach (var item in array) VisitArgument(item);
|
||||
if (argument.Value is CustomAttributeArgument[] array) foreach (CustomAttributeArgument item in array) VisitArgument(item);
|
||||
}
|
||||
foreach (var attribute in attributes)
|
||||
foreach (CustomAttribute attribute in attributes)
|
||||
{
|
||||
// Decode blobs before changing assembly scopes. System.Type arguments are typed
|
||||
// metadata even though the ECMA-335 blob stores assembly-qualified text.
|
||||
foreach (var argument in attribute.ConstructorArguments) VisitArgument(argument);
|
||||
foreach (CustomAttributeArgument argument in attribute.ConstructorArguments) VisitArgument(argument);
|
||||
void NamedArguments(Mono.Collections.Generic.Collection<CustomAttributeNamedArgument> arguments, string kind)
|
||||
{
|
||||
for (int i = 0; i < arguments.Count; i++)
|
||||
{
|
||||
var argument = arguments[i]; VisitArgument(argument.Argument);
|
||||
CustomAttributeNamedArgument argument = arguments[i]; VisitArgument(argument.Argument);
|
||||
if (!IsGame(attribute.AttributeType)) continue;
|
||||
string declaring = TypeKey(attribute.AttributeType);
|
||||
var entry = table.members.SingleOrDefault(m => m.kind == kind &&
|
||||
MemberName entry = table.members.SingleOrDefault(m => m.kind == kind &&
|
||||
(toReadable ? m.declaring_type : readableByOriginal[m.declaring_type]) == declaring &&
|
||||
(toReadable ? m.original : m.readable) == argument.Name);
|
||||
if (entry != null) arguments[i] = new CustomAttributeNamedArgument(toReadable ? entry.readable : entry.original, argument.Argument);
|
||||
@@ -506,43 +505,43 @@ internal static class Program
|
||||
}
|
||||
NamedArguments(attribute.Fields, "field"); NamedArguments(attribute.Properties, "property");
|
||||
}
|
||||
foreach (var t in module.GetTypeReferences()) Visit(t);
|
||||
foreach (var member in memberRefs)
|
||||
foreach (TypeReference t in module.GetTypeReferences()) Visit(t);
|
||||
foreach (MemberReference member in memberRefs)
|
||||
{
|
||||
Visit(member.DeclaringType);
|
||||
if (member is MethodReference m) { Visit(m.ReturnType); foreach (var p in m.Parameters) Visit(p.ParameterType); if (m is GenericInstanceMethod gm) foreach (var a in gm.GenericArguments) Visit(a); }
|
||||
if (member is MethodReference m) { Visit(m.ReturnType); foreach (ParameterDefinition p in m.Parameters) Visit(p.ParameterType); if (m is GenericInstanceMethod gm) foreach (TypeReference a in gm.GenericArguments) Visit(a); }
|
||||
if (member is FieldReference f) Visit(f.FieldType);
|
||||
}
|
||||
foreach (var type in Types(module))
|
||||
foreach (TypeDefinition type in Types(module))
|
||||
{
|
||||
Visit(type.BaseType);
|
||||
foreach (var i in type.Interfaces) Visit(i.InterfaceType);
|
||||
foreach (var f in type.Fields) Visit(f.FieldType);
|
||||
foreach (var p in type.Properties) { Visit(p.PropertyType); foreach (var a in p.Parameters) Visit(a.ParameterType); }
|
||||
foreach (var e in type.Events) Visit(e.EventType);
|
||||
foreach (var gp in type.GenericParameters) foreach (var c in gp.Constraints) Visit(c.ConstraintType);
|
||||
foreach (var m in type.Methods)
|
||||
foreach (InterfaceImplementation i in type.Interfaces) Visit(i.InterfaceType);
|
||||
foreach (FieldDefinition f in type.Fields) Visit(f.FieldType);
|
||||
foreach (PropertyDefinition p in type.Properties) { Visit(p.PropertyType); foreach (ParameterDefinition a in p.Parameters) Visit(a.ParameterType); }
|
||||
foreach (EventDefinition e in type.Events) Visit(e.EventType);
|
||||
foreach (GenericParameter gp in type.GenericParameters) foreach (GenericParameterConstraint c in gp.Constraints) Visit(c.ConstraintType);
|
||||
foreach (MethodDefinition m in type.Methods)
|
||||
{
|
||||
Visit(m.ReturnType);
|
||||
foreach (var p in m.Parameters) Visit(p.ParameterType);
|
||||
foreach (var gp in m.GenericParameters) foreach (var c in gp.Constraints) Visit(c.ConstraintType);
|
||||
if (m.HasBody) { foreach (var v in m.Body.Variables) Visit(v.VariableType); foreach (var h in m.Body.ExceptionHandlers) Visit(h.CatchType); foreach (var i in m.Body.Instructions) if (i.Operand is TypeReference t) Visit(t); }
|
||||
foreach (ParameterDefinition p in m.Parameters) Visit(p.ParameterType);
|
||||
foreach (GenericParameter gp in m.GenericParameters) foreach (GenericParameterConstraint c in gp.Constraints) Visit(c.ConstraintType);
|
||||
if (m.HasBody) { foreach (VariableDefinition v in m.Body.Variables) Visit(v.VariableType); foreach (ExceptionHandler h in m.Body.ExceptionHandlers) Visit(h.CatchType); foreach (Instruction i in m.Body.Instructions) if (i.Operand is TypeReference t) Visit(t); }
|
||||
}
|
||||
}
|
||||
foreach (var pair in renames) SetTypeName(pair.Key, pair.Value);
|
||||
foreach (KeyValuePair<TypeReference, string> pair in renames) SetTypeName(pair.Key, pair.Value);
|
||||
}
|
||||
|
||||
internal static void Reobfuscate(string tablePath, string input, string output, string originalAssembly = null, string dependencyDirectory = null)
|
||||
{
|
||||
var table = ReadTable(tablePath);
|
||||
NameTable table = ReadTable(tablePath);
|
||||
var dependencies = new List<string> { Path.GetDirectoryName(Path.GetFullPath(tablePath)), Path.GetDirectoryName(Path.GetFullPath(output)) };
|
||||
if (originalAssembly != null) dependencies.Add(Path.GetDirectoryName(Path.GetFullPath(originalAssembly)));
|
||||
if (dependencyDirectory != null) dependencies.Add(Path.GetFullPath(dependencyDirectory));
|
||||
using var module = ReadModule(input, dependencies.ToArray());
|
||||
using ModuleDefinition module = ReadModule(input, [.. dependencies]);
|
||||
if (module.Assembly.Name.HasPublicKey) throw new InvalidDataException("Signed plugins require an explicit signing workflow");
|
||||
VerifyStamp(module, table);
|
||||
Rewrite(module, table, false);
|
||||
foreach (var a in module.AssemblyReferences.Where(a => a.Name == ShellName)) a.Name = table.assembly_name;
|
||||
foreach (AssemblyNameReference a in module.AssemblyReferences.Where(a => a.Name == ShellName)) a.Name = table.assembly_name;
|
||||
// Preserve compiler PDBs in obj; rewritten runtime DLL deliberately has no stale symbols.
|
||||
string absoluteOutput = Path.GetFullPath(output);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(absoluteOutput));
|
||||
@@ -559,17 +558,17 @@ internal static class Program
|
||||
|
||||
internal static void Verify(string tablePath, string plugin, string originalAssembly = null)
|
||||
{
|
||||
var table = ReadTable(tablePath);
|
||||
using var module = originalAssembly == null ? ReadModule(plugin) : ReadModule(plugin, Path.GetDirectoryName(Path.GetFullPath(originalAssembly)));
|
||||
NameTable table = ReadTable(tablePath);
|
||||
using ModuleDefinition module = originalAssembly == null ? ReadModule(plugin) : ReadModule(plugin, Path.GetDirectoryName(Path.GetFullPath(originalAssembly)));
|
||||
if (module.AssemblyReferences.Any(a => a.Name == ShellName)) throw new InvalidDataException("Runtime DLL still references the readable shell");
|
||||
VerifyStamp(module, table);
|
||||
if (originalAssembly != null)
|
||||
{
|
||||
if (Hash(originalAssembly) != table.assembly_sha256) throw new InvalidDataException("Verification game binary does not match the names table");
|
||||
bool IsGame(TypeReference t) => t.GetElementType().Scope is AssemblyNameReference a && a.Name == table.assembly_name;
|
||||
foreach (var type in module.GetTypeReferences().Where(IsGame))
|
||||
foreach (TypeReference type in module.GetTypeReferences().Where(IsGame))
|
||||
if (type.Resolve() == null) throw new InvalidDataException("Unresolvable game type reference: " + type.FullName);
|
||||
foreach (var member in module.GetMemberReferences().Where(m => IsGame(m.DeclaringType)))
|
||||
foreach (MemberReference member in module.GetMemberReferences().Where(m => IsGame(m.DeclaringType)))
|
||||
{
|
||||
if (member.DeclaringType is ArrayType) continue;
|
||||
if (member is MethodReference method && method.Resolve() == null || member is FieldReference field && field.Resolve() == null)
|
||||
@@ -580,7 +579,7 @@ internal static class Program
|
||||
|
||||
private static void VerifyStamp(ModuleDefinition module, NameTable table)
|
||||
{
|
||||
var markers = module.Assembly.CustomAttributes.Where(a => a.AttributeType.FullName == "System.Reflection.AssemblyMetadataAttribute" && a.ConstructorArguments.Count == 2 && a.ConstructorArguments[0].Value as string == "BD2.GameNames").ToArray();
|
||||
CustomAttribute[] markers = module.Assembly.CustomAttributes.Where(a => a.AttributeType.FullName == "System.Reflection.AssemblyMetadataAttribute" && a.ConstructorArguments.Count == 2 && a.ConstructorArguments[0].Value as string == "BD2.GameNames").ToArray();
|
||||
if (markers.Length != 1 || markers[0].ConstructorArguments[1].Value as string != Stamp(table))
|
||||
throw new InvalidDataException("Missing/mismatched SDK stamp: compile with GameSdkIdentity.g.cs from this names table");
|
||||
}
|
||||
|
||||
+22
-153
@@ -1,34 +1,36 @@
|
||||
# BD2.GameSdk
|
||||
|
||||
本插件不会提供任何封装的游戏 API,任何功能的 patch 等操作需要自行处理。
|
||||
|
||||
给 Brown Dust II 插件作者使用的 C# 开发包。通过标准 NuGet `PackageReference` 导入,自动完成 **生成可读引用程序集和全量源码导航 → 编译插件 → reobf → 验证运行 DLL**。源码可以使用可读类型和成员,字符串反射由配套的 `BD2.GameNames` 处理。转到定义可查看完整反编译方法体。
|
||||
|
||||
## 包与版本
|
||||
## 本发布包
|
||||
|
||||
| NuGet 包 | 内容 | 使用方式 |
|
||||
| --- | --- | --- |
|
||||
| `BD2.GameSdk` | .NET 8 构建工具、`build/*.props/targets`、压缩名字表 | 插件项目直接引用,`PrivateAssets="all"` |
|
||||
| `BD2.GameNames` | `lib/netstandard2.0/BD2.GameNames.dll`、XML API 文档、同一份内嵌表 | SDK 固定依赖对应版本,自动引入;DLL 随插件部署 |
|
||||
|
||||
当前包版本为 `0.2.1-game.2.35.10`:`0.2.1` 是开发工具/API 的语义版本,`game.2.35.10` 指定游戏版本。采用 SemVer 的 prerelease 段,安装时明确指定版本。升级游戏后更新包并重新构建插件;相同游戏版本下的不同官方 DLL 也会因指纹不同而被拒绝。
|
||||
升级游戏后更新此包并重新构建插件;相同游戏版本下的不同官方 DLL 也会因指纹不同而被拒绝。
|
||||
|
||||
包不包含游戏 DLL 或可读壳。维护者用官方映射生成名字表,提交为 `plugins/GameNames/Mappings/names.json.gz`,SDK 和运行时从同一文件嵌入,插件作者只需要对应游戏客户端和 BepInEx,无需官方映射、Python、仓库 `versions.json` 或本仓库源码。
|
||||
包不包含游戏 DLL 或可读壳。用官方映射生成名字表,提交为 `plugins/GameNames/Mappings/names.json.gz`,SDK 和运行时从同一文件嵌入,插件作者只需要对应游戏客户端和 BepInEx。
|
||||
|
||||
包当前由维护者提供 `.nupkg` 或 NuGet 源,**尚未发布到 nuget.org**。包内包含仓库 LICENSE,许可条款沿用项目现有授权,不声明为开源许可。
|
||||
|
||||
## 导入到自己的插件项目
|
||||
|
||||
前提:安装 **.NET 8 SDK**,准备与包对应的游戏目录,并在该目录安装 BepInEx。推荐 SDK-style `.csproj` 与 `netstandard2.1`;运行时库本身兼容 `.NET Standard 2.0`。旧式 `packages.config` 不受支持。
|
||||
前提:安装 **.NET 8 SDK**,准备与包对应版本的游戏目录,并在该目录安装 BepInEx。推荐 SDK-style `.csproj` 与 `netstandard2.1`;运行时库本身兼容 `.NET Standard 2.0`。旧式 `packages.config` 不受支持。
|
||||
|
||||
将维护者提供的两个 `.nupkg` 放在一个目录,例如 `D:\NuGet\BD2`,添加为本地 NuGet 源:
|
||||
|
||||
```powershell
|
||||
dotnet nuget add source 'D:\NuGet\BD2' --name BD2
|
||||
dotnet add MyPlugin.csproj package BD2.GameSdk --version 0.2.1-game.2.35.10
|
||||
dotnet add MyPlugin.csproj package BD2.GameSdk --version 0.2.2-game.2.35.10
|
||||
```
|
||||
|
||||
Visual Studio / Rider 也可在 NuGet 包管理界面添加该源,打开“包含预发布版本”,安装指定版本。若维护者提供远程 NuGet 源,把上面的目录换成该源 URL。
|
||||
Visual Studio / Rider 也可在 NuGet 包管理界面添加该源。
|
||||
|
||||
最小项目文件:
|
||||
简单的一个项目文件:
|
||||
|
||||
```xml
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
@@ -39,14 +41,12 @@ Visual Studio / Rider 也可在 NuGet 包管理界面添加该源,打开“包
|
||||
<BD2GameVersion>2.35.10</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BD2.GameSdk"
|
||||
Version="0.2.1-game.2.35.10"
|
||||
PrivateAssets="all" />
|
||||
<PackageReference Include="BD2.GameSdk" Version="0.2.2-game.2.35.10" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
`PrivateAssets="all"` 让构建步骤只用于当前插件项目;它不会阻止运行时 DLL 复制到输出目录。SDK 自动引入 `BD2.GameNames`,以及游戏目录中的 `BepInEx`、`0Harmony`、`UnityEngine`、`UnityEngine.CoreModule` 引用,无需手写 `<Import>`。**不要再引用真实的 `Assembly-CSharp.dll`**,游戏 API 编译引用由 SDK 提供。
|
||||
`PrivateAssets="all"` 让构建步骤只用于当前插件项目。SDK 自动引入 `BD2.GameNames`,以及游戏目录中的 `BepInEx`、`0Harmony`、`UnityEngine`、`UnityEngine.CoreModule` 引用,无需手写 `<Import>`。**不要再引用真实的 `Assembly-CSharp.dll`**,游戏 API 编译引用由 SDK 提供。
|
||||
|
||||
在项目旁创建仅保存在本机的 `Directory.Build.props`,并加入自己的 `.gitignore`:
|
||||
|
||||
@@ -64,21 +64,15 @@ Visual Studio / Rider 也可在 NuGet 包管理界面添加该源,打开“包
|
||||
dotnet build MyPlugin.csproj -c Release '-p:GameDir=E:\Games\BrownDustII'
|
||||
```
|
||||
|
||||
IDE 项目加载/设计时构建会准备可读引用;CLI 首次构建同样会自动生成。使用 SDK 不需要运行额外的生成命令。完整可复制示例在 [samples/ExamplePlugin](samples/ExamplePlugin),包含 `.csproj`、插件源码和本机配置示例。
|
||||
IDE 项目加载时构建会准备可读引用,CLI 首次构建同样会自动生成。完整示例在 [samples/ExamplePlugin](samples/ExamplePlugin)。
|
||||
|
||||
## 完整源码导航
|
||||
|
||||
导入包、设置 `GameDir` 后,先完成一次构建。SDK 使用 ILSpy 从匹配版本的真实游戏 DLL 生成**全部类型的可读 C# 源码**,保留方法体、私有成员、嵌套类型和编译器生成实现;同步生成 Portable PDB,将源码内嵌到 PDB。名字仍来自同一份内嵌表,没有另一份源码映射。
|
||||
导入包、设置 `GameDir` 后,先完成一次构建。SDK 会使用 ILSpy 从匹配版本的真实游戏 DLL 生成**全部类型的可读 C# 源码**,保留方法体、私有成员、嵌套类型和编译器生成实现;同步生成 Portable PDB,将源码内嵌到 PDB。
|
||||
|
||||
在支持外部源码导航的 IDE 中,对 `NetworkManager.Send` 等可读 API 使用“转到定义”(Visual Studio 的 F12),即可打开完整方法体。重载、泛型、参数、属性、字段、事件和嵌套类型使用真实元数据及 PDB 定位,不靠搜索同名字符串。
|
||||
在支持外部源码导航的 IDE 中,对 `NetworkManager.Send` 等可读 API 使用“转到定义”(例如 Visual Studio 的 F12),即可打开完整方法体。重载、泛型、参数、属性、字段、事件和嵌套类型使用真实元数据及 PDB 定位。
|
||||
|
||||
- **Visual Studio 2022**:在“工具 → 选项 → 文本编辑器 → C# → 高级”中启用“导航到 Source Link 和嵌入源”(不同语言/版本的名称可能略有差异)。如果仍打开旧的签名视图,关闭原外部源码页并重新加载项目后再 F12。只阅读源码不需要关闭“仅我的代码”调试设置。
|
||||
- **Rider**:启用外部代码的源文件/PDB 或反编译导航。可读引用保留完整 IL,IDE 也可直接反编译出方法体;本项目的自动测试验证了 Visual Studio 的 Roslyn PDB 导航引擎,尚未手动验证 Rider 各版本界面。
|
||||
- 项目中还会链接一个 **`Game Sources`** 文件夹,支持直接浏览和文本搜索。首次生成后若文件夹未出现,重新加载项目使生成的 MSBuild 导入生效。这些 `.cs` 是 `None` 项,**不参与插件编译,也不复制到部署目录**。
|
||||
|
||||
普通视图恢复 `async/await`、迭代器和 lambda,便于阅读;`generated` 视图补全被这些语法隐藏的状态机、访问器等,`metadata` 视图补全其他隐藏声明。无法作为 C# 标识符的 CLR 生成名在源码中显示为 `__generated_...`,`navigation.json` 和名字表仍保留真实元数据身份。
|
||||
|
||||
首次全量生成会花费数分钟,日志持续报告已处理的类型数。本机 2.35.10 的一次验证生成了 **24,856 个源码文件、654,265 个声明、319,350 个带方法体的符号**。生成结果按名字表、生成器及其依赖、全部游戏 Managed DLL 的指纹缓存,同一台机器上的插件项目共用;并行构建会等待同一个缓存生成完成。后续构建不再执行全量反编译。
|
||||
首次全量生成会花费数分钟,且体积稍微有些许庞大。本机 2.35.10 的一次验证生成了 **24,856 个源码文件、654,265 个声明、319,350 个带方法体的符号**。生成结果按名字表、生成器及其依赖、全部游戏 Managed DLL 的指纹缓存,同一台机器上的插件项目共用。
|
||||
|
||||
所有依赖 SDK 的插件必须在自己的 `.csproj` 明确声明目标**游戏版本**:
|
||||
|
||||
@@ -86,60 +80,13 @@ IDE 项目加载/设计时构建会准备可读引用;CLI 首次构建同样
|
||||
<BD2GameVersion>2.35.10</BD2GameVersion>
|
||||
```
|
||||
|
||||
这个值与 SDK/API 工具版本(如 `0.2.1`)不同。构建核对声明值、SDK 内嵌表、真实游戏 DLL 指纹,以及仓库 `versions.json`(仓库插件)。缺少声明或版本不匹配会报错;不会自动选用其他版本。NuGet 项目仍需安装带对应游戏版本的包。
|
||||
构建核对声明值、SDK 内嵌表、真实游戏 DLL 指纹。缺少声明或版本不匹配会报错;不会自动选用其他版本。NuGet 项目仍需安装带对应游戏版本的包。
|
||||
|
||||
共享目录按 `<缓存根>/<游戏版本>/<内容指纹>/` 存放。同版本的三个插件、Debug/Release、NuGet 项目在输入一致时直接引用同一份产物;内容指纹用于隔离同一游戏版本内不同 SDK 实现或 Managed DLL,避免覆盖正在使用的旧引用。
|
||||
仓库默认缓存根为 `.build/game-sdk`,与源码位于同一盘。第三方 NuGet 项目默认使用 `%LOCALAPPDATA%\BD2\GameSdk\navigation`;可在本机 `Directory.Build.props` 设置 `BD2GameSdkCache`,或设置环境变量 `BD2_GAME_SDK_CACHE`。 `obj` 不影响共享缓存。缺失的共享源码可在下次准备时从 PDB 恢复,只有删除共享缓存才会触发重新生成。
|
||||
|
||||
仓库默认缓存根为 `.build/game-sdk`,与源码位于同一盘。第三方 NuGet 项目默认使用 `%LOCALAPPDATA%\BD2\GameSdk\navigation`;可在本机 `Directory.Build.props` 设置 `BD2GameSdkCache`,或设置环境变量 `BD2_GAME_SDK_CACHE`。删除插件 `obj` 不影响共享缓存。缺失的共享源码可在下次准备时从 PDB 恢复;删除共享缓存才会触发重新生成。
|
||||
`lib` 中的程序集仅供开发导航,**不要部署或执行**。这里展示的是当前 DLL 的反编译源码,局部变量名和语法可能与原始工程不同。导航 PDB 对应可读程序集,不能用于真实混淆游戏 DLL 的逐行调试。
|
||||
|
||||
共享目录包含如下产物,**每个插件 obj 不再复制这些大文件**:
|
||||
|
||||
| 路径 | 用途 |
|
||||
| --- | --- |
|
||||
| `ref/Assembly-CSharp.Readable.dll` + XML | 编译器引用,带引用程序集标记,禁止执行 |
|
||||
| `lib/Assembly-CSharp.Readable.dll` + `.pdb` | IDE 对应实现和内嵌源码符号 |
|
||||
| `lib/sources` | 完整可读源码,供项目浏览与搜索 |
|
||||
| `names.json` + `.gz` | 同一名字表的缓存导出,供 reobf 使用 |
|
||||
| `navigation.json` | 全量 token 索引;schema 2 路径相对于 `SourceRoot` |
|
||||
| `GameSourceNavigation.props` | 共享源码的 MSBuild 文件列表 |
|
||||
|
||||
每个插件 `obj/<配置>/<框架>/game-sdk`(NuGet 为 `bd2-game-sdk`)只保留小型 `GameSdkIdentity.g.cs`、`shared-sdk.txt`、导航导入 `.props` 和锁文件。首次构建通过生成的指针设置引用路径,后续 IDE 加载直接导入共享配置;`Game Sources` 仍可浏览搜索。旧布局的大文件副本在成功准备后自动清理。
|
||||
|
||||
`lib` 中的程序集仅供开发导航,**不要部署或执行**。这里展示的是当前 DLL 的反编译源码,局部变量名和语法可能与原始工程不同。导航 PDB 对应可读程序集,不能用于真实混淆游戏 DLL 的逐行调试。所有开发产物都不会复制到游戏部署目录。
|
||||
|
||||
## 插件代码
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using BD2.GameNames;
|
||||
using BepInEx;
|
||||
using HarmonyLib;
|
||||
|
||||
[BepInPlugin("example.my-plugin", "My Plugin", "1.0.0")]
|
||||
public sealed class MyPlugin : BaseUnityPlugin
|
||||
{
|
||||
private void Awake()
|
||||
{
|
||||
try
|
||||
{
|
||||
Game.Validate(typeof(MyPlugin).Assembly,
|
||||
message => Logger.LogInfo(message));
|
||||
|
||||
var target = Game.Method<IntroUI>(ui => ui.SendMaintenanceInfo(false));
|
||||
new Harmony("example.my-plugin").Patch(target,
|
||||
prefix: new HarmonyMethod(typeof(MyPlugin), nameof(BeforeMaintenance)));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Logger.LogError("My Plugin initialization failed: " + exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static void BeforeMaintenance() { }
|
||||
}
|
||||
```
|
||||
|
||||
表达式只取得 `MethodInfo`,不会执行游戏调用;签名由 C# 编译器检查。已知游戏类型优先使用 `typeof`,公开成员优先使用强类型表达式或 `nameof`,可以获得 IDE 补全和编译检查。实际公开调用和字段访问也能直接使用可读名字。私有成员保持原访问性,通过已知类型和映射反射 API 查询:
|
||||
公开方法调用、字段和属性访问可以直接使用可读名字,获得 IDE 补全和编译检查。需要通过反射或 Harmony 定位成员时,已知游戏类型优先使用 `typeof(GameType)`,避免用字符串查找类型,可访问的成员可以使用 `nameof` 提供经过编译检查的名字,或者通过强类型表达式取得 `MethodInfo`,让编译器检查所选重载及参数类型。表达式只用于取得方法信息,不执行方法。私有成员保留原访问性,通过已知类型和映射反射 API 查询,例如:
|
||||
|
||||
```csharp
|
||||
using System.Reflection;
|
||||
@@ -160,15 +107,13 @@ var maintenance = typeof(IntroUI).GetGameMethod(nameof(IntroUI.SendMaintenanceIn
|
||||
owner.StartCoroutine(Game.MemberName(owner.GetType(), "ReadableCoroutineName"));
|
||||
```
|
||||
|
||||
`GetGameMethod/GetGameField/GetGameProperty/GetGameEvent` 采用 .NET 反射约定:查不到返回 null,重载歧义抛出 `AmbiguousMatchException`,null 名字参数抛出 `ArgumentNullException`。`MemberName` 的成员种类使用 `GameMemberKind` 枚举。未知映射保留字面名;普通 UI 文案、`nameof` 字符串和协程常量都不会被 reobf 自动替换。
|
||||
`GetGameMethod/GetGameField/GetGameProperty/GetGameEvent` 采用 .NET 反射约定:查不到返回 null,重载歧义抛出 `AmbiguousMatchException`,null 名字参数抛出 `ArgumentNullException`。`MemberName` 的成员种类使用 `GameMemberKind` 枚举。未知映射保留字面名,普通 UI 文案、`nameof` 字符串和协程常量都不会被 reobf 自动替换。
|
||||
|
||||
`Game.FindType` 保留给运行时才知道类型名称的查询。只做字符串反射的项目可单独安装 `BD2.GameNames`,启动时用 `Game.ValidateGame(...)`。这种方式没有可读游戏类型引用,也没有编译指纹;使用 SDK 的项目必须用 `Game.Validate(typeof(MyPlugin).Assembly, ...)`。
|
||||
`Game.FindType` 保留给运行时才知道类型名称的查询。只做字符串反射的项目可单独安装 `BD2.GameNames`,启动时用 `Game.ValidateGame(...)`。这种方式没有可读游戏类型引用,也没有编译指纹,使用 SDK 的项目必须用 `Game.Validate(typeof(MyPlugin).Assembly, ...)`。
|
||||
|
||||
## 构建与部署
|
||||
|
||||
构建成功后,将 `bin/Release/netstandard2.1/MyPlugin.dll` 和相邻的 **`BD2.GameNames.dll`** 安装到游戏 `BepInEx/plugins`。客户端只安装一份共享库;多个插件应使用同一游戏表。不要部署 `obj`、可读壳、源码、导航 PDB、`GameSdk.dll`、`Mono.Cecil.dll`、`ICSharpCode.Decompiler.dll` 或其他构建工具。
|
||||
|
||||
最终插件 DLL 已回映射,`obj` 保留可读编译产物和 PDB,最终目录删除改写前的旧 PDB。SDK 包是构建依赖;玩家电脑不需要 .NET 8 SDK 或 NuGet。这里支持 Unity 的 Mono/Managed 客户端,要求存在真实 `Assembly-CSharp.dll`;IL2CPP/AOT 客户端不受支持。
|
||||
构建成功后,将你的插件产物和相邻的 **`BD2.GameNames.dll`** 安装到游戏 `BepInEx/plugins`。当然,客户端只需要安装一个`BD2.GameNames.dll`,`GameSdk.dll`只是编写时需要。
|
||||
|
||||
| MSBuild 属性 | 用途 |
|
||||
| --- | --- |
|
||||
@@ -180,79 +125,3 @@ owner.StartCoroutine(Game.MemberName(owner.GetType(), "ReadableCoroutineName"));
|
||||
| `BD2AddBepInExReferences=false` | 使用其他宿主或自己提供 BepInEx/Harmony 引用时关闭自动引用 |
|
||||
| `BD2AddUnityReferences=false` | 自己提供 Unity 引用时关闭自动引用 |
|
||||
| `BD2GameSdkEnabled=false` | 暂时关闭壳生成与 reobf;只适用于不依赖可读游戏 API 的项目 |
|
||||
|
||||
额外 Unity 模块或第三方游戏依赖仍以普通 `<Reference>` 添加,并设 `<Private>false</Private>`。强签名插件需要重新签名流程,当前 reobf 明确拒绝。CI 用相同的 PackageReference 和 `GameDir` 参数构建,直接分发 Build 的 DLL 产物;不要把原始 `obj` DLL 放进发布包。
|
||||
|
||||
## 维护者打包
|
||||
|
||||
在本仓库运行:
|
||||
|
||||
```powershell
|
||||
.\plugins\GameSdk\Pack.ps1 `
|
||||
-GameDir '<当前客户端目录>'
|
||||
```
|
||||
|
||||
默认生成 `.build/nuget/BD2.GameSdk.<版本>.nupkg` 和 `BD2.GameNames.<版本>.nupkg`。工具版本来自 `plugins/PackageMetadata.props`,游戏版本来自根目录 `versions.json`,组合成 `工具版本-game.游戏版本`。可传 `-PackageVersion` 和 `-OutputDirectory`;发布后的同一包版本必须保持内容不可变,有任何变更都递增工具版本。
|
||||
|
||||
SDK 精确依赖同版本运行时包;两个包中的压缩表都直接来自同一生成结果。工具通过 `dotnet publish` 打包自带 Mono.Cecil,不把 Cecil 作为插件的 NuGet 依赖。包内携带 README、LICENSE、仓库地址和作者信息。本脚本只生成本地包,不上传到任何 NuGet 服务。
|
||||
|
||||
工具包也包含 Mono.Cecil、ILSpy 和相关 .NET 组件的 MIT 授权原文 `THIRD-PARTY-NOTICES.txt`;第三方组件保持其自身许可。打包后运行 `VerifyPackages.ps1 -GameDir '<客户端目录>'`,它在仓库外的全新目录和 NuGet 缓存中构建示例插件,检查运行时复制、禁止部署的文件、回映射引用、完整内嵌表、源码/PDB 覆盖和重复构建。
|
||||
|
||||
打包工程在普通 IDE 加载/源码构建时直接引用 `GameNames.csproj`,无需先生成包,也不会到 nuget.org 查找未发布的 `BD2.GameNames`。`Pack.ps1` 用 `BD2Packaging=true` 切换到同版本的精确 NuGet 依赖,并把打包用 `obj/bin` 放在独立 staging 目录,避免 IDE restore 与 pack 互相覆盖依赖资产。不要直接对打包 `.csproj` 执行 `dotnet pack`,使用脚本才能保证两个包版本配套。
|
||||
|
||||
仓库中的 `samples/ExamplePlugin/NuGet.Config` 指向 `.build/nuget`,示例保持真正的 NuGet 消费方式;先运行 `Pack.ps1` 再构建示例。复制示例到其他目录时按前文配置自己的包源,不要照搬仓库相对路径。
|
||||
|
||||
## 仓库源码构建与内嵌表
|
||||
|
||||
仓库的三个插件与 NuGet 消费项目采用同样的内嵌表流程。开发启动命令保持不变:
|
||||
|
||||
公共配置见 `plugins/Directory.Build.props`,本机游戏安装位置见不提交的 `plugins/Directory.Build.local.props`。可从 `Directory.Build.local.props.example` 复制并设置 `BD2LocalGameDir`、`BD2CaptureGameDir`、可选的 `BD2GameSdkCache`。配置和目标框架确定后,由 `Directory.Build.targets` 计算中间目录并导入 SDK/版本构建步骤。
|
||||
|
||||
仓库插件通过普通 `ProjectReference` 使用共享运行时;IDE 设计时加载不会嵌套构建三份运行时。SDK 准备过程按输出目录加锁,导航 `.props` 只在内容改变时原子替换,重复设计时构建不会因重写该文件触发连续项目加载。设计时构建不执行 reobf。
|
||||
|
||||
```powershell
|
||||
# 从 go 目录运行;游戏目录来自 go/config.json
|
||||
go run .\cmd\bd2client --dev run
|
||||
```
|
||||
|
||||
直接构建源码插件也只需要游戏目录:
|
||||
|
||||
```powershell
|
||||
dotnet build plugins/LocalIdentity/LocalIdentity.csproj -c Release '-p:GameDir=<客户端目录>'
|
||||
```
|
||||
|
||||
构建工具把表和可读引用生成到按游戏版本分组的共享缓存,插件 `obj` 只保存该目录的指针,再使用共享表做回映射。`GameSdk` 和 `BD2.GameNames` 的唯一名字数据源是仓库内的 `GameNames/Mappings/names.json.gz`。两份程序集内嵌的是同一份压缩字节,不维护第二份映射;共享目录里的表只是可以删除重建的缓存。NuGet 包同样不再包含单独的 `tools/data` 表文件。
|
||||
|
||||
表包含 `game_version`、完整类型名、成员声明类型/签名/metadata token、参数映射、真实 DLL 的 MVID/SHA-256 和官方映射 SHA-256。构建时先验证 DLL 指纹,仓库构建还核对 `versions.json`;不匹配会要求更新 SDK,不会尝试使用其他版本或猜名字。插件启动时核对表指纹、游戏 DLL 和少量已知条目。
|
||||
|
||||
## 更新游戏版本的名字表
|
||||
|
||||
只有维护者更新 SDK 名字数据时需要官方 `.obfuscate`。先更新仓库 `versions.json`,然后执行:
|
||||
|
||||
```powershell
|
||||
.\plugins\GameSdk\UpdateNames.ps1 `
|
||||
-GameDir '<新版本客户端目录>' `
|
||||
-GameMapping '<ObfuscationTranslation_新版本.obfuscate>'
|
||||
```
|
||||
|
||||
脚本从官方映射和真实元数据生成表,完成全量壳转换验证后才替换 `plugins/GameNames/Mappings/names.json.gz`。提交这份表与对应版本变更;重新构建插件并发布新版本配套包。更新过程中产生的明文表和壳留在 `.build/names-update`,不作为源码提交。
|
||||
|
||||
`tools/python/deobfuscate_client_source.py` 继续生成阅读镜像;程序集映射使用这里的元数据名字表,保留作用域、泛型位置和重载签名。官方映射冲突或可读签名冲突会报错。
|
||||
|
||||
工具也提供独立命令:
|
||||
|
||||
```powershell
|
||||
dotnet build plugins/GameSdk/GameSdk.csproj -c Release
|
||||
$tool = 'plugins/GameSdk/bin/Release/net8.0/GameSdk.dll'
|
||||
dotnet $tool prepare-embedded '<Assembly-CSharp.dll>' '<插件 obj 指针目录>' --game-version 2.35.10
|
||||
dotnet $tool export-names '<导出的 names.json>'
|
||||
dotnet $tool reobf '<names.json>' '<可读插件.dll>' '<运行插件.dll>' '<Assembly-CSharp.dll>' '<BepInEx/core>'
|
||||
dotnet $tool verify '<names.json>' '<运行插件.dll>' '<Assembly-CSharp.dll>'
|
||||
dotnet $tool verify-runtime '<names.json>' '<BD2.GameNames.dll>'
|
||||
dotnet $tool verify-navigation '<生成的 SDK 目录>'
|
||||
dotnet $tool self-test
|
||||
```
|
||||
|
||||
手动编译通过 `shared-sdk.txt` 找到共享目录,引用其中 `ref/Assembly-CSharp.Readable.dll`,并编译指针目录中的 `GameSdkIdentity.g.cs`;共享目录相邻 `lib` 供 IDE 查找。`verify-navigation` 全量检查 PE/PDB 身份、内嵌/本地源码校验和、类型文档和全部方法体的符号。
|
||||
|
||||
`self-test` 生成合成游戏 DLL,验证重载、泛型、继承、嵌套/编译器生成类型、私有成员、事件、参数、表达式、字符串不变和版本拒绝。`.build/game-sdk-tests` 仅保存每次自测的临时产物,不参与 SDK 构建、源码导航或客户端启动,用完可以删除;下次自测会重新生成。`VerifyPackages.ps1` 验证仓库外 NuGet 项目及完整源码/PDB 覆盖。实际 Unity/Harmony 行为需在游戏启动后检查日志。
|
||||
|
||||
+39
-37
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.Loader;
|
||||
using Mono.Cecil;
|
||||
@@ -8,6 +9,7 @@ namespace BD2.GameSdk;
|
||||
/// <summary>End-to-end tests with synthetic binaries. Never execute the production game or readable shell.</summary>
|
||||
internal static class SelfTest
|
||||
{
|
||||
private static readonly string[] PublicRuntimeTypes = ["BD2.GameNames.Game", "BD2.GameNames.GameMemberKind"];
|
||||
private static void Assert(bool condition, string message)
|
||||
{
|
||||
if (!condition) throw new InvalidOperationException("Self-test: " + message);
|
||||
@@ -17,7 +19,7 @@ internal static class SelfTest
|
||||
var start = new ProcessStartInfo("dotnet") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (string arg in new[] { "build", project, "--nologo", "-c", "Release" }.Concat(properties)) start.ArgumentList.Add(arg);
|
||||
using var process = Process.Start(start);
|
||||
var stdout = process.StandardOutput.ReadToEndAsync(); var stderr = process.StandardError.ReadToEndAsync();
|
||||
Task<string> stdout = process.StandardOutput.ReadToEndAsync(); Task<string> stderr = process.StandardError.ReadToEndAsync();
|
||||
process.WaitForExit();
|
||||
string output = stdout.GetAwaiter().GetResult() + stderr.GetAwaiter().GetResult();
|
||||
if (process.ExitCode != 0) throw new InvalidOperationException(output);
|
||||
@@ -72,22 +74,22 @@ internal static class SelfTest
|
||||
string mappingPath = Path.Combine(root, "ObfuscationTranslation_9.8.7.obfuscate"), versionPath = Path.Combine(root, "versions.json");
|
||||
File.WriteAllText(versionPath, "{\"game_version\":\"9.8.7\"}");
|
||||
var rows = new List<string> { "#ReverseOrder", "#Classes", "#Methods", "#Fields", "#Properties", "#Events", "#Parameters" };
|
||||
using (var game = Program.ReadModule(gamePath))
|
||||
using (ModuleDefinition game = Program.ReadModule(gamePath))
|
||||
{
|
||||
var table = new BD2.GameNames.Internal.NameTable { assembly_name = "Assembly-CSharp" };
|
||||
var defs = game.GetTypes().ToArray(); int counter = 0;
|
||||
string Obfuscated() => "ὠ" + string.Concat((counter++).ToString().Select(c => (char)('ὠ' + c - '0')));
|
||||
TypeDefinition[] defs = game.GetTypes().ToArray(); int counter = 0;
|
||||
string Obfuscated() => "ὠ" + string.Concat((counter++).ToString(CultureInfo.InvariantCulture).Select(c => (char)('ὠ' + c - '0')));
|
||||
var newNames = new Dictionary<TypeDefinition, string>();
|
||||
string Full(TypeDefinition t) => t.DeclaringType != null ? Full(t.DeclaringType) + "+" + newNames[t] : newNames.TryGetValue(t, out var n) ? n : Program.TypeKey(t);
|
||||
foreach (var t in defs)
|
||||
string Full(TypeDefinition t) => t.DeclaringType != null ? Full(t.DeclaringType) + "+" + newNames[t] : newNames.TryGetValue(t, out string n) ? n : Program.TypeKey(t);
|
||||
foreach (TypeDefinition t in defs)
|
||||
if (t.Namespace == "Readable" || t.DeclaringType?.Namespace == "Readable")
|
||||
{
|
||||
newNames[t] = Obfuscated();
|
||||
string meaning = t.DeclaringType == null ? Program.TypeKey(t) : newNames[t.DeclaringType] + "/" + (t.Name == "State" ? "<Run>d__0" : t.Name);
|
||||
rows.Add(newNames[t] + "⇨" + meaning);
|
||||
}
|
||||
foreach (var t in defs) table.types.Add(new BD2.GameNames.Internal.TypeName { token = t.MetadataToken.ToInt32(), original = Program.TypeKey(t), readable = Full(t) });
|
||||
foreach (var t in defs)
|
||||
foreach (TypeDefinition t in defs) table.types.Add(new BD2.GameNames.Internal.TypeName { token = t.MetadataToken.ToInt32(), original = Program.TypeKey(t), readable = Full(t) });
|
||||
foreach (TypeDefinition t in defs)
|
||||
{
|
||||
void Rename(IMemberDefinition member, string kind, string signature = null, MethodDefinition method = null)
|
||||
{
|
||||
@@ -95,31 +97,31 @@ internal static class SelfTest
|
||||
string original = member.Name, target = renamed ? Obfuscated() : original;
|
||||
if (renamed) rows.Add(target + "⇨" + original);
|
||||
var entry = new BD2.GameNames.Internal.MemberName { token = member.MetadataToken.ToInt32(), declaring_type = Program.TypeKey(t), original = original, readable = target, kind = kind, signature = signature };
|
||||
if (method != null) foreach (var p in method.Parameters)
|
||||
{
|
||||
if (string.IsNullOrEmpty(p.Name)) continue;
|
||||
string name = Obfuscated(); rows.Add(name + "⇨" + p.Name);
|
||||
entry.parameters.Add(new BD2.GameNames.Internal.ParameterName { position = p.Index, original = p.Name, readable = name });
|
||||
}
|
||||
if (method != null) foreach (ParameterDefinition p in method.Parameters)
|
||||
{
|
||||
if (string.IsNullOrEmpty(p.Name)) continue;
|
||||
string name = Obfuscated(); rows.Add(name + "⇨" + p.Name);
|
||||
entry.parameters.Add(new BD2.GameNames.Internal.ParameterName { position = p.Index, original = p.Name, readable = name });
|
||||
}
|
||||
table.members.Add(entry);
|
||||
}
|
||||
foreach (var m in t.Methods) Rename(m, "method", Program.Signature(m), m);
|
||||
foreach (var f in t.Fields) Rename(f, "field", Program.Signature(f));
|
||||
foreach (var p in t.Properties) Rename(p, "property");
|
||||
foreach (var e in t.Events) Rename(e, "event", Program.TypeKey(e.EventType));
|
||||
foreach (MethodDefinition m in t.Methods) Rename(m, "method", Program.Signature(m), m);
|
||||
foreach (FieldDefinition f in t.Fields) Rename(f, "field", Program.Signature(f));
|
||||
foreach (PropertyDefinition p in t.Properties) Rename(p, "property");
|
||||
foreach (EventDefinition e in t.Events) Rename(e, "event", Program.TypeKey(e.EventType));
|
||||
}
|
||||
Program.Rewrite(game, table, true);
|
||||
var entries = table.members.ToDictionary(m => m.token);
|
||||
foreach (var t in defs)
|
||||
foreach (TypeDefinition t in defs)
|
||||
{
|
||||
foreach (var m in t.Methods)
|
||||
foreach (MethodDefinition m in t.Methods)
|
||||
{
|
||||
var entry = entries[m.MetadataToken.ToInt32()]; m.Name = entry.readable;
|
||||
foreach (var p in entry.parameters) m.Parameters[p.position].Name = p.readable;
|
||||
GameNames.Internal.MemberName entry = entries[m.MetadataToken.ToInt32()]; m.Name = entry.readable;
|
||||
foreach (GameNames.Internal.ParameterName p in entry.parameters) m.Parameters[p.position].Name = p.readable;
|
||||
}
|
||||
foreach (var f in t.Fields) f.Name = entries[f.MetadataToken.ToInt32()].readable;
|
||||
foreach (var p in t.Properties) p.Name = entries[p.MetadataToken.ToInt32()].readable;
|
||||
foreach (var e in t.Events) e.Name = entries[e.MetadataToken.ToInt32()].readable;
|
||||
foreach (FieldDefinition f in t.Fields) f.Name = entries[f.MetadataToken.ToInt32()].readable;
|
||||
foreach (PropertyDefinition p in t.Properties) p.Name = entries[p.MetadataToken.ToInt32()].readable;
|
||||
foreach (EventDefinition e in t.Events) e.Name = entries[e.MetadataToken.ToInt32()].readable;
|
||||
Program.SetTypeName(t, table.types.Single(e => e.token == t.MetadataToken.ToInt32()).readable);
|
||||
}
|
||||
game.Write(gamePath);
|
||||
@@ -132,9 +134,9 @@ internal static class SelfTest
|
||||
Program.Prepare(gamePath, mappingPath, versionPath, sdkDir);
|
||||
SourceNavigation.Verify(sdkDir);
|
||||
string tablePath = Path.Combine(sdkDir, "names.json");
|
||||
var generated = Program.ReadTable(tablePath);
|
||||
GameNames.Internal.NameTable generated = Program.ReadTable(tablePath);
|
||||
Assert(generated.types.Any(t => t.readable == "Readable.Agent+<Run>d__0"), "compiler-generated scoped type");
|
||||
using (var shell = Program.ReadModule(Path.Combine(sdkDir, Program.ShellName + ".dll")))
|
||||
using (ModuleDefinition shell = Program.ReadModule(Path.Combine(sdkDir, Program.ShellName + ".dll")))
|
||||
{
|
||||
Assert(shell.Assembly.CustomAttributes.Any(a => a.AttributeType.Name == "ReferenceAssemblyAttribute"), "reference assembly marker");
|
||||
Assert(shell.GetType("Readable.Agent").Methods.First(m => m.Name == "Ping").Body.Instructions.Any(i => i.OpCode == OpCodes.Ret), "readable IL retained for offline decompiler fallback");
|
||||
@@ -206,7 +208,7 @@ internal static class SelfTest
|
||||
""");
|
||||
Build(probeProject);
|
||||
string readablePlugin = Path.Combine(probeDir, "bin/Release/netstandard2.1/Probe.dll"), pluginPath = Path.Combine(root, "Probe.dll");
|
||||
using (var plugin = Program.ReadModule(readablePlugin))
|
||||
using (ModuleDefinition plugin = Program.ReadModule(readablePlugin))
|
||||
{
|
||||
var foreign = new TypeReference("Readable", "Agent", plugin, new AssemblyNameReference("Foreign", new Version(1, 0)));
|
||||
var holder = new TypeDefinition("", "ExternalHolder", TypeAttributes.Public, plugin.TypeSystem.Object);
|
||||
@@ -214,7 +216,7 @@ internal static class SelfTest
|
||||
plugin.Write(readablePlugin);
|
||||
}
|
||||
Program.Reobfuscate(tablePath, readablePlugin, pluginPath, gamePath);
|
||||
using (var rewritten = Program.ReadModule(pluginPath))
|
||||
using (ModuleDefinition rewritten = Program.ReadModule(pluginPath))
|
||||
{
|
||||
Assert(rewritten.GetType("ExternalHolder").Fields[0].FieldType.FullName == "Readable.Agent", "external assembly scope isolation");
|
||||
Assert(!rewritten.AssemblyReferences.Any(a => a.Name == "System.Private.CoreLib"), "target framework preserved");
|
||||
@@ -245,13 +247,13 @@ internal static class SelfTest
|
||||
}
|
||||
private static string[] Strings(string path)
|
||||
{
|
||||
using var module = Program.ReadModule(path);
|
||||
using ModuleDefinition module = Program.ReadModule(path);
|
||||
return module.GetTypes().SelectMany(t => t.Methods).Where(m => m.HasBody).SelectMany(m => m.Body.Instructions).Where(i => i.OpCode == OpCodes.Ldstr).Select(i => (string)i.Operand).ToArray();
|
||||
}
|
||||
internal static void VerifyRuntime(string tablePath, string runtimePath)
|
||||
{
|
||||
var table = Program.ReadTable(tablePath);
|
||||
using (var runtime = Program.ReadModule(runtimePath))
|
||||
GameNames.Internal.NameTable table = Program.ReadTable(tablePath);
|
||||
using (ModuleDefinition runtime = Program.ReadModule(runtimePath))
|
||||
{
|
||||
var resource = (EmbeddedResource)runtime.Resources.Single(r => r.Name == "BD2.GameNames.names.json.gz");
|
||||
Assert(resource.GetResourceData().SequenceEqual(File.ReadAllBytes(tablePath + ".gz")), "embedded runtime table equals the shared table");
|
||||
@@ -259,12 +261,12 @@ internal static class SelfTest
|
||||
var context = new AssemblyLoadContext("BD2 full runtime-table check", isCollectible: true);
|
||||
try
|
||||
{
|
||||
var runtime = context.LoadFromAssemblyPath(Path.GetFullPath(runtimePath));
|
||||
Assert(runtime.GetExportedTypes().Select(t => t.FullName).OrderBy(n => n).SequenceEqual(new[] { "BD2.GameNames.Game", "BD2.GameNames.GameMemberKind" }), "serialization models are not public API");
|
||||
var game = runtime.GetType("BD2.GameNames.Game");
|
||||
System.Reflection.Assembly runtime = context.LoadFromAssemblyPath(Path.GetFullPath(runtimePath));
|
||||
Assert(runtime.GetExportedTypes().Select(t => t.FullName).OrderBy(n => n).SequenceEqual(PublicRuntimeTypes), "serialization models are not public API");
|
||||
Type game = runtime.GetType("BD2.GameNames.Game");
|
||||
Assert((string)game.GetProperty("GameVersion").GetValue(null) == table.game_version, "runtime deserializes the full table");
|
||||
var translate = game.GetMethod("TypeName").CreateDelegate<Func<string, string>>();
|
||||
foreach (var type in table.types) Assert(translate(type.readable) == type.original, "runtime type translation: " + type.readable);
|
||||
Func<string, string> translate = game.GetMethod("TypeName").CreateDelegate<Func<string, string>>();
|
||||
foreach (GameNames.Internal.TypeName type in table.types) Assert(translate(type.readable) == type.original, "runtime type translation: " + type.readable);
|
||||
Assert(translate("Unknown.Type") == "Unknown.Type", "runtime literal fallback");
|
||||
Console.WriteLine($"Verified embedded runtime table: game={table.game_version}, {table.types.Count} type lookups; {runtimePath}");
|
||||
}
|
||||
|
||||
+116
-107
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics;
|
||||
@@ -42,10 +43,10 @@ internal static class SourceNavigation
|
||||
string directory = Path.GetDirectoryName(Path.GetFullPath(shellPath));
|
||||
string sourceRoot = Path.Combine(directory, "sources");
|
||||
Directory.CreateDirectory(sourceRoot);
|
||||
using var module = Program.ReadModule(shellPath, dependencyDirectory);
|
||||
using ModuleDefinition module = Program.ReadModule(shellPath, dependencyDirectory);
|
||||
using var pe = new PEFile(shellPath, new MemoryStream(File.ReadAllBytes(shellPath)), PEStreamOptions.PrefetchEntireImage);
|
||||
var reader = pe.Metadata;
|
||||
var types = reader.TypeDefinitions.Where(h => reader.GetTypeDefinition(h).GetDeclaringType().IsNil && reader.GetString(reader.GetTypeDefinition(h).Name) != "<Module>").ToArray();
|
||||
MetadataReader reader = pe.Metadata;
|
||||
TypeDefinitionHandle[] types = reader.TypeDefinitions.Where(h => reader.GetTypeDefinition(h).GetDeclaringType().IsNil && reader.GetString(reader.GetTypeDefinition(h).Name) != "<Module>").ToArray();
|
||||
var sources = new ConcurrentBag<Source>();
|
||||
var timer = Stopwatch.StartNew();
|
||||
int completed = 0;
|
||||
@@ -60,10 +61,10 @@ internal static class SourceNavigation
|
||||
{
|
||||
int token = MetadataTokens.GetToken(handle);
|
||||
string relative = PathFor(reader, handle);
|
||||
var primary = worker.Decompile(handle, Path.Combine(sourceRoot, relative), raw: false);
|
||||
Source primary = worker.Decompile(handle, Path.Combine(sourceRoot, relative), raw: false);
|
||||
ApplyImplicitDeclarations(primary.Declarations, definitionsByToken[MetadataTokens.GetToken(handle)]);
|
||||
sources.Add(primary);
|
||||
var typeTokens = Descendants(reader, handle).Select(h => MetadataTokens.GetToken(h)).ToArray();
|
||||
int[] typeTokens = Descendants(reader, handle).Select(h => MetadataTokens.GetToken(h)).ToArray();
|
||||
var wanted = typeTokens.SelectMany(t => expected[t]).ToHashSet();
|
||||
var covered = primary.Declarations.Keys.ToHashSet();
|
||||
if (wanted.Except(covered).Any())
|
||||
@@ -73,7 +74,7 @@ internal static class SourceNavigation
|
||||
// Roslyn materializes embedded documents by basename, so primary
|
||||
// and generated views must have distinct filenames as well as paths.
|
||||
string generatedPath = Path.Combine(Path.GetDirectoryName(relative), Path.GetFileNameWithoutExtension(relative) + ".generated.cs");
|
||||
var raw = worker.Decompile(handle, Path.Combine(sourceRoot, "generated", generatedPath), raw: true);
|
||||
Source raw = worker.Decompile(handle, Path.Combine(sourceRoot, "generated", generatedPath), raw: true);
|
||||
ApplyImplicitDeclarations(raw.Declarations, definitionsByToken[MetadataTokens.GetToken(handle)]);
|
||||
sources.Add(raw);
|
||||
covered.UnionWith(raw.Declarations.Keys);
|
||||
@@ -82,8 +83,8 @@ internal static class SourceNavigation
|
||||
{
|
||||
// ILSpy hides some runtime-only definitions even with transformations
|
||||
// disabled. Decompile them explicitly, retaining exact token identity.
|
||||
var supplemental = worker.DecompileMember(MetadataTokens.EntityHandle(missing),
|
||||
Path.Combine(sourceRoot, "metadata", missing.ToString("X8") + ".cs"));
|
||||
Source supplemental = worker.DecompileMember(MetadataTokens.EntityHandle(missing),
|
||||
Path.Combine(sourceRoot, "metadata", missing.ToString("X8", CultureInfo.InvariantCulture) + ".cs"));
|
||||
sources.Add(supplemental);
|
||||
if (!supplemental.Declarations.ContainsKey(missing))
|
||||
throw new InvalidDataException($"Decompiler omitted declaration 0x{missing:X8}; complete navigation cannot be published");
|
||||
@@ -94,50 +95,50 @@ internal static class SourceNavigation
|
||||
return worker;
|
||||
}, worker => worker.Dispose());
|
||||
|
||||
var ordered = sources.OrderBy(s => s.Path, StringComparer.Ordinal).ToArray();
|
||||
Source[] ordered = [.. sources.OrderBy(s => s.Path, StringComparer.Ordinal)];
|
||||
var sourceByPath = ordered.ToDictionary(s => s.Path, StringComparer.Ordinal);
|
||||
var declarations = new Dictionary<int, Declaration>();
|
||||
var methodPoints = new Dictionary<int, (Source Source, List<Point> Points)>();
|
||||
foreach (var source in ordered.OrderBy(s => s.Declarations.Values.FirstOrDefault()?.GeneratedView == true))
|
||||
foreach (Source source in ordered.OrderBy(s => s.Declarations.Values.FirstOrDefault()?.GeneratedView == true))
|
||||
{
|
||||
foreach (var declaration in source.Declarations) declarations.TryAdd(declaration.Key, declaration.Value);
|
||||
foreach (var method in source.Methods) methodPoints.TryAdd(method.Key, (source, method.Value));
|
||||
foreach (KeyValuePair<int, Declaration> declaration in source.Declarations) declarations.TryAdd(declaration.Key, declaration.Value);
|
||||
foreach (KeyValuePair<int, List<Point>> method in source.Methods) methodPoints.TryAdd(method.Key, (source, method.Value));
|
||||
}
|
||||
// Accessors may be folded into properties/events. Their declaration navigation
|
||||
// maps to the exact accessor when present, otherwise its owning declaration.
|
||||
foreach (var type in module.GetTypes())
|
||||
foreach (Mono.Cecil.TypeDefinition type in module.GetTypes())
|
||||
{
|
||||
foreach (var property in type.Properties)
|
||||
foreach (Mono.Cecil.PropertyDefinition property in type.Properties)
|
||||
Alias(property, property.GetMethod, property.SetMethod);
|
||||
foreach (var @event in type.Events)
|
||||
foreach (Mono.Cecil.EventDefinition @event in type.Events)
|
||||
Alias(@event, @event.AddMethod, @event.RemoveMethod, @event.InvokeMethod);
|
||||
}
|
||||
void Alias(IMemberDefinition owner, params MethodDefinition[] accessors)
|
||||
{
|
||||
if (!declarations.TryGetValue(owner.MetadataToken.ToInt32(), out var location)) return;
|
||||
foreach (var method in accessors.Where(m => m != null))
|
||||
if (!declarations.TryGetValue(owner.MetadataToken.ToInt32(), out Declaration location)) return;
|
||||
foreach (MethodDefinition method in accessors.Where(m => m != null))
|
||||
declarations.TryAdd(method.MetadataToken.ToInt32(), location with { Token = method.MetadataToken.ToInt32(), Name = method.FullName, Kind = "Method" });
|
||||
}
|
||||
foreach (var method in module.GetTypes().SelectMany(t => t.Methods).Where(m => m.HasBody))
|
||||
foreach (MethodDefinition method in module.GetTypes().SelectMany(t => t.Methods).Where(m => m.HasBody))
|
||||
{
|
||||
int token = method.MetadataToken.ToInt32();
|
||||
if (!methodPoints.ContainsKey(token) && declarations.TryGetValue(token, out var declaration))
|
||||
if (!methodPoints.ContainsKey(token) && declarations.TryGetValue(token, out Declaration declaration))
|
||||
{
|
||||
var source = sourceByPath[declaration.File];
|
||||
Source source = sourceByPath[declaration.File];
|
||||
methodPoints[token] = (source, new List<Point> { new(0, declaration.Line, declaration.Column, declaration.EndLine, declaration.EndColumn) });
|
||||
}
|
||||
}
|
||||
int bodies = module.GetTypes().Sum(t => t.Methods.Count(m => m.HasBody));
|
||||
if (methodPoints.Count < bodies) throw new InvalidDataException($"Navigation coverage incomplete: {methodPoints.Count} symbols for {bodies} method bodies");
|
||||
string pdbPath = Path.ChangeExtension(shellPath, ".pdb");
|
||||
var pdb = BuildPdb(pe, module, ordered, declarations, methodPoints, dependencyDirectory);
|
||||
File.WriteAllBytes(pdbPath, pdb.Bytes);
|
||||
(byte[] Bytes, BlobContentId Id) = BuildPdb(pe, module, ordered, declarations, methodPoints, dependencyDirectory);
|
||||
File.WriteAllBytes(pdbPath, Bytes);
|
||||
// Attach exactly the PDB we generated to this PE. No implementation is executed.
|
||||
module.Write(shellPath, new WriterParameters { WriteSymbols = true, SymbolWriterProvider = new NavigationSymbolWriterProvider(pdb.Id, pdbPath, pdb.Bytes) });
|
||||
module.Write(shellPath, new WriterParameters { WriteSymbols = true, SymbolWriterProvider = new NavigationSymbolWriterProvider(Id, pdbPath, Bytes) });
|
||||
// Store the source root once instead of repeating a long machine-specific
|
||||
// cache path for hundreds of thousands of declarations.
|
||||
var manifest = new Manifest(2, Program.Hash(shellPath), Program.Hash(pdbPath), typeof(CSharpDecompiler).Assembly.GetName().Version.ToString(), sourceRoot,
|
||||
ordered.Length, declarations.Count, bodies, methodPoints.Count, new List<string>(),
|
||||
ordered.Length, declarations.Count, bodies, methodPoints.Count, [],
|
||||
declarations.Values.OrderBy(d => d.Token).Select(d => d with { File = Path.GetRelativePath(sourceRoot, d.File) }).ToList());
|
||||
File.WriteAllText(Path.Combine(directory, "navigation.json"), JsonSerializer.Serialize(manifest));
|
||||
WriteXmlDocumentation(shellPath, pe, declarations);
|
||||
@@ -148,48 +149,48 @@ internal static class SourceNavigation
|
||||
{
|
||||
sdkDirectory = Program.ResolveSdkDirectory(sdkDirectory);
|
||||
string library = Path.Combine(sdkDirectory, "lib", Program.ShellName + ".dll"), pdbPath = Path.ChangeExtension(library, ".pdb");
|
||||
var manifest = JsonSerializer.Deserialize<Manifest>(File.ReadAllText(Path.Combine(sdkDirectory, "navigation.json")));
|
||||
Manifest manifest = JsonSerializer.Deserialize<Manifest>(File.ReadAllText(Path.Combine(sdkDirectory, "navigation.json")));
|
||||
if (Program.Hash(library) != manifest.AssemblySha256 || Program.Hash(pdbPath) != manifest.PdbSha256)
|
||||
throw new InvalidDataException("Source navigation manifest, DLL and PDB do not match");
|
||||
using var peStream = File.OpenRead(library); using var pe = new PEReader(peStream);
|
||||
using var pdbStream = File.OpenRead(pdbPath); using var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
|
||||
var pdb = provider.GetMetadataReader(); var dll = pe.GetMetadataReader();
|
||||
using FileStream peStream = File.OpenRead(library); using var pe = new PEReader(peStream);
|
||||
using FileStream pdbStream = File.OpenRead(pdbPath); using var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream);
|
||||
MetadataReader pdb = provider.GetMetadataReader(); MetadataReader dll = pe.GetMetadataReader();
|
||||
var id = new BlobContentId(pdb.DebugMetadataHeader.Id);
|
||||
var entry = pe.ReadDebugDirectory().Single(d => d.Type == DebugDirectoryEntryType.CodeView);
|
||||
var codeview = pe.ReadCodeViewDebugDirectoryData(entry);
|
||||
DebugDirectoryEntry entry = pe.ReadDebugDirectory().Single(d => d.Type == DebugDirectoryEntryType.CodeView);
|
||||
CodeViewDebugDirectoryData codeview = pe.ReadCodeViewDebugDirectoryData(entry);
|
||||
if (codeview.Guid != id.Guid || entry.Stamp != id.Stamp || codeview.Age != 1) throw new InvalidDataException("PDB identity does not match navigation assembly");
|
||||
var checksum = pe.ReadDebugDirectory().Single(d => d.Type == DebugDirectoryEntryType.PdbChecksum);
|
||||
DebugDirectoryEntry checksum = pe.ReadDebugDirectory().Single(d => d.Type == DebugDirectoryEntryType.PdbChecksum);
|
||||
if (!pe.ReadPdbChecksumDebugDirectoryData(checksum).Checksum.SequenceEqual(SHA256.HashData(File.ReadAllBytes(pdbPath))))
|
||||
throw new InvalidDataException("PE/PDB checksum mismatch");
|
||||
int documents = 0, methods = 0;
|
||||
foreach (var documentHandle in pdb.Documents)
|
||||
foreach (DocumentHandle documentHandle in pdb.Documents)
|
||||
{
|
||||
var document = pdb.GetDocument(documentHandle);
|
||||
System.Reflection.Metadata.Document document = pdb.GetDocument(documentHandle);
|
||||
if (pdb.GetGuid(document.Language) != CSharpLanguage) throw new InvalidDataException("Navigation document language is not C#");
|
||||
var embedded = pdb.GetCustomDebugInformation(documentHandle).Select(h => pdb.GetCustomDebugInformation(h)).Single(c => pdb.GetGuid(c.Kind) == EmbeddedSource);
|
||||
System.Reflection.Metadata.CustomDebugInformation embedded = pdb.GetCustomDebugInformation(documentHandle).Select(h => pdb.GetCustomDebugInformation(h)).Single(c => pdb.GetGuid(c.Kind) == EmbeddedSource);
|
||||
byte[] content = DecodeEmbedded(pdb.GetBlobBytes(embedded.Value));
|
||||
if (!SHA256.HashData(content).SequenceEqual(pdb.GetBlobBytes(document.Hash))) throw new InvalidDataException("Embedded-source checksum mismatch");
|
||||
string path = pdb.GetString(document.Name);
|
||||
if (!File.Exists(path) || !File.ReadAllBytes(path).SequenceEqual(content)) throw new InvalidDataException("Local source does not match embedded source: " + path);
|
||||
documents++;
|
||||
}
|
||||
foreach (var method in dll.MethodDefinitions)
|
||||
foreach (MethodDefinitionHandle method in dll.MethodDefinitions)
|
||||
{
|
||||
var definition = dll.GetMethodDefinition(method);
|
||||
System.Reflection.Metadata.MethodDefinition definition = dll.GetMethodDefinition(method);
|
||||
if (definition.RelativeVirtualAddress == 0) continue;
|
||||
var debug = pdb.GetMethodDebugInformation(method);
|
||||
var points = debug.GetSequencePoints().ToArray();
|
||||
if (debug.Document.IsNil || points.Length == 0) throw new InvalidDataException("Method lacks navigation symbols: 0x" + MetadataTokens.GetToken(method).ToString("X8"));
|
||||
System.Reflection.Metadata.MethodDebugInformation debug = pdb.GetMethodDebugInformation(method);
|
||||
System.Reflection.Metadata.SequencePoint[] points = [.. debug.GetSequencePoints()];
|
||||
if (debug.Document.IsNil || points.Length == 0) throw new InvalidDataException("Method lacks navigation symbols: 0x" + MetadataTokens.GetToken(method).ToString("X8", CultureInfo.InvariantCulture));
|
||||
int size = pe.GetMethodBody(definition.RelativeVirtualAddress).GetILContent().Length;
|
||||
if (points.Any(p => !p.IsHidden && (p.Offset >= size || p.StartLine <= 0 || p.EndLine < p.StartLine))) throw new InvalidDataException("Invalid navigation sequence point");
|
||||
methods++;
|
||||
}
|
||||
foreach (var type in dll.TypeDefinitions)
|
||||
foreach (TypeDefinitionHandle type in dll.TypeDefinitions)
|
||||
{
|
||||
if (dll.GetString(dll.GetTypeDefinition(type).Name) == "<Module>") continue;
|
||||
var custom = pdb.GetCustomDebugInformation(type).Select(h => pdb.GetCustomDebugInformation(h)).SingleOrDefault(c => pdb.GetGuid(c.Kind) == TypeDocuments);
|
||||
if (custom.Value.IsNil) throw new InvalidDataException("Type lacks source documents: 0x" + MetadataTokens.GetToken(type).ToString("X8"));
|
||||
var blob = pdb.GetBlobReader(custom.Value);
|
||||
System.Reflection.Metadata.CustomDebugInformation custom = pdb.GetCustomDebugInformation(type).Select(h => pdb.GetCustomDebugInformation(h)).SingleOrDefault(c => pdb.GetGuid(c.Kind) == TypeDocuments);
|
||||
if (custom.Value.IsNil) throw new InvalidDataException("Type lacks source documents: 0x" + MetadataTokens.GetToken(type).ToString("X8", CultureInfo.InvariantCulture));
|
||||
BlobReader blob = pdb.GetBlobReader(custom.Value);
|
||||
while (blob.RemainingBytes > 0) _ = pdb.GetDocument(MetadataTokens.DocumentHandle(blob.ReadCompressedInteger()));
|
||||
}
|
||||
if (documents != manifest.Documents || methods != manifest.MethodsWithBodies || manifest.Symbols.Select(s => s.Token).Distinct().Count() != manifest.Declarations)
|
||||
@@ -199,14 +200,14 @@ internal static class SourceNavigation
|
||||
|
||||
internal static void RestoreSources(string sdkDirectory)
|
||||
{
|
||||
using var stream = File.OpenRead(Path.Combine(sdkDirectory, "lib", Program.ShellName + ".pdb"));
|
||||
using FileStream stream = File.OpenRead(Path.Combine(sdkDirectory, "lib", Program.ShellName + ".pdb"));
|
||||
using var provider = MetadataReaderProvider.FromPortablePdbStream(stream);
|
||||
var reader = provider.GetMetadataReader();
|
||||
foreach (var handle in reader.Documents)
|
||||
MetadataReader reader = provider.GetMetadataReader();
|
||||
foreach (DocumentHandle handle in reader.Documents)
|
||||
{
|
||||
string path = reader.GetString(reader.GetDocument(handle).Name);
|
||||
if (File.Exists(path)) continue;
|
||||
var info = reader.GetCustomDebugInformation(handle).Select(h => reader.GetCustomDebugInformation(h)).Single(c => reader.GetGuid(c.Kind) == EmbeddedSource);
|
||||
System.Reflection.Metadata.CustomDebugInformation info = reader.GetCustomDebugInformation(handle).Select(h => reader.GetCustomDebugInformation(h)).Single(c => reader.GetGuid(c.Kind) == EmbeddedSource);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
File.WriteAllBytes(path, DecodeEmbedded(reader.GetBlobBytes(info.Value)));
|
||||
}
|
||||
@@ -225,38 +226,38 @@ internal static class SourceNavigation
|
||||
|
||||
private static void ApplyImplicitDeclarations(Dictionary<int, Declaration> declarations, Mono.Cecil.TypeDefinition type)
|
||||
{
|
||||
foreach (var property in type.Properties)
|
||||
if (declarations.TryGetValue(property.MetadataToken.ToInt32(), out var location))
|
||||
foreach (var accessor in new[] { property.GetMethod, property.SetMethod }.Where(m => m != null))
|
||||
foreach (Mono.Cecil.PropertyDefinition property in type.Properties)
|
||||
if (declarations.TryGetValue(property.MetadataToken.ToInt32(), out Declaration location))
|
||||
foreach (MethodDefinition accessor in new[] { property.GetMethod, property.SetMethod }.Where(m => m != null))
|
||||
declarations.TryAdd(accessor.MetadataToken.ToInt32(), location with { Token = accessor.MetadataToken.ToInt32(), Name = accessor.FullName, Kind = "Method" });
|
||||
foreach (var @event in type.Events)
|
||||
if (declarations.TryGetValue(@event.MetadataToken.ToInt32(), out var location))
|
||||
foreach (var accessor in new[] { @event.AddMethod, @event.RemoveMethod, @event.InvokeMethod }.Where(m => m != null))
|
||||
foreach (Mono.Cecil.EventDefinition @event in type.Events)
|
||||
if (declarations.TryGetValue(@event.MetadataToken.ToInt32(), out Declaration location))
|
||||
foreach (MethodDefinition accessor in new[] { @event.AddMethod, @event.RemoveMethod, @event.InvokeMethod }.Where(m => m != null))
|
||||
declarations.TryAdd(accessor.MetadataToken.ToInt32(), location with { Token = accessor.MetadataToken.ToInt32(), Name = accessor.FullName, Kind = "Method" });
|
||||
if (declarations.TryGetValue(type.MetadataToken.ToInt32(), out var declaration))
|
||||
if (declarations.TryGetValue(type.MetadataToken.ToInt32(), out Declaration declaration))
|
||||
{
|
||||
foreach (var constructor in type.Methods.Where(m => m.IsConstructor && !declarations.ContainsKey(m.MetadataToken.ToInt32())))
|
||||
foreach (MethodDefinition constructor in type.Methods.Where(m => m.IsConstructor && !declarations.ContainsKey(m.MetadataToken.ToInt32())))
|
||||
declarations.TryAdd(constructor.MetadataToken.ToInt32(), declaration with { Token = constructor.MetadataToken.ToInt32(), Name = constructor.FullName, Kind = "Method" });
|
||||
foreach (var field in type.Fields.Where(f => f.IsRuntimeSpecialName))
|
||||
foreach (Mono.Cecil.FieldDefinition field in type.Fields.Where(f => f.IsRuntimeSpecialName))
|
||||
declarations.TryAdd(field.MetadataToken.ToInt32(), declaration with { Token = field.MetadataToken.ToInt32(), Name = field.FullName, Kind = "Field" });
|
||||
}
|
||||
foreach (var nested in type.NestedTypes) ApplyImplicitDeclarations(declarations, nested);
|
||||
foreach (Mono.Cecil.TypeDefinition nested in type.NestedTypes) ApplyImplicitDeclarations(declarations, nested);
|
||||
}
|
||||
|
||||
private static IEnumerable<TypeDefinitionHandle> Descendants(MetadataReader reader, TypeDefinitionHandle handle)
|
||||
{
|
||||
yield return handle;
|
||||
foreach (var child in reader.GetTypeDefinition(handle).GetNestedTypes())
|
||||
foreach (var nested in Descendants(reader, child)) yield return nested;
|
||||
foreach (TypeDefinitionHandle child in reader.GetTypeDefinition(handle).GetNestedTypes())
|
||||
foreach (TypeDefinitionHandle nested in Descendants(reader, child)) yield return nested;
|
||||
}
|
||||
private static string PathFor(MetadataReader reader, TypeDefinitionHandle handle)
|
||||
{
|
||||
var type = reader.GetTypeDefinition(handle);
|
||||
System.Reflection.Metadata.TypeDefinition type = reader.GetTypeDefinition(handle);
|
||||
static string Safe(string name) => string.Concat(name.Select(c => char.IsLetterOrDigit(c) || c is '_' or '-' or '.' ? c : '_'));
|
||||
string ns = reader.GetString(type.Namespace), name = reader.GetString(type.Name);
|
||||
// Token suffix prevents collisions from generic arity, case-insensitive filesystems,
|
||||
// and names whose invalid filename characters normalize to the same spelling.
|
||||
return Path.Combine(Safe(ns), Safe(name) + "." + MetadataTokens.GetToken(handle).ToString("X8") + ".cs");
|
||||
return Path.Combine(Safe(ns), Safe(name) + "." + MetadataTokens.GetToken(handle).ToString("X8", CultureInfo.InvariantCulture) + ".cs");
|
||||
}
|
||||
|
||||
private sealed class Worker : IDisposable
|
||||
@@ -278,24 +279,32 @@ internal static class SourceNavigation
|
||||
}
|
||||
private static DecompilerSettings Settings(bool raw) => new()
|
||||
{
|
||||
ThrowOnAssemblyResolveErrors = true, UseDebugSymbols = false, ShowXmlDocumentation = false,
|
||||
UseNestedDirectoriesForNamespaces = true, AnonymousMethods = !raw, AnonymousTypes = !raw,
|
||||
AsyncAwait = !raw, YieldReturn = !raw, AutomaticProperties = !raw, AutomaticEvents = !raw,
|
||||
GetterOnlyAutomaticProperties = !raw, UseExpressionBodyForCalculatedGetterOnlyProperties = !raw
|
||||
ThrowOnAssemblyResolveErrors = true,
|
||||
UseDebugSymbols = false,
|
||||
ShowXmlDocumentation = false,
|
||||
UseNestedDirectoriesForNamespaces = true,
|
||||
AnonymousMethods = !raw,
|
||||
AnonymousTypes = !raw,
|
||||
AsyncAwait = !raw,
|
||||
YieldReturn = !raw,
|
||||
AutomaticProperties = !raw,
|
||||
AutomaticEvents = !raw,
|
||||
GetterOnlyAutomaticProperties = !raw,
|
||||
UseExpressionBodyForCalculatedGetterOnlyProperties = !raw
|
||||
};
|
||||
internal Source Decompile(TypeDefinitionHandle type, string path, bool raw)
|
||||
{
|
||||
var decompiler = raw ? this.raw : primary;
|
||||
return Render(decompiler, decompiler.DecompileTypes(new[] { type }), path, raw);
|
||||
CSharpDecompiler decompiler = raw ? this.raw : primary;
|
||||
return Render(decompiler, decompiler.DecompileTypes((TypeDefinitionHandle[])[type]), path, raw);
|
||||
}
|
||||
internal Source DecompileMember(EntityHandle member, string path)
|
||||
{
|
||||
var source = Render(raw, raw.Decompile(member), path, true);
|
||||
Source source = Render(raw, raw.Decompile(member), path, true);
|
||||
int token = MetadataTokens.GetToken(member);
|
||||
if (!source.Declarations.ContainsKey(token))
|
||||
{
|
||||
var text = Encoding.UTF8.GetString(source.Content);
|
||||
source.Declarations[token] = new Declaration(token, "Metadata declaration 0x" + token.ToString("X8"), member.Kind.ToString(), path, 2, 1, text.Count(c => c == '\n') + 1, 1, true);
|
||||
string text = Encoding.UTF8.GetString(source.Content);
|
||||
source.Declarations[token] = new Declaration(token, "Metadata declaration 0x" + token.ToString("X8", CultureInfo.InvariantCulture), member.Kind.ToString(), path, 2, 1, text.Count(c => c == '\n') + 1, 1, true);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
@@ -305,11 +314,11 @@ internal static class SourceNavigation
|
||||
// Keep token identity in the index/PDB while spelling those identifiers
|
||||
// legally in the generated view, so one state machine cannot break the
|
||||
// semantic parser and navigation for all ordinary members in its file.
|
||||
foreach (var identifier in tree.DescendantsAndSelf.OfType<Identifier>())
|
||||
foreach (Identifier identifier in tree.DescendantsAndSelf.OfType<Identifier>())
|
||||
{
|
||||
string name = identifier.Name;
|
||||
if (name.Any(c => !(char.IsLetterOrDigit(c) || c == '_')))
|
||||
identifier.Name = "__generated_" + string.Concat(name.Select(c => char.IsLetterOrDigit(c) || c == '_' ? c.ToString() : "u" + ((int)c).ToString("X4")));
|
||||
identifier.Name = "__generated_" + string.Concat(name.Select(c => char.IsLetterOrDigit(c) || c == '_' ? c.ToString() : "u" + ((int)c).ToString("X4", CultureInfo.InvariantCulture)));
|
||||
}
|
||||
tree.InsertChildAfter(null, new Comment(" Decompiled from the matching game DLL using the shared BD2 names table. For navigation; not compiled or executed."), Roles.Comment);
|
||||
using var text = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
|
||||
@@ -319,20 +328,20 @@ internal static class SourceNavigation
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
File.WriteAllBytes(path, content);
|
||||
var declarations = new Dictionary<int, Declaration>();
|
||||
foreach (var node in tree.DescendantsAndSelf)
|
||||
foreach (AstNode node in tree.DescendantsAndSelf)
|
||||
{
|
||||
if (node is not EntityDeclaration && node is not VariableInitializer && node is not Accessor) continue;
|
||||
if (node.GetSymbol() is not IEntity entity || entity.MetadataToken.IsNil) continue;
|
||||
int token = MetadataTokens.GetToken(entity.MetadataToken);
|
||||
var start = node is EntityDeclaration declaration && !declaration.NameToken.IsNull ? declaration.NameToken.StartLocation : node.StartLocation;
|
||||
var end = node.EndLocation;
|
||||
TextLocation start = node is EntityDeclaration declaration && !declaration.NameToken.IsNull ? declaration.NameToken.StartLocation : node.StartLocation;
|
||||
TextLocation end = node.EndLocation;
|
||||
if (start.Line <= 0 || end.Line < start.Line) continue;
|
||||
declarations.TryAdd(token, new Declaration(token, entity.ReflectionName, entity.SymbolKind.ToString(), path, start.Line, start.Column, end.Line, end.Column, generated));
|
||||
}
|
||||
var points = new Dictionary<int, List<Point>>();
|
||||
foreach (var function in decompiler.CreateSequencePoints(tree))
|
||||
foreach (KeyValuePair<ICSharpCode.Decompiler.IL.ILFunction, List<ICSharpCode.Decompiler.DebugInfo.SequencePoint>> function in decompiler.CreateSequencePoints(tree))
|
||||
{
|
||||
var method = function.Key.MoveNextMethod ?? function.Key.Method;
|
||||
IMethod method = function.Key.MoveNextMethod ?? function.Key.Method;
|
||||
if (method == null || method.MetadataToken.IsNil) continue;
|
||||
int token = MetadataTokens.GetToken(method.MetadataToken);
|
||||
var sequence = function.Value.Where(p => !p.IsHidden).Select(p => new Point(p.Offset, p.StartLine, p.StartColumn, p.EndLine, p.EndColumn)).ToList();
|
||||
@@ -349,11 +358,11 @@ internal static class SourceNavigation
|
||||
var metadata = new MetadataBuilder();
|
||||
var documents = new Dictionary<string, DocumentHandle>(StringComparer.Ordinal);
|
||||
var custom = new List<(EntityHandle Parent, Guid Kind, byte[] Bytes)>();
|
||||
var csharp = metadata.GetOrAddGuid(CSharpLanguage);
|
||||
var sha256 = metadata.GetOrAddGuid(new Guid("8829D00F-11B8-4213-878B-770E8597AC16"));
|
||||
foreach (var source in sources)
|
||||
GuidHandle csharp = metadata.GetOrAddGuid(CSharpLanguage);
|
||||
GuidHandle sha256 = metadata.GetOrAddGuid(new Guid("8829D00F-11B8-4213-878B-770E8597AC16"));
|
||||
foreach (Source source in sources)
|
||||
{
|
||||
var document = metadata.AddDocument(metadata.GetOrAddDocumentName(source.Path), sha256, metadata.GetOrAddBlob(SHA256.HashData(source.Content)), csharp);
|
||||
DocumentHandle document = metadata.AddDocument(metadata.GetOrAddDocumentName(source.Path), sha256, metadata.GetOrAddBlob(SHA256.HashData(source.Content)), csharp);
|
||||
documents.Add(source.Path, document);
|
||||
using var stream = new MemoryStream();
|
||||
using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) writer.Write(source.Content.Length);
|
||||
@@ -361,17 +370,17 @@ internal static class SourceNavigation
|
||||
custom.Add((document, EmbeddedSource, stream.ToArray()));
|
||||
}
|
||||
var methodDefs = module.GetTypes().SelectMany(t => t.Methods).ToDictionary(m => m.MetadataToken.ToInt32());
|
||||
foreach (var handle in pe.Metadata.MethodDefinitions)
|
||||
foreach (MethodDefinitionHandle handle in pe.Metadata.MethodDefinitions)
|
||||
{
|
||||
int token = MetadataTokens.GetToken(handle);
|
||||
if (!methods.TryGetValue(token, out var mapped)) { metadata.AddMethodDebugInformation(default, default); continue; }
|
||||
var points = mapped.Points.Where(p => p.Offset >= 0 && p.Offset < methodDefs[token].Body.CodeSize && p.Line > 0 && p.EndLine >= p.Line)
|
||||
.GroupBy(p => p.Offset).Select(g => g.First()).OrderBy(p => p.Offset).ToArray();
|
||||
if (!methods.TryGetValue(token, out (Source Source, List<Point> Points) mapped)) { metadata.AddMethodDebugInformation(default, default); continue; }
|
||||
Point[] points = [.. mapped.Points.Where(p => p.Offset >= 0 && p.Offset < methodDefs[token].Body.CodeSize && p.Line > 0 && p.EndLine >= p.Line)
|
||||
.GroupBy(p => p.Offset).Select(g => g.First()).OrderBy(p => p.Offset)];
|
||||
var blob = new BlobBuilder(); blob.WriteCompressedInteger(0); // no local signature is needed for navigation
|
||||
int previousOffset = 0, previousLine = 0, previousColumn = 0;
|
||||
for (int i = 0; i < points.Length; i++)
|
||||
{
|
||||
var p = points[i]; blob.WriteCompressedInteger(i == 0 ? p.Offset : p.Offset - previousOffset);
|
||||
Point p = points[i]; blob.WriteCompressedInteger(i == 0 ? p.Offset : p.Offset - previousOffset);
|
||||
int lines = p.EndLine - p.Line; blob.WriteCompressedInteger(lines);
|
||||
int columns = p.EndColumn - p.Column;
|
||||
if (lines == 0) blob.WriteCompressedInteger(Math.Max(1, columns)); else blob.WriteCompressedSignedInteger(columns);
|
||||
@@ -381,21 +390,21 @@ internal static class SourceNavigation
|
||||
}
|
||||
metadata.AddMethodDebugInformation(documents[mapped.Source.Path], metadata.GetOrAddBlob(blob));
|
||||
}
|
||||
foreach (var type in module.GetTypes())
|
||||
foreach (Mono.Cecil.TypeDefinition type in module.GetTypes())
|
||||
{
|
||||
if (!declarations.TryGetValue(type.MetadataToken.ToInt32(), out var d)) continue;
|
||||
if (!declarations.TryGetValue(type.MetadataToken.ToInt32(), out Declaration d)) continue;
|
||||
var docs = new BlobBuilder(); docs.WriteCompressedInteger(MetadataTokens.GetRowNumber(documents[d.File]));
|
||||
custom.Add((MetadataTokens.EntityHandle(type.MetadataToken.ToInt32()), TypeDocuments, docs.ToArray()));
|
||||
}
|
||||
var options = Encoding.UTF8.GetBytes("language\0C#\0language-version\0" + "12.0\0compiler-version\0BD2.GameSdk\0output-kind\0DynamicallyLinkedLibrary\0optimization\0debug\0");
|
||||
byte[] options = Encoding.UTF8.GetBytes("language\0C#\0language-version\0" + "12.0\0compiler-version\0BD2.GameSdk\0output-kind\0DynamicallyLinkedLibrary\0optimization\0debug\0");
|
||||
custom.Add((MetadataTokens.EntityHandle(1), CompilationOptions, options));
|
||||
var references = new BlobBuilder();
|
||||
foreach (var reference in module.AssemblyReferences)
|
||||
foreach (Mono.Cecil.AssemblyNameReference reference in module.AssemblyReferences)
|
||||
{
|
||||
string path = Path.Combine(dependencies, reference.Name + ".dll");
|
||||
if (!File.Exists(path)) continue;
|
||||
using var stream = File.OpenRead(path); using var dependency = new PEReader(stream);
|
||||
var reader = dependency.GetMetadataReader();
|
||||
using FileStream stream = File.OpenRead(path); using var dependency = new PEReader(stream);
|
||||
MetadataReader reader = dependency.GetMetadataReader();
|
||||
references.WriteBytes(Encoding.UTF8.GetBytes(Path.GetFileName(path))); references.WriteByte(0);
|
||||
references.WriteByte(0); // global alias
|
||||
references.WriteByte(1); // combined embedInteropTypes=false, image kind=assembly
|
||||
@@ -404,16 +413,16 @@ internal static class SourceNavigation
|
||||
references.WriteBytes(reader.GetGuid(reader.GetModuleDefinition().Mvid).ToByteArray());
|
||||
}
|
||||
custom.Add((MetadataTokens.EntityHandle(1), CompilationReferences, references.ToArray()));
|
||||
foreach (var info in custom.OrderBy(c => CodedIndex.HasCustomDebugInformation(c.Parent)))
|
||||
metadata.AddCustomDebugInformation(info.Parent, metadata.GetOrAddGuid(info.Kind), metadata.GetOrAddBlob(info.Bytes));
|
||||
foreach ((EntityHandle Parent, Guid Kind, byte[] Bytes) in custom.OrderBy(c => CodedIndex.HasCustomDebugInformation(c.Parent)))
|
||||
metadata.AddCustomDebugInformation(Parent, metadata.GetOrAddGuid(Kind), metadata.GetOrAddBlob(Bytes));
|
||||
var counts = Enumerable.Range(0, 64).Select(i => pe.Metadata.GetTableRowCount((TableIndex)i)).ToImmutableArray();
|
||||
var builder = new PortablePdbBuilder(metadata, counts, default, blobs =>
|
||||
{
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var blob in blobs) hash.AppendData(blob.GetBytes());
|
||||
foreach (Blob blob in blobs) hash.AppendData(blob.GetBytes());
|
||||
return BlobContentId.FromHash(hash.GetHashAndReset());
|
||||
});
|
||||
var output = new BlobBuilder(); var id = builder.Serialize(output);
|
||||
var output = new BlobBuilder(); BlobContentId id = builder.Serialize(output);
|
||||
return (output.ToArray(), id);
|
||||
}
|
||||
|
||||
@@ -428,14 +437,14 @@ internal static class SourceNavigation
|
||||
// navigation. Repeating the same boilerplate for every member inflated
|
||||
// each XML file to hundreds of MB without adding API documentation.
|
||||
foreach (IEntity entity in decompiler.TypeSystem.MainModule.TypeDefinitions)
|
||||
{
|
||||
if (entity.MetadataToken.IsNil || !declarations.TryGetValue(MetadataTokens.GetToken(entity.MetadataToken), out var location)) continue;
|
||||
string id = ICSharpCode.Decompiler.Documentation.IdStringProvider.GetIdString(entity);
|
||||
writer.WriteStartElement("member"); writer.WriteAttributeString("name", id);
|
||||
writer.WriteElementString("summary", "Readable game type. Decompiled source: " + Path.GetRelativePath(Path.Combine(Path.GetDirectoryName(assembly), "sources"), location.File) + ":" + location.Line);
|
||||
writer.WriteElementString("remarks", "Navigation-only reference; the runtime implementation is in the matching Assembly-CSharp.");
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
{
|
||||
if (entity.MetadataToken.IsNil || !declarations.TryGetValue(MetadataTokens.GetToken(entity.MetadataToken), out Declaration location)) continue;
|
||||
string id = ICSharpCode.Decompiler.Documentation.IdStringProvider.GetIdString(entity);
|
||||
writer.WriteStartElement("member"); writer.WriteAttributeString("name", id);
|
||||
writer.WriteElementString("summary", "Readable game type. Decompiled source: " + Path.GetRelativePath(Path.Combine(Path.GetDirectoryName(assembly), "sources"), location.File) + ":" + location.Line);
|
||||
writer.WriteElementString("remarks", "Navigation-only reference; the runtime implementation is in the matching Assembly-CSharp.");
|
||||
writer.WriteEndElement();
|
||||
}
|
||||
writer.WriteEndElement(); writer.WriteEndElement();
|
||||
}
|
||||
|
||||
@@ -455,10 +464,10 @@ internal static class SourceNavigation
|
||||
using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream);
|
||||
writer.Write(0x53445352); writer.Write(id.Guid.ToByteArray()); writer.Write(1); writer.Write(Encoding.UTF8.GetBytes(path)); writer.Write((byte)0);
|
||||
byte[] codeview = stream.ToArray();
|
||||
return new ImageDebugHeader(new[] {
|
||||
return new ImageDebugHeader([
|
||||
new ImageDebugHeaderEntry(new ImageDebugDirectory { Type = ImageDebugType.CodeView, MajorVersion = 0x100, MinorVersion = 0x504d, TimeDateStamp = (int)id.Stamp, SizeOfData = codeview.Length }, codeview),
|
||||
new ImageDebugHeaderEntry(new ImageDebugDirectory { Type = ImageDebugType.PdbChecksum, SizeOfData = 39 }, Encoding.UTF8.GetBytes("SHA256\0").Concat(SHA256.HashData(pdb)).ToArray())
|
||||
});
|
||||
new ImageDebugHeaderEntry(new ImageDebugDirectory { Type = ImageDebugType.PdbChecksum, SizeOfData = 39 }, [.. Encoding.UTF8.GetBytes("SHA256\0"), .. SHA256.HashData(pdb)])
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)] [string]$GameDir,
|
||||
[Parameter(Mandatory)] [string]$GameMapping,
|
||||
[string]$VersionConfig
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $VersionConfig) { $VersionConfig = Join-Path $PSScriptRoot '..\..\versions.json' }
|
||||
$repository = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))
|
||||
$staging = Join-Path $repository ('.build\names-update\' + [guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Force -Path $staging | Out-Null
|
||||
function Invoke-Dotnet([string[]]$Arguments) {
|
||||
& dotnet @Arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
Invoke-Dotnet @('build', (Join-Path $PSScriptRoot 'GameSdk.csproj'), '-c', 'Release', '--nologo')
|
||||
$tool = Join-Path $PSScriptRoot 'bin\Release\net8.0\GameSdk.dll'
|
||||
$assembly = Join-Path $GameDir 'BrownDust II_Data\Managed\Assembly-CSharp.dll'
|
||||
$table = Join-Path $staging 'names.json'
|
||||
Invoke-Dotnet @($tool, 'names', $assembly, $GameMapping, $VersionConfig, $table)
|
||||
# Validate the full metadata transformation before replacing the checked-in table.
|
||||
Invoke-Dotnet @($tool, 'shell', $table, $assembly, (Join-Path $staging 'Assembly-CSharp.Readable.dll'))
|
||||
$destination = Join-Path $PSScriptRoot '..\GameNames\Mappings\names.json.gz'
|
||||
Copy-Item -LiteralPath "$table.gz" -Destination $destination -Force
|
||||
Write-Host "Updated SDK/runtime shared table: $destination. Rebuild SDK and plugins, then pack a new version."
|
||||
@@ -1,82 +0,0 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)] [string]$GameDir,
|
||||
[string]$PackageVersion,
|
||||
[string]$PackageDirectory
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $PackageDirectory) { $PackageDirectory = Join-Path $PSScriptRoot '..\..\.build\nuget' }
|
||||
if (-not $PackageVersion) {
|
||||
[xml]$metadata = Get-Content -LiteralPath (Join-Path $PSScriptRoot '..\PackageMetadata.props') -Raw
|
||||
$versions = Get-Content -LiteralPath (Join-Path $PSScriptRoot '..\..\versions.json') -Raw | ConvertFrom-Json
|
||||
$PackageVersion = "$($metadata.Project.PropertyGroup.BD2PackageVersion)-game.$($versions.game_version)"
|
||||
}
|
||||
$PackageDirectory = [IO.Path]::GetFullPath($PackageDirectory)
|
||||
# A fresh external directory and package cache prevent repository imports and stale
|
||||
# same-version development packages from making an invalid package appear to work.
|
||||
$verificationRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../.build/nuget-tests'))
|
||||
$workspace = Join-Path $verificationRoot ([guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $workspace | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'samples\ExamplePlugin\ExamplePlugin.csproj'), (Join-Path $PSScriptRoot 'samples\ExamplePlugin\Plugin.cs') -Destination $workspace
|
||||
$project = Join-Path $workspace 'ExamplePlugin.csproj'
|
||||
$projectText = [IO.File]::ReadAllText($project).Replace('Version="0.2.1-game.2.35.10"', "Version=`"$PackageVersion`"")
|
||||
[IO.File]::WriteAllText($project, $projectText)
|
||||
$feed = [Security.SecurityElement]::Escape($PackageDirectory)
|
||||
$cache = [Security.SecurityElement]::Escape((Join-Path $workspace 'packages'))
|
||||
[IO.File]::WriteAllText((Join-Path $workspace 'NuGet.Config'), "<configuration><packageSources><clear/><add key=`"bd2`" value=`"$feed`"/><add key=`"nuget.org`" value=`"https://api.nuget.org/v3/index.json`"/></packageSources><config><add key=`"globalPackagesFolder`" value=`"$cache`"/></config></configuration>")
|
||||
function Invoke-Dotnet([string[]]$Arguments) {
|
||||
& dotnet @Arguments
|
||||
if ($LASTEXITCODE -ne 0) { throw "dotnet failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
$sharedCacheRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../.build/game-sdk'))
|
||||
Invoke-Dotnet @('build', $project, '-c', 'Release', '--nologo', "-p:GameDir=$GameDir", "-p:BD2GameSdkCache=$sharedCacheRoot")
|
||||
$output = Join-Path $workspace 'bin\Release\netstandard2.1'
|
||||
$runtime = Join-Path $output 'BD2.GameNames.dll'
|
||||
foreach ($required in @('BD2.GameNames.dll', 'ExamplePlugin.dll')) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $output $required))) { throw "Missing output: $required" }
|
||||
}
|
||||
foreach ($forbidden in @('Assembly-CSharp.Readable.dll', 'Assembly-CSharp.Readable.pdb', 'Assembly-CSharp.dll', 'GameSdk.dll', 'Mono.Cecil.dll', 'ICSharpCode.Decompiler.dll', 'BepInEx.dll', '0Harmony.dll', 'UnityEngine.dll', 'ExamplePlugin.pdb', 'navigation.json', 'sources', 'ref', 'lib')) {
|
||||
if (Test-Path -LiteralPath (Join-Path $output $forbidden)) { throw "Unexpected deployment artifact: $forbidden" }
|
||||
}
|
||||
$tool = Join-Path $workspace "packages\bd2.gamesdk\$PackageVersion\tools\net8.0\GameSdk.dll"
|
||||
$sdk = Join-Path $workspace 'obj\Release\netstandard2.1\bd2-game-sdk'
|
||||
$sharedSdk = [IO.File]::ReadAllText((Join-Path $sdk 'shared-sdk.txt')).Trim()
|
||||
$table = Join-Path $sharedSdk 'names.json'
|
||||
if ((Get-ChildItem -LiteralPath $sdk -Recurse -File | Measure-Object Length -Sum).Sum -gt 65536) {
|
||||
throw 'SDK obj still contains large copied artifacts instead of shared references.'
|
||||
}
|
||||
[xml]$exampleProject = Get-Content -LiteralPath $project -Raw
|
||||
if ([IO.Path]::GetFileName([IO.Path]::GetDirectoryName($sharedSdk)) -ne $exampleProject.Project.PropertyGroup.BD2GameVersion) {
|
||||
throw 'Shared SDK directory is not grouped by the plugin-declared game version.'
|
||||
}
|
||||
$sharedReadyTimestamp = (Get-Item -LiteralPath (Join-Path $sharedSdk 'ready.txt')).LastWriteTimeUtc
|
||||
Invoke-Dotnet @($tool, 'verify-runtime', $table, $runtime)
|
||||
Invoke-Dotnet @($tool, 'verify-navigation', $sdk)
|
||||
Invoke-Dotnet @($tool, 'verify', $table, (Join-Path $output 'ExamplePlugin.dll'), (Join-Path $GameDir 'BrownDust II_Data\Managed\Assembly-CSharp.dll'))
|
||||
# Repeated builds must always transform the readable obj DLL, never reprocess bin.
|
||||
$navigationProps = Join-Path $sdk 'GameSourceNavigation.props'
|
||||
$navigationTimestamp = (Get-Item -LiteralPath $navigationProps).LastWriteTimeUtc
|
||||
Invoke-Dotnet @('build', $project, '-c', 'Release', '--no-restore', '--nologo', "-p:GameDir=$GameDir", "-p:BD2GameSdkCache=$sharedCacheRoot")
|
||||
if ((Get-Item -LiteralPath $navigationProps).LastWriteTimeUtc -ne $navigationTimestamp) {
|
||||
throw 'Unchanged navigation props were rewritten; this triggers repeated IDE reloads.'
|
||||
}
|
||||
if ((Get-Item -LiteralPath (Join-Path $sharedSdk 'ready.txt')).LastWriteTimeUtc -ne $sharedReadyTimestamp) {
|
||||
throw 'Repeated build unexpectedly regenerated the shared SDK.'
|
||||
}
|
||||
Invoke-Dotnet @($tool, 'verify', $table, (Join-Path $output 'ExamplePlugin.dll'), (Join-Path $GameDir 'BrownDust II_Data\Managed\Assembly-CSharp.dll'))
|
||||
foreach ($invalidVersion in @('', '0.0.0')) {
|
||||
$rejectedBuild = & dotnet build $project -c Release --no-restore --nologo "-p:GameDir=$GameDir" "-p:BD2GameSdkCache=$sharedCacheRoot" "-p:BD2GameVersion=$invalidVersion" 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0 -or ($invalidVersion -eq '' -and -not $rejectedBuild.Contains('BD2GameVersion')) -or
|
||||
($invalidVersion -ne '' -and -not $rejectedBuild.Contains('Plugin requires game 0.0.0'))) {
|
||||
throw "Missing/mismatched game version was not rejected: $invalidVersion"
|
||||
}
|
||||
}
|
||||
Write-Host "Verified external PackageReference consumer, complete source navigation, shared runtime and incremental rebuild: $workspace"
|
||||
# Successful probes are disposable. Retain a failed probe for diagnostics, but
|
||||
# do not accumulate package caches after successful verification.
|
||||
$resolvedProbe = [IO.Path]::GetFullPath($workspace)
|
||||
if ([IO.Path]::GetDirectoryName($resolvedProbe) -ne $verificationRoot -or
|
||||
[IO.Path]::GetFileName($resolvedProbe) -notmatch '^[a-f0-9]{32}$') {
|
||||
throw 'Invalid verification cleanup path.'
|
||||
}
|
||||
Remove-Item -LiteralPath $resolvedProbe -Recurse -Force
|
||||
@@ -2,11 +2,24 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<!-- Adjust these settings as needed. -->
|
||||
<EnableNETAnalyzers>false</EnableNETAnalyzers>
|
||||
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
||||
<AssemblyName>ExamplePlugin</AssemblyName>
|
||||
<BD2GameVersion>2.35.10</BD2GameVersion>
|
||||
<BD2ManagedDir Condition="'$(BD2ManagedDir)' == ''">$(GameDir)/BrownDust II_Data/Managed</BD2ManagedDir>
|
||||
<!-- GameDir belongs in local Directory.Build.props or on the command line. -->
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BD2.GameSdk" Version="0.2.1-game.2.35.10" PrivateAssets="all" />
|
||||
<PackageReference Include="BD2.GameSdk" Version="0.2.2-game.2.35.10" PrivateAssets="all" />
|
||||
<!-- Adjust these references as needed. -->
|
||||
<Reference Include="Unity.TextMeshPro">
|
||||
<HintPath>$(BD2ManagedDir)/Unity.TextMeshPro.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.UI">
|
||||
<HintPath>$(BD2ManagedDir)/UnityEngine.UI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<clear />
|
||||
<!-- Repository sample consumes the packages produced by GameSdk/Pack.ps1. -->
|
||||
<!-- Repository sample consumes the packages produced by bd2w sdk pack. -->
|
||||
<add key="bd2-local" value="../../../../.build/nuget" />
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
|
||||
</packageSources>
|
||||
|
||||
@@ -3,36 +3,31 @@ using System.Reflection;
|
||||
using BD2.GameNames;
|
||||
using BepInEx;
|
||||
using HarmonyLib;
|
||||
using TMPro;
|
||||
|
||||
namespace ExamplePlugin;
|
||||
|
||||
[BepInPlugin("example.readable-names", "Readable Names Example", "1.0.0")]
|
||||
[BepInPlugin("example.plugin", "example plugin", "1.0.0")]
|
||||
public sealed class Plugin : BaseUnityPlugin
|
||||
{
|
||||
private Harmony harmony;
|
||||
private const string Greeting = "\nHello! Brown Dust Ⅱ";
|
||||
private static FieldInfo versionTextField;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Fail before installing any game patches when binary/table/plugin versions differ.
|
||||
Game.Validate(typeof(Plugin).Assembly, message => Logger.LogInfo(message));
|
||||
MethodInfo target = Game.Method<IntroUI>(ui => ui.SendMaintenanceInfo(false));
|
||||
harmony = new Harmony("example.readable-names");
|
||||
harmony.Patch(target, prefix: new HarmonyMethod(typeof(Plugin), nameof(BeforeMaintenance)));
|
||||
|
||||
// Private members require the runtime string channel. The prefix expression above
|
||||
// and the Unity callback name below belong to separate channels.
|
||||
var awake = typeof(IntroUI).GetGameMethod("Awake",
|
||||
BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
|
||||
Logger.LogInfo("Resolved IntroUI.Awake: " + (awake != null));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Logger.LogError("Readable Names Example initialization failed: " + exception);
|
||||
}
|
||||
Game.Validate(typeof(Plugin).Assembly);
|
||||
MethodInfo target = Game.Method<IntroUI>(ui => ui.SetVersionText());
|
||||
versionTextField = typeof(IntroUI).GetGameField("_textVersion", BindingFlags.Instance | BindingFlags.NonPublic)
|
||||
?? throw new MissingFieldException("IntroUI._textVersion");
|
||||
var harmony = new Harmony("example.plugin");
|
||||
harmony.Patch(target, postfix: new HarmonyMethod(typeof(Plugin), nameof(AfterSetVersionText)));
|
||||
}
|
||||
|
||||
private static void BeforeMaintenance() { }
|
||||
private void OnDestroy() => harmony?.UnpatchSelf();
|
||||
private static void AfterSetVersionText(IntroUI __instance)
|
||||
{
|
||||
if (versionTextField.GetValue(__instance) is not TMP_Text versionText) return;
|
||||
string current = versionText.text ?? string.Empty;
|
||||
if (current.EndsWith(Greeting, StringComparison.Ordinal)) return;
|
||||
versionText.text = current + Greeting;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user