├── .gitignore
├── DInvoke.Data
├── DInvoke.Data.csproj
├── Native.cs
├── PE.cs
└── Win32.cs
├── DInvoke.DynamicInvoke
├── DInvoke.DynamicInvoke.csproj
├── Generic.cs
├── Native.cs
└── Utilities.cs
├── DInvoke.ManualMap
├── DInvoke.ManualMap.csproj
├── Map.cs
└── Overload.cs
├── DInvoke.Tests
├── DInvoke.Tests.csproj
├── DynamicInvokeTests.cs
├── GlobalUsings.cs
└── ManualMapTests.cs
├── DInvoke.sln
└── README.md
/.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 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Nuget personal access tokens and Credentials
210 | # nuget.config
211 |
212 | # Microsoft Azure Build Output
213 | csx/
214 | *.build.csdef
215 |
216 | # Microsoft Azure Emulator
217 | ecf/
218 | rcf/
219 |
220 | # Windows Store app package directories and files
221 | AppPackages/
222 | BundleArtifacts/
223 | Package.StoreAssociation.xml
224 | _pkginfo.txt
225 | *.appx
226 | *.appxbundle
227 | *.appxupload
228 |
229 | # Visual Studio cache files
230 | # files ending in .cache can be ignored
231 | *.[Cc]ache
232 | # but keep track of directories ending in .cache
233 | !?*.[Cc]ache/
234 |
235 | # Others
236 | ClientBin/
237 | ~$*
238 | *~
239 | *.dbmdl
240 | *.dbproj.schemaview
241 | *.jfm
242 | *.pfx
243 | *.publishsettings
244 | orleans.codegen.cs
245 |
246 | # Including strong name files can present a security risk
247 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
248 | #*.snk
249 |
250 | # Since there are multiple workflows, uncomment next line to ignore bower_components
251 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
252 | #bower_components/
253 |
254 | # RIA/Silverlight projects
255 | Generated_Code/
256 |
257 | # Backup & report files from converting an old project file
258 | # to a newer Visual Studio version. Backup files are not needed,
259 | # because we have git ;-)
260 | _UpgradeReport_Files/
261 | Backup*/
262 | UpgradeLog*.XML
263 | UpgradeLog*.htm
264 | ServiceFabricBackup/
265 | *.rptproj.bak
266 |
267 | # SQL Server files
268 | *.mdf
269 | *.ldf
270 | *.ndf
271 |
272 | # Business Intelligence projects
273 | *.rdl.data
274 | *.bim.layout
275 | *.bim_*.settings
276 | *.rptproj.rsuser
277 | *- [Bb]ackup.rdl
278 | *- [Bb]ackup ([0-9]).rdl
279 | *- [Bb]ackup ([0-9][0-9]).rdl
280 |
281 | # Microsoft Fakes
282 | FakesAssemblies/
283 |
284 | # GhostDoc plugin setting file
285 | *.GhostDoc.xml
286 |
287 | # Node.js Tools for Visual Studio
288 | .ntvs_analysis.dat
289 | node_modules/
290 |
291 | # Visual Studio 6 build log
292 | *.plg
293 |
294 | # Visual Studio 6 workspace options file
295 | *.opt
296 |
297 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
298 | *.vbw
299 |
300 | # Visual Studio LightSwitch build output
301 | **/*.HTMLClient/GeneratedArtifacts
302 | **/*.DesktopClient/GeneratedArtifacts
303 | **/*.DesktopClient/ModelManifest.xml
304 | **/*.Server/GeneratedArtifacts
305 | **/*.Server/ModelManifest.xml
306 | _Pvt_Extensions
307 |
308 | # Paket dependency manager
309 | .paket/paket.exe
310 | paket-files/
311 |
312 | # FAKE - F# Make
313 | .fake/
314 |
315 | # CodeRush personal settings
316 | .cr/personal
317 |
318 | # Python Tools for Visual Studio (PTVS)
319 | __pycache__/
320 | *.pyc
321 |
322 | # Cake - Uncomment if you are using it
323 | # tools/**
324 | # !tools/packages.config
325 |
326 | # Tabs Studio
327 | *.tss
328 |
329 | # Telerik's JustMock configuration file
330 | *.jmconfig
331 |
332 | # BizTalk build output
333 | *.btp.cs
334 | *.btm.cs
335 | *.odx.cs
336 | *.xsd.cs
337 |
338 | # OpenCover UI analysis results
339 | OpenCover/
340 |
341 | # Azure Stream Analytics local run output
342 | ASALocalRun/
343 |
344 | # MSBuild Binary and Structured Log
345 | *.binlog
346 |
347 | # NVidia Nsight GPU debugger configuration file
348 | *.nvuser
349 |
350 | # MFractors (Xamarin productivity tool) working folder
351 | .mfractor/
352 |
353 | # Local History for Visual Studio
354 | .localhistory/
355 |
356 | # BeatPulse healthcheck temp database
357 | healthchecksdb
358 |
359 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
360 | MigrationBackup/
361 |
362 | # Ionide (cross platform F# VS Code tools) working folder
363 | .ionide/
364 |
365 | # Fody - auto-generated XML schema
366 | FodyWeavers.xsd
367 |
368 | # VS Code files for those working on multiple tools
369 | .vscode/*
370 | !.vscode/settings.json
371 | !.vscode/tasks.json
372 | !.vscode/launch.json
373 | !.vscode/extensions.json
374 | *.code-workspace
375 |
376 | # Local History for Visual Studio Code
377 | .history/
378 |
379 | # Windows Installer files from build outputs
380 | *.cab
381 | *.msi
382 | *.msix
383 | *.msm
384 | *.msp
385 |
386 | # JetBrains Rider
387 | .idea/
388 | *.sln.iml
389 |
--------------------------------------------------------------------------------
/DInvoke.Data/DInvoke.Data.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | enable
6 | disable
7 | 12
8 | true
9 | TheWover, RastaMouse
10 | Required data classes, structs and enums.
11 | 1.0.7
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/DInvoke.Data/Native.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | namespace DInvoke.Data;
4 |
5 | ///
6 | /// Native is a library of enums and structures for Native (NtDll) API functions.
7 | ///
8 | ///
9 | /// A majority of this library is adapted from signatures found at www.pinvoke.net.
10 | ///
11 | public static class Native
12 | {
13 | [StructLayout(LayoutKind.Sequential)]
14 | public struct UNICODE_STRING
15 | {
16 | public ushort Length;
17 | public ushort MaximumLength;
18 | public IntPtr Buffer;
19 | }
20 |
21 | [StructLayout(LayoutKind.Sequential)]
22 | public struct ANSI_STRING
23 | {
24 | public ushort Length;
25 | public ushort MaximumLength;
26 | public IntPtr Buffer;
27 | }
28 |
29 | public struct PROCESS_BASIC_INFORMATION
30 | {
31 | public IntPtr ExitStatus;
32 | public IntPtr PebBaseAddress;
33 | public IntPtr AffinityMask;
34 | public IntPtr BasePriority;
35 | public UIntPtr UniqueProcessId;
36 | public int InheritedFromUniqueProcessId;
37 |
38 | public int Size => Marshal.SizeOf(typeof(PROCESS_BASIC_INFORMATION));
39 | }
40 |
41 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
42 | public struct OBJECT_ATTRIBUTES
43 | {
44 | public int Length;
45 | public IntPtr RootDirectory;
46 | public IntPtr ObjectName;
47 | public uint Attributes;
48 | public IntPtr SecurityDescriptor;
49 | public IntPtr SecurityQualityOfService;
50 | }
51 |
52 | [StructLayout(LayoutKind.Sequential)]
53 | public struct IO_STATUS_BLOCK
54 | {
55 | public IntPtr Status;
56 | public IntPtr Information;
57 | }
58 |
59 | [StructLayout(LayoutKind.Sequential)]
60 | public struct OSVERSIONINFOEX
61 | {
62 | public uint OSVersionInfoSize;
63 | public uint MajorVersion;
64 | public uint MinorVersion;
65 | public uint BuildNumber;
66 | public uint PlatformId;
67 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
68 | public string CSDVersion;
69 | public ushort ServicePackMajor;
70 | public ushort ServicePackMinor;
71 | public ushort SuiteMask;
72 | public byte ProductType;
73 | public byte Reserved;
74 | }
75 |
76 | [StructLayout(LayoutKind.Sequential)]
77 | public struct LIST_ENTRY
78 | {
79 | public IntPtr Flink;
80 | public IntPtr Blink;
81 | }
82 |
83 | public enum PROCESSINFOCLASS : int
84 | {
85 | ProcessBasicInformation = 0, // 0, q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION
86 | ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX
87 | ProcessIoCounters, // q: IO_COUNTERS
88 | ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX
89 | ProcessTimes, // q: KERNEL_USER_TIMES
90 | ProcessBasePriority, // s: KPRIORITY
91 | ProcessRaisePriority, // s: ULONG
92 | ProcessDebugPort, // q: HANDLE
93 | ProcessExceptionPort, // s: HANDLE
94 | ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN
95 | ProcessLdtInformation, // 10
96 | ProcessLdtSize,
97 | ProcessDefaultHardErrorMode, // qs: ULONG
98 | ProcessIoPortHandlers, // (kernel-mode only)
99 | ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS
100 | ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void
101 | ProcessUserModeIOPL,
102 | ProcessEnableAlignmentFaultFixup, // s: BOOLEAN
103 | ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS
104 | ProcessWx86Information,
105 | ProcessHandleCount, // 20, q: ULONG, PROCESS_HANDLE_INFORMATION
106 | ProcessAffinityMask, // s: KAFFINITY
107 | ProcessPriorityBoost, // qs: ULONG
108 | ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX
109 | ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION
110 | ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND
111 | ProcessWow64Information, // q: ULONG_PTR
112 | ProcessImageFileName, // q: UNICODE_STRING
113 | ProcessLUIDDeviceMapsEnabled, // q: ULONG
114 | ProcessBreakOnTermination, // qs: ULONG
115 | ProcessDebugObjectHandle, // 30, q: HANDLE
116 | ProcessDebugFlags, // qs: ULONG
117 | ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables
118 | ProcessIoPriority, // qs: ULONG
119 | ProcessExecuteFlags, // qs: ULONG
120 | ProcessResourceManagement,
121 | ProcessCookie, // q: ULONG
122 | ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION
123 | ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION
124 | ProcessPagePriority, // q: ULONG
125 | ProcessInstrumentationCallback, // 40
126 | ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX
127 | ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]
128 | ProcessImageFileNameWin32, // q: UNICODE_STRING
129 | ProcessImageFileMapping, // q: HANDLE (input)
130 | ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE
131 | ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE
132 | ProcessGroupInformation, // q: USHORT[]
133 | ProcessTokenVirtualizationEnabled, // s: ULONG
134 | ProcessConsoleHostProcess, // q: ULONG_PTR
135 | ProcessWindowInformation, // 50, q: PROCESS_WINDOW_INFORMATION
136 | ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8
137 | ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION
138 | ProcessDynamicFunctionTableInformation,
139 | ProcessHandleCheckingMode,
140 | ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION
141 | ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION
142 | MaxProcessInfoClass
143 | };
144 |
145 | ///
146 | /// NTSTATUS is an undocument enum. https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55
147 | /// https://www.pinvoke.net/default.aspx/Enums/NtStatus.html
148 | ///
149 | public enum NTSTATUS : uint
150 | {
151 | // Success
152 | Success = 0x00000000,
153 | Wait0 = 0x00000000,
154 | Wait1 = 0x00000001,
155 | Wait2 = 0x00000002,
156 | Wait3 = 0x00000003,
157 | Wait63 = 0x0000003f,
158 | Abandoned = 0x00000080,
159 | AbandonedWait0 = 0x00000080,
160 | AbandonedWait1 = 0x00000081,
161 | AbandonedWait2 = 0x00000082,
162 | AbandonedWait3 = 0x00000083,
163 | AbandonedWait63 = 0x000000bf,
164 | UserApc = 0x000000c0,
165 | KernelApc = 0x00000100,
166 | Alerted = 0x00000101,
167 | Timeout = 0x00000102,
168 | Pending = 0x00000103,
169 | Reparse = 0x00000104,
170 | MoreEntries = 0x00000105,
171 | NotAllAssigned = 0x00000106,
172 | SomeNotMapped = 0x00000107,
173 | OpLockBreakInProgress = 0x00000108,
174 | VolumeMounted = 0x00000109,
175 | RxActCommitted = 0x0000010a,
176 | NotifyCleanup = 0x0000010b,
177 | NotifyEnumDir = 0x0000010c,
178 | NoQuotasForAccount = 0x0000010d,
179 | PrimaryTransportConnectFailed = 0x0000010e,
180 | PageFaultTransition = 0x00000110,
181 | PageFaultDemandZero = 0x00000111,
182 | PageFaultCopyOnWrite = 0x00000112,
183 | PageFaultGuardPage = 0x00000113,
184 | PageFaultPagingFile = 0x00000114,
185 | CrashDump = 0x00000116,
186 | ReparseObject = 0x00000118,
187 | NothingToTerminate = 0x00000122,
188 | ProcessNotInJob = 0x00000123,
189 | ProcessInJob = 0x00000124,
190 | ProcessCloned = 0x00000129,
191 | FileLockedWithOnlyReaders = 0x0000012a,
192 | FileLockedWithWriters = 0x0000012b,
193 |
194 | // Informational
195 | Informational = 0x40000000,
196 | ObjectNameExists = 0x40000000,
197 | ThreadWasSuspended = 0x40000001,
198 | WorkingSetLimitRange = 0x40000002,
199 | ImageNotAtBase = 0x40000003,
200 | RegistryRecovered = 0x40000009,
201 |
202 | // Warning
203 | Warning = 0x80000000,
204 | GuardPageViolation = 0x80000001,
205 | DatatypeMisalignment = 0x80000002,
206 | Breakpoint = 0x80000003,
207 | SingleStep = 0x80000004,
208 | BufferOverflow = 0x80000005,
209 | NoMoreFiles = 0x80000006,
210 | HandlesClosed = 0x8000000a,
211 | PartialCopy = 0x8000000d,
212 | DeviceBusy = 0x80000011,
213 | InvalidEaName = 0x80000013,
214 | EaListInconsistent = 0x80000014,
215 | NoMoreEntries = 0x8000001a,
216 | LongJump = 0x80000026,
217 | DllMightBeInsecure = 0x8000002b,
218 |
219 | // Error
220 | Error = 0xc0000000,
221 | Unsuccessful = 0xc0000001,
222 | NotImplemented = 0xc0000002,
223 | InvalidInfoClass = 0xc0000003,
224 | InfoLengthMismatch = 0xc0000004,
225 | AccessViolation = 0xc0000005,
226 | InPageError = 0xc0000006,
227 | PagefileQuota = 0xc0000007,
228 | InvalidHandle = 0xc0000008,
229 | BadInitialStack = 0xc0000009,
230 | BadInitialPc = 0xc000000a,
231 | InvalidCid = 0xc000000b,
232 | TimerNotCanceled = 0xc000000c,
233 | InvalidParameter = 0xc000000d,
234 | NoSuchDevice = 0xc000000e,
235 | NoSuchFile = 0xc000000f,
236 | InvalidDeviceRequest = 0xc0000010,
237 | EndOfFile = 0xc0000011,
238 | WrongVolume = 0xc0000012,
239 | NoMediaInDevice = 0xc0000013,
240 | NoMemory = 0xc0000017,
241 | ConflictingAddresses = 0xc0000018,
242 | NotMappedView = 0xc0000019,
243 | UnableToFreeVm = 0xc000001a,
244 | UnableToDeleteSection = 0xc000001b,
245 | IllegalInstruction = 0xc000001d,
246 | AlreadyCommitted = 0xc0000021,
247 | AccessDenied = 0xc0000022,
248 | BufferTooSmall = 0xc0000023,
249 | ObjectTypeMismatch = 0xc0000024,
250 | NonContinuableException = 0xc0000025,
251 | BadStack = 0xc0000028,
252 | NotLocked = 0xc000002a,
253 | NotCommitted = 0xc000002d,
254 | InvalidParameterMix = 0xc0000030,
255 | ObjectNameInvalid = 0xc0000033,
256 | ObjectNameNotFound = 0xc0000034,
257 | ObjectNameCollision = 0xc0000035,
258 | ObjectPathInvalid = 0xc0000039,
259 | ObjectPathNotFound = 0xc000003a,
260 | ObjectPathSyntaxBad = 0xc000003b,
261 | DataOverrun = 0xc000003c,
262 | DataLate = 0xc000003d,
263 | DataError = 0xc000003e,
264 | CrcError = 0xc000003f,
265 | SectionTooBig = 0xc0000040,
266 | PortConnectionRefused = 0xc0000041,
267 | InvalidPortHandle = 0xc0000042,
268 | SharingViolation = 0xc0000043,
269 | QuotaExceeded = 0xc0000044,
270 | InvalidPageProtection = 0xc0000045,
271 | MutantNotOwned = 0xc0000046,
272 | SemaphoreLimitExceeded = 0xc0000047,
273 | PortAlreadySet = 0xc0000048,
274 | SectionNotImage = 0xc0000049,
275 | SuspendCountExceeded = 0xc000004a,
276 | ThreadIsTerminating = 0xc000004b,
277 | BadWorkingSetLimit = 0xc000004c,
278 | IncompatibleFileMap = 0xc000004d,
279 | SectionProtection = 0xc000004e,
280 | EasNotSupported = 0xc000004f,
281 | EaTooLarge = 0xc0000050,
282 | NonExistentEaEntry = 0xc0000051,
283 | NoEasOnFile = 0xc0000052,
284 | EaCorruptError = 0xc0000053,
285 | FileLockConflict = 0xc0000054,
286 | LockNotGranted = 0xc0000055,
287 | DeletePending = 0xc0000056,
288 | CtlFileNotSupported = 0xc0000057,
289 | UnknownRevision = 0xc0000058,
290 | RevisionMismatch = 0xc0000059,
291 | InvalidOwner = 0xc000005a,
292 | InvalidPrimaryGroup = 0xc000005b,
293 | NoImpersonationToken = 0xc000005c,
294 | CantDisableMandatory = 0xc000005d,
295 | NoLogonServers = 0xc000005e,
296 | NoSuchLogonSession = 0xc000005f,
297 | NoSuchPrivilege = 0xc0000060,
298 | PrivilegeNotHeld = 0xc0000061,
299 | InvalidAccountName = 0xc0000062,
300 | UserExists = 0xc0000063,
301 | NoSuchUser = 0xc0000064,
302 | GroupExists = 0xc0000065,
303 | NoSuchGroup = 0xc0000066,
304 | MemberInGroup = 0xc0000067,
305 | MemberNotInGroup = 0xc0000068,
306 | LastAdmin = 0xc0000069,
307 | WrongPassword = 0xc000006a,
308 | IllFormedPassword = 0xc000006b,
309 | PasswordRestriction = 0xc000006c,
310 | LogonFailure = 0xc000006d,
311 | AccountRestriction = 0xc000006e,
312 | InvalidLogonHours = 0xc000006f,
313 | InvalidWorkstation = 0xc0000070,
314 | PasswordExpired = 0xc0000071,
315 | AccountDisabled = 0xc0000072,
316 | NoneMapped = 0xc0000073,
317 | TooManyLuidsRequested = 0xc0000074,
318 | LuidsExhausted = 0xc0000075,
319 | InvalidSubAuthority = 0xc0000076,
320 | InvalidAcl = 0xc0000077,
321 | InvalidSid = 0xc0000078,
322 | InvalidSecurityDescr = 0xc0000079,
323 | ProcedureNotFound = 0xc000007a,
324 | InvalidImageFormat = 0xc000007b,
325 | NoToken = 0xc000007c,
326 | BadInheritanceAcl = 0xc000007d,
327 | RangeNotLocked = 0xc000007e,
328 | DiskFull = 0xc000007f,
329 | ServerDisabled = 0xc0000080,
330 | ServerNotDisabled = 0xc0000081,
331 | TooManyGuidsRequested = 0xc0000082,
332 | GuidsExhausted = 0xc0000083,
333 | InvalidIdAuthority = 0xc0000084,
334 | AgentsExhausted = 0xc0000085,
335 | InvalidVolumeLabel = 0xc0000086,
336 | SectionNotExtended = 0xc0000087,
337 | NotMappedData = 0xc0000088,
338 | ResourceDataNotFound = 0xc0000089,
339 | ResourceTypeNotFound = 0xc000008a,
340 | ResourceNameNotFound = 0xc000008b,
341 | ArrayBoundsExceeded = 0xc000008c,
342 | FloatDenormalOperand = 0xc000008d,
343 | FloatDivideByZero = 0xc000008e,
344 | FloatInexactResult = 0xc000008f,
345 | FloatInvalidOperation = 0xc0000090,
346 | FloatOverflow = 0xc0000091,
347 | FloatStackCheck = 0xc0000092,
348 | FloatUnderflow = 0xc0000093,
349 | IntegerDivideByZero = 0xc0000094,
350 | IntegerOverflow = 0xc0000095,
351 | PrivilegedInstruction = 0xc0000096,
352 | TooManyPagingFiles = 0xc0000097,
353 | FileInvalid = 0xc0000098,
354 | InsufficientResources = 0xc000009a,
355 | InstanceNotAvailable = 0xc00000ab,
356 | PipeNotAvailable = 0xc00000ac,
357 | InvalidPipeState = 0xc00000ad,
358 | PipeBusy = 0xc00000ae,
359 | IllegalFunction = 0xc00000af,
360 | PipeDisconnected = 0xc00000b0,
361 | PipeClosing = 0xc00000b1,
362 | PipeConnected = 0xc00000b2,
363 | PipeListening = 0xc00000b3,
364 | InvalidReadMode = 0xc00000b4,
365 | IoTimeout = 0xc00000b5,
366 | FileForcedClosed = 0xc00000b6,
367 | ProfilingNotStarted = 0xc00000b7,
368 | ProfilingNotStopped = 0xc00000b8,
369 | NotSameDevice = 0xc00000d4,
370 | FileRenamed = 0xc00000d5,
371 | CantWait = 0xc00000d8,
372 | PipeEmpty = 0xc00000d9,
373 | CantTerminateSelf = 0xc00000db,
374 | InternalError = 0xc00000e5,
375 | InvalidParameter1 = 0xc00000ef,
376 | InvalidParameter2 = 0xc00000f0,
377 | InvalidParameter3 = 0xc00000f1,
378 | InvalidParameter4 = 0xc00000f2,
379 | InvalidParameter5 = 0xc00000f3,
380 | InvalidParameter6 = 0xc00000f4,
381 | InvalidParameter7 = 0xc00000f5,
382 | InvalidParameter8 = 0xc00000f6,
383 | InvalidParameter9 = 0xc00000f7,
384 | InvalidParameter10 = 0xc00000f8,
385 | InvalidParameter11 = 0xc00000f9,
386 | InvalidParameter12 = 0xc00000fa,
387 | ProcessIsTerminating = 0xc000010a,
388 | MappedFileSizeZero = 0xc000011e,
389 | TooManyOpenedFiles = 0xc000011f,
390 | Cancelled = 0xc0000120,
391 | CannotDelete = 0xc0000121,
392 | InvalidComputerName = 0xc0000122,
393 | FileDeleted = 0xc0000123,
394 | SpecialAccount = 0xc0000124,
395 | SpecialGroup = 0xc0000125,
396 | SpecialUser = 0xc0000126,
397 | MembersPrimaryGroup = 0xc0000127,
398 | FileClosed = 0xc0000128,
399 | TooManyThreads = 0xc0000129,
400 | ThreadNotInProcess = 0xc000012a,
401 | TokenAlreadyInUse = 0xc000012b,
402 | PagefileQuotaExceeded = 0xc000012c,
403 | CommitmentLimit = 0xc000012d,
404 | InvalidImageLeFormat = 0xc000012e,
405 | InvalidImageNotMz = 0xc000012f,
406 | InvalidImageProtect = 0xc0000130,
407 | InvalidImageWin16 = 0xc0000131,
408 | LogonServer = 0xc0000132,
409 | DifferenceAtDc = 0xc0000133,
410 | SynchronizationRequired = 0xc0000134,
411 | DllNotFound = 0xc0000135,
412 | IoPrivilegeFailed = 0xc0000137,
413 | OrdinalNotFound = 0xc0000138,
414 | EntryPointNotFound = 0xc0000139,
415 | ControlCExit = 0xc000013a,
416 | InvalidAddress = 0xc0000141,
417 | PortNotSet = 0xc0000353,
418 | DebuggerInactive = 0xc0000354,
419 | CallbackBypass = 0xc0000503,
420 | PortClosed = 0xc0000700,
421 | MessageLost = 0xc0000701,
422 | InvalidMessage = 0xc0000702,
423 | RequestCanceled = 0xc0000703,
424 | RecursiveDispatch = 0xc0000704,
425 | LpcReceiveBufferExpected = 0xc0000705,
426 | LpcInvalidConnectionUsage = 0xc0000706,
427 | LpcRequestsNotAllowed = 0xc0000707,
428 | ResourceInUse = 0xc0000708,
429 | ProcessIsProtected = 0xc0000712,
430 | VolumeDirty = 0xc0000806,
431 | FileCheckedOut = 0xc0000901,
432 | CheckOutRequired = 0xc0000902,
433 | BadFileType = 0xc0000903,
434 | FileTooLarge = 0xc0000904,
435 | FormsAuthRequired = 0xc0000905,
436 | VirusInfected = 0xc0000906,
437 | VirusDeleted = 0xc0000907,
438 | TransactionalConflict = 0xc0190001,
439 | InvalidTransaction = 0xc0190002,
440 | TransactionNotActive = 0xc0190003,
441 | TmInitializationFailed = 0xc0190004,
442 | RmNotActive = 0xc0190005,
443 | RmMetadataCorrupt = 0xc0190006,
444 | TransactionNotJoined = 0xc0190007,
445 | DirectoryNotRm = 0xc0190008,
446 | CouldNotResizeLog = 0xc0190009,
447 | TransactionsUnsupportedRemote = 0xc019000a,
448 | LogResizeInvalidSize = 0xc019000b,
449 | RemoteFileVersionMismatch = 0xc019000c,
450 | CrmProtocolAlreadyExists = 0xc019000f,
451 | TransactionPropagationFailed = 0xc0190010,
452 | CrmProtocolNotFound = 0xc0190011,
453 | TransactionSuperiorExists = 0xc0190012,
454 | TransactionRequestNotValid = 0xc0190013,
455 | TransactionNotRequested = 0xc0190014,
456 | TransactionAlreadyAborted = 0xc0190015,
457 | TransactionAlreadyCommitted = 0xc0190016,
458 | TransactionInvalidMarshallBuffer = 0xc0190017,
459 | CurrentTransactionNotValid = 0xc0190018,
460 | LogGrowthFailed = 0xc0190019,
461 | ObjectNoLongerExists = 0xc0190021,
462 | StreamMiniversionNotFound = 0xc0190022,
463 | StreamMiniversionNotValid = 0xc0190023,
464 | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
465 | CantOpenMiniversionWithModifyIntent = 0xc0190025,
466 | CantCreateMoreStreamMiniversions = 0xc0190026,
467 | HandleNoLongerValid = 0xc0190028,
468 | NoTxfMetadata = 0xc0190029,
469 | LogCorruptionDetected = 0xc0190030,
470 | CantRecoverWithHandleOpen = 0xc0190031,
471 | RmDisconnected = 0xc0190032,
472 | EnlistmentNotSuperior = 0xc0190033,
473 | RecoveryNotNeeded = 0xc0190034,
474 | RmAlreadyStarted = 0xc0190035,
475 | FileIdentityNotPersistent = 0xc0190036,
476 | CantBreakTransactionalDependency = 0xc0190037,
477 | CantCrossRmBoundary = 0xc0190038,
478 | TxfDirNotEmpty = 0xc0190039,
479 | IndoubtTransactionsExist = 0xc019003a,
480 | TmVolatile = 0xc019003b,
481 | RollbackTimerExpired = 0xc019003c,
482 | TxfAttributeCorrupt = 0xc019003d,
483 | EfsNotAllowedInTransaction = 0xc019003e,
484 | TransactionalOpenNotAllowed = 0xc019003f,
485 | TransactedMappingUnsupportedRemote = 0xc0190040,
486 | TxfMetadataAlreadyPresent = 0xc0190041,
487 | TransactionScopeCallbacksNotSet = 0xc0190042,
488 | TransactionRequiredPromotion = 0xc0190043,
489 | CannotExecuteFileInTransaction = 0xc0190044,
490 | TransactionsNotFrozen = 0xc0190045,
491 |
492 | MaximumNtStatus = 0xffffffff
493 | }
494 | }
--------------------------------------------------------------------------------
/DInvoke.Data/PE.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | namespace DInvoke.Data;
4 |
5 | ///
6 | /// Holds data structures for using PEs.
7 | ///
8 | public static class PE
9 | {
10 | public const uint DLL_PROCESS_DETACH = 0;
11 | public const uint DLL_PROCESS_ATTACH = 1;
12 | public const uint DLL_THREAD_ATTACH = 2;
13 | public const uint DLL_THREAD_DETACH = 3;
14 |
15 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
16 | public delegate bool DllMain(IntPtr hinstDll, uint fdwReason, IntPtr lpvReserved);
17 |
18 | [Flags]
19 | public enum DataSectionFlags : uint
20 | {
21 | TYPE_NO_PAD = 0x00000008,
22 | CNT_CODE = 0x00000020,
23 | CNT_INITIALIZED_DATA = 0x00000040,
24 | CNT_UNINITIALIZED_DATA = 0x00000080,
25 | LNK_INFO = 0x00000200,
26 | LNK_REMOVE = 0x00000800,
27 | LNK_COMDAT = 0x00001000,
28 | NO_DEFER_SPEC_EXC = 0x00004000,
29 | GPREL = 0x00008000,
30 | MEM_FARDATA = 0x00008000,
31 | MEM_PURGEABLE = 0x00020000,
32 | MEM_16BIT = 0x00020000,
33 | MEM_LOCKED = 0x00040000,
34 | MEM_PRELOAD = 0x00080000,
35 | ALIGN_1BYTES = 0x00100000,
36 | ALIGN_2BYTES = 0x00200000,
37 | ALIGN_4BYTES = 0x00300000,
38 | ALIGN_8BYTES = 0x00400000,
39 | ALIGN_16BYTES = 0x00500000,
40 | ALIGN_32BYTES = 0x00600000,
41 | ALIGN_64BYTES = 0x00700000,
42 | ALIGN_128BYTES = 0x00800000,
43 | ALIGN_256BYTES = 0x00900000,
44 | ALIGN_512BYTES = 0x00A00000,
45 | ALIGN_1024BYTES = 0x00B00000,
46 | ALIGN_2048BYTES = 0x00C00000,
47 | ALIGN_4096BYTES = 0x00D00000,
48 | ALIGN_8192BYTES = 0x00E00000,
49 | ALIGN_MASK = 0x00F00000,
50 | LNK_NRELOC_OVFL = 0x01000000,
51 | MEM_DISCARDABLE = 0x02000000,
52 | MEM_NOT_CACHED = 0x04000000,
53 | MEM_NOT_PAGED = 0x08000000,
54 | MEM_SHARED = 0x10000000,
55 | MEM_EXECUTE = 0x20000000,
56 | MEM_READ = 0x40000000,
57 | MEM_WRITE = 0x80000000
58 | }
59 |
60 | [StructLayout(LayoutKind.Sequential)]
61 | public struct IMAGE_DATA_DIRECTORY
62 | {
63 | public uint VirtualAddress;
64 | public uint Size;
65 | }
66 |
67 | [StructLayout(LayoutKind.Sequential, Pack = 1)]
68 | public struct IMAGE_OPTIONAL_HEADER32
69 | {
70 | public ushort Magic;
71 | public byte MajorLinkerVersion;
72 | public byte MinorLinkerVersion;
73 | public uint SizeOfCode;
74 | public uint SizeOfInitializedData;
75 | public uint SizeOfUninitializedData;
76 | public uint AddressOfEntryPoint;
77 | public uint BaseOfCode;
78 | public uint BaseOfData;
79 | public uint ImageBase;
80 | public uint SectionAlignment;
81 | public uint FileAlignment;
82 | public ushort MajorOperatingSystemVersion;
83 | public ushort MinorOperatingSystemVersion;
84 | public ushort MajorImageVersion;
85 | public ushort MinorImageVersion;
86 | public ushort MajorSubsystemVersion;
87 | public ushort MinorSubsystemVersion;
88 | public uint Win32VersionValue;
89 | public uint SizeOfImage;
90 | public uint SizeOfHeaders;
91 | public uint CheckSum;
92 | public ushort Subsystem;
93 | public ushort DllCharacteristics;
94 | public uint SizeOfStackReserve;
95 | public uint SizeOfStackCommit;
96 | public uint SizeOfHeapReserve;
97 | public uint SizeOfHeapCommit;
98 | public uint LoaderFlags;
99 | public uint NumberOfRvaAndSizes;
100 |
101 | public IMAGE_DATA_DIRECTORY ExportTable;
102 | public IMAGE_DATA_DIRECTORY ImportTable;
103 | public IMAGE_DATA_DIRECTORY ResourceTable;
104 | public IMAGE_DATA_DIRECTORY ExceptionTable;
105 | public IMAGE_DATA_DIRECTORY CertificateTable;
106 | public IMAGE_DATA_DIRECTORY BaseRelocationTable;
107 | public IMAGE_DATA_DIRECTORY Debug;
108 | public IMAGE_DATA_DIRECTORY Architecture;
109 | public IMAGE_DATA_DIRECTORY GlobalPtr;
110 | public IMAGE_DATA_DIRECTORY TLSTable;
111 | public IMAGE_DATA_DIRECTORY LoadConfigTable;
112 | public IMAGE_DATA_DIRECTORY BoundImport;
113 | public IMAGE_DATA_DIRECTORY IAT;
114 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
115 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
116 | public IMAGE_DATA_DIRECTORY Reserved;
117 | }
118 |
119 | [StructLayout(LayoutKind.Sequential, Pack = 1)]
120 | public struct IMAGE_OPTIONAL_HEADER64
121 | {
122 | public ushort Magic;
123 | public byte MajorLinkerVersion;
124 | public byte MinorLinkerVersion;
125 | public uint SizeOfCode;
126 | public uint SizeOfInitializedData;
127 | public uint SizeOfUninitializedData;
128 | public uint AddressOfEntryPoint;
129 | public uint BaseOfCode;
130 | public ulong ImageBase;
131 | public uint SectionAlignment;
132 | public uint FileAlignment;
133 | public ushort MajorOperatingSystemVersion;
134 | public ushort MinorOperatingSystemVersion;
135 | public ushort MajorImageVersion;
136 | public ushort MinorImageVersion;
137 | public ushort MajorSubsystemVersion;
138 | public ushort MinorSubsystemVersion;
139 | public uint Win32VersionValue;
140 | public uint SizeOfImage;
141 | public uint SizeOfHeaders;
142 | public uint CheckSum;
143 | public ushort Subsystem;
144 | public ushort DllCharacteristics;
145 | public ulong SizeOfStackReserve;
146 | public ulong SizeOfStackCommit;
147 | public ulong SizeOfHeapReserve;
148 | public ulong SizeOfHeapCommit;
149 | public uint LoaderFlags;
150 | public uint NumberOfRvaAndSizes;
151 |
152 | public IMAGE_DATA_DIRECTORY ExportTable;
153 | public IMAGE_DATA_DIRECTORY ImportTable;
154 | public IMAGE_DATA_DIRECTORY ResourceTable;
155 | public IMAGE_DATA_DIRECTORY ExceptionTable;
156 | public IMAGE_DATA_DIRECTORY CertificateTable;
157 | public IMAGE_DATA_DIRECTORY BaseRelocationTable;
158 | public IMAGE_DATA_DIRECTORY Debug;
159 | public IMAGE_DATA_DIRECTORY Architecture;
160 | public IMAGE_DATA_DIRECTORY GlobalPtr;
161 | public IMAGE_DATA_DIRECTORY TLSTable;
162 | public IMAGE_DATA_DIRECTORY LoadConfigTable;
163 | public IMAGE_DATA_DIRECTORY BoundImport;
164 | public IMAGE_DATA_DIRECTORY IAT;
165 | public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
166 | public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
167 | public IMAGE_DATA_DIRECTORY Reserved;
168 | }
169 |
170 | [StructLayout(LayoutKind.Sequential, Pack = 1)]
171 | public struct IMAGE_FILE_HEADER
172 | {
173 | public ushort Machine;
174 | public ushort NumberOfSections;
175 | public uint TimeDateStamp;
176 | public uint PointerToSymbolTable;
177 | public uint NumberOfSymbols;
178 | public ushort SizeOfOptionalHeader;
179 | public ushort Characteristics;
180 | }
181 |
182 | [StructLayout(LayoutKind.Explicit)]
183 | public struct IMAGE_SECTION_HEADER
184 | {
185 | [FieldOffset(0)]
186 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
187 | public char[] Name;
188 | [FieldOffset(8)]
189 | public uint VirtualSize;
190 | [FieldOffset(12)]
191 | public uint VirtualAddress;
192 | [FieldOffset(16)]
193 | public uint SizeOfRawData;
194 | [FieldOffset(20)]
195 | public uint PointerToRawData;
196 | [FieldOffset(24)]
197 | public uint PointerToRelocations;
198 | [FieldOffset(28)]
199 | public uint PointerToLinenumbers;
200 | [FieldOffset(32)]
201 | public ushort NumberOfRelocations;
202 | [FieldOffset(34)]
203 | public ushort NumberOfLinenumbers;
204 | [FieldOffset(36)]
205 | public DataSectionFlags Characteristics;
206 |
207 | public string Section => new(Name);
208 | }
209 |
210 | [StructLayout(LayoutKind.Sequential)]
211 | public struct IMAGE_BASE_RELOCATION
212 | {
213 | public uint VirtualAdress;
214 | public uint SizeOfBlock;
215 | }
216 |
217 | [StructLayout(LayoutKind.Sequential)]
218 | public struct PE_META_DATA
219 | {
220 | public uint Pe;
221 | public bool Is32Bit;
222 | public IMAGE_FILE_HEADER ImageFileHeader;
223 | public IMAGE_OPTIONAL_HEADER32 OptHeader32;
224 | public IMAGE_OPTIONAL_HEADER64 OptHeader64;
225 | public IMAGE_SECTION_HEADER[] Sections;
226 | }
227 |
228 | [StructLayout(LayoutKind.Sequential)]
229 | public struct PE_MANUAL_MAP
230 | {
231 | public string DecoyModule;
232 | public IntPtr ModuleBase;
233 | public PE_META_DATA PEINFO;
234 | }
235 |
236 | [StructLayout(LayoutKind.Explicit)]
237 | public struct IMAGE_THUNK_DATA32
238 | {
239 | [FieldOffset(0)]
240 | public uint ForwarderString;
241 | [FieldOffset(0)]
242 | public uint Function;
243 | [FieldOffset(0)]
244 | public uint Ordinal;
245 | [FieldOffset(0)]
246 | public uint AddressOfData;
247 | }
248 |
249 | [StructLayout(LayoutKind.Explicit)]
250 | public struct IMAGE_THUNK_DATA64
251 | {
252 | [FieldOffset(0)]
253 | public ulong ForwarderString;
254 | [FieldOffset(0)]
255 | public ulong Function;
256 | [FieldOffset(0)]
257 | public ulong Ordinal;
258 | [FieldOffset(0)]
259 | public ulong AddressOfData;
260 | }
261 |
262 | [StructLayout(LayoutKind.Explicit)]
263 | public struct ApiSetNamespace
264 | {
265 | [FieldOffset(0x0C)]
266 | public int Count;
267 |
268 | [FieldOffset(0x10)]
269 | public int EntryOffset;
270 | }
271 |
272 | [StructLayout(LayoutKind.Explicit)]
273 | public struct ApiSetNamespaceEntry
274 | {
275 | [FieldOffset(0x04)]
276 | public int NameOffset;
277 |
278 | [FieldOffset(0x08)]
279 | public int NameLength;
280 |
281 | [FieldOffset(0x10)]
282 | public int ValueOffset;
283 |
284 | [FieldOffset(0x14)]
285 | public int ValueLength;
286 | }
287 |
288 | [StructLayout(LayoutKind.Explicit)]
289 | public struct ApiSetValueEntry
290 | {
291 | [FieldOffset(0x00)]
292 | public int Flags;
293 |
294 | [FieldOffset(0x04)]
295 | public int NameOffset;
296 |
297 | [FieldOffset(0x08)]
298 | public int NameCount;
299 |
300 | [FieldOffset(0x0C)]
301 | public int ValueOffset;
302 |
303 | [FieldOffset(0x10)]
304 | public int ValueCount;
305 | }
306 |
307 | [StructLayout(LayoutKind.Sequential)]
308 | public struct LDR_DATA_TABLE_ENTRY
309 | {
310 | public Native.LIST_ENTRY InLoadOrderLinks;
311 | public Native.LIST_ENTRY InMemoryOrderLinks;
312 | public Native.LIST_ENTRY InInitializationOrderLinks;
313 | public IntPtr DllBase;
314 | public IntPtr EntryPoint;
315 | public uint SizeOfImage;
316 | public Native.UNICODE_STRING FullDllName;
317 | public Native.UNICODE_STRING BaseDllName;
318 | }
319 | }
--------------------------------------------------------------------------------
/DInvoke.Data/Win32.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System.Runtime.InteropServices;
6 |
7 | namespace DInvoke.Data;
8 |
9 | ///
10 | /// Win32 is a library of enums and structures for Win32 API functions.
11 | ///
12 | ///
13 | /// A majority of this library is adapted from signatures found at www.pinvoke.net.
14 | ///
15 | public static class Win32
16 | {
17 | public static class Kernel32
18 | {
19 | public const uint MEM_COMMIT = 0x1000;
20 | public const uint MEM_RESERVE = 0x2000;
21 | public const uint MEM_RELEASE = 0x8000;
22 |
23 | [StructLayout(LayoutKind.Sequential)]
24 | public struct IMAGE_IMPORT_DESCRIPTOR
25 | {
26 | public uint OriginalFirstThunk;
27 | public uint TimeDateStamp;
28 | public uint ForwarderChain;
29 | public uint Name;
30 | public uint FirstThunk;
31 | }
32 |
33 | [Flags]
34 | public enum FileAccessFlags : uint
35 | {
36 | DELETE = 0x10000,
37 | FILE_READ_DATA = 0x1,
38 | FILE_READ_ATTRIBUTES = 0x80,
39 | FILE_READ_EA = 0x8,
40 | READ_CONTROL = 0x20000,
41 | FILE_WRITE_DATA = 0x2,
42 | FILE_WRITE_ATTRIBUTES = 0x100,
43 | FILE_WRITE_EA = 0x10,
44 | FILE_APPEND_DATA = 0x4,
45 | WRITE_DAC = 0x40000,
46 | WRITE_OWNER = 0x80000,
47 | SYNCHRONIZE = 0x100000,
48 | FILE_EXECUTE = 0x20
49 | }
50 |
51 | [Flags]
52 | public enum FileShareFlags : uint
53 | {
54 | FILE_SHARE_NONE = 0x0,
55 | FILE_SHARE_READ = 0x1,
56 | FILE_SHARE_WRITE = 0x2,
57 | FILE_SHARE_DELETE = 0x4
58 | }
59 |
60 | [Flags]
61 | public enum FileOpenFlags : uint
62 | {
63 | FILE_DIRECTORY_FILE = 0x1,
64 | FILE_WRITE_THROUGH = 0x2,
65 | FILE_SEQUENTIAL_ONLY = 0x4,
66 | FILE_NO_INTERMEDIATE_BUFFERING = 0x8,
67 | FILE_SYNCHRONOUS_IO_ALERT = 0x10,
68 | FILE_SYNCHRONOUS_IO_NONALERT = 0x20,
69 | FILE_NON_DIRECTORY_FILE = 0x40,
70 | FILE_CREATE_TREE_CONNECTION = 0x80,
71 | FILE_COMPLETE_IF_OPLOCKED = 0x100,
72 | FILE_NO_EA_KNOWLEDGE = 0x200,
73 | FILE_OPEN_FOR_RECOVERY = 0x400,
74 | FILE_RANDOM_ACCESS = 0x800,
75 | FILE_DELETE_ON_CLOSE = 0x1000,
76 | FILE_OPEN_BY_FILE_ID = 0x2000,
77 | FILE_OPEN_FOR_BACKUP_INTENT = 0x4000,
78 | FILE_NO_COMPRESSION = 0x8000
79 | }
80 | }
81 |
82 | public static class WinNT
83 | {
84 | public const uint PAGE_READONLY = 0x02;
85 | public const uint PAGE_READWRITE = 0x04;
86 | public const uint PAGE_EXECUTE = 0x10;
87 | public const uint PAGE_EXECUTE_READ = 0x20;
88 | public const uint PAGE_EXECUTE_READWRITE = 0x40;
89 |
90 | public const uint SEC_IMAGE = 0x1000000;
91 |
92 | [Flags]
93 | public enum ACCESS_MASK : uint
94 | {
95 | DELETE = 0x00010000,
96 | READ_CONTROL = 0x00020000,
97 | WRITE_DAC = 0x00040000,
98 | WRITE_OWNER = 0x00080000,
99 | SYNCHRONIZE = 0x00100000,
100 | STANDARD_RIGHTS_REQUIRED = 0x000F0000,
101 | STANDARD_RIGHTS_READ = 0x00020000,
102 | STANDARD_RIGHTS_WRITE = 0x00020000,
103 | STANDARD_RIGHTS_EXECUTE = 0x00020000,
104 | STANDARD_RIGHTS_ALL = 0x001F0000,
105 | SPECIFIC_RIGHTS_ALL = 0x0000FFF,
106 | ACCESS_SYSTEM_SECURITY = 0x01000000,
107 | MAXIMUM_ALLOWED = 0x02000000,
108 | GENERIC_READ = 0x80000000,
109 | GENERIC_WRITE = 0x40000000,
110 | GENERIC_EXECUTE = 0x20000000,
111 | GENERIC_ALL = 0x10000000,
112 | DESKTOP_READOBJECTS = 0x00000001,
113 | DESKTOP_CREATEWINDOW = 0x00000002,
114 | DESKTOP_CREATEMENU = 0x00000004,
115 | DESKTOP_HOOKCONTROL = 0x00000008,
116 | DESKTOP_JOURNALRECORD = 0x00000010,
117 | DESKTOP_JOURNALPLAYBACK = 0x00000020,
118 | DESKTOP_ENUMERATE = 0x00000040,
119 | DESKTOP_WRITEOBJECTS = 0x00000080,
120 | DESKTOP_SWITCHDESKTOP = 0x00000100,
121 | WINSTA_ENUMDESKTOPS = 0x00000001,
122 | WINSTA_READATTRIBUTES = 0x00000002,
123 | WINSTA_ACCESSCLIPBOARD = 0x00000004,
124 | WINSTA_CREATEDESKTOP = 0x00000008,
125 | WINSTA_WRITEATTRIBUTES = 0x00000010,
126 | WINSTA_ACCESSGLOBALATOMS = 0x00000020,
127 | WINSTA_EXITWINDOWS = 0x00000040,
128 | WINSTA_ENUMERATE = 0x00000100,
129 | WINSTA_READSCREEN = 0x00000200,
130 | WINSTA_ALL_ACCESS = 0x0000037F,
131 |
132 | SECTION_ALL_ACCESS = 0x10000000,
133 | SECTION_QUERY = 0x0001,
134 | SECTION_MAP_WRITE = 0x0002,
135 | SECTION_MAP_READ = 0x0004,
136 | SECTION_MAP_EXECUTE = 0x0008,
137 | SECTION_EXTEND_SIZE = 0x0010
138 | };
139 | }
140 | }
--------------------------------------------------------------------------------
/DInvoke.DynamicInvoke/DInvoke.DynamicInvoke.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | enable
6 | disable
7 | 12
8 | true
9 | TheWover, RastaMouse
10 | Dynamically invoke arbitrary unmanaged code from managed code without P/Invoke.
11 | DInvoke.DynamicInvoke
12 | DInvoke.DynamicInvoke
13 | 1.0.7
14 |
15 |
16 |
17 | true
18 |
19 |
20 |
21 | true
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/DInvoke.DynamicInvoke/Generic.cs:
--------------------------------------------------------------------------------
1 | // Author: Ryan Cobb (@cobbr_io)
2 | // Project: SharpSploit (https://github.com/cobbr/SharpSploit)
3 | // License: BSD 3-Clause
4 |
5 | using System.Diagnostics;
6 | using System.Runtime.InteropServices;
7 |
8 | namespace DInvoke.DynamicInvoke;
9 |
10 | ///
11 | /// Generic is a class for dynamically invoking arbitrary API calls from memory or disk. DynamicInvoke avoids suspicious
12 | /// P/Invoke signatures, imports, and IAT entries by loading modules and invoking their functions at runtime.
13 | ///
14 | public static class Generic
15 | {
16 | [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
17 | private delegate IntPtr ReadGs();
18 |
19 | private static readonly byte[] X64SyscallStub =
20 | [
21 | 0x49, 0x89, 0xCA, // mov r10, rcx
22 | 0xB8, 0x00, 0x00, 0x00, 0x00, // mov eax, ssn
23 | 0x0F, 0x05, // syscall
24 | 0xC3 // ret
25 | ];
26 |
27 | ///
28 | /// Dynamically invoke an arbitrary function from a DLL, providing its name, function prototype, and arguments.
29 | ///
30 | /// The Wover (@TheRealWover)
31 | /// Name of the DLL.
32 | /// Name of the function.
33 | /// Prototype for the function, represented as a Delegate object.
34 | /// Parameters to pass to the function. Can be modified if function uses call by reference.
35 | /// Whether the DLL may be loaded from disk if it is not already loaded. Default is false.
36 | /// Whether or not to resolve export forwards. Default is true.
37 | /// Object returned by the function. Must be unmarshalled by the caller.
38 | public static T DynamicApiInvoke(string dllName, string functionName, Type functionDelegateType, ref object[] parameters, bool canLoadFromDisk = false, bool resolveForwards = true)
39 | {
40 | var pFunction = GetLibraryAddress(dllName, functionName, canLoadFromDisk, resolveForwards);
41 | return DynamicFunctionInvoke(pFunction, functionDelegateType, ref parameters);
42 | }
43 |
44 | ///
45 | /// Dynamically invokes an arbitrary function from a pointer. Useful for manually mapped modules or loading/invoking unmanaged code from memory.
46 | ///
47 | /// The Wover (@TheRealWover)
48 | /// A pointer to the unmanaged function.
49 | /// Prototype for the function, represented as a Delegate object.
50 | /// Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.
51 | /// Object returned by the function. Must be unmarshalled by the caller.
52 | public static T DynamicFunctionInvoke(IntPtr functionPointer, Type functionDelegateType, ref object[] parameters)
53 | {
54 | var funcDelegate = Marshal.GetDelegateForFunctionPointer(functionPointer, functionDelegateType);
55 | return (T)funcDelegate.DynamicInvoke(parameters);
56 | }
57 |
58 | public static T DynamicAsmInvoke(byte[] asmStub, Type functionDelegateType, ref object[] parameters)
59 | {
60 | unsafe
61 | {
62 | fixed (byte* buffer = asmStub)
63 | {
64 | var ptr = (IntPtr)buffer;
65 | var size = new IntPtr(asmStub.Length);
66 |
67 | var oldProtect = Native.NtProtectVirtualMemory(new IntPtr(-1), ref ptr,
68 | ref size, Data.Win32.WinNT.PAGE_EXECUTE_READWRITE);
69 |
70 | var result = DynamicFunctionInvoke(ptr, functionDelegateType, ref parameters);
71 |
72 | Native.NtProtectVirtualMemory(new IntPtr(-1), ref ptr,
73 | ref size, oldProtect);
74 |
75 | return result;
76 | }
77 | }
78 | }
79 |
80 | ///
81 | /// Resolves LdrLoadDll and uses that function to load a DLL from disk.
82 | ///
83 | /// Ruben Boonen (@FuzzySec)
84 | /// The path to the DLL on disk. Uses the LoadLibrary convention.
85 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully.
86 | public static IntPtr LoadModuleFromDisk(string dllPath)
87 | {
88 | var uModuleName = new Data.Native.UNICODE_STRING();
89 | Native.RtlInitUnicodeString(ref uModuleName, dllPath);
90 |
91 | var hModule = IntPtr.Zero;
92 | var callResult = Native.LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule);
93 |
94 | if (callResult != Data.Native.NTSTATUS.Success || hModule == IntPtr.Zero)
95 | return IntPtr.Zero;
96 |
97 | return hModule;
98 | }
99 |
100 | ///
101 | /// Helper for getting the pointer to a function from a DLL loaded by the process.
102 | ///
103 | /// Ruben Boonen (@FuzzySec)
104 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").
105 | /// Name of the exported procedure.
106 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.
107 | /// Whether or not to resolve export forwards. Default is true.
108 | /// IntPtr for the desired function.
109 | public static IntPtr GetLibraryAddress(string dllName, string functionName, bool canLoadFromDisk = false, bool resolveForwards = true)
110 | {
111 | var hModule = GetLoadedModuleAddress(dllName);
112 |
113 | if (hModule == IntPtr.Zero && canLoadFromDisk)
114 | {
115 | hModule = LoadModuleFromDisk(dllName);
116 |
117 | if (hModule == IntPtr.Zero)
118 | throw new FileNotFoundException(dllName + ", unable to find the specified file.");
119 | }
120 | else if (hModule == IntPtr.Zero)
121 | {
122 | throw new DllNotFoundException(dllName + ", Dll was not found.");
123 | }
124 |
125 | return GetExportAddress(hModule, functionName, resolveForwards);
126 | }
127 |
128 | ///
129 | /// Helper for getting the pointer to a function from a DLL loaded by the process.
130 | ///
131 | /// Ruben Boonen (@FuzzySec)
132 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").
133 | /// Ordinal of the exported procedure.
134 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.
135 | /// Whether or not to resolve export forwards. Default is true.
136 | /// IntPtr for the desired function.
137 | public static IntPtr GetLibraryAddress(string dllName, short ordinal, bool canLoadFromDisk = false, bool resolveForwards = true)
138 | {
139 | var hModule = GetLoadedModuleAddress(dllName);
140 |
141 | if (hModule == IntPtr.Zero && canLoadFromDisk)
142 | {
143 | hModule = LoadModuleFromDisk(dllName);
144 |
145 | if (hModule == IntPtr.Zero)
146 | throw new FileNotFoundException(dllName + ", unable to find the specified file.");
147 | }
148 | else if (hModule == IntPtr.Zero)
149 | {
150 | throw new DllNotFoundException(dllName + ", Dll was not found.");
151 | }
152 |
153 | return GetExportAddress(hModule, ordinal, resolveForwards);
154 | }
155 |
156 | ///
157 | /// Helper for getting the pointer to a function from a DLL loaded by the process.
158 | ///
159 | /// Ruben Boonen (@FuzzySec)
160 | /// The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").
161 | /// Hash of the exported procedure.
162 | /// 64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).
163 | /// Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.
164 | /// Whether or not to resolve export forwards. Default is true.
165 | /// IntPtr for the desired function.
166 | public static IntPtr GetLibraryAddress(string dllName, string functionHash, long key, bool canLoadFromDisk = false, bool resolveForwards = true)
167 | {
168 | var hModule = GetLoadedModuleAddress(dllName);
169 |
170 | if (hModule == IntPtr.Zero && canLoadFromDisk)
171 | {
172 | hModule = LoadModuleFromDisk(dllName);
173 |
174 | if (hModule == IntPtr.Zero)
175 | throw new FileNotFoundException(dllName + ", unable to find the specified file.");
176 | }
177 | else if (hModule == IntPtr.Zero)
178 | {
179 | throw new DllNotFoundException(dllName + ", Dll was not found.");
180 | }
181 |
182 | return GetExportAddress(hModule, functionHash, key, resolveForwards);
183 | }
184 |
185 | ///
186 | /// Helper for getting the base address of a module loaded by the current process. This base
187 | /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for
188 | /// manual export parsing. This function uses the .NET System.Diagnostics.Process class.
189 | ///
190 | /// Ruben Boonen (@FuzzySec)
191 | /// The name of the DLL (e.g. "ntdll.dll").
192 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.
193 | public static IntPtr GetLoadedModuleAddress(string dllName)
194 | {
195 | using var process = Process.GetCurrentProcess();
196 |
197 | foreach (ProcessModule module in process.Modules)
198 | {
199 | if (module.ModuleName.Equals(dllName, StringComparison.OrdinalIgnoreCase))
200 | return module.BaseAddress;
201 | }
202 |
203 | return IntPtr.Zero;
204 | }
205 |
206 | ///
207 | /// Helper for getting the base address of a module loaded by the current process. This base
208 | /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for
209 | /// manual export parsing. This function uses the .NET System.Diagnostics.Process class.
210 | ///
211 | /// Hash of the DLL name.
212 | /// 64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).
213 | /// IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.
214 | public static IntPtr GetLoadedModuleAddress(string hashedDllName, long key)
215 | {
216 | using var process = Process.GetCurrentProcess();
217 |
218 | foreach (ProcessModule module in process.Modules)
219 | {
220 | var hashedName = Utilities.GetApiHash(module.ModuleName, key);
221 |
222 | if (hashedName.Equals(hashedDllName))
223 | return module.BaseAddress;
224 | }
225 |
226 | return IntPtr.Zero;
227 | }
228 |
229 | ///
230 | /// This function uses dynamic assembly invocation to obtain a pointer to the PEB.
231 | /// __readgsqword(0x60) or __readfsdword(0x30)
232 | ///
233 | /// Base address of the PEB as an IntPtr.
234 | public static IntPtr GetPebAddress()
235 | {
236 | byte[] stub;
237 |
238 | if (IntPtr.Size == 8)
239 | {
240 | stub =
241 | [
242 | 0x65, 0x48, 0x8B, 0x04, 0x25, 0x60, // mov rax, qword ptr gs:[0x60]
243 | 0x00, 0x00, 0x00,
244 | 0xc3 // ret
245 | ];
246 | }
247 | else
248 | {
249 | stub =
250 | [
251 | 0x64, 0xA1, 0x30, 0x00, 0x00, 0x00, // mov eax,dword ptr fs:[30]
252 | 0xC3 // ret
253 | ];
254 | }
255 |
256 | var parameters = Array.Empty