├── .gitattributes ├── .gitignore ├── Builders ├── IWrapperBuilder.cs ├── PortableWrapper.cs ├── PortableWrapperUnsafe.cs ├── SRLHook.cs ├── SRLWrapper.cs └── Wrapper.cs ├── Extensions.cs ├── LICENSE ├── Main.Designer.cs ├── Main.cs ├── Main.resx ├── Program.cs ├── Readme.md ├── SourceParser.cs ├── WrapperGenerator.csproj └── WrapperGenerator.sln /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # JustCode is a .NET coding add-in 131 | .JustCode 132 | 133 | # TeamCity is a build add-in 134 | _TeamCity* 135 | 136 | # DotCover is a Code Coverage Tool 137 | *.dotCover 138 | 139 | # AxoCover is a Code Coverage Tool 140 | .axoCover/* 141 | !.axoCover/settings.json 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | -------------------------------------------------------------------------------- /Builders/IWrapperBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace WrapperGenerator 4 | { 5 | interface IWrapperBuilder 6 | { 7 | public string Name { get; } 8 | public string BuildWrapper(string Name, Function[] Exports); 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Builders/PortableWrapper.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace WrapperGenerator 4 | { 5 | class PortableWrapper : IWrapperBuilder 6 | { 7 | public string Name => "Portable Wrapper"; 8 | 9 | public string BuildWrapper(string Name, Function[] Exports) 10 | { 11 | StringBuilder Builder = new StringBuilder(); 12 | Builder.AppendLine("using System;"); 13 | Builder.AppendLine("using System.IO;"); 14 | Builder.AppendLine("using System.Reflection;"); 15 | Builder.AppendLine("using System.Runtime.InteropServices;"); 16 | Builder.AppendLine(); 17 | Builder.AppendLine("namespace Wrapper"); 18 | Builder.AppendLine("{"); 19 | Builder.AppendLine(" /// "); 20 | Builder.AppendLine($" /// This is a wrapper to the {Name}.dll"); 21 | Builder.AppendLine(" /// "); 22 | Builder.AppendLine($" public static class {Name.Trim().Replace(" ", "")}"); 23 | Builder.AppendLine(" {"); 24 | Builder.AppendLine(); 25 | Builder.AppendLine(" static string CurrentDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);"); 26 | Builder.AppendLine(" static string CurrentDllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);"); 27 | Builder.AppendLine(" static string RealDllPath = null;"); 28 | Builder.AppendLine(" static bool WOW64 => !Environment.Is64BitProcess && Environment.Is64BitOperatingSystem;"); 29 | Builder.AppendLine(); 30 | Builder.AppendLine(" public static IntPtr RealHandler;"); 31 | Builder.AppendLine($" static {Name.Trim().Replace(" ", "")}()"); 32 | Builder.AppendLine(" {"); 33 | Builder.AppendLine(" if (RealHandler != IntPtr.Zero)"); 34 | Builder.AppendLine(" return;"); 35 | Builder.AppendLine(); 36 | Builder.AppendLine(" RealHandler = LoadLibrary(CurrentDllName);"); 37 | Builder.AppendLine(); 38 | Builder.AppendLine(" if (RealHandler == IntPtr.Zero)"); 39 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 40 | 41 | Builder.AppendLine(); 42 | foreach (Function Export in Exports) 43 | { 44 | Builder.AppendLine($" d{Export.Name} = GetDelegate(RealHandler, \"{Export.Name}\", false);"); 45 | } 46 | Builder.AppendLine(); 47 | Builder.AppendLine(" }"); 48 | 49 | Builder.AppendLine(); 50 | 51 | foreach (Function Export in Exports) 52 | { 53 | var Return = Export.ReturnType != "void" ? "return " : ""; 54 | Builder.AppendLine($" [DllExport(CallingConvention = CallingConvention.{Export.Calling})]"); 55 | Builder.AppendLine($" public static {Export}"); 56 | Builder.AppendLine(" {"); 57 | Builder.AppendLine($" {Return}d{Export.Name}({Export.ArgumentNames});"); 58 | Builder.AppendLine(" }"); 59 | Builder.AppendLine(); 60 | } 61 | 62 | Builder.AppendLine(); 63 | 64 | 65 | Builder.AppendLine(" [DllImport(\"kernel32\", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]"); 66 | Builder.AppendLine(" internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);"); 67 | Builder.AppendLine(); 68 | Builder.AppendLine(" [DllImport(\"kernel32\", SetLastError = true, CharSet = CharSet.Unicode)]"); 69 | Builder.AppendLine(" internal static extern IntPtr LoadLibraryW(string lpFileName);"); 70 | Builder.AppendLine(); 71 | Builder.AppendLine(" internal static IntPtr LoadLibrary(string lpFileName)"); 72 | Builder.AppendLine(" {"); 73 | Builder.AppendLine(" string DllPath = lpFileName;"); 74 | Builder.AppendLine(" if (lpFileName.Length < 2 || lpFileName[1] != ':')"); 75 | Builder.AppendLine(" {"); 76 | Builder.AppendLine(" string DLL = Path.GetFileNameWithoutExtension(lpFileName);"); 77 | Builder.AppendLine(" DllPath = Path.Combine(Environment.CurrentDirectory, $\"{DLL}_ori.dll\");"); 78 | Builder.AppendLine(" if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower())"); 79 | Builder.AppendLine(" DllPath = Path.Combine(Environment.CurrentDirectory, $\"{DLL}.dll\");"); 80 | Builder.AppendLine(" if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower())"); 81 | Builder.AppendLine(" DllPath = Path.Combine(CurrentDllPath, $\"{DLL}_ori.dll\");"); 82 | Builder.AppendLine(" if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower())"); 83 | Builder.AppendLine(" DllPath = Path.Combine(CurrentDllPath, $\"{DLL}.dll.ori\");"); 84 | Builder.AppendLine(" if (!File.Exists(DllPath))"); 85 | Builder.AppendLine(" {"); 86 | Builder.AppendLine(" DllPath = WOW64 ? Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) : Environment.SystemDirectory;"); 87 | Builder.AppendLine(" DllPath = Path.Combine(DllPath, $\"{DLL}.dll\");"); 88 | Builder.AppendLine(" }"); 89 | Builder.AppendLine(" }"); 90 | Builder.AppendLine(" RealDllPath = DllPath;"); 91 | Builder.AppendLine(); 92 | Builder.AppendLine(" IntPtr Handler = LoadLibraryW(DllPath);"); 93 | Builder.AppendLine(); 94 | Builder.AppendLine(" if (Handler == IntPtr.Zero)"); 95 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 96 | Builder.AppendLine(); 97 | Builder.AppendLine(" return Handler;"); 98 | Builder.AppendLine(" }"); 99 | Builder.AppendLine(); 100 | Builder.AppendLine(" internal static T GetDelegate(IntPtr Handler, string Function, bool Optional = true) where T : Delegate"); 101 | Builder.AppendLine(" {"); 102 | Builder.AppendLine(" IntPtr Address = GetProcAddress(Handler, Function);"); 103 | Builder.AppendLine(" if (Address == IntPtr.Zero)"); 104 | Builder.AppendLine(" {"); 105 | Builder.AppendLine(" if (Optional)"); 106 | Builder.AppendLine(" {"); 107 | Builder.AppendLine(" return null;"); 108 | Builder.AppendLine(" }"); 109 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 110 | Builder.AppendLine(" }"); 111 | Builder.AppendLine(" return (T)Marshal.GetDelegateForFunctionPointer(Address, typeof(T));"); 112 | Builder.AppendLine(" }"); 113 | 114 | Builder.AppendLine(); 115 | 116 | 117 | 118 | foreach (Function Export in Exports) 119 | { 120 | 121 | Builder.AppendLine($" static t{Export.Name} d{Export.Name};"); 122 | } 123 | 124 | Builder.AppendLine(); 125 | foreach (Function Export in Exports) 126 | { 127 | Function tmp = Export; 128 | tmp.Name = "t" + tmp.Name; 129 | Builder.AppendLine($" [UnmanagedFunctionPointer(CallingConvention.{Export.Calling}, CharSet = CharSet.{Export.Charset})]"); 130 | Builder.AppendLine($" delegate {tmp};"); 131 | } 132 | 133 | Builder.AppendLine(); 134 | Builder.AppendLine(" }"); 135 | Builder.AppendLine("}"); 136 | 137 | return Builder.ToString(); 138 | } 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /Builders/PortableWrapperUnsafe.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace WrapperGenerator 4 | { 5 | class PortableWrapperUnsafe : IWrapperBuilder 6 | { 7 | public string Name => "Portable Wrapper Unsafe"; 8 | 9 | public string BuildWrapper(string Name, Function[] Exports) 10 | { 11 | Exports.SetUnsafeMode(true); 12 | 13 | StringBuilder Builder = new StringBuilder(); 14 | Builder.AppendLine("using System;"); 15 | Builder.AppendLine("using System.IO;"); 16 | Builder.AppendLine("using System.Reflection;"); 17 | Builder.AppendLine("using System.Runtime.InteropServices;"); 18 | Builder.AppendLine(); 19 | Builder.AppendLine("namespace Wrapper"); 20 | Builder.AppendLine("{"); 21 | Builder.AppendLine(" /// "); 22 | Builder.AppendLine($" /// This is a wrapper to the {Name}.dll"); 23 | Builder.AppendLine(" /// "); 24 | Builder.AppendLine($" public unsafe static class {Name.Trim().Replace(" ", "")}"); 25 | Builder.AppendLine(" {"); 26 | Builder.AppendLine(); 27 | Builder.AppendLine(" static string CurrentDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);"); 28 | Builder.AppendLine(" static string CurrentDllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);"); 29 | Builder.AppendLine(" static string RealDllPath = null;"); 30 | Builder.AppendLine(" static bool WOW64 => !Environment.Is64BitProcess && Environment.Is64BitOperatingSystem;"); 31 | Builder.AppendLine(); 32 | Builder.AppendLine(" public static void* RealHandler;"); 33 | Builder.AppendLine($" static {Name.Trim().Replace(" ", "")}()"); 34 | Builder.AppendLine(" {"); 35 | Builder.AppendLine(" if (RealHandler != null)"); 36 | Builder.AppendLine(" return;"); 37 | Builder.AppendLine(); 38 | Builder.AppendLine(" RealHandler = LoadLibrary(CurrentDllName);"); 39 | Builder.AppendLine(); 40 | Builder.AppendLine(" if (RealHandler == null)"); 41 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 42 | 43 | Builder.AppendLine(); 44 | foreach (Function Export in Exports) 45 | { 46 | Builder.AppendLine($" d{Export.Name} = GetDelegate(RealHandler, \"{Export.Name}\", false);"); 47 | } 48 | Builder.AppendLine(); 49 | Builder.AppendLine(" }"); 50 | 51 | Builder.AppendLine(); 52 | 53 | foreach (Function Export in Exports) 54 | { 55 | var Return = Export.ReturnType != "void" ? "return " : ""; 56 | Builder.AppendLine($" [DllExport(CallingConvention = CallingConvention.{Export.Calling})]"); 57 | Builder.AppendLine($" public static {Export}"); 58 | Builder.AppendLine(" {"); 59 | Builder.AppendLine($" {Return}d{Export.Name}({Export.ArgumentNames});"); 60 | Builder.AppendLine(" }"); 61 | Builder.AppendLine(); 62 | } 63 | 64 | Builder.AppendLine(); 65 | 66 | 67 | Builder.AppendLine(" [DllImport(\"kernel32\", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]"); 68 | Builder.AppendLine(" internal static extern void* GetProcAddress(void* hModule, string procName);"); 69 | Builder.AppendLine(); 70 | Builder.AppendLine(" [DllImport(\"kernel32\", SetLastError = true, CharSet = CharSet.Unicode)]"); 71 | Builder.AppendLine(" internal static extern void* LoadLibraryW(string lpFileName);"); 72 | Builder.AppendLine(); 73 | Builder.AppendLine(" internal static void* LoadLibrary(string lpFileName)"); 74 | Builder.AppendLine(" {"); 75 | Builder.AppendLine(" string DllPath = lpFileName;"); 76 | Builder.AppendLine(" if (lpFileName.Length < 2 || lpFileName[1] != ':')"); 77 | Builder.AppendLine(" {"); 78 | Builder.AppendLine(" string DLL = Path.GetFileNameWithoutExtension(lpFileName);"); 79 | Builder.AppendLine(" DllPath = Path.Combine(Environment.CurrentDirectory, $\"{DLL}_ori.dll\");"); 80 | Builder.AppendLine(" if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower())"); 81 | Builder.AppendLine(" DllPath = Path.Combine(Environment.CurrentDirectory, $\"{DLL}.dll\");"); 82 | Builder.AppendLine(" if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower())"); 83 | Builder.AppendLine(" DllPath = Path.Combine(CurrentDllPath, $\"{DLL}_ori.dll\");"); 84 | Builder.AppendLine(" if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower())"); 85 | Builder.AppendLine(" DllPath = Path.Combine(CurrentDllPath, $\"{DLL}.dll.ori\");"); 86 | Builder.AppendLine(" if (!File.Exists(DllPath))"); 87 | Builder.AppendLine(" {"); 88 | Builder.AppendLine(" DllPath = WOW64 ? Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) : Environment.SystemDirectory;"); 89 | Builder.AppendLine(" DllPath = Path.Combine(DllPath, $\"{DLL}.dll\");"); 90 | Builder.AppendLine(" }"); 91 | Builder.AppendLine(" }"); 92 | Builder.AppendLine(" RealDllPath = DllPath;"); 93 | Builder.AppendLine(); 94 | Builder.AppendLine(" void* Handler = LoadLibraryW(DllPath);"); 95 | Builder.AppendLine(); 96 | Builder.AppendLine(" if (Handler == null)"); 97 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 98 | Builder.AppendLine(); 99 | Builder.AppendLine(" return Handler;"); 100 | Builder.AppendLine(" }"); 101 | Builder.AppendLine(); 102 | Builder.AppendLine(" internal static T GetDelegate(void* Handler, string Function, bool Optional = true) where T : Delegate"); 103 | Builder.AppendLine(" {"); 104 | Builder.AppendLine(" void* Address = GetProcAddress(Handler, Function);"); 105 | Builder.AppendLine(" if (Address == null)"); 106 | Builder.AppendLine(" {"); 107 | Builder.AppendLine(" if (Optional)"); 108 | Builder.AppendLine(" {"); 109 | Builder.AppendLine(" return null;"); 110 | Builder.AppendLine(" }"); 111 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 112 | Builder.AppendLine(" }"); 113 | Builder.AppendLine(" return (T)Marshal.GetDelegateForFunctionPointer(new IntPtr(Address), typeof(T));"); 114 | Builder.AppendLine(" }"); 115 | 116 | Builder.AppendLine(); 117 | 118 | 119 | 120 | foreach (Function Export in Exports) 121 | { 122 | 123 | Builder.AppendLine($" static t{Export.Name} d{Export.Name};"); 124 | } 125 | 126 | Builder.AppendLine(); 127 | foreach (Function Export in Exports) 128 | { 129 | Function tmp = Export; 130 | tmp.Name = "t" + tmp.Name; 131 | Builder.AppendLine($" [UnmanagedFunctionPointer(CallingConvention.{Export.Calling}, CharSet = CharSet.{Export.Charset})]"); 132 | Builder.AppendLine($" delegate {tmp};".Replace("delegate unsafe", "unsafe delegate")); 133 | } 134 | 135 | Builder.AppendLine(); 136 | Builder.AppendLine(" }"); 137 | Builder.AppendLine("}"); 138 | 139 | return Builder.ToString(); 140 | } 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /Builders/SRLHook.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace WrapperGenerator.Builders 6 | { 7 | class SRLHook : IWrapperBuilder 8 | { 9 | public string Name => "SRL Hook"; 10 | 11 | public string BuildWrapper(string Name, Function[] Exports) 12 | { 13 | Exports.SetUnsafeMode(true); 14 | 15 | StringBuilder Builder = new StringBuilder(); 16 | Builder.AppendLine("namespace StringReloads.Hook"); 17 | Builder.AppendLine("{"); 18 | for (int i = 0; i < Exports.Length; i++) 19 | { 20 | var Export = Exports[i]; 21 | Builder.AppendLine($" public unsafe class {Export.Name} : Base.Hook<{Export.Name}Delegate>"); 22 | Builder.AppendLine(" {"); 23 | Builder.AppendLine($" public override string Library => \"{Name}.dll\";"); 24 | Builder.AppendLine(); 25 | Builder.AppendLine($" public override string Export => \"{Export.Name}\";"); 26 | Builder.AppendLine(); 27 | Builder.AppendLine(" public override void Initialize()"); 28 | Builder.AppendLine(" {"); 29 | 30 | var Return = Export.ReturnType != "void" ? "return " : ""; 31 | string ExportName = Export.Name; 32 | Export.Name += "Hook"; 33 | Builder.AppendLine($" HookDelegate = new {Export.Name}Delegate({Export.Name});"); 34 | Builder.AppendLine(" Compile();"); 35 | Builder.AppendLine(" }"); 36 | Builder.AppendLine(); 37 | Builder.AppendLine($" private {Export}"); 38 | Builder.AppendLine(" {"); 39 | Builder.AppendLine($" {Return}Bypass({Export.ArgumentNames});"); 40 | Builder.AppendLine(" }"); 41 | Builder.AppendLine(); 42 | Export.Name = ExportName; 43 | Builder.AppendLine($" [UnmanagedFunctionPointer(CallingConvention.{Export.Calling}, CharSet = CharSet.{Export.Charset})]"); 44 | Export.Name += "Delegate"; 45 | Builder.AppendLine($" public delegate {Export};"); 46 | Builder.AppendLine(" }"); 47 | Builder.AppendLine(); 48 | Export.Name = ExportName; 49 | } 50 | Builder.AppendLine("}"); 51 | 52 | return Builder.ToString(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Builders/SRLWrapper.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace WrapperGenerator 4 | { 5 | class SRLWrapper : IWrapperBuilder 6 | { 7 | public string Name => "SRL Wrapper"; 8 | 9 | public string BuildWrapper(string Name, Function[] Exports) 10 | { 11 | Exports.SetAnonType(true); 12 | 13 | StringBuilder Builder = new StringBuilder(); 14 | Builder.AppendLine("using System;"); 15 | Builder.AppendLine("using System.Runtime.InteropServices;"); 16 | Builder.AppendLine("using SRLWrapper.Wrapper.Base;"); 17 | Builder.AppendLine("using static SRLWrapper.Wrapper.Base.Wrapper;"); 18 | Builder.AppendLine(); 19 | Builder.AppendLine("namespace SRLWrapper.Wrapper"); 20 | Builder.AppendLine("{"); 21 | Builder.AppendLine(" /// "); 22 | Builder.AppendLine($" /// This is a wrapper to the {Name.ToUpperInvariant()}.dll"); 23 | Builder.AppendLine(" /// "); 24 | Builder.AppendLine($" public unsafe static class {Name.Trim().Replace(" ", "")}"); 25 | Builder.AppendLine(" {"); 26 | Builder.AppendLine(" public static void* RealHandler;"); 27 | Builder.AppendLine($" public static {Name.Trim().Replace(" ", "")}()"); 28 | Builder.AppendLine(" {"); 29 | Builder.AppendLine(" if (RealHandler != null)"); 30 | Builder.AppendLine(" return;"); 31 | Builder.AppendLine(); 32 | Builder.AppendLine(" RealHandler = LoadLibrary(CurrentDllName);"); 33 | Builder.AppendLine(); 34 | Builder.AppendLine(" if (RealHandler == null)"); 35 | Builder.AppendLine(" Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED"); 36 | 37 | Builder.AppendLine(); 38 | foreach (Function Export in Exports) 39 | { 40 | Builder.AppendLine($" d{Export.Name} = GetDelegate(RealHandler, \"{Export.Name}\", false);"); 41 | } 42 | Builder.AppendLine(); 43 | 44 | Builder.AppendLine(" InitializeSRL();"); 45 | Builder.AppendLine(" }"); 46 | 47 | Builder.AppendLine(); 48 | 49 | foreach (Function Export in Exports) 50 | { 51 | var Return = Export.ReturnType != "void" ? "return " : ""; 52 | Builder.AppendLine($" [DllExport(CallingConvention = CallingConvention.{Export.Calling})]"); 53 | Builder.AppendLine($" public static {Export}"); 54 | Builder.AppendLine(" {"); 55 | Builder.AppendLine($" {Return}d{Export.Name}({Export.ArgumentNames});"); 56 | Builder.AppendLine(" }"); 57 | Builder.AppendLine(); 58 | } 59 | 60 | Builder.AppendLine(); 61 | 62 | foreach (Function Export in Exports) 63 | { 64 | Builder.AppendLine($" static RET_{Export.Arguments.Length} d{Export.Name};"); 65 | } 66 | Builder.AppendLine(); 67 | Builder.AppendLine(" }"); 68 | Builder.AppendLine("}"); 69 | 70 | return Builder.ToString(); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Builders/Wrapper.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace WrapperGenerator 4 | { 5 | class Wrapper : IWrapperBuilder 6 | { 7 | public string Name => "Wrapper"; 8 | 9 | public string BuildWrapper(string Name, Function[] Exports) 10 | { 11 | Exports.SetAnonType(true); 12 | 13 | StringBuilder Builder = new StringBuilder(); 14 | Builder.AppendLine("using System;"); 15 | Builder.AppendLine("using System.Runtime.InteropServices;"); 16 | Builder.AppendLine(); 17 | Builder.AppendLine("namespace Wrapper"); 18 | Builder.AppendLine("{"); 19 | Builder.AppendLine(" /// "); 20 | Builder.AppendLine($" /// This is a wrapper to the {Name}.dll"); 21 | Builder.AppendLine(" /// "); 22 | Builder.AppendLine($" public static class {Name.Trim().Replace(" ", "")}"); 23 | Builder.AppendLine(" {"); 24 | Builder.AppendLine(); 25 | 26 | foreach (Function Export in Exports) 27 | { 28 | Builder.AppendLine($" [DllImport(\"{Name.Trim().Replace(" ", "")}.dll\", CallingConvention = CallingConvention.{Export.Calling})]"); 29 | Builder.AppendLine($" public static extern {Export};"); 30 | Builder.AppendLine(); 31 | } 32 | 33 | Builder.AppendLine(" }"); 34 | Builder.AppendLine("}"); 35 | 36 | return Builder.ToString(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace WrapperGenerator 6 | { 7 | static class Extensions 8 | { 9 | /// 10 | /// Waits asynchronously for the process to exit. 11 | /// 12 | /// The process to wait for cancellation. 13 | /// A cancellation token. If invoked, the task will return 14 | /// immediately as canceled. 15 | /// A Task representing waiting for the process to end. 16 | public static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) 17 | { 18 | var tcs = new TaskCompletionSource(); 19 | process.EnableRaisingEvents = true; 20 | process.Exited += (sender, args) => tcs.TrySetResult(null); 21 | if (cancellationToken != default) 22 | cancellationToken.Register(tcs.SetCanceled); 23 | 24 | return tcs.Task; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /Main.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace WrapperGenerator 2 | { 3 | partial class Main 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.bntBrowser = new System.Windows.Forms.Button(); 32 | this.tbFilePath = new System.Windows.Forms.TextBox(); 33 | this.CBoxMode = new System.Windows.Forms.ComboBox(); 34 | this.lblMode = new System.Windows.Forms.Label(); 35 | this.tbCodeBox = new System.Windows.Forms.TextBox(); 36 | this.lblRegex = new System.Windows.Forms.Label(); 37 | this.tbRegex = new System.Windows.Forms.TextBox(); 38 | this.SuspendLayout(); 39 | // 40 | // bntBrowser 41 | // 42 | this.bntBrowser.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); 43 | this.bntBrowser.Location = new System.Drawing.Point(659, 11); 44 | this.bntBrowser.Name = "bntBrowser"; 45 | this.bntBrowser.Size = new System.Drawing.Size(32, 24); 46 | this.bntBrowser.TabIndex = 0; 47 | this.bntBrowser.Text = "..."; 48 | this.bntBrowser.UseVisualStyleBackColor = true; 49 | this.bntBrowser.Click += new System.EventHandler(this.SelectFileClicked); 50 | // 51 | // tbFilePath 52 | // 53 | this.tbFilePath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 54 | | System.Windows.Forms.AnchorStyles.Right))); 55 | this.tbFilePath.Location = new System.Drawing.Point(12, 12); 56 | this.tbFilePath.Name = "tbFilePath"; 57 | this.tbFilePath.Size = new System.Drawing.Size(641, 23); 58 | this.tbFilePath.TabIndex = 1; 59 | // 60 | // CBoxMode 61 | // 62 | this.CBoxMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; 63 | this.CBoxMode.FormattingEnabled = true; 64 | this.CBoxMode.Location = new System.Drawing.Point(59, 41); 65 | this.CBoxMode.Name = "CBoxMode"; 66 | this.CBoxMode.Size = new System.Drawing.Size(268, 23); 67 | this.CBoxMode.TabIndex = 2; 68 | this.CBoxMode.SelectedIndexChanged += new System.EventHandler(this.ModeChanged); 69 | // 70 | // lblMode 71 | // 72 | this.lblMode.AutoSize = true; 73 | this.lblMode.Location = new System.Drawing.Point(12, 44); 74 | this.lblMode.Name = "lblMode"; 75 | this.lblMode.Size = new System.Drawing.Size(41, 15); 76 | this.lblMode.TabIndex = 3; 77 | this.lblMode.Text = "Mode:"; 78 | // 79 | // tbCodeBox 80 | // 81 | this.tbCodeBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 82 | | System.Windows.Forms.AnchorStyles.Left) 83 | | System.Windows.Forms.AnchorStyles.Right))); 84 | this.tbCodeBox.Location = new System.Drawing.Point(12, 70); 85 | this.tbCodeBox.Multiline = true; 86 | this.tbCodeBox.Name = "tbCodeBox"; 87 | this.tbCodeBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; 88 | this.tbCodeBox.Size = new System.Drawing.Size(680, 420); 89 | this.tbCodeBox.TabIndex = 4; 90 | this.tbCodeBox.WordWrap = false; 91 | // 92 | // lblRegex 93 | // 94 | this.lblRegex.AutoSize = true; 95 | this.lblRegex.Location = new System.Drawing.Point(333, 44); 96 | this.lblRegex.Name = "lblRegex"; 97 | this.lblRegex.Size = new System.Drawing.Size(41, 15); 98 | this.lblRegex.TabIndex = 3; 99 | this.lblRegex.Text = "Regex:"; 100 | // 101 | // tbRegex 102 | // 103 | this.tbRegex.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 104 | | System.Windows.Forms.AnchorStyles.Right))); 105 | this.tbRegex.Location = new System.Drawing.Point(380, 41); 106 | this.tbRegex.Name = "tbRegex"; 107 | this.tbRegex.Size = new System.Drawing.Size(311, 23); 108 | this.tbRegex.TabIndex = 1; 109 | this.tbRegex.TextChanged += new System.EventHandler(this.RegexChanged); 110 | // 111 | // Main 112 | // 113 | this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); 114 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 115 | this.ClientSize = new System.Drawing.Size(704, 502); 116 | this.Controls.Add(this.lblRegex); 117 | this.Controls.Add(this.tbRegex); 118 | this.Controls.Add(this.tbCodeBox); 119 | this.Controls.Add(this.CBoxMode); 120 | this.Controls.Add(this.lblMode); 121 | this.Controls.Add(this.tbFilePath); 122 | this.Controls.Add(this.bntBrowser); 123 | this.MinimumSize = new System.Drawing.Size(720, 540); 124 | this.Name = "Main"; 125 | this.Text = "WrapperGenerator"; 126 | this.ResumeLayout(false); 127 | this.PerformLayout(); 128 | 129 | } 130 | 131 | #endregion 132 | 133 | private System.Windows.Forms.Button bntBrowser; 134 | private System.Windows.Forms.TextBox tbFilePath; 135 | private System.Windows.Forms.ComboBox CBoxMode; 136 | private System.Windows.Forms.Label lblMode; 137 | private System.Windows.Forms.TextBox tbCodeBox; 138 | private System.Windows.Forms.Label lblRegex; 139 | private System.Windows.Forms.TextBox tbRegex; 140 | } 141 | } -------------------------------------------------------------------------------- /Main.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Reflection; 7 | using System.Runtime.InteropServices; 8 | using System.Text.RegularExpressions; 9 | using System.Threading.Tasks; 10 | using System.Windows.Forms; 11 | using System.Windows.Forms.VisualStyles; 12 | 13 | namespace WrapperGenerator 14 | { 15 | public partial class Main : Form 16 | { 17 | IWrapperBuilder[] Builders = (from Asm in AppDomain.CurrentDomain.GetAssemblies() 18 | from Typ in Asm.GetTypes() 19 | where typeof(IWrapperBuilder).IsAssignableFrom(Typ) && !Typ.IsInterface 20 | select (IWrapperBuilder)Activator.CreateInstance(Typ)).ToArray(); 21 | 22 | IWrapperBuilder CurrentBuilder { 23 | get { 24 | return (from x in Builders where x.Name == CBoxMode.Text select x).Single(); 25 | } 26 | } 27 | public Main() 28 | { 29 | InitializeComponent(); 30 | 31 | foreach (var Builder in Builders) 32 | CBoxMode.Items.Add(Builder.Name); 33 | 34 | CBoxMode.SelectedIndex = 0; 35 | } 36 | 37 | private void SelectFileClicked(object sender, EventArgs e) 38 | { 39 | OpenFileDialog Dialog = new OpenFileDialog(); 40 | Dialog.Filter = "All Supported Files|*.c;*.h;*.dll|All Files|*.*"; 41 | Dialog.Title = "Select a File"; 42 | if (Dialog.ShowDialog() != DialogResult.OK) 43 | return; 44 | 45 | tbFilePath.Text = Dialog.FileName; 46 | BeginInvoke(new MethodInvoker(async () => await PostFileSelect(Dialog.FileName))); 47 | } 48 | 49 | private void ModeChanged(object sender, EventArgs e) 50 | { 51 | if (string.IsNullOrWhiteSpace(tbFilePath.Text) || !File.Exists(tbFilePath.Text)) 52 | return; 53 | BeginInvoke(new MethodInvoker(async () => await PostFileSelect(tbFilePath.Text))); 54 | } 55 | private void RegexChanged(object sender, EventArgs e) 56 | { 57 | if (string.IsNullOrWhiteSpace(tbFilePath.Text) || !File.Exists(tbFilePath.Text)) 58 | return; 59 | BeginInvoke(new MethodInvoker(async () => await PostFileSelect(tbFilePath.Text))); 60 | } 61 | 62 | string LastFile; 63 | async Task PostFileSelect(string FileName) 64 | { 65 | IntPtr Handler = IntPtr.Zero; 66 | string[] Symbols = new string[0]; 67 | 68 | if (Path.GetExtension(FileName).ToLower() == ".dll") 69 | { 70 | Symbols = GetExports(FileName); 71 | Handler = LoadLibraryW(FileName); 72 | 73 | if (Marshal.GetLastWin32Error() == 0x000000c1 && LastFile != FileName) 74 | MessageBox.Show("This Library isn't to the current architeture of the WrapperGenerator instance.", "WrapperGenerator", MessageBoxButtons.OK, MessageBoxIcon.Warning); 75 | 76 | LastFile = FileName; 77 | FileName = await Decompile(FileName); 78 | } 79 | 80 | if (!File.Exists(FileName)) 81 | { 82 | MessageBox.Show("Failed to Open the File:\n" + FileName, "WrapperGenerator", MessageBoxButtons.OK, MessageBoxIcon.Error); 83 | return; 84 | } 85 | 86 | string[] Source = await File.ReadAllLinesAsync(FileName); 87 | 88 | SourceParser Parser = new SourceParser(Source); 89 | var Functions = (from x in Parser.Parse() where 90 | !x.Name.StartsWith("sub_") && 91 | !x.Name.StartsWith("SEH_") 92 | select x).ToArray(); 93 | 94 | 95 | if (Handler != IntPtr.Zero) 96 | Functions = (from x in Functions where 97 | GetProcAddress(Handler, x.Name) != IntPtr.Zero || Symbols.Where(z => z.Equals(x.Name, StringComparison.InvariantCultureIgnoreCase)).Any() 98 | select x).ToArray(); 99 | 100 | if (tbRegex.Text.Trim() != string.Empty && IsValidRegex(tbRegex.Text)) 101 | Functions = (from x in Functions where 102 | Regex.IsMatch(x.Name, tbRegex.Text) || 103 | Regex.IsMatch(x.ToString(), tbRegex.Text) 104 | select x).ToArray(); 105 | 106 | var Builder = CurrentBuilder; 107 | 108 | tbCodeBox.Text = Builder.BuildWrapper(Path.GetFileNameWithoutExtension(FileName), Functions); 109 | } 110 | 111 | private async Task Decompile(string FileName) 112 | { 113 | string OutFile = Path.Combine(Path.GetDirectoryName(FileName), Path.GetFileNameWithoutExtension(FileName) + ".c"); 114 | if (File.Exists(OutFile)) 115 | return OutFile; 116 | 117 | Text = "Decompiling..."; 118 | Enabled = false; 119 | bool x64 = MessageBox.Show("This is a x64 application?", "Decompiler", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; 120 | string IDA = SearchIDA(x64); 121 | if (IDA == null) 122 | { 123 | MessageBox.Show("Please, Decompile your library using IDA PRO and try again.", "IDA PRO Not Found", MessageBoxButtons.OK, MessageBoxIcon.Information); 124 | return null; 125 | } 126 | 127 | //-Ohexrays:-nosave:-new:outfile:ALL -A "C:\Users\Marcus\Documents\My Games\Ustrack\恋×シンアイ彼女\koikake.exe" 128 | 129 | ProcessStartInfo ProcSI = new ProcessStartInfo(); 130 | ProcSI.FileName = IDA; 131 | ProcSI.Arguments = $"\"-Ohexrays:-nosave:-new:{Path.GetFileNameWithoutExtension(FileName)}:ALL\" -A \"{FileName}\""; 132 | ProcSI.WorkingDirectory = Path.GetDirectoryName(FileName); 133 | ProcSI.CreateNoWindow = true; 134 | ProcSI.UseShellExecute = false; 135 | 136 | var Proc = Process.Start(ProcSI); 137 | await Proc.WaitForExitAsync(); 138 | 139 | Text = "WrapperGenerator"; 140 | Enabled = true; 141 | 142 | return OutFile; 143 | } 144 | 145 | private string LastIDADir = null; 146 | private string SearchIDA(bool x64) 147 | { 148 | string[] Names = x64 ? new string[] { "idat64.exe", "idaw64.exe", "idaq64.exe", "ida64.exe" } : new string[] { "idat.exe", "idaw.exe", "idaq.exe", "ida.exe" }; 149 | if (LastIDADir != null) 150 | { 151 | foreach (string Name in Names) 152 | { 153 | string FullPath = Path.Combine(LastIDADir, Name); 154 | if (File.Exists(FullPath)) 155 | return FullPath; 156 | } 157 | } 158 | 159 | string X64ProgFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).Replace(" (x86)", ""); 160 | string X86ProgFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); 161 | 162 | X64ProgFiles = X64ProgFiles.Substring(3); 163 | X86ProgFiles = X86ProgFiles.Substring(3); 164 | 165 | List AllProgramFiles = new List(); 166 | 167 | foreach (DriveInfo Drive in DriveInfo.GetDrives()) 168 | { 169 | string ProgFilesPath = Path.Combine(Drive.RootDirectory.FullName, X64ProgFiles); 170 | if (Directory.Exists(ProgFilesPath)) 171 | AllProgramFiles.AddRange(Directory.GetDirectories(ProgFilesPath)); 172 | 173 | 174 | ProgFilesPath = Path.Combine(Drive.RootDirectory.FullName, X86ProgFiles); 175 | if (Directory.Exists(ProgFilesPath)) 176 | AllProgramFiles.AddRange(Directory.GetDirectories(ProgFilesPath)); 177 | } 178 | 179 | foreach (string Dir in AllProgramFiles) 180 | { 181 | foreach (string Name in Names) 182 | { 183 | LastIDADir = Dir; 184 | string FullPath = Path.Combine(Dir, Name); 185 | if (File.Exists(FullPath)) 186 | return FullPath; 187 | } 188 | } 189 | 190 | return null; 191 | } 192 | 193 | private static bool IsValidRegex(string pattern) 194 | { 195 | if (string.IsNullOrEmpty(pattern)) return false; 196 | 197 | try 198 | { 199 | Regex.Match("", pattern); 200 | } 201 | catch (ArgumentException) 202 | { 203 | return false; 204 | } 205 | 206 | return true; 207 | } 208 | 209 | private static string[] GetExports(string Module) 210 | { 211 | IntPtr hCurrentProcess = Process.GetCurrentProcess().Handle; 212 | 213 | ulong baseOfDll; 214 | bool status; 215 | 216 | // Initialize sym. 217 | // Please read the remarks on MSDN for the hProcess 218 | // parameter. 219 | status = SymInitialize(hCurrentProcess, null, false); 220 | 221 | if (status == false) 222 | { 223 | return null; 224 | } 225 | 226 | baseOfDll = SymLoadModuleEx(hCurrentProcess,IntPtr.Zero, Module, null, 0, 0, IntPtr.Zero, 0); 227 | 228 | if (baseOfDll == 0) 229 | { 230 | Console.Out.WriteLine("Failed to load module."); 231 | SymCleanup(hCurrentProcess); 232 | return null; 233 | } 234 | 235 | List Exports = new List(); 236 | // Enumerate symbols. For every symbol the 237 | // callback method EnumSyms is called. 238 | SymEnumerateSymbols64(hCurrentProcess, baseOfDll, (Name, Addr, Size, Context) => 239 | { 240 | Exports.Add(Name); 241 | return true; 242 | }, IntPtr.Zero); 243 | 244 | // Cleanup. 245 | SymCleanup(hCurrentProcess); 246 | 247 | return Exports.ToArray(); 248 | } 249 | [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] 250 | static extern IntPtr LoadLibraryW(string FileName); 251 | 252 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 253 | static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 254 | 255 | [DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)] 256 | [return: MarshalAs(UnmanagedType.Bool)] 257 | public static extern bool SymInitialize(IntPtr hProcess, string UserSearchPath, [MarshalAs(UnmanagedType.Bool)]bool fInvadeProcess); 258 | 259 | [DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)] 260 | [return: MarshalAs(UnmanagedType.Bool)] 261 | public static extern bool SymCleanup(IntPtr hProcess); 262 | 263 | [DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)] 264 | public static extern ulong SymLoadModuleEx(IntPtr hProcess, IntPtr hFile, 265 | string ImageName, string ModuleName, long BaseOfDll, int DllSize, IntPtr Data, int Flags); 266 | 267 | [DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)] 268 | [return: MarshalAs(UnmanagedType.Bool)] 269 | public static extern bool SymEnumerateSymbols64(IntPtr hProcess, ulong BaseOfDll, SymEnumerateSymbolsProc64Delegate EnumSymbolsCallback, IntPtr UserContext); 270 | 271 | //[UnmanagedFunctionPointer(CallingConvention.StdCall)] 272 | public delegate bool SymEnumerateSymbolsProc64Delegate(string SymbolName, ulong SymbolAddress, uint SymbolSize, IntPtr UserContext); 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /Main.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | text/microsoft-resx 51 | 52 | 53 | 2.0 54 | 55 | 56 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 57 | 58 | 59 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 60 | 61 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using System.Windows.Forms; 6 | 7 | namespace WrapperGenerator 8 | { 9 | static class Program 10 | { 11 | /// 12 | /// The main entry point for the application. 13 | /// 14 | [STAThread] 15 | static void Main() 16 | { 17 | Application.SetHighDpiMode(HighDpiMode.SystemAware); 18 | Application.EnableVisualStyles(); 19 | Application.SetCompatibleTextRenderingDefault(false); 20 | Application.Run(new Main()); 21 | } 22 | 23 | 24 | public static void SetUnsafeMode(this Function[] Exports, bool Unsafe) { 25 | for (int i = 0; i < Exports.Length; i++) 26 | { 27 | Exports[i].AnonType = Unsafe; 28 | Exports[i].Unsafe = Unsafe; 29 | for (int x = 0; x < Exports[i].Arguments.Length; x++) 30 | { 31 | Exports[i].Arguments[x].Unsafe = Unsafe; 32 | Exports[i].Arguments[x].AnonType = Unsafe; 33 | } 34 | } 35 | } 36 | public static void SetAnonType(this Function[] Exports, bool Anon) 37 | { 38 | for (int i = 0; i < Exports.Length; i++) 39 | { 40 | Exports[i].AnonType = Anon; 41 | for (int x = 0; x < Exports[i].Arguments.Length; x++) 42 | { 43 | Exports[i].Arguments[x].AnonType = Anon; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # WrapperGenerator 2 | My utility to create a C# dll wrapper class (Using DLLExport) automatically with help of the IDA PRO 3 | 4 | It's easy to implement your own code generator as well. 5 | 6 | ## By Marcussacana 7 | 8 | # Sample genareted code 9 | ```csharp 10 | using System; 11 | using System.IO; 12 | using System.Reflection; 13 | using System.Runtime.InteropServices; 14 | 15 | namespace Wrapper 16 | { 17 | /// 18 | /// This is a wrapper to the d3d10.dll 19 | /// 20 | public static class d3d10 21 | { 22 | 23 | static string CurrentDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); 24 | static string CurrentDllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 25 | static string RealDllPath = null; 26 | static bool WOW64 => !Environment.Is64BitProcess && Environment.Is64BitOperatingSystem; 27 | 28 | public static IntPtr RealHandler; 29 | static d3d10() 30 | { 31 | if (RealHandler != IntPtr.Zero) 32 | return; 33 | 34 | RealHandler = LoadLibrary(CurrentDllName); 35 | 36 | if (RealHandler == IntPtr.Zero) 37 | Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED 38 | 39 | dD3D10CreateDevice = GetDelegate(RealHandler, "D3D10CreateDevice", false); 40 | dRevertToOldImplementation = GetDelegate(RealHandler, "RevertToOldImplementation", false); 41 | dD3D10CreateDeviceAndSwapChain = GetDelegate(RealHandler, "D3D10CreateDeviceAndSwapChain", false); 42 | dD3D10CreateBlob = GetDelegate(RealHandler, "D3D10CreateBlob", false); 43 | dD3D10CompileShader = GetDelegate(RealHandler, "D3D10CompileShader", false); 44 | dD3D10GetPixelShaderProfile = GetDelegate(RealHandler, "D3D10GetPixelShaderProfile", false); 45 | dD3D10GetVertexShaderProfile = GetDelegate(RealHandler, "D3D10GetVertexShaderProfile", false); 46 | dD3D10GetGeometryShaderProfile = GetDelegate(RealHandler, "D3D10GetGeometryShaderProfile", false); 47 | dD3D10GetShaderDebugInfo = GetDelegate(RealHandler, "D3D10GetShaderDebugInfo", false); 48 | dD3D10PreprocessShader = GetDelegate(RealHandler, "D3D10PreprocessShader", false); 49 | dD3D10GetInputSignatureBlob = GetDelegate(RealHandler, "D3D10GetInputSignatureBlob", false); 50 | dD3D10GetOutputSignatureBlob = GetDelegate(RealHandler, "D3D10GetOutputSignatureBlob", false); 51 | dD3D10GetInputAndOutputSignatureBlob = GetDelegate(RealHandler, "D3D10GetInputAndOutputSignatureBlob", false); 52 | dD3D10CreateEffectFromMemory = GetDelegate(RealHandler, "D3D10CreateEffectFromMemory", false); 53 | dD3D10CreateEffectPoolFromMemory = GetDelegate(RealHandler, "D3D10CreateEffectPoolFromMemory", false); 54 | dD3D10CompileEffectFromMemory = GetDelegate(RealHandler, "D3D10CompileEffectFromMemory", false); 55 | dD3D10ReflectShader = GetDelegate(RealHandler, "D3D10ReflectShader", false); 56 | dD3D10DisassembleEffect = GetDelegate(RealHandler, "D3D10DisassembleEffect", false); 57 | dD3D10CreateStateBlock = GetDelegate(RealHandler, "D3D10CreateStateBlock", false); 58 | dD3D10StateBlockMaskUnion = GetDelegate(RealHandler, "D3D10StateBlockMaskUnion", false); 59 | dD3D10StateBlockMaskIntersect = GetDelegate(RealHandler, "D3D10StateBlockMaskIntersect", false); 60 | dD3D10StateBlockMaskDifference = GetDelegate(RealHandler, "D3D10StateBlockMaskDifference", false); 61 | dD3D10StateBlockMaskEnableCapture = GetDelegate(RealHandler, "D3D10StateBlockMaskEnableCapture", false); 62 | dD3D10StateBlockMaskDisableCapture = GetDelegate(RealHandler, "D3D10StateBlockMaskDisableCapture", false); 63 | dD3D10StateBlockMaskEnableAll = GetDelegate(RealHandler, "D3D10StateBlockMaskEnableAll", false); 64 | dD3D10StateBlockMaskDisableAll = GetDelegate(RealHandler, "D3D10StateBlockMaskDisableAll", false); 65 | dD3D10StateBlockMaskGetSetting = GetDelegate(RealHandler, "D3D10StateBlockMaskGetSetting", false); 66 | 67 | } 68 | 69 | [DllExport(CallingConvention = CallingConvention.StdCall)] 70 | public static IntPtr D3D10CreateDevice(IntPtr pAdapter, IntPtr DriverType, IntPtr Software, uint Flags, uint SDKVersion, IntPtr ppDevice) 71 | { 72 | return dD3D10CreateDevice(pAdapter, DriverType, Software, Flags, SDKVersion, ppDevice); 73 | } 74 | 75 | [DllExport(CallingConvention = CallingConvention.StdCall)] 76 | public static uint RevertToOldImplementation() 77 | { 78 | return dRevertToOldImplementation(); 79 | } 80 | 81 | [DllExport(CallingConvention = CallingConvention.StdCall)] 82 | public static IntPtr D3D10CreateDeviceAndSwapChain(IntPtr pAdapter, IntPtr DriverType, IntPtr Software, uint Flags, uint SDKVersion, IntPtr pSwapChainDesc, IntPtr ppSwapChain, IntPtr ppDevice) 83 | { 84 | return dD3D10CreateDeviceAndSwapChain(pAdapter, DriverType, Software, Flags, SDKVersion, pSwapChainDesc, ppSwapChain, ppDevice); 85 | } 86 | 87 | [DllExport(CallingConvention = CallingConvention.StdCall)] 88 | public static IntPtr D3D10CreateBlob(IntPtr NumBytes, IntPtr ppBuffer) 89 | { 90 | return dD3D10CreateBlob(NumBytes, ppBuffer); 91 | } 92 | 93 | [DllExport(CallingConvention = CallingConvention.StdCall)] 94 | public static IntPtr D3D10CompileShader(IntPtr pSrcData, IntPtr SrcDataLen, IntPtr pFileName, IntPtr pDefines, IntPtr pInclude, IntPtr pFunctionName, IntPtr pProfile, uint Flags, IntPtr ppShader, IntPtr ppErrorMsgs) 95 | { 96 | return dD3D10CompileShader(pSrcData, SrcDataLen, pFileName, pDefines, pInclude, pFunctionName, pProfile, Flags, ppShader, ppErrorMsgs); 97 | } 98 | 99 | [DllExport(CallingConvention = CallingConvention.StdCall)] 100 | public static IntPtr D3D10GetPixelShaderProfile(IntPtr pDevice) 101 | { 102 | return dD3D10GetPixelShaderProfile(pDevice); 103 | } 104 | 105 | [DllExport(CallingConvention = CallingConvention.StdCall)] 106 | public static IntPtr D3D10GetVertexShaderProfile(IntPtr pDevice) 107 | { 108 | return dD3D10GetVertexShaderProfile(pDevice); 109 | } 110 | 111 | [DllExport(CallingConvention = CallingConvention.StdCall)] 112 | public static IntPtr D3D10GetGeometryShaderProfile(IntPtr pDevice) 113 | { 114 | return dD3D10GetGeometryShaderProfile(pDevice); 115 | } 116 | 117 | [DllExport(CallingConvention = CallingConvention.StdCall)] 118 | public static IntPtr D3D10GetShaderDebugInfo(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppDebugInfo) 119 | { 120 | return dD3D10GetShaderDebugInfo(pShaderBytecode, BytecodeLength, ppDebugInfo); 121 | } 122 | 123 | [DllExport(CallingConvention = CallingConvention.StdCall)] 124 | public static IntPtr D3D10PreprocessShader(IntPtr pSrcData, IntPtr SrcDataSize, IntPtr pFileName, IntPtr pDefines, IntPtr pInclude, IntPtr ppShaderText, IntPtr ppErrorMsgs) 125 | { 126 | return dD3D10PreprocessShader(pSrcData, SrcDataSize, pFileName, pDefines, pInclude, ppShaderText, ppErrorMsgs); 127 | } 128 | 129 | [DllExport(CallingConvention = CallingConvention.StdCall)] 130 | public static IntPtr D3D10GetInputSignatureBlob(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppSignatureBlob) 131 | { 132 | return dD3D10GetInputSignatureBlob(pShaderBytecode, BytecodeLength, ppSignatureBlob); 133 | } 134 | 135 | [DllExport(CallingConvention = CallingConvention.StdCall)] 136 | public static IntPtr D3D10GetOutputSignatureBlob(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppSignatureBlob) 137 | { 138 | return dD3D10GetOutputSignatureBlob(pShaderBytecode, BytecodeLength, ppSignatureBlob); 139 | } 140 | 141 | [DllExport(CallingConvention = CallingConvention.StdCall)] 142 | public static IntPtr D3D10GetInputAndOutputSignatureBlob(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppSignatureBlob) 143 | { 144 | return dD3D10GetInputAndOutputSignatureBlob(pShaderBytecode, BytecodeLength, ppSignatureBlob); 145 | } 146 | 147 | [DllExport(CallingConvention = CallingConvention.StdCall)] 148 | public static IntPtr D3D10CreateEffectFromMemory(IntPtr pData, IntPtr DataLength, uint FXFlags, IntPtr pDevice, IntPtr pEffectPool, IntPtr ppEffect) 149 | { 150 | return dD3D10CreateEffectFromMemory(pData, DataLength, FXFlags, pDevice, pEffectPool, ppEffect); 151 | } 152 | 153 | [DllExport(CallingConvention = CallingConvention.StdCall)] 154 | public static IntPtr D3D10CreateEffectPoolFromMemory(IntPtr pData, IntPtr DataLength, uint FXFlags, IntPtr pDevice, IntPtr ppEffectPool) 155 | { 156 | return dD3D10CreateEffectPoolFromMemory(pData, DataLength, FXFlags, pDevice, ppEffectPool); 157 | } 158 | 159 | [DllExport(CallingConvention = CallingConvention.StdCall)] 160 | public static IntPtr D3D10CompileEffectFromMemory(IntPtr pData, IntPtr DataLength, IntPtr pSrcFileName, IntPtr pDefines, IntPtr pInclude, uint HLSLFlags, uint FXFlags, IntPtr ppCompiledEffect, IntPtr ppErrors) 161 | { 162 | return dD3D10CompileEffectFromMemory(pData, DataLength, pSrcFileName, pDefines, pInclude, HLSLFlags, FXFlags, ppCompiledEffect, ppErrors); 163 | } 164 | 165 | [DllExport(CallingConvention = CallingConvention.StdCall)] 166 | public static IntPtr D3D10ReflectShader(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppReflector) 167 | { 168 | return dD3D10ReflectShader(pShaderBytecode, BytecodeLength, ppReflector); 169 | } 170 | 171 | [DllExport(CallingConvention = CallingConvention.StdCall)] 172 | public static IntPtr D3D10DisassembleEffect(IntPtr pEffect, bool EnableColorCode, IntPtr ppDisassembly) 173 | { 174 | return dD3D10DisassembleEffect(pEffect, EnableColorCode, ppDisassembly); 175 | } 176 | 177 | [DllExport(CallingConvention = CallingConvention.StdCall)] 178 | public static IntPtr D3D10CreateStateBlock(IntPtr pDevice, IntPtr pStateBlockMask, IntPtr ppStateBlock) 179 | { 180 | return dD3D10CreateStateBlock(pDevice, pStateBlockMask, ppStateBlock); 181 | } 182 | 183 | [DllExport(CallingConvention = CallingConvention.StdCall)] 184 | public static IntPtr D3D10StateBlockMaskUnion(IntPtr pA, IntPtr pB, IntPtr pResult) 185 | { 186 | return dD3D10StateBlockMaskUnion(pA, pB, pResult); 187 | } 188 | 189 | [DllExport(CallingConvention = CallingConvention.StdCall)] 190 | public static IntPtr D3D10StateBlockMaskIntersect(IntPtr pA, IntPtr pB, IntPtr pResult) 191 | { 192 | return dD3D10StateBlockMaskIntersect(pA, pB, pResult); 193 | } 194 | 195 | [DllExport(CallingConvention = CallingConvention.StdCall)] 196 | public static IntPtr D3D10StateBlockMaskDifference(IntPtr pA, IntPtr pB, IntPtr pResult) 197 | { 198 | return dD3D10StateBlockMaskDifference(pA, pB, pResult); 199 | } 200 | 201 | [DllExport(CallingConvention = CallingConvention.StdCall)] 202 | public static IntPtr D3D10StateBlockMaskEnableCapture(IntPtr pMask, IntPtr StateType, uint RangeStart, uint RangeLength) 203 | { 204 | return dD3D10StateBlockMaskEnableCapture(pMask, StateType, RangeStart, RangeLength); 205 | } 206 | 207 | [DllExport(CallingConvention = CallingConvention.StdCall)] 208 | public static IntPtr D3D10StateBlockMaskDisableCapture(IntPtr pMask, IntPtr StateType, uint RangeStart, uint RangeLength) 209 | { 210 | return dD3D10StateBlockMaskDisableCapture(pMask, StateType, RangeStart, RangeLength); 211 | } 212 | 213 | [DllExport(CallingConvention = CallingConvention.StdCall)] 214 | public static IntPtr D3D10StateBlockMaskEnableAll(IntPtr pMask) 215 | { 216 | return dD3D10StateBlockMaskEnableAll(pMask); 217 | } 218 | 219 | [DllExport(CallingConvention = CallingConvention.StdCall)] 220 | public static IntPtr D3D10StateBlockMaskDisableAll(IntPtr pMask) 221 | { 222 | return dD3D10StateBlockMaskDisableAll(pMask); 223 | } 224 | 225 | [DllExport(CallingConvention = CallingConvention.StdCall)] 226 | public static bool D3D10StateBlockMaskGetSetting(IntPtr pMask, IntPtr StateType, uint Entry) 227 | { 228 | return dD3D10StateBlockMaskGetSetting(pMask, StateType, Entry); 229 | } 230 | 231 | 232 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 233 | internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 234 | 235 | [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] 236 | internal static extern IntPtr LoadLibraryW(string lpFileName); 237 | 238 | internal static IntPtr LoadLibrary(string lpFileName) 239 | { 240 | string DllPath = lpFileName; 241 | if (lpFileName.Length < 2 || lpFileName[1] != ':') 242 | { 243 | string DLL = Path.GetFileNameWithoutExtension(lpFileName); 244 | DllPath = Path.Combine(Environment.CurrentDirectory, $"{DLL}_ori.dll"); 245 | if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower()) 246 | DllPath = Path.Combine(Environment.CurrentDirectory, $"{DLL}.dll"); 247 | if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower()) 248 | DllPath = Path.Combine(CurrentDllPath, $"{DLL}_ori.dll"); 249 | if (!File.Exists(DllPath) && CurrentDllName != lpFileName.ToLower()) 250 | DllPath = Path.Combine(CurrentDllPath, $"{DLL}.dll.ori"); 251 | if (!File.Exists(DllPath)) 252 | { 253 | DllPath = WOW64 ? Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) : Environment.SystemDirectory; 254 | DllPath = Path.Combine(DllPath, $"{DLL}.dll"); 255 | } 256 | } 257 | RealDllPath = DllPath; 258 | 259 | IntPtr Handler = LoadLibraryW(DllPath); 260 | 261 | if (Handler == IntPtr.Zero) 262 | Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED 263 | 264 | return Handler; 265 | } 266 | 267 | internal static T GetDelegate(IntPtr Handler, string Function, bool Optional = true) where T : Delegate 268 | { 269 | IntPtr Address = GetProcAddress(Handler, Function); 270 | if (Address == IntPtr.Zero) 271 | { 272 | if (Optional) 273 | { 274 | return null; 275 | } 276 | Environment.Exit(0x505);//ERROR_DELAY_LOAD_FAILED 277 | } 278 | return (T)Marshal.GetDelegateForFunctionPointer(Address, typeof(T)); 279 | } 280 | 281 | static tD3D10CreateDevice dD3D10CreateDevice; 282 | static tRevertToOldImplementation dRevertToOldImplementation; 283 | static tD3D10CreateDeviceAndSwapChain dD3D10CreateDeviceAndSwapChain; 284 | static tD3D10CreateBlob dD3D10CreateBlob; 285 | static tD3D10CompileShader dD3D10CompileShader; 286 | static tD3D10GetPixelShaderProfile dD3D10GetPixelShaderProfile; 287 | static tD3D10GetVertexShaderProfile dD3D10GetVertexShaderProfile; 288 | static tD3D10GetGeometryShaderProfile dD3D10GetGeometryShaderProfile; 289 | static tD3D10GetShaderDebugInfo dD3D10GetShaderDebugInfo; 290 | static tD3D10PreprocessShader dD3D10PreprocessShader; 291 | static tD3D10GetInputSignatureBlob dD3D10GetInputSignatureBlob; 292 | static tD3D10GetOutputSignatureBlob dD3D10GetOutputSignatureBlob; 293 | static tD3D10GetInputAndOutputSignatureBlob dD3D10GetInputAndOutputSignatureBlob; 294 | static tD3D10CreateEffectFromMemory dD3D10CreateEffectFromMemory; 295 | static tD3D10CreateEffectPoolFromMemory dD3D10CreateEffectPoolFromMemory; 296 | static tD3D10CompileEffectFromMemory dD3D10CompileEffectFromMemory; 297 | static tD3D10ReflectShader dD3D10ReflectShader; 298 | static tD3D10DisassembleEffect dD3D10DisassembleEffect; 299 | static tD3D10CreateStateBlock dD3D10CreateStateBlock; 300 | static tD3D10StateBlockMaskUnion dD3D10StateBlockMaskUnion; 301 | static tD3D10StateBlockMaskIntersect dD3D10StateBlockMaskIntersect; 302 | static tD3D10StateBlockMaskDifference dD3D10StateBlockMaskDifference; 303 | static tD3D10StateBlockMaskEnableCapture dD3D10StateBlockMaskEnableCapture; 304 | static tD3D10StateBlockMaskDisableCapture dD3D10StateBlockMaskDisableCapture; 305 | static tD3D10StateBlockMaskEnableAll dD3D10StateBlockMaskEnableAll; 306 | static tD3D10StateBlockMaskDisableAll dD3D10StateBlockMaskDisableAll; 307 | static tD3D10StateBlockMaskGetSetting dD3D10StateBlockMaskGetSetting; 308 | 309 | delegate IntPtr tD3D10CreateDevice(IntPtr pAdapter, IntPtr DriverType, IntPtr Software, uint Flags, uint SDKVersion, IntPtr ppDevice); 310 | delegate uint tRevertToOldImplementation(); 311 | delegate IntPtr tD3D10CreateDeviceAndSwapChain(IntPtr pAdapter, IntPtr DriverType, IntPtr Software, uint Flags, uint SDKVersion, IntPtr pSwapChainDesc, IntPtr ppSwapChain, IntPtr ppDevice); 312 | delegate IntPtr tD3D10CreateBlob(IntPtr NumBytes, IntPtr ppBuffer); 313 | delegate IntPtr tD3D10CompileShader(IntPtr pSrcData, IntPtr SrcDataLen, IntPtr pFileName, IntPtr pDefines, IntPtr pInclude, IntPtr pFunctionName, IntPtr pProfile, uint Flags, IntPtr ppShader, IntPtr ppErrorMsgs); 314 | delegate IntPtr tD3D10GetPixelShaderProfile(IntPtr pDevice); 315 | delegate IntPtr tD3D10GetVertexShaderProfile(IntPtr pDevice); 316 | delegate IntPtr tD3D10GetGeometryShaderProfile(IntPtr pDevice); 317 | delegate IntPtr tD3D10GetShaderDebugInfo(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppDebugInfo); 318 | delegate IntPtr tD3D10PreprocessShader(IntPtr pSrcData, IntPtr SrcDataSize, IntPtr pFileName, IntPtr pDefines, IntPtr pInclude, IntPtr ppShaderText, IntPtr ppErrorMsgs); 319 | delegate IntPtr tD3D10GetInputSignatureBlob(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppSignatureBlob); 320 | delegate IntPtr tD3D10GetOutputSignatureBlob(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppSignatureBlob); 321 | delegate IntPtr tD3D10GetInputAndOutputSignatureBlob(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppSignatureBlob); 322 | delegate IntPtr tD3D10CreateEffectFromMemory(IntPtr pData, IntPtr DataLength, uint FXFlags, IntPtr pDevice, IntPtr pEffectPool, IntPtr ppEffect); 323 | delegate IntPtr tD3D10CreateEffectPoolFromMemory(IntPtr pData, IntPtr DataLength, uint FXFlags, IntPtr pDevice, IntPtr ppEffectPool); 324 | delegate IntPtr tD3D10CompileEffectFromMemory(IntPtr pData, IntPtr DataLength, IntPtr pSrcFileName, IntPtr pDefines, IntPtr pInclude, uint HLSLFlags, uint FXFlags, IntPtr ppCompiledEffect, IntPtr ppErrors); 325 | delegate IntPtr tD3D10ReflectShader(IntPtr pShaderBytecode, IntPtr BytecodeLength, IntPtr ppReflector); 326 | delegate IntPtr tD3D10DisassembleEffect(IntPtr pEffect, bool EnableColorCode, IntPtr ppDisassembly); 327 | delegate IntPtr tD3D10CreateStateBlock(IntPtr pDevice, IntPtr pStateBlockMask, IntPtr ppStateBlock); 328 | delegate IntPtr tD3D10StateBlockMaskUnion(IntPtr pA, IntPtr pB, IntPtr pResult); 329 | delegate IntPtr tD3D10StateBlockMaskIntersect(IntPtr pA, IntPtr pB, IntPtr pResult); 330 | delegate IntPtr tD3D10StateBlockMaskDifference(IntPtr pA, IntPtr pB, IntPtr pResult); 331 | delegate IntPtr tD3D10StateBlockMaskEnableCapture(IntPtr pMask, IntPtr StateType, uint RangeStart, uint RangeLength); 332 | delegate IntPtr tD3D10StateBlockMaskDisableCapture(IntPtr pMask, IntPtr StateType, uint RangeStart, uint RangeLength); 333 | delegate IntPtr tD3D10StateBlockMaskEnableAll(IntPtr pMask); 334 | delegate IntPtr tD3D10StateBlockMaskDisableAll(IntPtr pMask); 335 | delegate bool tD3D10StateBlockMaskGetSetting(IntPtr pMask, IntPtr StateType, uint Entry); 336 | 337 | } 338 | } 339 | ``` 340 | -------------------------------------------------------------------------------- /SourceParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | 7 | namespace WrapperGenerator 8 | { 9 | internal class SourceParser 10 | { 11 | string[] Lines; 12 | public SourceParser(string[] Lines) 13 | { 14 | this.Lines = Lines; 15 | } 16 | 17 | public Function[] Parse() 18 | { 19 | bool Commented = false; 20 | List Functions = new List(); 21 | for (int i = 0; i < Lines.Length; i++) 22 | { 23 | string Line = Lines[i].Trim(); 24 | 25 | if (Line.Contains("*/")) 26 | { 27 | Commented = false; 28 | Line = Line.Substring(Line.IndexOf("*/")).Trim(); 29 | } 30 | 31 | if (Commented) 32 | continue; 33 | 34 | if (Line.Contains("/*")) 35 | { 36 | Commented = true; 37 | Line = Line.Substring(0, Line.IndexOf("/*")).Trim(); 38 | } 39 | 40 | if (Line.Contains("//")) 41 | Line = Line.Substring(0, Line.IndexOf("//")).Trim(); 42 | if (string.IsNullOrWhiteSpace(Line)) 43 | continue; 44 | 45 | if (Line.EndsWith(";") && !(Line.Contains("__stdcall") || Line.Contains("__fastcall") || Line.Contains("__thiscall"))) 46 | continue; 47 | 48 | if (Line.EndsWith(";")) 49 | Line = Line.Substring(0, Line.Length - 1); 50 | 51 | if (!Line.Contains("(") || !Line.EndsWith(")")) 52 | continue; 53 | if (Line.StartsWith("#")) 54 | continue; 55 | if (Line.StartsWith("&& ") || Line.StartsWith("|| ")) 56 | continue; 57 | if (Line.EndsWith(",") && (!Line.Contains(" ") || Line.Contains("\""))) 58 | continue; 59 | if (Line.Contains("=")) 60 | continue; 61 | //int __thiscall sub_100BB7B0(int this, LPVOID lpBuffer, int a3, int a4, LPDWORD lpNumberOfBytesRead) 62 | try 63 | { 64 | Function FuncInfo = new Function(); 65 | FuncInfo.Line = i; 66 | FuncInfo.Type = Line.Substring(0, Line.IndexOf("(")); 67 | if (FuncInfo.Calling == null) 68 | continue; 69 | 70 | FuncInfo.Name = FuncInfo.Type.Split(' ').Last(); 71 | FuncInfo.Type = FuncInfo.Type.Substring(0, FuncInfo.Type.LastIndexOf(" ")); 72 | 73 | while (FuncInfo.Name.StartsWith("*")) 74 | { 75 | FuncInfo.Type += '*'; 76 | FuncInfo.Name = FuncInfo.Name.Substring(1); 77 | } 78 | 79 | if (FuncInfo.Name.Contains("@<")) 80 | FuncInfo.Name = FuncInfo.Name.Substring(0, FuncInfo.Name.IndexOf("@<")); 81 | 82 | FuncInfo.Arguments = ParseArguments(Line.Substring(Line.IndexOf("("))); 83 | 84 | if (string.IsNullOrWhiteSpace(FuncInfo.Name)) 85 | continue; 86 | 87 | Functions.Add(FuncInfo); 88 | } 89 | catch 90 | { 91 | continue; 92 | } 93 | } 94 | 95 | List Additionals = new List(); 96 | foreach (var Function in Functions) 97 | { 98 | if (Function.Name.Contains("Stub") && !Functions.Where(x => Function.Name.Replace("Stub", "") == x.Name).Any()) 99 | { 100 | Additionals.Add(new Function() 101 | { 102 | AnonType = Function.AnonType, 103 | Arguments = Function.Arguments, 104 | Line = Function.Line, 105 | Name = Function.Name.Replace("Stub", ""), 106 | Type = Function.Type, 107 | Unsafe = Function.Unsafe 108 | }); 109 | } 110 | } 111 | 112 | return Functions.Concat(Additionals).GroupBy(x=>x.Name).Select(grp => grp.First()).ToArray(); 113 | } 114 | 115 | private Argument[] ParseArguments(string Source) 116 | { 117 | //(__int64 (***a1)(void)) 118 | //(__int64 (__fastcall ***a1)(_QWORD, signed __int64)) 119 | //(__int64 a1@, __int64 a2@, float *a3@, double a4@) 120 | //(int this, LPVOID lpBuffer, int a3, int a4, LPDWORD lpNumberOfBytesRead) 121 | if (Source.StartsWith("(") && Source.EndsWith(")")) 122 | Source = Source.Substring(1, Source.Length - 2); 123 | List Arguments = new List(); 124 | Argument Arg = new Argument(); 125 | 126 | int Group = 0; 127 | string Buffer = string.Empty; 128 | foreach (char c in Source) 129 | { 130 | switch (c) 131 | { 132 | case ' ': 133 | if (Group != 0) 134 | goto default; 135 | Arg.Type += Buffer + c; 136 | Buffer = string.Empty; 137 | break; 138 | case ',': 139 | if (Group != 0) 140 | goto default; 141 | CloseArg(ref Arg, Buffer); 142 | Buffer = string.Empty; 143 | Arguments.Add(Arg); 144 | Arg = new Argument(); 145 | break; 146 | case '(': 147 | Group++; 148 | goto default; 149 | case ')': 150 | Group--; 151 | goto default; 152 | default: 153 | ; 154 | Buffer += c; 155 | break; 156 | } 157 | } 158 | 159 | if (!string.IsNullOrWhiteSpace(Buffer)) 160 | { 161 | CloseArg(ref Arg, Buffer); 162 | Arguments.Add(Arg); 163 | } 164 | 165 | 166 | return Arguments.ToArray(); 167 | } 168 | 169 | private void CloseArg(ref Argument Arg, string Buffer) 170 | { 171 | Arg.Type = Arg.Type.Trim(); 172 | Arg.Name = Buffer; 173 | 174 | if (Arg.Name.Contains(")("))//Func Argument 175 | { 176 | Arg.Type = "void*"; 177 | Arg.Name = Arg.Name.Substring(0, Arg.Name.IndexOf(")(")); 178 | Arg.Name = Arg.Name.Substring(Arg.Name.LastIndexOf("(") + 1);//__fastcall ***a1 179 | Arg.Name = Arg.Name.Split(' ').Last(); 180 | } 181 | 182 | while (Arg.Name.StartsWith('*'))//Ptr Argument 183 | { 184 | Arg.Type += '*'; 185 | Arg.Name = Arg.Name.Substring(1); 186 | } 187 | 188 | if (Arg.Name.Contains("@<"))//FastCall Register 189 | Arg.Name = Arg.Name.Substring(0, Arg.Name.IndexOf("@<")); 190 | } 191 | } 192 | 193 | struct Function 194 | { 195 | public bool Unsafe; 196 | public bool AnonType; 197 | public int Line; 198 | public string Type; 199 | public string Name; 200 | 201 | public string ReturnType 202 | { 203 | get 204 | { 205 | if (Type.ToLower().Contains("void")) 206 | return "void"; 207 | 208 | if (!AnonType) 209 | { 210 | if (Type.ToLower().Contains("bool")) 211 | return "bool"; 212 | if (Type.ToLower().Contains("signed int")) 213 | return "int"; 214 | if (Type.ToLower().Contains("int")) 215 | return "uint"; 216 | if (Type.ToLower().Contains("dword")) 217 | return "uint"; 218 | } 219 | 220 | return Unsafe ? "void*" : "IntPtr"; 221 | } 222 | } 223 | 224 | public string ArgumentNames 225 | { 226 | get 227 | { 228 | var Str = string.Empty; 229 | foreach (var Arg in Arguments) 230 | { 231 | Str += $"{Arg.Name}, "; 232 | } 233 | return Str.TrimEnd(' ', ','); 234 | } 235 | } 236 | public CallingConvention? Calling 237 | { 238 | get 239 | { 240 | if (Type.ToLower().Contains("stdcall")) 241 | return CallingConvention.StdCall; 242 | if (Type.ToLower().Contains("cdecl")) 243 | return CallingConvention.Cdecl; 244 | if (Type.ToLower().Contains("thiscall")) 245 | return CallingConvention.ThisCall; 246 | if (Type.ToLower().Contains("fastcall")) 247 | return CallingConvention.FastCall; 248 | if (Type.ToLower().Contains("winapi")) 249 | return CallingConvention.Winapi; 250 | return CallingConvention.StdCall; 251 | } 252 | } 253 | 254 | public string Charset 255 | { 256 | get 257 | { 258 | string Charset = "Auto"; 259 | if (Name.EndsWith("A")) 260 | Charset = "Ansi"; 261 | if (Name.EndsWith("W")) 262 | Charset = "Unicode"; 263 | return Charset; 264 | } 265 | } 266 | 267 | public Argument[] Arguments; 268 | 269 | public override string ToString() 270 | { 271 | string Args = string.Empty; 272 | foreach (var Arg in Arguments) 273 | { 274 | Args += $"{Arg.ReturnType} {Arg.Name}, "; 275 | } 276 | 277 | Args = Args.TrimEnd(' ', ','); 278 | return (Unsafe ? "unsafe " : "") + $"{ReturnType} {Name}({Args})"; 279 | } 280 | } 281 | 282 | struct Argument 283 | { 284 | public bool Unsafe; 285 | public bool AnonType; 286 | 287 | public string Name; 288 | public string Type; 289 | 290 | public string ReturnType 291 | { 292 | get 293 | { 294 | if (!AnonType) 295 | { 296 | if (Type.ToLower().Contains("bool")) 297 | return "bool"; 298 | if (Type.ToLower().Contains("signed int")) 299 | return "int"; 300 | if (Type.ToLower().Contains("int")) 301 | return "uint"; 302 | if (Type.ToLower().Contains("dword")) 303 | return "uint"; 304 | } 305 | 306 | return Unsafe ? "void*" : "IntPtr"; 307 | } 308 | } 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /WrapperGenerator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | netcoreapp3.0 6 | true 7 | AnyCPU;x86;x64 8 | Always 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /WrapperGenerator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29512.175 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WrapperGenerator", "WrapperGenerator.csproj", "{861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Debug|x64.ActiveCfg = Debug|x64 17 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Debug|x64.Build.0 = Debug|x64 18 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Debug|x86.ActiveCfg = Debug|x86 19 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Debug|x86.Build.0 = Debug|x86 20 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Release|x64.ActiveCfg = Release|x64 21 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Release|x64.Build.0 = Release|x64 22 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Release|x86.ActiveCfg = Release|x86 23 | {861934C7-BCC2-43FB-AE0A-1B3ECE058BC8}.Release|x86.Build.0 = Release|x86 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {0F0C6D37-3515-45F8-ACDB-EEAE2AE6AE33} 30 | EndGlobalSection 31 | EndGlobal 32 | --------------------------------------------------------------------------------