Simplify InteropPatcher a bit

This commit is contained in:
UnknownShadow200 2018-07-14 12:07:37 +10:00
parent db6c2c6140
commit a1ce953149
7 changed files with 197 additions and 256 deletions

View File

@ -403,7 +403,6 @@
<Link>credits.txt</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="app.config" />
<None Include="..\readme.md">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

View File

@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727" /></startup></configuration>

View File

@ -1,71 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="2.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{4A4110EE-21CA-4715-AF67-0C8B7CE0642F}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<OutputType>Exe</OutputType>
<RootNamespace>InteropPatcher</RootNamespace>
<AssemblyName>InteropPatcher</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<AppDesignerFolder>Properties</AppDesignerFolder>
<NoWin32Manifest>False</NoWin32Manifest>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<IntermediateOutputPath>obj\$(Configuration)\</IntermediateOutputPath>
<WarningLevel>4</WarningLevel>
<SignAssembly>False</SignAssembly>
<DelaySign>False</DelaySign>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<BaseAddress>4194304</BaseAddress>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>..\output\debug\</OutputPath>
<DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<BaseIntermediateOutputPath>obj\</BaseIntermediateOutputPath>
<StartAction>Project</StartAction>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>..\output\release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
<BaseIntermediateOutputPath>obj\</BaseIntermediateOutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Cecil">
<HintPath>Mono.Cecil.dll</HintPath>
</Reference>
<Reference Include="Mono.Cecil.Mdb">
<HintPath>Mono.Cecil.Mdb.dll</HintPath>
</Reference>
<Reference Include="Mono.Cecil.Pdb">
<HintPath>Mono.Cecil.Pdb.dll</HintPath>
</Reference>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Patcher.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="2.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{4A4110EE-21CA-4715-AF67-0C8B7CE0642F}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<OutputType>Exe</OutputType>
<RootNamespace>InteropPatcher</RootNamespace>
<AssemblyName>InteropPatcher</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<AppDesignerFolder>Properties</AppDesignerFolder>
<NoWin32Manifest>False</NoWin32Manifest>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<IntermediateOutputPath>obj\$(Configuration)\</IntermediateOutputPath>
<WarningLevel>4</WarningLevel>
<SignAssembly>False</SignAssembly>
<DelaySign>False</DelaySign>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<BaseAddress>4194304</BaseAddress>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>..\output\debug\</OutputPath>
<DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<BaseIntermediateOutputPath>obj\</BaseIntermediateOutputPath>
<StartAction>Project</StartAction>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>..\output\release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
<BaseIntermediateOutputPath>obj\</BaseIntermediateOutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Cecil">
<HintPath>Mono.Cecil.dll</HintPath>
</Reference>
<Reference Include="Mono.Cecil.Mdb">
<HintPath>Mono.Cecil.Mdb.dll</HintPath>
</Reference>
<Reference Include="Mono.Cecil.Pdb">
<HintPath>Mono.Cecil.Pdb.dll</HintPath>
</Reference>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
</Project>

View File

@ -1,153 +0,0 @@
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
namespace InteropPatcher {
public static class Patcher {
static void ReplaceFixedStatement(MethodDefinition method, ILProcessor ilProcessor, Instruction fixedtoPatch) {
TypeReference paramT = ((GenericInstanceMethod)fixedtoPatch.Operand).GenericArguments[0];
// Preparing locals
// local(0) T*
method.Body.Variables.Add(new VariableDefinition("pin", new PinnedType(new ByReferenceType(paramT))));
int index = method.Body.Variables.Count - 1;
Instruction ldlocFixed, stlocFixed;
switch (index) {
case 0:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_0);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_0);
break;
case 1:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_1);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_1);
break;
case 2:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_2);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_2);
break;
case 3:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_3);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_3);
break;
default:
stlocFixed = ilProcessor.Create(OpCodes.Stloc, index);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc, index);
break;
}
ilProcessor.InsertBefore(fixedtoPatch, stlocFixed);
ilProcessor.Replace(fixedtoPatch, ldlocFixed);
}
static void PatchMethod(MethodDefinition method) {
if( !method.HasBody ) return;
ILProcessor ilProcessor = method.Body.GetILProcessor();
Collection<Instruction> instructions = method.Body.Instructions;
for (int i = 0; i < instructions.Count; i++)
{
Instruction instruction = instructions[i];
if (instruction.OpCode == OpCodes.Call && instruction.Operand is MethodReference)
{
MethodReference desc = (MethodReference)instruction.Operand;
if( desc.DeclaringType.Name != "Interop" ) continue;
if( desc.Name.StartsWith( "Calli" ) ) {
CallSite callSite = new CallSite(desc.ReturnType);
callSite.CallingConvention = MethodCallingConvention.StdCall;
// Last parameter is the function ptr, so we don't add it as a parameter for calli
// as it is already an implicit parameter for calli
for (int j = 0; j < desc.Parameters.Count - 1; j++) {
callSite.Parameters.Add(desc.Parameters[j]);
}
Instruction callIInstruction = ilProcessor.Create(OpCodes.Calli, callSite);
ilProcessor.Replace(instruction, callIInstruction);
} else if( desc.Name.StartsWith( "Fixed" ) ) {
ReplaceFixedStatement(method, ilProcessor, instruction);
}
}
}
}
static void PatchType( TypeDefinition type ) {
if( type.Name == "Interop" ) return;
if( NeedsToBePatched( type ) ) {
Console.WriteLine( "Patching type: " + type );
foreach( MethodDefinition method in type.Methods )
PatchMethod( method );
foreach( TypeDefinition nestedType in type.NestedTypes )
PatchType( nestedType );
}
}
static bool NeedsToBePatched( TypeDefinition type ) {
foreach( CustomAttribute attrib in type.CustomAttributes ) {
if( attrib.AttributeType.Name == "InteropPatchAttribute" )
return true;
}
return false;
}
public static void PatchFile( string file ) {
// Copy PDB from input assembly to output assembly if any
ReaderParameters rParams = new ReaderParameters();
rParams.AssemblyResolver = new DefaultAssemblyResolver();
WriterParameters wParams = new WriterParameters();
string pdbName = Path.ChangeExtension( file, "pdb" );
if( File.Exists( pdbName ) ) {
rParams.SymbolReaderProvider = new PdbReaderProvider();
rParams.ReadSymbols = true;
wParams.WriteSymbols = true;
}
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(file, rParams);
TypeDefinition interopTypeDefinition = null;
Console.WriteLine( "SharpDX interop patch for: " + file );
foreach( TypeDefinition type in assembly.MainModule.Types ) {
if( type.Name == "Interop" ) {
interopTypeDefinition = type;
break;
}
}
if( interopTypeDefinition == null ) {
Console.WriteLine( "Nothing to do, already patched." );
return;
}
foreach( TypeDefinition type in assembly.MainModule.Types ) {
PatchType( type );
}
assembly.MainModule.Types.Remove( interopTypeDefinition );
assembly.Write( file, wParams );
Console.WriteLine( "Done patching." );
}
}
}

