commit 7475ccb4679fc2ebcd045890cd4cfb6120dc518d Author: gitea Date: Mon Nov 30 09:52:36 2026 +0800 mirror: 上游快照导入 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c24589a --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CSharpLoader.sln b/CSharpLoader.sln new file mode 100644 index 0000000..9e18968 --- /dev/null +++ b/CSharpLoader.sln @@ -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 diff --git a/CSharpLoaderDll/CSharpLoaderDll.vcxproj b/CSharpLoaderDll/CSharpLoaderDll.vcxproj new file mode 100644 index 0000000..0b776ed --- /dev/null +++ b/CSharpLoaderDll/CSharpLoaderDll.vcxproj @@ -0,0 +1,179 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {9504cd32-5959-4dc7-ba59-6d4debac8688} + CSharpLoaderDll + 10.0 + + + + DynamicLibrary + true + v143 + Unicode + + + DynamicLibrary + false + v143 + true + Unicode + + + DynamicLibrary + true + v143 + Unicode + + + DynamicLibrary + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + version + + + version + + + version + + + version + + + + Level3 + true + WIN32;_DEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + false + + + + + Level3 + true + true + true + WIN32;NDEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + true + true + false + + + + + Level3 + true + _DEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + MultiThreadedDebug + + + Windows + true + false + + + + + Level3 + true + true + true + NDEBUG;CSHARPLOADERDLL_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + MultiThreaded + + + Windows + true + true + true + false + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + \ No newline at end of file diff --git a/CSharpLoaderDll/CSharpLoaderDll.vcxproj.filters b/CSharpLoaderDll/CSharpLoaderDll.vcxproj.filters new file mode 100644 index 0000000..d349b8a --- /dev/null +++ b/CSharpLoaderDll/CSharpLoaderDll.vcxproj.filters @@ -0,0 +1,57 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + 头文件 + + + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + \ No newline at end of file diff --git a/CSharpLoaderDll/dllmain.cpp b/CSharpLoaderDll/dllmain.cpp new file mode 100644 index 0000000..43e3461 --- /dev/null +++ b/CSharpLoaderDll/dllmain.cpp @@ -0,0 +1,231 @@ +// dllmain.cpp : 定义 DLL 应用程序的入口点。 +#include "pch.h" +#include +#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(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; +} + diff --git a/CSharpLoaderDll/framework.h b/CSharpLoaderDll/framework.h new file mode 100644 index 0000000..80cbbc9 --- /dev/null +++ b/CSharpLoaderDll/framework.h @@ -0,0 +1,5 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容 +// Windows 头文件 +#include diff --git a/CSharpLoaderDll/hid_dll.cpp b/CSharpLoaderDll/hid_dll.cpp new file mode 100644 index 0000000..aad2b17 --- /dev/null +++ b/CSharpLoaderDll/hid_dll.cpp @@ -0,0 +1,221 @@ +#include "pch.h" +#include "hid_dll.hpp" +#include +#include +#include +#include + +/////////////////////////////////////////////////////////////// +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 +void setup(T*& funcPtr, const char* funcName) { + if(funcPtr != nullptr) { + return; + } + funcPtr = reinterpret_cast(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); +} diff --git a/CSharpLoaderDll/hid_dll.hpp b/CSharpLoaderDll/hid_dll.hpp new file mode 100644 index 0000000..af54fc1 --- /dev/null +++ b/CSharpLoaderDll/hid_dll.hpp @@ -0,0 +1,4 @@ +#pragma once + +bool init_hid_dll(); +bool deinit_hid_dll(); diff --git a/CSharpLoaderDll/memory.cpp b/CSharpLoaderDll/memory.cpp new file mode 100644 index 0000000..2737d82 --- /dev/null +++ b/CSharpLoaderDll/memory.cpp @@ -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 _(this->mutex_); + + for (auto& data : this->pool_) + { + memory::free(data); + } + + this->pool_.clear(); +} + +void memory::allocator::free(void* data) +{ + std::lock_guard _(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(data)); +} + +void* memory::allocator::allocate(const size_t length) +{ + std::lock_guard _(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(data)); +} + +bool memory::is_set(const void* mem, const char chr, const size_t length) +{ + const auto mem_arr = static_cast(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{}; + const auto start = const_cast(pattern); + const auto end = const_cast(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, ¤t, 16)); + } + } + return bytes; + }; + + const auto dos_header = reinterpret_cast(module); + const auto nt_headers = + reinterpret_cast(reinterpret_cast(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(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; +} \ No newline at end of file diff --git a/CSharpLoaderDll/memory.h b/CSharpLoaderDll/memory.h new file mode 100644 index 0000000..f9c9984 --- /dev/null +++ b/CSharpLoaderDll/memory.h @@ -0,0 +1,105 @@ +#pragma once +#include +#include +#include + +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 + T* allocate() + { + return this->allocate_array(1); + } + + template + T* allocate_array(const size_t count = 1) + { + auto base = static_cast(this->allocate(count * sizeof(T))); + + T(); + return base; + } + + bool empty() const; + + private: + std::mutex mutex_; + std::vector pool_; + }; + + static void* allocate(size_t length); + + template + static inline T* allocate() + { + return allocate_array(1); + } + + template + static inline T* allocate_array(const size_t count = 1) + { + return static_cast(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); diff --git a/CSharpLoaderDll/pch.cpp b/CSharpLoaderDll/pch.cpp new file mode 100644 index 0000000..b6fb8f4 --- /dev/null +++ b/CSharpLoaderDll/pch.cpp @@ -0,0 +1,5 @@ +// pch.cpp: 与预编译标头对应的源文件 + +#include "pch.h" + +// 当使用预编译的头时,需要使用此源文件,编译才能成功。 diff --git a/CSharpLoaderDll/pch.h b/CSharpLoaderDll/pch.h new file mode 100644 index 0000000..9660927 --- /dev/null +++ b/CSharpLoaderDll/pch.h @@ -0,0 +1,13 @@ +// pch.h: 这是预编译标头文件。 +// 下方列出的文件仅编译一次,提高了将来生成的生成性能。 +// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。 +// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。 +// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。 + +#ifndef PCH_H +#define PCH_H + +// 添加要在此处预编译的标头 +#include "framework.h" + +#endif //PCH_H diff --git a/CSharpLoaderDll/plugin.cpp b/CSharpLoaderDll/plugin.cpp new file mode 100644 index 0000000..a073c33 --- /dev/null +++ b/CSharpLoaderDll/plugin.cpp @@ -0,0 +1,98 @@ +// https://github.com/t-mat/pseudo-version-dll/ +#include "pch.h" +#include "plugin.hpp" +#include +#include +#include +#include + + +static std::vector hModules; + +struct Path : std::array { + 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 moduleName; + GetModuleFileNameW(h, moduleName.data(), static_cast(moduleName.size())); + return Path(moduleName.data()); +} + +void recursiveFileEnumerator(const wchar_t* path, const std::function& 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 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(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(); +} diff --git a/CSharpLoaderDll/plugin.hpp b/CSharpLoaderDll/plugin.hpp new file mode 100644 index 0000000..a872773 --- /dev/null +++ b/CSharpLoaderDll/plugin.hpp @@ -0,0 +1,4 @@ +#pragma once + +void loadPluginDlls(); +void unloadPluginDlls(); diff --git a/CSharpLoaderDll/version_dll.cpp b/CSharpLoaderDll/version_dll.cpp new file mode 100644 index 0000000..c0ac3ad --- /dev/null +++ b/CSharpLoaderDll/version_dll.cpp @@ -0,0 +1,166 @@ +#include "pch.h" +#pragma unmanaged +#include "version_dll.hpp" +#include +#include +#include + +/////////////////////////////////////////////////////////////// +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 +void setup(T*& funcPtr, const char* funcName) { + if(funcPtr != nullptr) { + return; + } + funcPtr = reinterpret_cast(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); +} diff --git a/CSharpLoaderDll/version_dll.hpp b/CSharpLoaderDll/version_dll.hpp new file mode 100644 index 0000000..2db9d14 --- /dev/null +++ b/CSharpLoaderDll/version_dll.hpp @@ -0,0 +1,4 @@ +#pragma once + +bool init_version_dll(); +bool deinit_version_dll(); diff --git a/CSharpManager/CSharpManager.csproj b/CSharpManager/CSharpManager.csproj new file mode 100644 index 0000000..9ec4149 --- /dev/null +++ b/CSharpManager/CSharpManager.csproj @@ -0,0 +1,24 @@ + + + + Exe + net472 + enable + True + latest + 0.0.6.0 + + + + + + + + + + + + + + + diff --git a/CSharpManager/CSharpModManager.cs b/CSharpManager/CSharpModManager.cs new file mode 100644 index 0000000..c9c28ff --- /dev/null +++ b/CSharpManager/CSharpModManager.cs @@ -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 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 + } + } + } +} diff --git a/CSharpManager/Ini.cs b/CSharpManager/Ini.cs new file mode 100644 index 0000000..e19d41c --- /dev/null +++ b/CSharpManager/Ini.cs @@ -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> ini = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); + string file; + + /// + /// Initialize an INI file + /// Load it if it exists + /// + /// Full path where the INI file has to be read from or written to + public Ini(string file) + { + this.file = file; + + if (!File.Exists(file)) + return; + + Load(); + } + + /// + /// Load the INI file content + /// + public void Load() + { + var txt = File.ReadAllText(file); + + Dictionary currentSection = new Dictionary(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(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); + } + } + + /// + /// Get a parameter value at the root level + /// + /// parameter key + /// + public string GetValue(string key) + { + return GetValue(key, "", ""); + } + + /// + /// Get a parameter value in the section + /// + /// parameter key + /// section + /// + public string GetValue(string key, string section) + { + return GetValue(key, section, ""); + } + + /// + /// Returns a parameter value in the section, with a default value if not found + /// + /// parameter key + /// section + /// default value + /// + 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]; + } + + /// + /// Save the INI file + /// + 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'; + } + + /// + /// Write a parameter value at the root level + /// + /// parameter key + /// parameter value + public void WriteValue(string key, string value) + { + WriteValue(key, "", value); + } + + /// + /// Write a parameter value in a section + /// + /// parameter key + /// section + /// parameter value + public void WriteValue(string key, string section, string value) + { + Dictionary currentSection; + if (!ini.ContainsKey(section)) + { + currentSection = new Dictionary(); + ini.Add(section, currentSection); + } + else + currentSection = ini[section]; + + currentSection[key] = value; + } + + /// + /// Get all the keys names in a section + /// + /// section + /// + public string[] GetKeys(string section) + { + if (!ini.ContainsKey(section)) + return new string[0]; + + return ini[section].Keys.ToArray(); + } + + /// + /// Get all the section names of the INI file + /// + /// + public string[] GetSections() + { + return ini.Keys.Where(t => t != "").ToArray(); + } +} diff --git a/CSharpManager/InputManager.cs b/CSharpManager/InputManager.cs new file mode 100644 index 0000000..70e97d6 --- /dev/null +++ b/CSharpManager/InputManager.cs @@ -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 BuiltinHotKeyItems { get; } = new(); + public List 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 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; + } + } +} diff --git a/CSharpManager/Program.cs b/CSharpManager/Program.cs new file mode 100644 index 0000000..963df59 --- /dev/null +++ b/CSharpManager/Program.cs @@ -0,0 +1,13 @@ + +namespace CSharpManager +{ + internal class Program + { + public static void Main(string[] args) + { + CSharpModManager manager = new(); + manager.LoadMods(); + manager.StartLoop(); + } + } +} diff --git a/CSharpManager/README.md b/CSharpManager/README.md new file mode 100644 index 0000000..6440321 --- /dev/null +++ b/CSharpManager/README.md @@ -0,0 +1,6 @@ +# CSharpManager +C# mod的管理器,CSharpLoader会加载CSharpManager,通过CSharpManager加载其他C# mod + +## 编译 + +dotnet build diff --git a/CSharpManager/b1cs.ini b/CSharpManager/b1cs.ini new file mode 100644 index 0000000..04de55c --- /dev/null +++ b/CSharpManager/b1cs.ini @@ -0,0 +1,4 @@ +[Settings] +Develop=1 +Console=1 +EnableJit=1 \ No newline at end of file diff --git a/CSharpModBase/CSharpModBase.cs b/CSharpModBase/CSharpModBase.cs new file mode 100644 index 0000000..5f5b904 --- /dev/null +++ b/CSharpModBase/CSharpModBase.cs @@ -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 + { + /// + /// mod name + /// + string Name { get; } + + /// + /// mod version + /// + string Version { get; } + + /// + /// when mod loaded, will call OnInit + /// + void Init(); + /// + /// when manamger reload mods, will call OnDeInit, + /// + /// + void DeInit(); + } +} diff --git a/CSharpModBase/CSharpModBase.csproj b/CSharpModBase/CSharpModBase.csproj new file mode 100644 index 0000000..68192f0 --- /dev/null +++ b/CSharpModBase/CSharpModBase.csproj @@ -0,0 +1,27 @@ + + + + net472 + enable + latest + True + 0.0.6.0 + + + + + + + + + + + + + + ..\GameDll\UnrealEngine.Runtime.dll + False + + + + diff --git a/CSharpModBase/Input/GamePad.cs b/CSharpModBase/Input/GamePad.cs new file mode 100644 index 0000000..b225fc3 --- /dev/null +++ b/CSharpModBase/Input/GamePad.cs @@ -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); +} diff --git a/CSharpModBase/Input/HotKeyItem.cs b/CSharpModBase/Input/HotKeyItem.cs new file mode 100644 index 0000000..852e36b --- /dev/null +++ b/CSharpModBase/Input/HotKeyItem.cs @@ -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; } + /// + /// 0为不支持连按,大于0为连按触发毫秒间隔 + /// + public int RepeatMs { get; set; } + /// + /// 上一次触发的时间,毫秒 + /// + public long LastTriggerMs { get; set; } + /// + /// 正在被按下 + /// + 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() + { + } + } +} diff --git a/CSharpModBase/Input/IInputManager.cs b/CSharpModBase/Input/IInputManager.cs new file mode 100644 index 0000000..2412625 --- /dev/null +++ b/CSharpModBase/Input/IInputManager.cs @@ -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); + } +} diff --git a/CSharpModBase/Input/Key.cs b/CSharpModBase/Input/Key.cs new file mode 100644 index 0000000..9ae37b4 --- /dev/null +++ b/CSharpModBase/Input/Key.cs @@ -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, // '\'' + } +} diff --git a/CSharpModBase/Input/KeyUtils.cs b/CSharpModBase/Input/KeyUtils.cs new file mode 100644 index 0000000..1f2618b --- /dev/null +++ b/CSharpModBase/Input/KeyUtils.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace CSharpModBase.Input +{ + public static class KeyUtils + { + /// + /// Keys转字符串,支持组合键 + /// + /// + /// + public static string KeyToString(ModifierKeys modifiers, Key key, List 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; + } + } + } +} diff --git a/CSharpModBase/Input/ModifierKeys.cs b/CSharpModBase/Input/ModifierKeys.cs new file mode 100644 index 0000000..7876a83 --- /dev/null +++ b/CSharpModBase/Input/ModifierKeys.cs @@ -0,0 +1,14 @@ +using System; + +namespace CSharpModBase.Input +{ + [Flags] + public enum ModifierKeys + { + None = 0, + Alt = 1, + Control = 2, + Shift = 4, + Windows = 8 + } +} diff --git a/CSharpModBase/Log.cs b/CSharpModBase/Log.cs new file mode 100644 index 0000000..f6a0eb8 --- /dev/null +++ b/CSharpModBase/Log.cs @@ -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; + } + } +} diff --git a/CSharpModBase/Utils.cs b/CSharpModBase/Utils.cs new file mode 100644 index 0000000..5901f8b --- /dev/null +++ b/CSharpModBase/Utils.cs @@ -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); + } + }); + } + } +} diff --git a/CSharpModExample/CSharpExample.csproj b/CSharpModExample/CSharpExample.csproj new file mode 100644 index 0000000..e52ac7e --- /dev/null +++ b/CSharpModExample/CSharpExample.csproj @@ -0,0 +1,64 @@ + + + + net472 + enable + True + latest + 0.0.1.0 + + + + + + + + + + + + + + ..\GameDll\BtlSvr.Main.dll + False + + + ..\GameDll\b1.Native.dll + False + + + ..\GameDll\b1.NativePlugins.dll + False + + + ..\GameDll\GSE.Core.dll + False + + + ..\GameDll\GSE.ProtobufDB.dll + False + + + ..\GameDll\Google.Protobuf.dll + False + + + ..\GameDll\Protobuf.RunTime.dll + False + + + ..\GameDll\UnrealEngine.Runtime.dll + False + + + ..\GameDll\UnrealEngine.dll + False + + + + diff --git a/CSharpModExample/MyUtils.cs b/CSharpModExample/MyUtils.cs new file mode 100644 index 0000000..7dc7e41 --- /dev/null +++ b/CSharpModExample/MyUtils.cs @@ -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(string asset) where T : UObject + { + return b1.BGW.BGW_PreloadAssetMgr.Get(GetWorld()).TryGetCachedResourceObj(asset, b1.BGW.ELoadResourceType.SyncLoadAndCache, b1.BGW.EAssetPriority.Default, null, -1, -1); + } + + public static UClass LoadClass(string asset) + { + return LoadAsset(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(classAsset)); + } + } +} diff --git a/CSharpModExample/Program.cs b/CSharpModExample/Program.cs new file mode 100644 index 0000000..90770ce --- /dev/null +++ b/CSharpModExample/Program.cs @@ -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}"); + } + } + } +} diff --git a/CSharpModExample/README.md b/CSharpModExample/README.md new file mode 100644 index 0000000..1882d07 --- /dev/null +++ b/CSharpModExample/README.md @@ -0,0 +1,3 @@ +# 编译 + +dotnet build diff --git a/CSharpModExample/build.sh b/CSharpModExample/build.sh new file mode 100644 index 0000000..2728920 --- /dev/null +++ b/CSharpModExample/build.sh @@ -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 \ No newline at end of file diff --git a/CSharpModExample/obfuscar.xml b/CSharpModExample/obfuscar.xml new file mode 100644 index 0000000..89a70df --- /dev/null +++ b/CSharpModExample/obfuscar.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/GameDll/B1UI_GSE.Script.dll b/GameDll/B1UI_GSE.Script.dll new file mode 100644 index 0000000..e376519 Binary files /dev/null and b/GameDll/B1UI_GSE.Script.dll differ diff --git a/GameDll/BtlSvr.Main.dll b/GameDll/BtlSvr.Main.dll new file mode 100644 index 0000000..0c34ac6 Binary files /dev/null and b/GameDll/BtlSvr.Main.dll differ diff --git a/GameDll/Diana.Client.Common.dll b/GameDll/Diana.Client.Common.dll new file mode 100644 index 0000000..1e8f3ef Binary files /dev/null and b/GameDll/Diana.Client.Common.dll differ diff --git a/GameDll/Diana.Common.dll b/GameDll/Diana.Common.dll new file mode 100644 index 0000000..db6771e Binary files /dev/null and b/GameDll/Diana.Common.dll differ diff --git a/GameDll/Diana.Server.Common.dll b/GameDll/Diana.Server.Common.dll new file mode 100644 index 0000000..d09ef35 Binary files /dev/null and b/GameDll/Diana.Server.Common.dll differ diff --git a/GameDll/GSE.Core.dll b/GameDll/GSE.Core.dll new file mode 100644 index 0000000..0e6055a Binary files /dev/null and b/GameDll/GSE.Core.dll differ diff --git a/GameDll/GSE.GSNet.dll b/GameDll/GSE.GSNet.dll new file mode 100644 index 0000000..00ded08 Binary files /dev/null and b/GameDll/GSE.GSNet.dll differ diff --git a/GameDll/GSE.GSSdk.dll b/GameDll/GSE.GSSdk.dll new file mode 100644 index 0000000..2ff1583 Binary files /dev/null and b/GameDll/GSE.GSSdk.dll differ diff --git a/GameDll/GSE.OnlineBase.dll b/GameDll/GSE.OnlineBase.dll new file mode 100644 index 0000000..eef5889 Binary files /dev/null and b/GameDll/GSE.OnlineBase.dll differ diff --git a/GameDll/GSE.ProtobufDB.dll b/GameDll/GSE.ProtobufDB.dll new file mode 100644 index 0000000..1bbd25b Binary files /dev/null and b/GameDll/GSE.ProtobufDB.dll differ diff --git a/GameDll/GUR.Runtime.dll b/GameDll/GUR.Runtime.dll new file mode 100644 index 0000000..b29fd23 Binary files /dev/null and b/GameDll/GUR.Runtime.dll differ diff --git a/GameDll/Google.Protobuf.dll b/GameDll/Google.Protobuf.dll new file mode 100644 index 0000000..d55190c Binary files /dev/null and b/GameDll/Google.Protobuf.dll differ diff --git a/GameDll/ICSharpCode.SharpZipLib.dll b/GameDll/ICSharpCode.SharpZipLib.dll new file mode 100644 index 0000000..76ddc96 Binary files /dev/null and b/GameDll/ICSharpCode.SharpZipLib.dll differ diff --git a/GameDll/ILRuntime.Mono.Cecil.Mdb.dll b/GameDll/ILRuntime.Mono.Cecil.Mdb.dll new file mode 100644 index 0000000..bf51879 Binary files /dev/null and b/GameDll/ILRuntime.Mono.Cecil.Mdb.dll differ diff --git a/GameDll/ILRuntime.Mono.Cecil.Pdb.dll b/GameDll/ILRuntime.Mono.Cecil.Pdb.dll new file mode 100644 index 0000000..0345219 Binary files /dev/null and b/GameDll/ILRuntime.Mono.Cecil.Pdb.dll differ diff --git a/GameDll/ILRuntime.Mono.Cecil.dll b/GameDll/ILRuntime.Mono.Cecil.dll new file mode 100644 index 0000000..bc615a6 Binary files /dev/null and b/GameDll/ILRuntime.Mono.Cecil.dll differ diff --git a/GameDll/ILRuntime.dll b/GameDll/ILRuntime.dll new file mode 100644 index 0000000..2bf97e4 Binary files /dev/null and b/GameDll/ILRuntime.dll differ diff --git a/GameDll/LitJson.dll b/GameDll/LitJson.dll new file mode 100644 index 0000000..ce2bcc7 Binary files /dev/null and b/GameDll/LitJson.dll differ diff --git a/GameDll/LiteNetLib.dll b/GameDll/LiteNetLib.dll new file mode 100644 index 0000000..17ca8ee Binary files /dev/null and b/GameDll/LiteNetLib.dll differ diff --git a/GameDll/Microsoft.Bcl.AsyncInterfaces.dll b/GameDll/Microsoft.Bcl.AsyncInterfaces.dll new file mode 100644 index 0000000..3edd34f Binary files /dev/null and b/GameDll/Microsoft.Bcl.AsyncInterfaces.dll differ diff --git a/GameDll/Mono.Cecil.dll b/GameDll/Mono.Cecil.dll new file mode 100644 index 0000000..bf1b4e7 Binary files /dev/null and b/GameDll/Mono.Cecil.dll differ diff --git a/GameDll/Mono.Data.Sqlite.dll b/GameDll/Mono.Data.Sqlite.dll new file mode 100644 index 0000000..13e56da Binary files /dev/null and b/GameDll/Mono.Data.Sqlite.dll differ diff --git a/GameDll/Mono.Posix.dll b/GameDll/Mono.Posix.dll new file mode 100644 index 0000000..47bc181 Binary files /dev/null and b/GameDll/Mono.Posix.dll differ diff --git a/GameDll/Mono.Security.dll b/GameDll/Mono.Security.dll new file mode 100644 index 0000000..0160468 Binary files /dev/null and b/GameDll/Mono.Security.dll differ diff --git a/GameDll/Mono.WebBrowser.dll b/GameDll/Mono.WebBrowser.dll new file mode 100644 index 0000000..e6b6d15 Binary files /dev/null and b/GameDll/Mono.WebBrowser.dll differ diff --git a/GameDll/Novell.Directory.Ldap.dll b/GameDll/Novell.Directory.Ldap.dll new file mode 100644 index 0000000..b927bd7 Binary files /dev/null and b/GameDll/Novell.Directory.Ldap.dll differ diff --git a/GameDll/Protobuf.RunTime.dll b/GameDll/Protobuf.RunTime.dll new file mode 100644 index 0000000..fed0b57 Binary files /dev/null and b/GameDll/Protobuf.RunTime.dll differ diff --git a/GameDll/Sentry.dll b/GameDll/Sentry.dll new file mode 100644 index 0000000..0be61a6 Binary files /dev/null and b/GameDll/Sentry.dll differ diff --git a/GameDll/System.Buffers.dll b/GameDll/System.Buffers.dll new file mode 100644 index 0000000..d3fdc22 Binary files /dev/null and b/GameDll/System.Buffers.dll differ diff --git a/GameDll/System.Collections.Immutable.dll b/GameDll/System.Collections.Immutable.dll new file mode 100644 index 0000000..a7c1d83 Binary files /dev/null and b/GameDll/System.Collections.Immutable.dll differ diff --git a/GameDll/System.IO.FileSystem.dll b/GameDll/System.IO.FileSystem.dll new file mode 100644 index 0000000..b259fc2 Binary files /dev/null and b/GameDll/System.IO.FileSystem.dll differ diff --git a/GameDll/System.Memory.dll b/GameDll/System.Memory.dll new file mode 100644 index 0000000..c534eee Binary files /dev/null and b/GameDll/System.Memory.dll differ diff --git a/GameDll/System.Numerics.Vectors.dll b/GameDll/System.Numerics.Vectors.dll new file mode 100644 index 0000000..5b13c3f Binary files /dev/null and b/GameDll/System.Numerics.Vectors.dll differ diff --git a/GameDll/System.Reflection.Metadata.dll b/GameDll/System.Reflection.Metadata.dll new file mode 100644 index 0000000..99fceed Binary files /dev/null and b/GameDll/System.Reflection.Metadata.dll differ diff --git a/GameDll/System.Runtime.CompilerServices.Unsafe.dll b/GameDll/System.Runtime.CompilerServices.Unsafe.dll new file mode 100644 index 0000000..d8605f9 Binary files /dev/null and b/GameDll/System.Runtime.CompilerServices.Unsafe.dll differ diff --git a/GameDll/System.ServiceModel.Internals.dll b/GameDll/System.ServiceModel.Internals.dll new file mode 100644 index 0000000..f0d36b1 Binary files /dev/null and b/GameDll/System.ServiceModel.Internals.dll differ diff --git a/GameDll/System.Text.Encodings.Web.dll b/GameDll/System.Text.Encodings.Web.dll new file mode 100644 index 0000000..938d58f Binary files /dev/null and b/GameDll/System.Text.Encodings.Web.dll differ diff --git a/GameDll/System.Text.Json.dll b/GameDll/System.Text.Json.dll new file mode 100644 index 0000000..164c5d1 Binary files /dev/null and b/GameDll/System.Text.Json.dll differ diff --git a/GameDll/System.Threading.Tasks.Extensions.dll b/GameDll/System.Threading.Tasks.Extensions.dll new file mode 100644 index 0000000..97484fa Binary files /dev/null and b/GameDll/System.Threading.Tasks.Extensions.dll differ diff --git a/GameDll/UnrealEngine.Runtime.dll b/GameDll/UnrealEngine.Runtime.dll new file mode 100644 index 0000000..8f991ab Binary files /dev/null and b/GameDll/UnrealEngine.Runtime.dll differ diff --git a/GameDll/UnrealEngine.dll b/GameDll/UnrealEngine.dll new file mode 100644 index 0000000..26356a1 Binary files /dev/null and b/GameDll/UnrealEngine.dll differ diff --git a/GameDll/b1.Managed.dll b/GameDll/b1.Managed.dll new file mode 100644 index 0000000..918bbfc Binary files /dev/null and b/GameDll/b1.Managed.dll differ diff --git a/GameDll/b1.Native.dll b/GameDll/b1.Native.dll new file mode 100644 index 0000000..ef70bdc Binary files /dev/null and b/GameDll/b1.Native.dll differ diff --git a/GameDll/b1.NativePlugins.dll b/GameDll/b1.NativePlugins.dll new file mode 100644 index 0000000..54c568b Binary files /dev/null and b/GameDll/b1.NativePlugins.dll differ diff --git a/GameDll/netstandard.dll b/GameDll/netstandard.dll new file mode 100644 index 0000000..13df695 Binary files /dev/null and b/GameDll/netstandard.dll differ diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..e0f9fe8 --- /dev/null +++ b/README.en.md @@ -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//.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//` or `CSharpLoader/Mods/Common/`, Common is shared by all mods. diff --git a/README.md b/README.md new file mode 100644 index 0000000..56ead34 --- /dev/null +++ b/README.md @@ -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//.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//`或者`CSharpLoader/Mods/Common/`中,这样其他Mod也能用里面的依赖