Skip to content

Commit 1b88783

Browse files
committed
Windows library loader: add support for hModule == 0
1 parent a0a1dc1 commit 1b88783

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/runtime/platform/LibraryLoader.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using System;
22
using System.ComponentModel;
3+
using System.Diagnostics;
4+
using System.Linq;
35
using System.Runtime.InteropServices;
46

57
namespace Python.Runtime.Platform
@@ -195,6 +197,15 @@ public IntPtr Load(string dllToLoad)
195197

196198
public IntPtr GetFunction(IntPtr hModule, string procedureName)
197199
{
200+
if (hModule == IntPtr.Zero)
201+
{
202+
foreach(var module in GetAllModules())
203+
{
204+
var func = GetProcAddress(module, procedureName);
205+
if (func != IntPtr.Zero) return func;
206+
}
207+
}
208+
198209
var res = WindowsLoader.GetProcAddress(hModule, procedureName);
199210
if (res == IntPtr.Zero)
200211
throw new MissingMethodException($"Failed to load symbol {procedureName}", new Win32Exception());
@@ -203,6 +214,24 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName)
203214

204215
public void Free(IntPtr hModule) => WindowsLoader.FreeLibrary(hModule);
205216

217+
static IntPtr[] GetAllModules()
218+
{
219+
var self = Process.GetCurrentProcess().Handle;
220+
221+
uint bytes = 0;
222+
var result = new IntPtr[0];
223+
if (!EnumProcessModules(self, result, bytes, out var needsBytes))
224+
throw new Win32Exception();
225+
while (bytes < needsBytes)
226+
{
227+
bytes = needsBytes;
228+
result = new IntPtr[bytes / IntPtr.Size];
229+
if (!EnumProcessModules(self, result, bytes, out needsBytes))
230+
throw new Win32Exception();
231+
}
232+
return result.Take((int)(needsBytes / IntPtr.Size)).ToArray();
233+
}
234+
206235
[DllImport(NativeDll, SetLastError = true)]
207236
static extern IntPtr LoadLibrary(string dllToLoad);
208237

@@ -211,5 +240,8 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName)
211240

212241
[DllImport(NativeDll)]
213242
static extern bool FreeLibrary(IntPtr hModule);
243+
244+
[DllImport("Psapi.dll", SetLastError = true)]
245+
static extern bool EnumProcessModules(IntPtr hProcess, [In, Out] IntPtr[] lphModule, uint lphModuleByteCount, out uint byteCountNeeded);
214246
}
215247
}

0 commit comments

Comments
 (0)