mirror: 上游快照导入

This commit is contained in:
gitea committed 2026-11-30 09:52:36 +08:00
commit 7475ccb467
86 files changed
+3213

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
# Build and Object Folders
bin/
obj/
publish/
# Nuget packages directory
packages/
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.log
*.vspscc
*.vssscc
.builds
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help
UpgradeLog*.XML
# Lightswitch
_Pvt_Extensions
GeneratedArtifacts
*.xap
ModelManifest.xml
#Backup file
*.bak
.vs
.vscode
+79
View File
@@ -0,0 +1,79 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35219.272
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CSharpLoaderDll", "CSharpLoaderDll\CSharpLoaderDll.vcxproj", "{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpManager", "CSharpManager\CSharpManager.csproj", "{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpModBase", "CSharpModBase\CSharpModBase.csproj", "{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpExample", "CSharpModExample\CSharpExample.csproj", "{541076F4-03E4-4C7E-B511-E5D548DD6707}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Debug|Any CPU.ActiveCfg = Debug|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Debug|Any CPU.Build.0 = Debug|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Debug|x64.ActiveCfg = Debug|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Debug|x64.Build.0 = Debug|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Debug|x86.ActiveCfg = Debug|Win32
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Debug|x86.Build.0 = Debug|Win32
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Release|Any CPU.ActiveCfg = Release|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Release|Any CPU.Build.0 = Release|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Release|x64.ActiveCfg = Release|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Release|x64.Build.0 = Release|x64
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Release|x86.ActiveCfg = Release|Win32
{9504CD32-5959-4DC7-BA59-6D4DEBAC8688}.Release|x86.Build.0 = Release|Win32
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Debug|x64.ActiveCfg = Debug|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Debug|x64.Build.0 = Debug|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Debug|x86.ActiveCfg = Debug|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Debug|x86.Build.0 = Debug|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Release|Any CPU.Build.0 = Release|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Release|x64.ActiveCfg = Release|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Release|x64.Build.0 = Release|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Release|x86.ActiveCfg = Release|Any CPU
{8FD00CCB-84AA-4ACA-971E-8838ECE0742C}.Release|x86.Build.0 = Release|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Debug|x64.ActiveCfg = Debug|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Debug|x64.Build.0 = Debug|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Debug|x86.ActiveCfg = Debug|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Debug|x86.Build.0 = Debug|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Release|Any CPU.ActiveCfg = Release|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Release|Any CPU.Build.0 = Release|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Release|x64.ActiveCfg = Release|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Release|x64.Build.0 = Release|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Release|x86.ActiveCfg = Release|Any CPU
{82BC94A3-CB1D-4A7C-9C0A-1860D8C57942}.Release|x86.Build.0 = Release|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Debug|Any CPU.Build.0 = Debug|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Debug|x64.ActiveCfg = Debug|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Debug|x64.Build.0 = Debug|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Debug|x86.ActiveCfg = Debug|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Debug|x86.Build.0 = Debug|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Release|Any CPU.ActiveCfg = Release|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Release|Any CPU.Build.0 = Release|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Release|x64.ActiveCfg = Release|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Release|x64.Build.0 = Release|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Release|x86.ActiveCfg = Release|Any CPU
{541076F4-03E4-4C7E-B511-E5D548DD6707}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EAEB9F1E-6B3F-4096-9D52-0768BF081E66}
EndGlobalSection
EndGlobal
+179
View File
@@ -0,0 +1,179 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{9504cd32-5959-4dc7-ba59-6d4debac8688}</ProjectGuid>
<RootNamespace>CSharpLoaderDll</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<TargetName>version</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<TargetName>version</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<TargetName>version</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<TargetName>version</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="framework.h" />
<ClInclude Include="hid_dll.hpp" />
<ClInclude Include="memory.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="plugin.hpp" />
<ClInclude Include="version_dll.hpp" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="hid_dll.cpp" />
<ClCompile Include="memory.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="plugin.cpp" />
<ClCompile Include="version_dll.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="framework.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="pch.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="memory.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="hid_dll.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="version_dll.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="plugin.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="memory.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="hid_dll.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="version_dll.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="plugin.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>
+231
View File
@@ -0,0 +1,231 @@
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
#include <iostream>
#include "memory.h"
#include "hid_dll.hpp"
#include "version_dll.hpp"
#include "plugin.hpp"
enum class DllType {
Unknown,
Version,
Hid,
};
static DllType dllType = DllType::Unknown;
struct MonoAssemblyOpenRequest
{
uint8_t raw[40];
};
typedef enum {
MONO_IMAGE_OK,
MONO_IMAGE_ERROR_ERRNO,
MONO_IMAGE_MISSING_ASSEMBLYREF,
MONO_IMAGE_IMAGE_INVALID
} MonoImageOpenStatus;
// MonoThread * mono_thread_internal_attach (MonoDomain *domain)
typedef void* (*mono_thread_internal_attach_t)(void* domain);
// MonoAssembly * mono_assembly_request_open (const char *filename, const MonoAssemblyOpenRequest *open_req, MonoImageOpenStatus *status)
typedef void* (*mono_assembly_request_open_t)(const char* filename, const MonoAssemblyOpenRequest* open_req, MonoImageOpenStatus* status);
/*
gint32 ves_icall_System_AppDomain_ExecuteAssembly (
MonoAppDomainHandle ad, MonoReflectionAssemblyHandle refass, MonoArrayHandle args, MonoError *error)
struct _MonoAppDomain { // size: 32
MonoMarshalByRefObject mbr; // 0
MonoDomain *data; // 24
};
struct _MonoReflectionAssembly { // size: 32
MonoObject object; // 0
MonoAssembly *assembly; // 16
MonoObject *evidence; // 24
};
*/
struct _MonoAppDomain { // size: 32
uint8_t mbr[24]; // 0
void* data; // 24
};
struct _MonoReflectionAssembly { // size: 32
uint8_t object[16]; // 0
void* assembly; // 16
void* evidence; // 24
};
struct MonoError {
uint8_t raw[104];
};
typedef int (*ves_icall_System_AppDomain_ExecuteAssembly_t)(_MonoAppDomain** ad, _MonoReflectionAssembly** refass, void** args, MonoError* error);
DWORD WINAPI MainThread(LPVOID dwModule)
{
if (dllType == DllType::Version)
{
Sleep(3000);
}
const char* configFile = "./CSharpLoader/b1cs.ini";
UINT enableConsole = GetPrivateProfileIntA("Settings", "Console", 0, configFile);
BOOL enableJit = GetPrivateProfileIntA("Settings", "EnableJit", 1, configFile);
if (enableConsole == 1) {
AllocConsole();
FILE* fDummy;
freopen_s(&fDummy, "CONIN$", "r", stdin);
freopen_s(&fDummy, "CONOUT$", "w", stdout);
freopen_s(&fDummy, "CONOUT$", "w", stderr);
}
loadPluginDlls();
std::cout << "CSharpLoader enableJit: " << enableJit << std::endl;
std::cout << "CSharpLoader wait for init." << std::endl;
// enable jit
if (enableJit) {
uint64_t memory_fuction_ptr = signature("83 3D ? ? ? ? 00 0F 84 ? ? ? ? C7 84 24 ? ? 00 00 01 00 00 00").GetPointer();
if (memory_fuction_ptr == 0) {
std::cout << "memory function signature found." << std::endl;
} else {
DWORD old_protect;
if (VirtualProtect((void*)(memory_fuction_ptr + 7), 2, PAGE_EXECUTE_READWRITE, &old_protect)) {
*(uint16_t*)(memory_fuction_ptr + 7) = 0xE990; // nop; jmp
VirtualProtect((void*)(memory_fuction_ptr + 7), 2, old_protect, &old_protect);
uint64_t mono_mode_ptr = signature("48 8D 0D ? ? ? ? E8 ? ? ? ? 89 44 24 ? 83 7C 24 ? 00").GetPointer();
if (mono_mode_ptr == 0) {
std::cout << "mono_mode signature found." << std::endl;
} else {
if (VirtualProtect((void*)(mono_mode_ptr + 7), 5, PAGE_EXECUTE_READWRITE, &old_protect)) {
*(uint8_t*)(mono_mode_ptr + 7) = 0xB8;
*(uint32_t*)(mono_mode_ptr + 8) = 1;
VirtualProtect((void*)(mono_mode_ptr + 7), 5, old_protect, &old_protect);
}
}
}
}
}
signature domain_s("F0 FF 88 B0 00 00 00 48 8B 05 ? ? ? ? 48 3B D8 49 0F 44 C4");
if (domain_s.GetPointer() == 0) {
std::cout << "domainPtr pattern not found." << std::endl;
return EXIT_FAILURE;
}
void **domainPtr = (void**)domain_s.instruction(10).add(14).GetPointer();
if (domainPtr == nullptr) {
std::cout << "domainPtr not found." << std::endl;
return EXIT_FAILURE;
}
auto mono_thread_internal_attach = (mono_thread_internal_attach_t)signature(
"40 57 48 83 EC 30 8B 15 ? ? ? ? 48 8B F9 65 48 8B 04 25 58 00 00 00 B9 A8 02 00 00 48 8B 04 D0 48 83 3C 01 00").GetPointer();
if (mono_thread_internal_attach == nullptr) {
std::cout << "mono_thread_internal_attach not found." << std::endl;
return EXIT_FAILURE;
}
auto mono_assembly_request_open = (mono_assembly_request_open_t)signature(
"40 55 41 56 41 57 48 8D AC 24 40 FF FF FF 48 81 EC C0 01 00 00 48 8B 05 ? ? ? ? 48 33 C4 48 89 85 90 00 00 00 48 89 4D 90").GetPointer();
if (mono_assembly_request_open == nullptr) {
std::cout << "mono_assembly_request_open not found." << std::endl;
return EXIT_FAILURE;
}
auto ves_icall_System_AppDomain_ExecuteAssembly = (ves_icall_System_AppDomain_ExecuteAssembly_t)signature(
"48 89 5C 24 08 55 56 57 41 56 41 57 48 83 EC 50 48 89 94 24 88 00 00 00").GetPointer();
if (ves_icall_System_AppDomain_ExecuteAssembly == nullptr) {
std::cout << "ves_icall_System_AppDomain_ExecuteAssembly not found." << std::endl;
return EXIT_FAILURE;
}
void* domain = nullptr;
for (size_t i = 0; i < 180; i++) {
domain = *domainPtr;
if (domain != nullptr) {
break;
}
Sleep(1000); // 1s
}
if (domain == nullptr) {
std::cout << "domain is null." << std::endl;
return EXIT_FAILURE;
}
Sleep(2000); // 2s
void* mono_thread = mono_thread_internal_attach(domain);
if (mono_thread == nullptr) {
std::cout << "mono_thread_internal_attach failed." << std::endl;
return EXIT_FAILURE;
}
MonoAssemblyOpenRequest open_request{};
MonoImageOpenStatus status = MonoImageOpenStatus::MONO_IMAGE_OK;
wchar_t fullFilename[MAX_PATH];
GetFullPathName(L"CSharpLoader\\CSharpManager.bin", MAX_PATH, fullFilename, nullptr);
char fullFilenameA[MAX_PATH];
// convert to utf-8 to support Chinese path
WideCharToMultiByte(CP_UTF8, 0, fullFilename, MAX_PATH, fullFilenameA, MAX_PATH, NULL, NULL);
void* assembly = mono_assembly_request_open(fullFilenameA, &open_request, &status);
if (assembly == nullptr) {
std::cout << "mono_assembly_request_open failed." << std::endl;
return EXIT_FAILURE;
}
_MonoAppDomain ad{};
ad.data = domain;
_MonoReflectionAssembly refass{};
refass.assembly = assembly;
MonoError mono_error{};
_MonoAppDomain* p_ad = &ad;
_MonoReflectionAssembly* p_refass = &refass;
void* args = nullptr;
int res = ves_icall_System_AppDomain_ExecuteAssembly(&p_ad, &p_refass, &args, &mono_error);
if (res != 0) {
std::cout << "ves_icall_System_AppDomain_ExecuteAssembly failed: " << res << std::endl;
return EXIT_FAILURE;
}
std::cout << "CSharpLoader init success." << std::endl;
return EXIT_SUCCESS;
}
void init_dll(HMODULE hModule) {
DisableThreadLibraryCalls(hModule);
wchar_t moduleFullpathFilename[MAX_PATH + 1];
GetModuleFileNameW(hModule, moduleFullpathFilename, static_cast<UINT>(std::size(moduleFullpathFilename)));
wchar_t fname[_MAX_FNAME+1];
{
wchar_t drive[_MAX_DRIVE+1];
wchar_t dir[_MAX_DIR+1];
wchar_t ext[_MAX_EXT+1];
_wsplitpath_s(moduleFullpathFilename, drive, dir, fname, ext);
}
if (_wcsicmp(fname, L"version") == 0) {
dllType = DllType::Version;
init_version_dll();
} else if (_wcsicmp(fname, L"hid") == 0) {
dllType = DllType::Hid;
init_hid_dll();
}
CreateThread(nullptr, 0, MainThread, hModule, 0, nullptr);
}
void deinit_dll() {
if (dllType == DllType::Version) {
deinit_version_dll();
} else if (dllType == DllType::Hid) {
deinit_hid_dll();
}
// unloadPluginDlls();
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
static std::once_flag initFlag;
static std::once_flag cleanupFlag;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
std::call_once(initFlag, [&]() { init_dll(hModule); });
break;
case DLL_PROCESS_DETACH:
std::call_once(cleanupFlag, [&]() { deinit_dll(); });
break;
}
return TRUE;
}
+5
View File
@@ -0,0 +1,5 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>
+221
View File
@@ -0,0 +1,221 @@
#include "pch.h"
#include "hid_dll.hpp"
#include <windows.h>
#include <hidsdi.h>
#include <string>
#include <stdio.h>
///////////////////////////////////////////////////////////////
static HMODULE hModuleDll = nullptr;
static const wchar_t dllFname[] = L"hid";
bool init_hid_dll() {
deinit_hid_dll();
wchar_t systemDirectory[MAX_PATH]{0};
GetSystemDirectoryW(systemDirectory, MAX_PATH);
wchar_t fullpathDllName[MAX_PATH]{0};
swprintf_s(fullpathDllName, MAX_PATH, L"%s\\%s.dll", systemDirectory, dllFname);
if ((hModuleDll = LoadLibraryW(fullpathDllName)) == NULL) {
return false;
}
wprintf(L"load %s success\n", dllFname);
return true;
}
bool deinit_hid_dll() {
if(hModuleDll != nullptr) {
FreeLibrary(hModuleDll);
hModuleDll = nullptr;
}
return true;
}
///////////////////////////////////////////////////////////////
template<typename T>
void setup(T*& funcPtr, const char* funcName) {
if(funcPtr != nullptr) {
return;
}
funcPtr = reinterpret_cast<T*>(GetProcAddress(hModuleDll, funcName));
}
#define D(funcname, ...) \
static decltype(funcname)* p; \
setup(p, #funcname); \
return p(__VA_ARGS__); \
__pragma(comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__))
// https://github.com/reactos/reactos/blob/7033ab18dfa936168a279913035587858dd143e7/dll/win32/hid/hid.c#L376
extern "C" ULONG WINAPI HidD_Hello(PCHAR Buffer, ULONG BufferLength) {
D(HidD_Hello, Buffer, BufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetAttributes(HANDLE HidDeviceObject, PHIDD_ATTRIBUTES Attributes) {
D(HidD_GetAttributes, HidDeviceObject, Attributes);
}
extern "C" void WINAPI HidD_GetHidGuid(LPGUID HidGuid) {
D(HidD_GetHidGuid, HidGuid);
}
extern "C" BOOLEAN WINAPI HidD_GetPreparsedData(HANDLE HidDeviceObject, PHIDP_PREPARSED_DATA * PreparsedData) {
D(HidD_GetPreparsedData, HidDeviceObject, PreparsedData);
}
extern "C" BOOLEAN WINAPI HidD_FreePreparsedData(PHIDP_PREPARSED_DATA PreparsedData) {
D(HidD_FreePreparsedData, PreparsedData);
}
extern "C" BOOLEAN WINAPI HidD_FlushQueue(HANDLE HidDeviceObject) {
D(HidD_FlushQueue, HidDeviceObject);
}
extern "C" BOOLEAN WINAPI HidD_GetConfiguration(HANDLE HidDeviceObject, PHIDD_CONFIGURATION Configuration, ULONG ConfigurationLength) {
D(HidD_GetConfiguration, HidDeviceObject, Configuration, ConfigurationLength);
}
extern "C" BOOLEAN WINAPI HidD_SetConfiguration(HANDLE HidDeviceObject, PHIDD_CONFIGURATION Configuration, ULONG ConfigurationLength) {
D(HidD_SetConfiguration, HidDeviceObject, Configuration, ConfigurationLength);
}
extern "C" BOOLEAN WINAPI HidD_GetFeature(HANDLE HidDeviceObject, PVOID ReportBuffer, ULONG ReportBufferLength) {
D(HidD_GetFeature, HidDeviceObject, ReportBuffer, ReportBufferLength);
}
extern "C" BOOLEAN WINAPI HidD_SetFeature(HANDLE HidDeviceObject, PVOID ReportBuffer, ULONG ReportBufferLength) {
D(HidD_SetFeature, HidDeviceObject, ReportBuffer, ReportBufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetInputReport(HANDLE HidDeviceObject, PVOID ReportBuffer, ULONG ReportBufferLength) {
D(HidD_GetInputReport, HidDeviceObject, ReportBuffer, ReportBufferLength);
}
extern "C" BOOLEAN WINAPI HidD_SetOutputReport(HANDLE HidDeviceObject, PVOID ReportBuffer, ULONG ReportBufferLength) {
D(HidD_SetOutputReport, HidDeviceObject, ReportBuffer, ReportBufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetNumInputBuffers(HANDLE HidDeviceObject, PULONG NumberBuffers) {
D(HidD_GetNumInputBuffers, HidDeviceObject, NumberBuffers);
}
extern "C" BOOLEAN WINAPI HidD_SetNumInputBuffers(HANDLE HidDeviceObject, ULONG NumberBuffers) {
D(HidD_SetNumInputBuffers, HidDeviceObject, NumberBuffers);
}
extern "C" BOOLEAN WINAPI HidD_GetPhysicalDescriptor(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength) {
D(HidD_GetPhysicalDescriptor, HidDeviceObject, Buffer, BufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetManufacturerString(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength) {
D(HidD_GetManufacturerString, HidDeviceObject, Buffer, BufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetProductString(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength) {
D(HidD_GetProductString, HidDeviceObject, Buffer, BufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetIndexedString(HANDLE HidDeviceObject, ULONG StringIndex, PVOID Buffer, ULONG BufferLength) {
D(HidD_GetIndexedString, HidDeviceObject, StringIndex, Buffer, BufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetSerialNumberString(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength) {
D(HidD_GetSerialNumberString, HidDeviceObject, Buffer, BufferLength);
}
extern "C" BOOLEAN WINAPI HidD_GetMsGenreDescriptor(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength) {
D(HidD_GetMsGenreDescriptor, HidDeviceObject, Buffer, BufferLength);
}
extern "C" NTSTATUS WINAPI HidP_GetCaps(PHIDP_PREPARSED_DATA PreparsedData, PHIDP_CAPS Capabilities) {
D(HidP_GetCaps, PreparsedData, Capabilities);
}
extern "C" NTSTATUS WINAPI HidP_GetLinkCollectionNodes(PHIDP_LINK_COLLECTION_NODE LinkCollectionNodes, PULONG LinkCollectionNodesLength, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_GetLinkCollectionNodes, LinkCollectionNodes, LinkCollectionNodesLength, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_GetSpecificButtonCaps(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, PHIDP_BUTTON_CAPS ButtonCaps, PUSHORT ButtonCapsLength, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_GetSpecificButtonCaps, ReportType, UsagePage, LinkCollection, Usage, ButtonCaps, ButtonCapsLength, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_GetButtonCaps(HIDP_REPORT_TYPE ReportType, PHIDP_BUTTON_CAPS ButtonCaps, PUSHORT ButtonCapsLength, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_GetButtonCaps, ReportType, ButtonCaps, ButtonCapsLength, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_GetSpecificValueCaps(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, PHIDP_VALUE_CAPS ValueCaps, PUSHORT ValueCapsLength, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_GetSpecificValueCaps, ReportType, UsagePage, LinkCollection, Usage, ValueCaps, ValueCapsLength, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_GetValueCaps(HIDP_REPORT_TYPE ReportType, PHIDP_VALUE_CAPS ValueCaps, PUSHORT ValueCapsLength, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_GetValueCaps, ReportType, ValueCaps, ValueCapsLength, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_GetExtendedAttributes(HIDP_REPORT_TYPE ReportType, USHORT DataIndex, PHIDP_PREPARSED_DATA PreparsedData, PHIDP_EXTENDED_ATTRIBUTES Attributes, PULONG LengthAttributes) {
D(HidP_GetExtendedAttributes, ReportType, DataIndex, PreparsedData, Attributes, LengthAttributes);
}
extern "C" NTSTATUS WINAPI HidP_InitializeReportForID(HIDP_REPORT_TYPE ReportType, UCHAR ReportID, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_InitializeReportForID, ReportType, ReportID, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_SetData(HIDP_REPORT_TYPE ReportType, PHIDP_DATA DataList, PULONG DataLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_SetData, ReportType, DataList, DataLength, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_GetData(HIDP_REPORT_TYPE ReportType, PHIDP_DATA DataList, PULONG DataLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_GetData, ReportType, DataList, DataLength, PreparsedData, Report, ReportLength);
}
extern "C" ULONG WINAPI HidP_MaxDataListLength(HIDP_REPORT_TYPE ReportType, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_MaxDataListLength, ReportType, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_SetUsages(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, PUSAGE UsageList, PULONG UsageLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength ) {
D(HidP_SetUsages, ReportType, UsagePage, LinkCollection, UsageList, UsageLength, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_UnsetUsages(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, PUSAGE UsageList, PULONG UsageLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_UnsetUsages, ReportType, UsagePage, LinkCollection, UsageList, UsageLength, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_GetUsages(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, PUSAGE UsageList, PULONG UsageLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_GetUsages, ReportType, UsagePage, LinkCollection, UsageList, UsageLength, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_GetUsagesEx(HIDP_REPORT_TYPE ReportType, USHORT LinkCollection, PUSAGE_AND_PAGE ButtonList, ULONG * UsageLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_GetUsagesEx, ReportType, LinkCollection, ButtonList, UsageLength, PreparsedData, Report, ReportLength);
}
extern "C" ULONG WINAPI HidP_MaxUsageListLength(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, PHIDP_PREPARSED_DATA PreparsedData) {
D(HidP_MaxUsageListLength, ReportType, UsagePage, PreparsedData);
}
extern "C" NTSTATUS WINAPI HidP_SetUsageValue(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, ULONG UsageValue, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_SetUsageValue, ReportType, UsagePage, LinkCollection, Usage, UsageValue, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_SetScaledUsageValue(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, LONG UsageValue, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_SetScaledUsageValue, ReportType, UsagePage, LinkCollection, Usage, UsageValue, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_SetUsageValueArray(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, PCHAR UsageValue, USHORT UsageValueByteLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_SetUsageValueArray, ReportType, UsagePage, LinkCollection, Usage, UsageValue, UsageValueByteLength, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_GetUsageValue(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, PULONG UsageValue, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_GetUsageValue, ReportType, UsagePage, LinkCollection, Usage, UsageValue, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_GetScaledUsageValue(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, PLONG UsageValue, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_GetScaledUsageValue, ReportType, UsagePage, LinkCollection, Usage, UsageValue, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_GetUsageValueArray(HIDP_REPORT_TYPE ReportType, USAGE UsagePage, USHORT LinkCollection, USAGE Usage, PCHAR UsageValue, USHORT UsageValueByteLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength) {
D(HidP_GetUsageValueArray, ReportType, UsagePage, LinkCollection, Usage, UsageValue, UsageValueByteLength, PreparsedData, Report, ReportLength);
}
extern "C" NTSTATUS WINAPI HidP_UsageListDifference(PUSAGE PreviousUsageList, PUSAGE CurrentUsageList, PUSAGE BreakUsageList, PUSAGE MakeUsageList, ULONG UsageListLength) {
D(HidP_UsageListDifference, PreviousUsageList, CurrentUsageList, BreakUsageList, MakeUsageList, UsageListLength);
}
+4
View File
@@ -0,0 +1,4 @@
#pragma once
bool init_hid_dll();
bool deinit_hid_dll();
+277
View File
@@ -0,0 +1,277 @@
#include "pch.h"
#include "memory.h"
memory::allocator memory::mem_allocator_;
memory::allocator::~allocator()
{
this->clear();
}
void memory::allocator::clear()
{
std::lock_guard<std::mutex> _(this->mutex_);
for (auto& data : this->pool_)
{
memory::free(data);
}
this->pool_.clear();
}
void memory::allocator::free(void* data)
{
std::lock_guard<std::mutex> _(this->mutex_);
const auto j = std::find(this->pool_.begin(), this->pool_.end(), data);
if (j != this->pool_.end())
{
memory::free(data);
this->pool_.erase(j);
}
}
void memory::allocator::free(const void* data)
{
this->free(const_cast<void*>(data));
}
void* memory::allocator::allocate(const size_t length)
{
std::lock_guard<std::mutex> _(this->mutex_);
const auto data = memory::allocate(length);
this->pool_.push_back(data);
return data;
}
bool memory::allocator::empty() const
{
return this->pool_.empty();
}
void* memory::allocate(const size_t length)
{
return calloc(length, 1);
}
void memory::free(void* data)
{
if (data)
{
::free(data);
}
}
void memory::free(const void* data)
{
free(const_cast<void*>(data));
}
bool memory::is_set(const void* mem, const char chr, const size_t length)
{
const auto mem_arr = static_cast<const char*>(mem);
for (size_t i = 0; i < length; ++i)
{
if (mem_arr[i] != chr)
{
return false;
}
}
return true;
}
memory::allocator* memory::get_allocator()
{
return &memory::mem_allocator_;
}
std::uint8_t* find_sig(LPCSTR module_name, const std::string& byte_array)
{
HMODULE module = GetModuleHandleA(module_name);
if (!module)
return nullptr;
static const auto pattern_to_byte = [](const char* pattern)
{
auto bytes = std::vector<int>{};
const auto start = const_cast<char*>(pattern);
const auto end = const_cast<char*>(pattern) + std::strlen(pattern);
for (auto current = start; current < end; ++current)
{
if (*current == '?')
{
++current;
if (*current == '?')
++current;
bytes.push_back(-1);
}
else
{
bytes.push_back(std::strtoul(current, &current, 16));
}
}
return bytes;
};
const auto dos_header = reinterpret_cast<PIMAGE_DOS_HEADER>(module);
const auto nt_headers =
reinterpret_cast<PIMAGE_NT_HEADERS>(reinterpret_cast<std::uint8_t*>(module) + dos_header->e_lfanew);
const auto size_of_image = nt_headers->OptionalHeader.SizeOfImage;
const auto pattern_bytes = pattern_to_byte(byte_array.c_str());
const auto scan_bytes = reinterpret_cast<std::uint8_t*>(module);
const auto pattern_size = pattern_bytes.size();
const auto pattern_data = pattern_bytes.data();
for (auto i = 0ul; i < size_of_image - pattern_size; ++i)
{
auto found = true;
for (auto j = 0ul; j < pattern_size; ++j)
{
if (scan_bytes[i + j] == pattern_data[j] || pattern_data[j] == -1)
continue;
found = false;
break;
}
if (!found)
continue;
return &scan_bytes[i];
}
return nullptr;
}
signature::signature(const std::string& sig)
{
this->imported = false;
this->sig = sig;
this->pointer = 0;
}
signature signature::import(const char* module_name)
{
this->imported = true;
this->pointer = (uint64_t)find_sig(module_name, this->sig);
return *this;
}
signature signature::add(uint32_t value)
{
if (!this->imported)
*this = this->import();
this->pointer += value;
return *this;
}
signature signature::sub(uint32_t value)
{
if (!this->imported)
*this = this->import();
this->pointer -= value;
return *this;
}
signature signature::dump(const std::string& func_name)
{
if (!this->imported)
*this = this->import();
return *this;
}
signature signature::instruction(uint32_t offset)
{
if (!this->imported)
*this = this->import();
this->pointer = *(int*)(this->pointer + offset) + this->pointer;
return *this;
}
#ifdef _WIN64
uint64_t signature::GetPointer()
{
if (!this->imported)
*this = this->import();
return this->pointer;
}
#else
uint32_t signature::GetPointer()
{
if (!this->imported)
*this = this->import();
return this->pointer;
}
#endif
static inline void memcpy_(void* _Dst, void const* _Src, size_t _Size)
{
auto csrc = (char*)_Src;
auto cdest = (char*)_Dst;
for (int i = 0; i < _Size; i++)
{
cdest[i] = csrc[i];
}
}
void swap_virtual_table(void* obj, uint32_t index, void* func)
{
auto currVt = *(void**)(obj);
auto vtable = *(void***)(obj);
int i = 0;
for (; vtable[i]; i++)
__noop();
auto newVt = new uintptr_t[i];
memcpy_(newVt, currVt, i * 0x8);
newVt[index] = (uintptr_t)func;
*(uintptr_t**)(obj) = newVt;
}
bool get_key_state(int key, int flag)
{
clock_t c = clock();
static BYTE btKeyState[0x100] = { 0 };
static clock_t clockKeyState[0x100] = { c };
bool r = false;
BYTE btState = (GetAsyncKeyState(key) & 0x8000U) >> 0xF;
short wDelay = btKeyState[key] & 2 ? 0x50 : 0x200;
if (btState) {
if (flag & 1) {
if (!(btKeyState[key] & 1) || c - clockKeyState[key] > wDelay)
{
if ((btKeyState[key] & 3) == 1)
btKeyState[key] |= 2;
r = true;
clockKeyState[key] = c;
}
}
else
r = true;
}
else
btKeyState[key] &= ~(2);
btKeyState[key] ^= (-btState ^ btKeyState[key]) & 1;
return r;
}
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include <Windows.h>
#include <mutex>
#include <vector>
std::uint8_t* find_sig(LPCSTR module_name, const std::string& byte_array);
class memory final
{
public:
class allocator final
{
public:
~allocator();
void clear();
void free(void* data);
void free(const void* data);
void* allocate(size_t length);
template <typename T>
T* allocate()
{
return this->allocate_array<T>(1);
}
template <typename T>
T* allocate_array(const size_t count = 1)
{
auto base = static_cast<T*>(this->allocate(count * sizeof(T)));
T();
return base;
}
bool empty() const;
private:
std::mutex mutex_;
std::vector<void*> pool_;
};
static void* allocate(size_t length);
template <typename T>
static inline T* allocate()
{
return allocate_array<T>(1);
}
template <typename T>
static inline T* allocate_array(const size_t count = 1)
{
return static_cast<T*>(allocate(count * sizeof(T)));
}
static void free(void* data);
static void free(const void* data);
static bool is_set(const void* mem, char chr, size_t length);
static allocator* get_allocator();
private:
static allocator mem_allocator_;
};
class signature
{
public:
signature(const std::string& sig);
signature import(const char* module_name = NULL);
signature add(uint32_t offset);
signature sub(uint32_t offset);
signature instruction(uint32_t offset);
signature dump(const std::string& func_name);
#ifdef _WIN64
uint64_t GetPointer();
#else
uint32_t GetPointer();
#endif
private:
#ifdef _WIN64
uint64_t pointer;
#else
uint32_t pointer;
#endif
bool imported;
std::string sig;
};
void swap_virtual_table(void* obj, uint32_t index, void* func);
bool get_key_state(int key, int flag = 1);
+5
View File
@@ -0,0 +1,5 @@
// pch.cpp: 与预编译标头对应的源文件
#include "pch.h"
// 当使用预编译的头时,需要使用此源文件,编译才能成功。
+13
View File
@@ -0,0 +1,13 @@
// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H
+98
View File
@@ -0,0 +1,98 @@
// https://github.com/t-mat/pseudo-version-dll/
#include "pch.h"
#include "plugin.hpp"
#include <functional>
#include <algorithm>
#include <array>
#include <vector>
static std::vector<HMODULE> hModules;
struct Path : std::array<wchar_t, MAX_PATH+1> {
Path() : Path {L""} {}
Path(const wchar_t* s) { wcsncpy_s(data(), size(), s, size()); }
operator const wchar_t*() const { return data(); }
static Path make(const wchar_t* fmt, ...) {
va_list args;
va_start(args, fmt);
Path path;
vswprintf_s(path.data(), path.size(), fmt, args);
return path;
}
};
Path getModuleFilenameW(HMODULE h) {
std::array<wchar_t, MAX_PATH> moduleName;
GetModuleFileNameW(h, moduleName.data(), static_cast<UINT>(moduleName.size()));
return Path(moduleName.data());
}
void recursiveFileEnumerator(const wchar_t* path, const std::function<void(const wchar_t*)>& func) {
WIN32_FIND_DATAW wfd;
HANDLE h = FindFirstFileW(Path::make(L"%s\\*.*", path), &wfd);
if(h == INVALID_HANDLE_VALUE) {
return;
}
do {
const auto a = wfd.dwFileAttributes;
const auto newPath = Path::make(L"%s\\%s", path, wfd.cFileName);
if(a & FILE_ATTRIBUTE_DIRECTORY) {
if(wfd.cFileName[0] != L'.') {
recursiveFileEnumerator(newPath, func);
}
} else if((a & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_NORMAL)) != 0) {
if(wfd.cFileName[0] != L'.') {
func(newPath);
}
}
} while(FindNextFileW(h, &wfd));
}
void loadPluginDlls() {
unloadPluginDlls();
Path pluginsPath = Path::make(L"CSharpLoader\\Plugins");
wprintf(L"loadPluginDlls : pluginsPath=[%s]\n", pluginsPath.data());
std::vector<Path> pluginFilenames;
recursiveFileEnumerator(pluginsPath, [&](const wchar_t* path) {
const wchar_t* ext = L".dll";
const auto extLen = wcslen(ext);
const auto pathLen = wcslen(path);
if(pathLen < extLen) {
return;
}
if(_wcsicmp(path + pathLen - extLen, ext) != 0) {
return;
}
pluginFilenames.push_back(path);
});
std::sort(pluginFilenames.begin(), pluginFilenames.end());
for(const auto& pluginFilename : pluginFilenames) {
auto* filename = static_cast<const wchar_t*>(pluginFilename);
auto hm = LoadLibraryW(filename);
if(hm == nullptr) {
wprintf(L"loadPluginDlls : failed to load %s\n", filename);
} else {
hModules.push_back(hm);
wprintf(L"loadPluginDlls : load %s\n", filename);
}
}
}
void unloadPluginDlls() {
for(auto it = hModules.rbegin(); it != hModules.rend(); ++it) {
const auto h = *it;
if(h != nullptr) {
wprintf(L"unloadPluginDlls : unload %s (hModules=0x%p)", getModuleFilenameW(h).data(), h);
FreeLibrary(h);
}
}
hModules.clear();
}
+4
View File
@@ -0,0 +1,4 @@
#pragma once
void loadPluginDlls();
void unloadPluginDlls();
+166
View File
@@ -0,0 +1,166 @@
#include "pch.h"
#pragma unmanaged
#include "version_dll.hpp"
#include <windows.h>
#include <array>
#include <stdio.h>
///////////////////////////////////////////////////////////////
static HMODULE hModuleDll = nullptr;
static const wchar_t dllFname[] = L"version";
bool init_version_dll() {
deinit_version_dll();
wchar_t systemDirectory[MAX_PATH]{0};
GetSystemDirectoryW(systemDirectory, MAX_PATH);
wchar_t fullpathDllName[MAX_PATH]{0};
swprintf_s(fullpathDllName, MAX_PATH, L"%s\\%s.dll", systemDirectory, dllFname);
if ((hModuleDll = LoadLibraryW(fullpathDllName)) == NULL) {
return false;
}
wprintf(L"load %s success\n", dllFname);
return true;
}
bool deinit_version_dll() {
if(hModuleDll != nullptr) {
FreeLibrary(hModuleDll);
hModuleDll = nullptr;
}
return true;
}
///////////////////////////////////////////////////////////////
template<typename T>
void setup(T*& funcPtr, const char* funcName) {
if(funcPtr != nullptr) {
return;
}
funcPtr = reinterpret_cast<T*>(GetProcAddress(hModuleDll, funcName));
}
#define D(funcname, ...) \
static decltype(funcname)* p; \
setup(p, #funcname); \
return p(__VA_ARGS__); \
__pragma(comment(linker, "/EXPORT:" __FUNCTION__))
// Function Name : GetFileVersionInfoA
// Ordinal : 1 (0x1)
extern "C" BOOL WINAPI GetFileVersionInfoA (LPCSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) {
D(GetFileVersionInfoA, lptstrFilename, dwHandle, dwLen, lpData);
}
// Function Name : GetFileVersionInfoByHandle
// Ordinal : 2 (0x2)
extern "C" int WINAPI GetFileVersionInfoByHandle (int hMem, LPCWSTR lpFileName, int v2, int v3) {
D(GetFileVersionInfoByHandle, hMem, lpFileName, v2, v3);
}
// Function Name : GetFileVersionInfoExA
// Ordinal : 3 (0x3)
extern "C" BOOL WINAPI GetFileVersionInfoExA (DWORD dwFlags, LPCSTR lpwstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) {
D(GetFileVersionInfoExA, dwFlags, lpwstrFilename, dwHandle, dwLen, lpData);
}
// Function Name : GetFileVersionInfoExW
// Ordinal : 4 (0x4)
extern "C" BOOL WINAPI GetFileVersionInfoExW (DWORD dwFlags, LPCWSTR lpwstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) {
D(GetFileVersionInfoExW, dwFlags, lpwstrFilename, dwHandle, dwLen, lpData);
}
// Function Name : GetFileVersionInfoSizeA
// Ordinal : 5 (0x5)
extern "C" DWORD WINAPI GetFileVersionInfoSizeA (LPCSTR lptstrFilename, LPDWORD lpdwHandle) {
D(GetFileVersionInfoSizeA, lptstrFilename, lpdwHandle);
}
// Function Name : GetFileVersionInfoSizeExA
// Ordinal : 6 (0x6)
extern "C" DWORD WINAPI GetFileVersionInfoSizeExA (DWORD dwFlags, LPCSTR lpwstrFilename, LPDWORD lpdwHandle) {
D(GetFileVersionInfoSizeExA, dwFlags, lpwstrFilename, lpdwHandle);
}
// Function Name : GetFileVersionInfoSizeExW
// Ordinal : 7 (0x7)
extern "C" DWORD WINAPI GetFileVersionInfoSizeExW (DWORD dwFlags, LPCWSTR lpwstrFilename, LPDWORD lpdwHandle) {
D(GetFileVersionInfoSizeExW, dwFlags, lpwstrFilename, lpdwHandle);
}
// Function Name : GetFileVersionInfoSizeW
// Ordinal : 8 (0x8)
extern "C" DWORD WINAPI GetFileVersionInfoSizeW (LPCWSTR lptstrFilename, LPDWORD lpdwHandle) {
D(GetFileVersionInfoSizeW, lptstrFilename, lpdwHandle);
}
// Function Name : GetFileVersionInfoW
// Ordinal : 9 (0x9)
extern "C" BOOL WINAPI GetFileVersionInfoW (LPCWSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) {
D(GetFileVersionInfoW, lptstrFilename, dwHandle, dwLen, lpData);
}
// Function Name : VerFindFileA
// Ordinal : 10 (0xa)
extern "C" DWORD WINAPI VerFindFileA (DWORD uFlags, LPCSTR szFileName, LPCSTR szWinDir, LPCSTR szAppDir, LPSTR szCurDir, PUINT lpuCurDirLen, LPSTR szDestDir, PUINT lpuDestDirLen) {
D(VerFindFileA, uFlags, szFileName, szWinDir, szAppDir, szCurDir, lpuCurDirLen, szDestDir, lpuDestDirLen);
}
// Function Name : VerFindFileW
// Ordinal : 11 (0xb)
extern "C" DWORD WINAPI VerFindFileW (DWORD uFlags, LPCWSTR szFileName, LPCWSTR szWinDir, LPCWSTR szAppDir, LPWSTR szCurDir, PUINT lpuCurDirLen, LPWSTR szDestDir, PUINT lpuDestDirLen) {
D(VerFindFileW, uFlags, szFileName, szWinDir, szAppDir, szCurDir, lpuCurDirLen, szDestDir, lpuDestDirLen);
}
// Function Name : VerInstallFileA
// Ordinal : 12 (0xc)
extern "C" DWORD WINAPI VerInstallFileA (DWORD uFlags, LPCSTR szSrcFileName, LPCSTR szDestFileName, LPCSTR szSrcDir, LPCSTR szDestDir, LPCSTR szCurDir, LPSTR szTmpFile, PUINT lpuTmpFileLen) {
D(VerInstallFileA, uFlags, szSrcFileName, szDestFileName, szSrcDir, szDestDir, szCurDir, szTmpFile, lpuTmpFileLen);
}
// Function Name : VerInstallFileW
// Ordinal : 13 (0xd)
extern "C" DWORD WINAPI VerInstallFileW (DWORD uFlags, LPCWSTR szSrcFileName, LPCWSTR szDestFileName, LPCWSTR szSrcDir, LPCWSTR szDestDir, LPCWSTR szCurDir, LPWSTR szTmpFile, PUINT lpuTmpFileLen) {
D(VerInstallFileW, uFlags, szSrcFileName, szDestFileName, szSrcDir, szDestDir, szCurDir, szTmpFile, lpuTmpFileLen);
}
// Function Name : VerLanguageNameA
// Ordinal : 14 (0xe)
extern "C" DWORD WINAPI VerLanguageNameA (DWORD wLang, LPSTR szLang, DWORD cchLang) {
D(VerLanguageNameA, wLang, szLang, cchLang);
}
// Function Name : VerLanguageNameW
// Ordinal : 15 (0xf)
extern "C" DWORD WINAPI VerLanguageNameW (DWORD wLang, LPWSTR szLang, DWORD cchLang) {
D(VerLanguageNameW, wLang, szLang, cchLang);
}
// Function Name : VerQueryValueA
// Ordinal : 16 (0x10)
extern "C" BOOL WINAPI VerQueryValueA (LPCVOID pBlock, LPCSTR lpSubBlock, LPVOID * lplpBuffer, PUINT puLen) {
D(VerQueryValueA, pBlock, lpSubBlock, lplpBuffer, puLen);
}
// Function Name : VerQueryValueW
// Ordinal : 17 (0x11)
extern "C" BOOL WINAPI VerQueryValueW (LPCVOID pBlock, LPCWSTR lpSubBlock, LPVOID * lplpBuffer, PUINT puLen) {
D(VerQueryValueW, pBlock, lpSubBlock, lplpBuffer, puLen);
}
+4
View File
@@ -0,0 +1,4 @@
#pragma once
bool init_version_dll();
bool deinit_version_dll();
+24
View File
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net472</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<AssemblyVersion>0.0.6.0</AssemblyVersion>
</PropertyGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="move /Y $(TargetPath) $(OutDir)CSharpManager.bin" />
</Target>
<ItemGroup>
<ProjectReference Include="..\CSharpModBase\CSharpModBase.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.5" />
</ItemGroup>
</Project>
+175
View File
@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using CSharpModBase;
using CSharpModBase.Input;
using Mono.Cecil;
namespace CSharpManager
{
public class CSharpModManager
{
static string? LoadingModName { get; set; }
public List<ICSharpMod> LoadedMods { get; } = new();
public InputManager InputManager { get; } = new();
public bool Develop { get; set; }
private Thread? loopThread;
static CSharpModManager()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += AssemblyResolve;
currentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
}
private static Assembly? TryLoadDll(string path)
{
if (File.Exists(path))
{
return Assembly.LoadFrom(path);
}
return null;
}
private static Assembly? AssemblyResolve(object sender, ResolveEventArgs args)
{
try
{
if (LoadingModName == null)
{
return null;
}
string dllName = $"{new AssemblyName(args.Name).Name}.dll";
return TryLoadDll(Path.Combine(Common.ModDir, LoadingModName, dllName)) ??
TryLoadDll(Path.Combine(Common.ModDir, "Common", dllName)) ??
TryLoadDll(Path.Combine(Common.LoaderDir, dllName));
}
catch (Exception e)
{
Log.Error($"Load assembly {args.Name} failed:");
Log.Error(e);
}
return Assembly.Load(args.Name);
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Log.Error($"UnhandledException:");
Log.Error((Exception)e.ExceptionObject);
}
private static void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
Log.Error($"UnobservedTaskException:");
Log.Error(e.Exception);
}
public CSharpModManager()
{
Utils.InitInputManager(InputManager);
// load config from ini
Ini iniFile = new(Path.Combine(Common.LoaderDir, "b1cs.ini"));
Develop = iniFile.GetValue("Develop", "Settings", "1").Trim() == "1";
Log.Debug($"Develop: {Develop}");
}
public void LoadMods()
{
LoadedMods.Clear();
if (!Directory.Exists(Common.ModDir))
{
Log.Error($"Mod dir {Common.ModDir} not exists");
return;
}
string[] dirs = Directory.GetDirectories(Common.ModDir);
Type ICSharpModType = typeof(ICSharpMod);
foreach (var dir in dirs)
{
LoadingModName = Path.GetFileName(dir);
string dllPath = Path.Combine(dir, $"{LoadingModName}.dll");
if (!File.Exists(dllPath)) continue;
try
{
Log.Debug($"======== Loading {dllPath} ========");
Assembly assembly;
if (Develop)
{
using var assemblyDef = AssemblyDefinition.ReadAssembly(dllPath);
assemblyDef.Name.Name += DateTime.Now.ToString("_yyyyMMdd_HHmmssffff");
using MemoryStream stream = new();
assemblyDef.Write(stream);
assembly = Assembly.Load(stream.GetBuffer());
}
else
{
assembly = Assembly.LoadFrom(dllPath);
}
foreach (Type type in assembly.GetTypes())
{
if (ICSharpModType.IsAssignableFrom(type))
{
Log.Debug($"Found ICSharpMod: {type}");
if (Activator.CreateInstance(type) is ICSharpMod mod)
{
mod.Init();
LoadedMods.Add(mod);
Log.Debug($"Loaded mod {mod.Name} {mod.Version}");
}
}
}
LoadingModName = null;
}
catch (Exception e)
{
Log.Error($"Load {dllPath} failed:");
Log.Error(e);
}
}
}
public void ReloadMods()
{
Log.Debug("ReloadMods");
InputManager.Clear();
foreach (var mod in LoadedMods)
{
try
{
mod.DeInit();
}
catch (Exception e)
{
Log.Error($"DeInit {mod.Name} failed:");
Log.Error(e);
}
}
LoadMods();
}
public void StartLoop()
{
InputManager.RegisterBuiltinKeyBind(ModifierKeys.Control, Key.F5, ReloadMods);
loopThread = new Thread(Loop)
{
// IsBackground = true,
};
loopThread.Start();
}
private void Loop()
{
while (true)
{
InputManager.Update();
Thread.Sleep(10); // 10ms
}
}
}
}
+208
View File
@@ -0,0 +1,208 @@
// https://gist.github.com/Larry57/5725301
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
public class Ini
{
Dictionary<string, Dictionary<string, string>> ini = new Dictionary<string, Dictionary<string, string>>(StringComparer.InvariantCultureIgnoreCase);
string file;
/// <summary>
/// Initialize an INI file
/// Load it if it exists
/// </summary>
/// <param name="file">Full path where the INI file has to be read from or written to</param>
public Ini(string file)
{
this.file = file;
if (!File.Exists(file))
return;
Load();
}
/// <summary>
/// Load the INI file content
/// </summary>
public void Load()
{
var txt = File.ReadAllText(file);
Dictionary<string, string> currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[""] = currentSection;
foreach (var l in txt.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select((t, i) => new
{
idx = i,
text = t.Trim()
}))
// .Where(t => !string.IsNullOrWhiteSpace(t) && !t.StartsWith(";")))
{
var line = l.text;
if (line.StartsWith(";") || string.IsNullOrWhiteSpace(line))
{
currentSection.Add(";" + l.idx.ToString(), line);
continue;
}
if (line.StartsWith("[") && line.EndsWith("]"))
{
currentSection = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
ini[line.Substring(1, line.Length - 2)] = currentSection;
continue;
}
var idx = line.IndexOf("=");
if (idx == -1)
currentSection[line] = "";
else
currentSection[line.Substring(0, idx)] = line.Substring(idx + 1);
}
}
/// <summary>
/// Get a parameter value at the root level
/// </summary>
/// <param name="key">parameter key</param>
/// <returns></returns>
public string GetValue(string key)
{
return GetValue(key, "", "");
}
/// <summary>
/// Get a parameter value in the section
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="section">section</param>
/// <returns></returns>
public string GetValue(string key, string section)
{
return GetValue(key, section, "");
}
/// <summary>
/// Returns a parameter value in the section, with a default value if not found
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="section">section</param>
/// <param name="default">default value</param>
/// <returns></returns>
public string GetValue(string key, string section, string @default)
{
if (!ini.ContainsKey(section))
return @default;
if (!ini[section].ContainsKey(key))
return @default;
return ini[section][key];
}
/// <summary>
/// Save the INI file
/// </summary>
public void Save()
{
var sb = new StringBuilder();
foreach (var section in ini)
{
if (section.Key != "")
{
sb.AppendFormat("[{0}]", section.Key);
sb.AppendLine();
}
foreach (var keyValue in section.Value)
{
if (keyValue.Key.StartsWith(";"))
{
sb.Append(keyValue.Value);
sb.AppendLine();
}
else
{
sb.AppendFormat("{0}={1}", keyValue.Key, keyValue.Value);
sb.AppendLine();
}
}
if (!endWithCRLF(sb))
sb.AppendLine();
}
File.WriteAllText(file, sb.ToString());
}
bool endWithCRLF(StringBuilder sb)
{
if (sb.Length < 4)
return sb[sb.Length - 2] == '\r' &&
sb[sb.Length - 1] == '\n';
else
return sb[sb.Length - 4] == '\r' &&
sb[sb.Length - 3] == '\n' &&
sb[sb.Length - 2] == '\r' &&
sb[sb.Length - 1] == '\n';
}
/// <summary>
/// Write a parameter value at the root level
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="value">parameter value</param>
public void WriteValue(string key, string value)
{
WriteValue(key, "", value);
}
/// <summary>
/// Write a parameter value in a section
/// </summary>
/// <param name="key">parameter key</param>
/// <param name="section">section</param>
/// <param name="value">parameter value</param>
public void WriteValue(string key, string section, string value)
{
Dictionary<string, string> currentSection;
if (!ini.ContainsKey(section))
{
currentSection = new Dictionary<string, string>();
ini.Add(section, currentSection);
}
else
currentSection = ini[section];
currentSection[key] = value;
}
/// <summary>
/// Get all the keys names in a section
/// </summary>
/// <param name="section">section</param>
/// <returns></returns>
public string[] GetKeys(string section)
{
if (!ini.ContainsKey(section))
return new string[0];
return ini[section].Keys.ToArray();
}
/// <summary>
/// Get all the section names of the INI file
/// </summary>
/// <returns></returns>
public string[] GetSections()
{
return ini.Keys.Where(t => t != "").ToArray();
}
}
+177
View File
@@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using CSharpModBase;
using CSharpModBase.Input;
namespace CSharpManager
{
public class InputManager : IInputManager
{
public List<HotKeyItem> BuiltinHotKeyItems { get; } = new();
public List<HotKeyItem> HotKeyItems { get; } = new();
public bool EnableGamePad { get; set; } = true;
public static GamePadButton CurrentGamePadButton { get; set; }
// public static GamePadButtonEventHandler? GamePadButtonDown { get; set; }
private IntPtr HWnd;
public InputManager()
{
}
private void FindMainWindow()
{
uint currentProcessId = GetCurrentProcessId();
StringBuilder stringBuilder = new(64);
EnumWindows(new EnumWindowsProc((hWnd, lParam) =>
{
GetWindowThreadProcessId(hWnd, out uint processId);
if (processId == GetCurrentProcessId() &&
GetClassName(hWnd, stringBuilder, stringBuilder.Capacity) > 0 &&
stringBuilder.ToString() == "UnrealWindow")
{
HWnd = hWnd;
return false;
}
return true; // 继续枚举
}), IntPtr.Zero);
}
private void HandleKeys(List<HotKeyItem> items)
{
var now = DateTime.Now.Ticks / 10000;
var modifiers = KeyUtils.Modifiers;
foreach (var item in items)
{
if (item.Modifiers == modifiers && KeyUtils.IsKeyDown(item.Key) ||
CurrentGamePadButton != GamePadButton.None && item.GamePadButton != GamePadButton.None && CurrentGamePadButton.HasFlag(item.GamePadButton))
{
if (item.IsPressed && (item.RepeatMs == 0 || item.LastTriggerMs > 0 && now - item.LastTriggerMs < item.RepeatMs))
{
continue;
}
item.IsPressed = true;
if (item.RunOnGameThread)
{
Utils.TryRunOnGameThread(item.Action);
}
else
{
Utils.TryRun(item.Action);
}
}
else if (item.IsPressed)
{
item.IsPressed = false;
}
}
}
public void Update()
{
if (!IsProgramFocused()) return;
if (EnableGamePad)
{
GamePadUtils.GetGamePadButtons(out var buttons);
// if (buttons != GamePadButton.None)
// {
// GamePadButtonDown?.Invoke(new GamePadButtonEvent { Button = buttons });
// }
CurrentGamePadButton = buttons;
}
HandleKeys(BuiltinHotKeyItems);
lock (HotKeyItems)
{
HandleKeys(HotKeyItems);
}
}
public void Clear()
{
lock (HotKeyItems)
{
HotKeyItems.Clear();
}
}
public bool IsProgramFocused()
{
if (HWnd == IntPtr.Zero)
{
Thread.Sleep(1000);
FindMainWindow();
}
var hwnd = GetForegroundWindow();
if (hwnd == IntPtr.Zero) return false;
return hwnd == HWnd;
}
[DllImport("user32.dll")]
private extern static IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
static extern uint GetCurrentProcessId();
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
// 导入Win32 API函数
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
public HotKeyItem RegisterBuiltinKeyBind(Key key, Action action)
{
var item = new HotKeyItem(ModifierKeys.None, key, action);
BuiltinHotKeyItems.Add(item);
return item;
}
public HotKeyItem RegisterBuiltinKeyBind(ModifierKeys modifiers, Key key, Action action)
{
var item = new HotKeyItem(modifiers, key, action);
BuiltinHotKeyItems.Add(item);
return item;
}
public void RegisterKeyBind(HotKeyItem item)
{
lock (HotKeyItems)
{
HotKeyItems.Add(item);
}
}
public HotKeyItem RegisterKeyBind(Key key, Action action)
{
var item = new HotKeyItem(ModifierKeys.None, key, action);
RegisterKeyBind(item);
return item;
}
public HotKeyItem RegisterKeyBind(ModifierKeys modifiers, Key key, Action action)
{
var item = new HotKeyItem(modifiers, key, action);
RegisterKeyBind(item);
return item;
}
public HotKeyItem RegisterGamePadBind(GamePadButton button, Action action)
{
var item = new HotKeyItem(ModifierKeys.None, Key.None, action)
{
GamePadButton = button
};
RegisterKeyBind(item);
return item;
}
}
}
+13
View File
@@ -0,0 +1,13 @@
namespace CSharpManager
{
internal class Program
{
public static void Main(string[] args)
{
CSharpModManager manager = new();
manager.LoadMods();
manager.StartLoop();
}
}
}
+6
View File
@@ -0,0 +1,6 @@
# CSharpManager
C# mod的管理器,CSharpLoader会加载CSharpManager,通过CSharpManager加载其他C# mod
## 编译
dotnet build
+4
View File
@@ -0,0 +1,4 @@
[Settings]
Develop=1
Console=1
EnableJit=1
+33
View File
@@ -0,0 +1,33 @@
namespace CSharpModBase
{
public static class Common
{
public const string LoaderDir = "CSharpLoader";
public const string ModDir = "CSharpLoader\\Mods";
public const string DataDir = "CSharpLoader\\Data";
}
public interface ICSharpMod
{
/// <summary>
/// mod name
/// </summary>
string Name { get; }
/// <summary>
/// mod version
/// </summary>
string Version { get; }
/// <summary>
/// when mod loaded, will call OnInit
/// </summary>
void Init();
/// <summary>
/// when manamger reload mods, will call OnDeInit,
///
/// </summary>
void DeInit();
}
}
+27
View File
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<AssemblyVersion>0.0.6.0</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Lib.Harmony" Version="2.3.3" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SharpDX" Version="4.2.0" />
<PackageReference Include="SharpDX.XInput" Version="4.2.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="UnrealEngine.Runtime">
<HintPath>..\GameDll\UnrealEngine.Runtime.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
</Project>
+60
View File
@@ -0,0 +1,60 @@
using System;
using SharpDX.XInput;
namespace CSharpModBase.Input
{
[Flags]
public enum GamePadButton
{
None = GamepadButtonFlags.None,
DPadUp = GamepadButtonFlags.DPadUp,
DPadDown = GamepadButtonFlags.DPadDown,
DPadLeft = GamepadButtonFlags.DPadLeft,
DPadRight = GamepadButtonFlags.DPadRight,
Start = GamepadButtonFlags.Start,
Back = GamepadButtonFlags.Back,
LeftThumb = GamepadButtonFlags.LeftThumb,
RightThumb = GamepadButtonFlags.RightThumb,
LeftShoulder = GamepadButtonFlags.LeftShoulder,
RightShoulder = GamepadButtonFlags.RightShoulder,
A = GamepadButtonFlags.A,
B = GamepadButtonFlags.B,
X = GamepadButtonFlags.X,
Y = GamepadButtonFlags.Y,
LeftTrigger = 0x10000,
RightTrigger = 0x20000,
DPadRightUp = DPadRight | DPadUp,
DPadLeftDown = DPadLeft | DPadDown,
DPadRightDown = DPadRight | DPadDown,
DPadLeftUp = DPadLeft | DPadUp,
}
public static class GamePadUtils
{
private static readonly Controller controller = new Controller(UserIndex.One);
public static bool GetGamePadButtons(out GamePadButton flags)
{
flags = GamePadButton.None;
if (controller.GetState(out State state))
{
Gamepad gamepad = state.Gamepad;
flags = (GamePadButton)gamepad.Buttons;
if (gamepad.LeftTrigger > 100) flags |= GamePadButton.LeftTrigger;
if (gamepad.RightTrigger > 100) flags |= GamePadButton.RightTrigger;
return true;
}
return false;
}
}
public class GamePadButtonEvent : EventArgs
{
public GamePadButton Button { get; set; }
}
public delegate void GamePadButtonEventHandler(GamePadButtonEvent e);
}
+112
View File
@@ -0,0 +1,112 @@
using System;
namespace CSharpModBase.Input
{
public class HotKeyData
{
public HotKeyData(ModifierKeys modifiers, Key key)
{
Modifiers = modifiers;
Key = key;
}
public HotKeyData() : this(ModifierKeys.None, Key.None) {}
public ModifierKeys Modifiers { get; set; }
public Key Key { get; set; }
public GamePadButton GamePadButton { get; set; }
public bool IsValid => Key != Key.None || GamePadButton != GamePadButton.None;
public string KeyString => KeyUtils.KeyToString(Modifiers, Key);
public static uint GetCode(ModifierKeys modifiers, Key key)
{
return ((uint)modifiers << 16) | (uint)key;
}
public uint Code
{
get
{
if (GamePadButton != GamePadButton.None)
{
return 0xF0000000 | (uint)GamePadButton;
}
else
{
return GetCode(Modifiers, Key);
}
}
}
public void SetFromCode(uint code)
{
if ((code >> 24) == 0xF0)
{
GamePadButton = (GamePadButton)(code & 0xFFFF);
Modifiers = ModifierKeys.None;
Key = Key.None;
}
else
{
GamePadButton = GamePadButton.None;
Modifiers = (ModifierKeys)(code >> 16);
Key = (Key)(code & 0xFF);
}
}
public void SetKey(ModifierKeys modifiers, Key key)
{
Modifiers = modifiers;
Key = key;
}
public override string ToString()
{
return KeyString;
}
}
public class HotKeyItem : HotKeyData
{
public string Label { get; set; }
public Action Action { get; set; }
/// <summary>
/// 0为不支持连按,大于0为连按触发毫秒间隔
/// </summary>
public int RepeatMs { get; set; }
/// <summary>
/// 上一次触发的时间,毫秒
/// </summary>
public long LastTriggerMs { get; set; }
/// <summary>
/// 正在被按下
/// </summary>
public bool IsPressed { get; set; }
public bool RunOnGameThread { get; set; } = true;
public HotKeyItem WithKey(ModifierKeys Modifiers, Key Key)
{
return new(Label, Modifiers, Key, Action);
}
public HotKeyItem(ModifierKeys modifiers, Key key, Action action) : this("", modifiers, key, action)
{
}
public HotKeyItem(string label, ModifierKeys modifiers, Key key, Action action) : base(modifiers, key)
{
Label = label;
Action = action;
}
public HotKeyItem() : this("", ModifierKeys.None, Key.None, EmptyAction)
{
}
private static void EmptyAction()
{
}
}
}
+12
View File
@@ -0,0 +1,12 @@
using System;
namespace CSharpModBase.Input
{
public interface IInputManager
{
HotKeyItem RegisterKeyBind(Key key, Action action);
HotKeyItem RegisterKeyBind(ModifierKeys modifiers, Key key, Action action);
HotKeyItem RegisterGamePadBind(GamePadButton button, Action action);
}
}
+146
View File
@@ -0,0 +1,146 @@
namespace CSharpModBase.Input
{
public enum Key
{
None = 0x00,
LBUTTON = 0x01,
RBUTTON = 0x02,
CANCEL = 0x03,
MBUTTON = 0x04,
XBUTTON1 = 0x05,
XBUTTON2 = 0x06,
BACK = 0x08,
TAB = 0x09,
CLEAR = 0x0C,
RETURN = 0x0D,
ENTER = RETURN,
SHIFT = 0x10,
CONTROL = 0x11,
MENU = 0x12,
PAUSE = 0x13,
CAPITAL = 0x14,
KANA = 0x15,
HANGEUL = 0x15,
HANGUL = 0x15,
ESCAPE = 0x1B,
CONVERT = 0x1C,
NONCONVERT = 0x1D,
ACCEPT = 0x1E,
MODECHANGE = 0x1F,
SPACE = 0x20,
PRIOR = 0x21,
NEXT = 0x22,
END = 0x23,
HOME = 0x24,
LEFT = 0x25,
UP = 0x26,
RIGHT = 0x27,
DOWN = 0x28,
SELECT = 0x29,
PRINT = 0x2A,
EXECUTE = 0x2B,
SNAPSHOT = 0x2C,
INSERT = 0x2D,
DELETE = 0x2E,
HELP = 0x2F,
D0 = 0x30,
D1 = 0x31,
D2 = 0x32,
D3 = 0x33,
D4 = 0x34,
D5 = 0x35,
D6 = 0x36,
D7 = 0x37,
D8 = 0x38,
D9 = 0x39,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4A,
K = 0x4B,
L = 0x4C,
M = 0x4D,
N = 0x4E,
O = 0x4F,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5A,
LWIN = 0x5B,
RWIN = 0x5C,
APPS = 0x5D,
SLEEP = 0x5F,
NUMPAD0 = 0x60,
NUMPAD1 = 0x61,
NUMPAD2 = 0x62,
NUMPAD3 = 0x63,
NUMPAD4 = 0x64,
NUMPAD5 = 0x65,
NUMPAD6 = 0x66,
NUMPAD7 = 0x67,
NUMPAD8 = 0x68,
NUMPAD9 = 0x69,
MULTIPLY = 0x6A,
ADD = 0x6B,
SEPARATOR = 0x6C,
SUBTRACT = 0x6D,
DECIMAL = 0x6E,
DIVIDE = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
NUMLOCK = 0x90,
SCROLL = 0x91,
LSHIFT = 0xA0,
RSHIFT = 0xA1,
LCONTROL = 0xA2,
RCONTROL = 0xA3,
LMENU = 0xA4,
RMENU = 0xA5,
OEM_1 = 0xBA, // ';'
OEM_PLUS = 0xBB, // '+'
OEM_COMMA = 0xBC, // ','
OEM_MINUS = 0xBD, // '-'
OEM_PERIOD = 0xBE, // '.'
OEM_2 = 0xBF, // '/'
OEM_3 = 0xC0, // '`'
OEM_4 = 0xDB, // '['
OEM_5 = 0xDC, // '\\'
OEM_6 = 0xDD, // ']'
OEM_7 = 0xDE, // '\''
}
}
+89
View File
@@ -0,0 +1,89 @@
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace CSharpModBase.Input
{
public static class KeyUtils
{
/// <summary>
/// Keys转字符串,支持组合键
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string KeyToString(ModifierKeys modifiers, Key key, List<string> buf)
{
if (modifiers.HasFlag(ModifierKeys.Control)) buf.Add("Ctrl");
if (modifiers.HasFlag(ModifierKeys.Shift)) buf.Add("Shift");
if (modifiers.HasFlag(ModifierKeys.Alt)) buf.Add("Alt");
string? keyCodeStr = null;
char oemKeyChar = OemKeyChar(key);
if (oemKeyChar != default) {
keyCodeStr = oemKeyChar.ToString();
} else {
keyCodeStr = key switch
{
Key.None => "",
_ => key.ToString(),
};
}
if (keyCodeStr != null)
{
buf.Add(keyCodeStr);
}
return string.Join("+", buf);
}
public static string KeyToString(ModifierKeys modifiers, Key key)
{
return KeyToString(modifiers, key, new());
}
public static char OemKeyChar(Key key)
{
return key switch
{
Key.OEM_PLUS => '+',
Key.OEM_COMMA => ',',
Key.OEM_MINUS => '-',
Key.OEM_PERIOD => '.',
Key.OEM_1 => ';',
Key.OEM_2 => '/',
Key.OEM_3 => '`',
Key.OEM_4 => '[',
Key.OEM_5 => '\\',
Key.OEM_6 => ']',
Key.OEM_7 => '\'',
_ => default,
};
}
[DllImport("user32.dll")]
private static extern short GetKeyState(uint vk);
public static bool IsKeyDown(Key key)
{
return GetKeyState((uint)key) < 0;
}
public static ModifierKeys Modifiers
{
get
{
ModifierKeys modifiers = ModifierKeys.None;
if (GetKeyState((uint)Key.MENU) < 0)
{
modifiers |= ModifierKeys.Alt;
}
if (GetKeyState((uint)Key.CONTROL) < 0)
{
modifiers |= ModifierKeys.Control;
}
if (GetKeyState((uint)Key.SHIFT) < 0)
{
modifiers |= ModifierKeys.Shift;
}
return modifiers;
}
}
}
}
+14
View File
@@ -0,0 +1,14 @@
using System;
namespace CSharpModBase.Input
{
[Flags]
public enum ModifierKeys
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
}
+78
View File
@@ -0,0 +1,78 @@
using System;
using System.IO;
namespace CSharpModBase
{
public static class Log
{
private static string DateTimeString => DateTime.Now.ToString("MM-dd HH:mm:ss"); // .fff
// private static readonly StreamWriter LogFile = File.CreateText("CSharpLog.txt");
public static void Info(string message)
{
string text = $"{DateTimeString} [I] {message}";
Console.WriteLine(text);
// LogFile.WriteLine(text);
}
public static void Debug(string message)
{
using (var color = new ChangeConsoleColor(ConsoleColor.Gray))
{
string text = $"{DateTimeString} [D] {message}";
Console.WriteLine(text);
// LogFile.WriteLine(text);
}
}
public static void Warn(string message)
{
using (var color = new ChangeConsoleColor(ConsoleColor.Yellow))
{
string text = $"{DateTimeString} [W] {message}";
Console.WriteLine(text);
// LogFile.WriteLine(text);
}
}
public static void WarnIf(bool condition, string message)
{
if (condition) {
Warn(message);
}
}
public static void Error(string message)
{
using (var color = new ChangeConsoleColor(ConsoleColor.Red))
{
string text = $"{DateTimeString} [E] {message}";
Console.Error.WriteLine(text);
// LogFile.WriteLine(text);
}
}
public static void Error(Exception e)
{
Error(e.Message);
Error(e.StackTrace);
}
}
public readonly struct ChangeConsoleColor : IDisposable
{
readonly ConsoleColor currentForeground;
public ChangeConsoleColor(ConsoleColor color)
{
currentForeground = Console.ForegroundColor;
Console.ForegroundColor = color;
}
public void Dispose()
{
Console.ForegroundColor = currentForeground;
}
}
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using CSharpModBase.Input;
using UnrealEngine.Runtime;
namespace CSharpModBase
{
public static class Utils
{
private static IInputManager? InputManager;
public static void InitInputManager(IInputManager inputManager)
{
InputManager = inputManager;
}
public static HotKeyItem RegisterKeyBind(Key key, Action action)
{
return InputManager!.RegisterKeyBind(key, action);
}
public static HotKeyItem RegisterKeyBind(ModifierKeys modifiers, Key key, Action action)
{
return InputManager!.RegisterKeyBind(modifiers, key, action);
}
public static HotKeyItem RegisterGamePadBind(GamePadButton button, Action action)
{
return InputManager!.RegisterGamePadBind(button, action);
}
public static void TryRun(Action aciton)
{
try
{
aciton();
}
catch (Exception e)
{
Log.Error(e);
};
}
public static void TryRunOnGameThread(Action aciton)
{
FThreading.RunOnGameThread(() =>
{
try
{
aciton();
}
catch (Exception e)
{
Log.Error(e);
}
});
}
}
}
+64
View File
@@ -0,0 +1,64 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<LangVersion>latest</LangVersion>
<AssemblyVersion>0.0.1.0</AssemblyVersion>
</PropertyGroup>
<!-- <ItemGroup>
<Reference Include="CSharpModBase">
<HintPath>..\CSharpModBase\bin\Debug\net472\CSharpModBase.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup> -->
<ItemGroup>
<ProjectReference Include="..\CSharpModBase\CSharpModBase.csproj">
<!-- <Private>False</Private> -->
<!-- <ExcludeAssets>runtime</ExcludeAssets> -->
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Reference Include="BtlSvr.Main">
<HintPath>..\GameDll\BtlSvr.Main.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="b1.Native">
<HintPath>..\GameDll\b1.Native.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="b1.NativePlugins">
<HintPath>..\GameDll\b1.NativePlugins.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="GSE.Core">
<HintPath>..\GameDll\GSE.Core.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="GSE.ProtobufDB">
<HintPath>..\GameDll\GSE.ProtobufDB.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Google.Protobuf">
<HintPath>..\GameDll\Google.Protobuf.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Protobuf.RunTime">
<HintPath>..\GameDll\Protobuf.RunTime.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnrealEngine.Runtime">
<HintPath>..\GameDll\UnrealEngine.Runtime.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnrealEngine">
<HintPath>..\GameDll\UnrealEngine.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
</Project>
+72
View File
@@ -0,0 +1,72 @@
using b1;
using UnrealEngine.Engine;
using UnrealEngine.Runtime;
namespace CSharpExample
{
public static class MyUtils
{
private static UWorld? world;
public static UWorld? GetWorld()
{
if (world == null)
{
UObjectRef uobjectRef = GCHelper.FindRef(FGlobals.GWorld);
world = uobjectRef?.Managed as UWorld;
}
return world;
}
public static APawn GetControlledPawn()
{
return UGSE_EngineFuncLib.GetFirstLocalPlayerController(GetWorld()).GetControlledPawn();
}
public static BGUPlayerCharacterCS GetBGUPlayerCharacterCS()
{
return (GetControlledPawn() as BGUPlayerCharacterCS)!;
}
public static BGP_PlayerControllerB1 GetPlayerController()
{
return (BGP_PlayerControllerB1)UGSE_EngineFuncLib.GetFirstLocalPlayerController(GetWorld());
}
public static BUS_GSEventCollection GetBUS_GSEventCollection()
{
return BUS_EventCollectionCS.Get(GetControlledPawn());
}
public static T LoadAsset<T>(string asset) where T : UObject
{
return b1.BGW.BGW_PreloadAssetMgr.Get(GetWorld()).TryGetCachedResourceObj<T>(asset, b1.BGW.ELoadResourceType.SyncLoadAndCache, b1.BGW.EAssetPriority.Default, null, -1, -1);
}
public static UClass LoadClass(string asset)
{
return LoadAsset<UClass>(asset);
}
public static AActor? SpawnActor(string classAsset)
{
var controlledPawn = GetControlledPawn();
FVector actorLocation = controlledPawn.GetActorLocation();
FVector b = controlledPawn.GetActorForwardVector() * 1000.0f;
FVector start = actorLocation + b;
FRotator frotator = UMathLibrary.FindLookAtRotation(start, actorLocation);
UClass uClass = LoadClass($"PrefabricatorAsset'{classAsset}'");
if (uClass == null)
{
return null;
}
return BGUFunctionLibraryCS.BGUSpawnActor(controlledPawn.World, uClass, start, frotator);
}
public static AActor GetActorOfClass(string classAsset)
{
return UGameplayStatics.GetActorOfClass(GetWorld(), LoadAsset<UClass>(classAsset));
}
}
}
+55
View File
@@ -0,0 +1,55 @@
using System;
using b1;
using BtlShare;
using CSharpModBase;
using CSharpModBase.Input;
// using HarmonyLib;
namespace CSharpExample
{
public class MyMod : ICSharpMod
{
public string Name => "ModExample";
public string Version => "0.0.1";
// private readonly Harmony harmony;
public MyMod()
{
// harmony = new Harmony(Name);
// Harmony.DEBUG = true;
}
public void Init()
{
Console.WriteLine($"{Name} Init");
Utils.RegisterKeyBind(Key.ENTER, () => Console.WriteLine("Enter pressed"));
Utils.RegisterKeyBind(ModifierKeys.Control, Key.ENTER, FindPlayer);
// hook
// harmony.PatchAll();
}
public void DeInit()
{
Console.WriteLine($"{Name} DeInit");
// harmony.UnpatchAll();
}
private void FindPlayer()
{
Console.WriteLine("Ctrl+Enter pressed");
var player = MyUtils.GetControlledPawn();
if (player == null)
{
Console.WriteLine("Player not found");
}
else
{
Console.WriteLine($"Player found: {player}");
float hp = BGUFunctionLibraryCS.GetAttrValue(player, EBGUAttrFloat.Hp);
float hpMax = BGUFunctionLibraryCS.GetAttrValue(player, EBGUAttrFloat.HpMax);
Console.WriteLine($"HP: {hp}/{hpMax}");
}
}
}
}
+3
View File
@@ -0,0 +1,3 @@
# 编译
dotnet build
+2
View File
@@ -0,0 +1,2 @@
dotnet build
cp bin/Debug/net472/CSharpExample.dll C:/Users/An/Soft/Steam/steamapps/common/BlackMythWukong/b1/Binaries/Win64/CSharpLoader/Mods
+8
View File
@@ -0,0 +1,8 @@
<?xml version='1.0'?>
<Obfuscator>
<Var name="OutPath" value="bin\Debug\net472\Obfuscated" />
<Var name="KeepPublicApi" value="false" />
<Var name="ReuseNames" value="false" />
<Module file="bin\Debug\net472\CSharpExample.dll">
</Module>
</Obfuscator>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+121
View File
@@ -0,0 +1,121 @@
# CSharp mod loader for BlackMythWukong
[中文](README.md)
## About
BlackMythWukong use USharp as script engine, many logic implements in C# (see GameDll). Some api can only access in C#, not in UE c++.
This mod loader allow you to load mods written in C#. C# mods can call C# api from b1-managed and Unreal Engine.
## How to use
### Install path
```
b1/Binaries/Win64/
CSharpLoader/
Data/
Mods/
Plugins/
0Harmony.dll
CSharpManager.bin
CSharpModBase.dll
Mono.Cecil.dll
Mono.Cecil.Pdb.dll
Mono.Cecil.Rocks.dll
b1cs.ini
version.dll
```
Mod dll should be placed in `CSharpLoader/Mods/<ModName>/<ModName>.dll`, for example `CSharpLoader/Mods/CSharpExample/CSharpExample.dll`
### config file
CSharpLoader/b1cs.ini
Develop: press ctrl+f5 reload C# mods
Console: show console window to print log
EnableJit: see Attention below
### Attention
In version 0.0.7 of the C# loader, to enable C# patch/hook features, the game's Mono runtime execution mode has been changed from the default interpreter mode to the JIT (Just-In-Time) mode. JIT can potentially bring some performance improvements, but it may not have been thoroughly tested by the game developers, which could impact the game's stability. Additionally, it is currently incompatible with some trainer, including flingtrainer, which may become ineffective. Please decide whether to use the C# loader that supports hooks based on the instructions of the mods you are using.
### Compatibility with Other Plugins
"version.dll" is a commonly used plugin name. If you are using other plugins with naming conflicts, you can rename their DLLs to any name other than "version.dll" (the suffix must be ".dll") and place them in the "CSharpLoader/Plugins/" directory. The C# loader will load these plugins together.
## modules
- CSharpLoaderDll
- loader for CSharpManager
- CSharpManager
- manager of C# mod
- CSharpModBase
- interface for mods
- CSharpModExample
- mod example
- GameDll
- inner C# dll of game
## Mod develop tutorial
Suggest install [.net 8 sdk](https://dotnet.microsoft.com/) to develop with latest syntax.
You can use vscode, visual studio or rider to write code.
See CSharpModExample.
### Mod entrance
Your mod should implements ICSharpMod
```C#
public class MyMod : ICSharpMod
{
public string Name => "ModExample";
public string Version => "0.0.1";
public void Init()
{
Console.WriteLine("Init");
}
public void DeInit()
{
Console.WriteLine("DeInit");
}
}
```
Manager will create instance of class that implements ICSharpMod and call Init.
When reload mods by Ctrl+F5, Manager will call DeInit() of loaded mods, then reload all mods.
In Develop mode, mod dll will load as new Assembly, why old Assembly keep in memory. So make sure finish your background thread and clear event handler in DeInit function..
Mod do not need to clear key listening, manager will do it.
### KeyBind
```C#
Utils.RegisterKeyBind(ModifierKeys.Alt, Key.X, () =>
{
});
```
### C# hook
see [harmony document](https://harmony.pardeike.net/articles/patching.html)
call in Init()
```C#
var harmony = new Harmony("your name");
var assembly = Assembly.GetExecutingAssembly();
harmony.PatchAll(assembly);
// or implying current assembly:
harmony.PatchAll();
```
call in DeInit()
```C#
harmony.UnpatchAll();
```
### Mod deps
Mod depends dll can put in `CSharpLoader/Mods/<ModName>/` or `CSharpLoader/Mods/Common/`, Common is shared by all mods.
+123
View File
@@ -0,0 +1,123 @@
# 黑神话悟空CSharp加载器
[English](README.en.md)
## 关于
黑神话悟空使用USharp作为脚本引擎,很多逻辑使用C#实现,提供接口给UE使用(见GameDll),而一些内部接口不能通过UE c++/lua访问。
这个mod加载器可以加载c#写的mod。C# mod可以调用USharp端提供的api,包括游戏内部的和USharp包装的UE引擎的api,也可以往游戏内部的事件和委托增加回调。
## 使用说明
### 安装路径
```
BlackMythWukong/b1/Binaries/Win64/
CSharpLoader/
Data/
Mods/
Plugins/
0Harmony.dll
CSharpManager.bin
CSharpModBase.dll
Mono.Cecil.dll
Mono.Cecil.Pdb.dll
Mono.Cecil.Rocks.dll
b1cs.ini
version.dll
```
mod的dll需要放在`CSharpLoader/Mods/<ModName>/<ModName>.dll`里面,例如`CSharpLoader/Mods/CSharpExample/CSharpExample.dll`
### 配置
配置文件CSharpLoader/b1cs.ini
Develop: 开启开发模式,可以按ctrl+f5重新加载C# mods
Console: 显示控制台窗口,打印log
EnableJit: 开启jit模式,请看下面的注意
### 注意
0.0.7版本C# loader为了开启C# patch/hook特性,把游戏的mono运行时的运行模式从默认的解释执行模式,改成了jit(运行时编译执行)模式。jit一定程度上可能会带来一些性能提升,但可能并未经过游戏开发商的充分测试,可能会对游戏的稳定性带来一些影响。同时由于修改了游戏的底层执行代码,目前与一些修改器不兼容,包括风灵月影在内的一些修改器会失效,请根据你使用的mod的说明,决定是否使用支持hook的C# loader。
### 与其他插件的兼容
version.dll是常用的插件名字,如果你使用了其他有名称冲突的插件,可以把这些插件的dll,改成除version.dll外的其他名字(后缀得是.dll),放到CSharpLoader/Plugins/目录里,C# loader会一起加载这些插件
## 模块介绍
- CSharpLoaderDll
- 加载器,用于调用mono api执行C#代码,加载器会在游戏启动后调用CSharpManager
- CSharpManager
- C# mod管理器,加载和管理C# mod
- CSharpModBase
- 提供给mod使用的接口
- CSharpModExample
- mod示例
- GameDll
- 游戏内的C# dll,写mod代码需要引用这些dll
## mod编写教程
建议安装.net 8 sdk,方便使用最新的语法。
开发工具可以使用vscode, visual studio 或者 rider。
示例工程可以参考CSharpModExample
### mod入口
mod的类需要实现ICSharpMod接口
```C#
public class MyMod : ICSharpMod
{
public string Name => "ModExample";
public string Version => "0.0.1";
public void Init()
{
Console.WriteLine("Init");
}
public void DeInit()
{
Console.WriteLine("DeInit");
}
}
```
Mod加载时会创建该类的实例,调用Init。Manager重新加载mod时会调用每个mod的DeInit(),再执行加载mod的流程。
Ctrl+F5重新加载Mod,Develop模式下,每次都会加载成新的Assembly,旧Asembly还会保留在进程中,所以请确保DeInit函数里结束mod的后台线程(如有)和事件监听,mod本身不用清理按键监听,Manager处理好。
### 按键监听
```C#
Utils.RegisterKeyBind(ModifierKeys.Alt, Key.X, () =>
{
});
```
### C# hook
参考 [harmony文档](https://harmony.pardeike.net/articles/patching.html)
Init()里调用
```C#
var harmony = new Harmony("myname");
var assembly = Assembly.GetExecutingAssembly();
harmony.PatchAll(assembly);
// or implying current assembly:
harmony.PatchAll();
```
DeInit()里调用
```C#
harmony.UnpatchAll();
```
### mod的其他依赖
mod dll的依赖可以放在`CSharpLoader/Mods/<ModName>/`或者`CSharpLoader/Mods/Common/`中,这样其他Mod也能用里面的依赖