View File

@ -1,24 +1,129 @@
using System;
namespace InteropPatcher {
public static class Program {
public static int Main( string[] args ) {
try {
if( args.Length == 0 ) {
Console.WriteLine( "Expecting single argument specifying the file to patch" );
return 2;
}
// Some older IDEs seem to like splitting the path when it has spaces.
// So we undo this and treat the arguments as a single path.
string path = String.Join( " ", args );
Patcher.PatchFile( path );
return 0;
} catch( Exception ex ) {
Console.WriteLine( ex );
return 1;
}
}
}
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
namespace InteropPatcher {
public static class Patcher {
public static int Main( string[] args ) {
try {
if( args.Length == 0 ) {
Console.WriteLine( "Expecting single argument specifying the file to patch" );
return 2;
}
// Some older IDEs seem to like splitting the path when it has spaces.
// So we undo this and treat the arguments as a single path.
string path = String.Join( " ", args );
PatchFile( path );
return 0;
} catch( Exception ex ) {
Console.WriteLine( ex );
return 1;
}
}
static void PatchMethod(MethodDefinition method) {
if (!method.HasBody) return;
ILProcessor ilProcessor = method.Body.GetILProcessor();
Collection<Instruction> instructions = method.Body.Instructions;
for (int i = 0; i < instructions.Count; i++) {
Instruction instruction = instructions[i];
if (instruction.OpCode == OpCodes.Call && instruction.Operand is MethodReference) {
MethodReference desc = (MethodReference)instruction.Operand;
if (desc.DeclaringType.Name != "Interop") continue;
if (!desc.Name.StartsWith("Calli")) continue;
CallSite callSite = new CallSite(desc.ReturnType);
callSite.CallingConvention = MethodCallingConvention.StdCall;
// Last parameter is the function ptr, so we don't add it as a parameter for calli
// as it is already an implicit parameter for calli
for (int j = 0; j < desc.Parameters.Count - 1; j++) {
callSite.Parameters.Add(desc.Parameters[j]);
}
Instruction calli_ins = ilProcessor.Create(OpCodes.Calli, callSite);
ilProcessor.Replace(instruction, calli_ins);
}
}
}
static void PatchType(TypeDefinition type) {
if (type.Name == "Interop") return;
if (!NeedsToBePatched(type)) return;
Console.WriteLine("Patching type: " + type);
foreach (MethodDefinition method in type.Methods)
PatchMethod(method);
foreach (TypeDefinition nestedType in type.NestedTypes)
PatchType(nestedType);
}
static bool NeedsToBePatched(TypeDefinition type) {
foreach (CustomAttribute attrib in type.CustomAttributes) {
if (attrib.AttributeType.Name == "InteropPatchAttribute")
return true;
}
return false;
}
public static void PatchFile(string file) {
ReaderParameters rParams = new ReaderParameters();
rParams.AssemblyResolver = new DefaultAssemblyResolver();
WriterParameters wParams = new WriterParameters();
// Copy PDB from input assembly to output assembly if any
if (File.Exists(Path.ChangeExtension(file, "pdb"))) {
rParams.SymbolReaderProvider = new PdbReaderProvider();
rParams.ReadSymbols = true;
wParams.WriteSymbols = true;
}
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(file, rParams);
TypeDefinition interopTypeDefinition = null;
Console.WriteLine("Interop patching: " + file);
foreach (TypeDefinition type in assembly.MainModule.Types) {
if (type.Name == "Interop") {
interopTypeDefinition = type; break;
}
}
if (interopTypeDefinition == null) {
Console.WriteLine("Nothing to do, already patched.");
return;
}
foreach (TypeDefinition type in assembly.MainModule.Types) {
PatchType(type);
}
assembly.MainModule.Types.Remove(interopTypeDefinition);
assembly.Write(file, wParams);
Console.WriteLine("Done patching.");
}
}
}

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
</startup>
</configuration>

View File

@ -253,5 +253,8 @@ void Camera_CycleActive(void) {
Camera_Active = &Camera_Cameras[i];
Camera_ActiveIndex = i;
/* reset rotation offset when changing cameras */
cam_rotOffset.X = 0.0f; cam_rotOffset.Y = 0.0f;
Game_UpdateProjection();
}