|
| 1 | +// Copyright (c) Six Labors. |
| 2 | +// Licensed under the Six Labors Split License. |
| 3 | + |
| 4 | +using System.Runtime.InteropServices; |
| 5 | +using FilePath = System.IO.Path; |
| 6 | + |
| 7 | +namespace SixLabors.ImageSharp.Drawing.Processing.Backends.Native; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Locates this library's own loaded module on disk. |
| 11 | +/// </summary> |
| 12 | +/// <remarks> |
| 13 | +/// <para> |
| 14 | +/// Under Native AOT this code is compiled into a shared library or executable image, and when |
| 15 | +/// that image is a plugin loaded by a foreign host, <see cref="AppContext.BaseDirectory"/> |
| 16 | +/// points at the host process rather than the image. Anchoring native-asset probing to the |
| 17 | +/// image itself keeps resolution correct there. Under JIT hosting managed code does not live |
| 18 | +/// inside a loadable image, so resolution reports failure and callers fall back to standard |
| 19 | +/// probing. |
| 20 | +/// </para> |
| 21 | +/// <para> |
| 22 | +/// The runtime provides no managed API for recovering a loaded image's path; the mechanism |
| 23 | +/// here follows <see href="https://github.com/dotnet/runtime/issues/112290"/> and the |
| 24 | +/// address-anchored approach demonstrated in |
| 25 | +/// <see href="https://github.com/dotnet/runtime/discussions/122457"/>. |
| 26 | +/// </para> |
| 27 | +/// </remarks> |
| 28 | +internal static unsafe partial class NativeModuleLocator |
| 29 | +{ |
| 30 | + /// <summary> |
| 31 | + /// <c>GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT</c> from <c>libloaderapi.h</c>. The |
| 32 | + /// returned handle does not take a reference on the module, so it must not be freed. |
| 33 | + /// </summary> |
| 34 | + private const uint GetModuleHandleExFlagUnchangedRefCount = 0x00000002; |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// <c>GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS</c> from <c>libloaderapi.h</c>. The address |
| 38 | + /// argument is any address inside the target module rather than a module name. |
| 39 | + /// </summary> |
| 40 | + private const uint GetModuleHandleExFlagFromAddress = 0x00000004; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Attempts to resolve the directory of the image containing this library's code. |
| 44 | + /// </summary> |
| 45 | + /// <param name="directory">Receives the image directory.</param> |
| 46 | + /// <returns><see langword="true"/> when the image path could be resolved.</returns> |
| 47 | + public static bool TryGetModuleDirectory(out string directory) |
| 48 | + { |
| 49 | + directory = string.Empty; |
| 50 | + delegate* managed<void> anchor = &Anchor; |
| 51 | + |
| 52 | + string modulePath; |
| 53 | + if (OperatingSystem.IsWindows()) |
| 54 | + { |
| 55 | + if (GetModuleHandleExW(GetModuleHandleExFlagFromAddress | GetModuleHandleExFlagUnchangedRefCount, (nint)anchor, out nint module) == 0) |
| 56 | + { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + modulePath = GetModuleFilePath(module); |
| 61 | + } |
| 62 | + else |
| 63 | + { |
| 64 | + // dladdr reports the image containing an address. Resolving it through the process |
| 65 | + // exports avoids binding to a platform-specific libdl name. |
| 66 | + if (!NativeLibrary.TryGetExport(NativeLibrary.GetMainProgramHandle(), "dladdr", out nint export)) |
| 67 | + { |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + delegate* unmanaged<void*, DlInfo*, int> dladdr = (delegate* unmanaged<void*, DlInfo*, int>)export; |
| 72 | + DlInfo info; |
| 73 | + if (dladdr(anchor, &info) == 0 || info.FileName is null) |
| 74 | + { |
| 75 | + return false; |
| 76 | + } |
| 77 | + |
| 78 | + modulePath = Marshal.PtrToStringUTF8((nint)info.FileName) ?? string.Empty; |
| 79 | + } |
| 80 | + |
| 81 | + if (modulePath.Length == 0) |
| 82 | + { |
| 83 | + return false; |
| 84 | + } |
| 85 | + |
| 86 | + string? parent = FilePath.GetDirectoryName(modulePath); |
| 87 | + if (parent is null || parent.Length == 0) |
| 88 | + { |
| 89 | + return false; |
| 90 | + } |
| 91 | + |
| 92 | + directory = parent; |
| 93 | + return true; |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Reads the file path of a loaded native module. |
| 98 | + /// </summary> |
| 99 | + /// <param name="module">The loaded module handle.</param> |
| 100 | + /// <returns>The module's file path, or an empty string when it cannot be read.</returns> |
| 101 | + public static string GetModuleFilePath(nint module) |
| 102 | + { |
| 103 | + Span<char> buffer = stackalloc char[260]; |
| 104 | + fixed (char* bufferPointer = buffer) |
| 105 | + { |
| 106 | + uint length = GetModuleFileNameW(module, bufferPointer, (uint)buffer.Length); |
| 107 | + if (length > 0 && length < buffer.Length) |
| 108 | + { |
| 109 | + return new string(buffer[..(int)length]); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + // Cold fallback for paths beyond MAX_PATH up to the documented Windows maximum. |
| 114 | + char[] largeBuffer = new char[short.MaxValue]; |
| 115 | + fixed (char* largePointer = largeBuffer) |
| 116 | + { |
| 117 | + uint length = GetModuleFileNameW(module, largePointer, (uint)largeBuffer.Length); |
| 118 | + return length > 0 && length < largeBuffer.Length ? new string(largeBuffer, 0, (int)length) : string.Empty; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + /// <summary> |
| 123 | + /// Provides an address that lives inside this library's compiled image. |
| 124 | + /// </summary> |
| 125 | + private static void Anchor() |
| 126 | + { |
| 127 | + } |
| 128 | + |
| 129 | + /// <summary> |
| 130 | + /// Reads the file path of a loaded module into the supplied buffer. |
| 131 | + /// </summary> |
| 132 | + /// <param name="module">The loaded module handle.</param> |
| 133 | + /// <param name="filename">The buffer receiving the path.</param> |
| 134 | + /// <param name="size">The buffer length in characters.</param> |
| 135 | + /// <returns>The number of characters written, or zero on failure.</returns> |
| 136 | + [LibraryImport("kernel32", EntryPoint = "GetModuleFileNameW", SetLastError = true)] |
| 137 | + private static partial uint GetModuleFileNameW(nint module, char* filename, uint size); |
| 138 | + |
| 139 | + /// <summary> |
| 140 | + /// Retrieves a module handle for the image containing the supplied address. |
| 141 | + /// </summary> |
| 142 | + /// <param name="flags">The handle retrieval flags.</param> |
| 143 | + /// <param name="address">An address inside the target image.</param> |
| 144 | + /// <param name="module">Receives the module handle.</param> |
| 145 | + /// <returns>A non-zero value on success.</returns> |
| 146 | + [LibraryImport("kernel32", EntryPoint = "GetModuleHandleExW", SetLastError = true)] |
| 147 | + private static partial int GetModuleHandleExW(uint flags, nint address, out nint module); |
| 148 | + |
| 149 | + /// <summary> |
| 150 | + /// Image information reported by <c>dladdr</c>. |
| 151 | + /// </summary> |
| 152 | + [StructLayout(LayoutKind.Sequential)] |
| 153 | + private struct DlInfo |
| 154 | + { |
| 155 | + /// <summary> |
| 156 | + /// The path of the image containing the queried address. |
| 157 | + /// </summary> |
| 158 | + public byte* FileName; |
| 159 | + |
| 160 | + /// <summary> |
| 161 | + /// The base address of the image. |
| 162 | + /// </summary> |
| 163 | + public void* BaseAddress; |
| 164 | + |
| 165 | + /// <summary> |
| 166 | + /// The name of the nearest symbol. |
| 167 | + /// </summary> |
| 168 | + public byte* SymbolName; |
| 169 | + |
| 170 | + /// <summary> |
| 171 | + /// The address of the nearest symbol. |
| 172 | + /// </summary> |
| 173 | + public void* SymbolAddress; |
| 174 | + } |
| 175 | +} |
0 commit comments