├── .gitignore
├── LICENSE
├── README.md
├── nuget
├── ClrMDExports.nuspec
├── nuget.exe
└── pack.cmd
└── src
├── ClrMDExports.sln
└── ClrMDExports
├── ClrMDExports.csproj
├── CrossDomainInvoker.cs
├── DbgEngStream.cs
├── DebuggingContext.cs
├── DelegateBuilder.cs
├── DispatchProxy.cs
├── DispatchProxyGenerator.cs
├── ILLDBDebugClient.cs
├── Init.cs
├── Initialization.cs
├── NativeInvoker.cs
├── Properties
└── AssemblyInfo.cs
└── StripDmlWriter.cs
/.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 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Kevin Gosse
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ClrMDExports
2 |
3 | Helpers to easily create WinDbg extensions using ClrMD.
4 |
5 | Create a new class library project, reference the nuget package, then add the `DllExport` attribute to the functions you want to export to WinDbg. Then call `DebuggingContext.Execute` with a callback, to be able to use ClrMD.
6 |
7 | **Note: you need to compile your project for x86 or x64 depending on the bitness of your target. AnyCPU is not supported.**
8 |
9 | ```C#
10 | using System;
11 | using System.Linq;
12 | using System.Runtime.InteropServices;
13 | using ClrMDExports;
14 | using Microsoft.Diagnostics.Runtime;
15 | using RGiesecke.DllExport;
16 |
17 | namespace TestWindbgExtension
18 | {
19 | public class Class1
20 | {
21 | [DllExport("helloworld")]
22 | public static void HelloWorld(IntPtr client, [MarshalAs(UnmanagedType.LPStr)] string args)
23 | {
24 | // Can't use ClrMD here. Use DebuggingContext.Execute with a callback to switch to another context:
25 | DebuggingContext.Execute(client, args, HelloWorld);
26 | }
27 |
28 | private static void HelloWorld(ClrRuntime runtime, string args)
29 | {
30 | // Can use ClrMD here
31 | Console.WriteLine("The first 10 types on the heap are: ");
32 |
33 | foreach (var obj in runtime.Heap.EnumerateObjects().Take(10))
34 | {
35 | Console.WriteLine(obj.Type);
36 | }
37 | }
38 | }
39 | }
40 |
41 | ```
42 |
43 |
--------------------------------------------------------------------------------
/nuget/ClrMDExports.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ClrMDExports
5 | 2.0.0.0-rc1
6 | ClrMD Exports
7 | Kevin Gosse
8 | Kevin Gosse
9 | false
10 | https://github.com/kevingosse/ClrMDExports/blob/master/LICENSE
11 | https://github.com/kevingosse/ClrMDExports
12 | Helper library to create extensions for WinDbg/LLDB using ClrMD.
13 | Update to ClrMD 2
14 | Copyright 2019-2021
15 | ClrMD WinDBG SOS LLDB
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/nuget/nuget.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kevingosse/ClrMDExports/86c37a4e71dd11b2ae358a0068b86eeb1bba4e44/nuget/nuget.exe
--------------------------------------------------------------------------------
/nuget/pack.cmd:
--------------------------------------------------------------------------------
1 | xcopy /R /Y "..\src\ClrMDExports\Init.cs" ".\contentFiles\cs\net471\"
2 | xcopy /R /Y "..\src\ClrMDExports\Init.cs" ".\contentFiles\cs\netstandard2.0\"
3 | xcopy /R /Y "..\src\ClrMDExports\Init.cs" ".\content\"
4 |
5 | nuget pack
--------------------------------------------------------------------------------
/src/ClrMDExports.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.329
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClrMDExports", "ClrMDExports\ClrMDExports.csproj", "{779ED776-74EF-4ADA-8E0F-7BE463811483}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {779ED776-74EF-4ADA-8E0F-7BE463811483}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {779ED776-74EF-4ADA-8E0F-7BE463811483}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {779ED776-74EF-4ADA-8E0F-7BE463811483}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {779ED776-74EF-4ADA-8E0F-7BE463811483}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {E085A3A4-3D3F-4310-B0FD-595A67818EDD}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/src/ClrMDExports/ClrMDExports.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net471
5 | ClrMDExports
6 | true
7 | false
8 | false
9 |
10 |
11 |
12 |
13 | xcopy /R /Y "$(TargetPath)" "$(ProjectDir)\..\..\nuget\lib\netstandard2.0\"
14 | xcopy /R /Y "$(TargetPath)" "$(ProjectDir)\..\..\nuget\lib\net471\"
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | All
25 | None
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/src/ClrMDExports/CrossDomainInvoker.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Reflection;
4 | using Microsoft.Diagnostics.Runtime;
5 |
6 | namespace ClrMDExports
7 | {
8 | [Serializable]
9 | public delegate void DebuggingMethod(ClrRuntime runtime, string args);
10 |
11 | [Serializable]
12 | public class CrossDomainInvoker
13 | {
14 | private readonly IntPtr _client;
15 | private readonly string _args;
16 | private readonly string _type;
17 | private readonly int _methodMetadataToken;
18 |
19 | public CrossDomainInvoker(IntPtr client, string args, string type, int methodMetadataToken)
20 | {
21 | _client = client;
22 | _args = args;
23 | _type = type;
24 | _methodMetadataToken = methodMetadataToken;
25 | }
26 |
27 | public void Invoke()
28 | {
29 | DebuggingContext.Initialize(_client, true);
30 |
31 | MethodInfo method = null;
32 | var type = Type.GetType(_type);
33 |
34 | if (type == null)
35 | {
36 | Console.WriteLine("Could not load type {0} in child AppDomain", _type);
37 | return;
38 | }
39 |
40 | var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
41 |
42 | method = methods.FirstOrDefault(m => m.MetadataToken == _methodMetadataToken);
43 |
44 | if (method == null)
45 | {
46 | Console.WriteLine("Could not find static method with metadata token {0} in type {1}", _methodMetadataToken, _type);
47 | return;
48 | }
49 |
50 | try
51 | {
52 | method.Invoke(null, new object[] { DebuggingContext.Runtime, _args });
53 | }
54 | catch (Exception ex)
55 | {
56 | Console.WriteLine("Error while executing the command: " + ex);
57 | }
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/src/ClrMDExports/DbgEngStream.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Runtime.InteropServices;
4 | using System.Text;
5 | using Microsoft.Diagnostics.Runtime.Interop;
6 |
7 | namespace ClrMDExports
8 | {
9 | internal class DbgEngStream : Stream
10 | {
11 | private readonly IDebugClient _client;
12 | private readonly IDebugControl _control;
13 |
14 | public DbgEngStream(IDebugClient client)
15 | {
16 | _client = client;
17 | _control = (IDebugControl)client;
18 | }
19 |
20 | public void Clear()
21 | {
22 | while (Marshal.ReleaseComObject(_client) > 0) { }
23 | while (Marshal.ReleaseComObject(_control) > 0) { }
24 | }
25 |
26 | public override bool CanRead => false;
27 |
28 | public override bool CanSeek => false;
29 |
30 | public override bool CanWrite => true;
31 |
32 | public override void Flush() { }
33 |
34 | public override long Length => -1;
35 |
36 | public override long Position
37 | {
38 | get => 0;
39 | set { }
40 | }
41 |
42 | public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException();
43 |
44 | public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();
45 |
46 | public override void SetLength(long value) => throw new NotImplementedException();
47 |
48 | public override void Write(byte[] buffer, int offset, int count)
49 | {
50 | string str = new UTF8Encoding().GetString(buffer, offset, count);
51 | _control.ControlledOutput(DEBUG_OUTCTL.ALL_CLIENTS | DEBUG_OUTCTL.DML, DEBUG_OUTPUT.NORMAL, str);
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/src/ClrMDExports/DebuggingContext.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Runtime.InteropServices;
7 | using Microsoft.Diagnostics.Runtime;
8 | using Microsoft.Diagnostics.Runtime.Interop;
9 |
10 | namespace ClrMDExports
11 | {
12 | public class DebuggingContext
13 | {
14 | private static AppDomain ChildDomain;
15 |
16 | public static bool IsWinDbg { get; internal set; }
17 |
18 | internal static IDebugClient DebugClient { get; private set; }
19 | internal static DataTarget DataTarget { get; private set; }
20 | internal static ClrRuntime Runtime { get; private set; }
21 |
22 | private static readonly string[] vtable =
23 | {
24 | "QueryInterface",
25 | "AddRef",
26 | "Release",
27 | "GetCoreClrDirectory",
28 | "GetExpression",
29 | "VirtualUnwind",
30 | "SetExceptionCallback",
31 | "ClearExceptionCallback",
32 |
33 | //----------------------------------------------------------------------------
34 | // IDebugControl2
35 | //----------------------------------------------------------------------------
36 |
37 | "GetInterrupt",
38 | "OutputVaList",
39 | "GetDebuggeeType",
40 | "GetPageSize",
41 | "GetExecutingProcessorType",
42 | "Execute",
43 | "GetLastEventInformation",
44 | "Disassemble",
45 |
46 | //----------------------------------------------------------------------------
47 | // IDebugControl4
48 | //----------------------------------------------------------------------------
49 |
50 | "GetContextStackTrace",
51 |
52 | //----------------------------------------------------------------------------
53 | // IDebugDataSpaces
54 | //----------------------------------------------------------------------------
55 |
56 | "ReadVirtual",
57 | "WriteVirtual",
58 |
59 | //----------------------------------------------------------------------------
60 | // IDebugSymbols
61 | //----------------------------------------------------------------------------
62 |
63 | "GetSymbolOptions",
64 | "GetNameByOffset",
65 | "GetNumberModules",
66 | "GetModuleByIndex",
67 | "GetModuleByModuleName",
68 | "GetModuleByOffset",
69 | "GetModuleNames",
70 | "GetModuleParameters",
71 | "GetModuleNameString",
72 | "IsPointer64Bit",
73 | "GetLineByOffset",
74 | "GetSourceFileLineOffsets",
75 | "FindSourceFile",
76 |
77 | //----------------------------------------------------------------------------
78 | // IDebugSystemObjects
79 | //----------------------------------------------------------------------------
80 |
81 | "GetCurrentProcessId",
82 | "GetCurrentThreadId",
83 | "SetCurrentThreadId",
84 | "GetCurrentThreadSystemId",
85 | "GetThreadIdBySystemId",
86 | "GetThreadContextById",
87 |
88 | //----------------------------------------------------------------------------
89 | // IDebugRegisters
90 | //----------------------------------------------------------------------------
91 |
92 | "GetValueByName",
93 | "GetInstructionOffset",
94 | "GetStackOffset",
95 | "GetFrameOffset",
96 |
97 | //----------------------------------------------------------------------------
98 | // LLDBServices (internal)
99 | //----------------------------------------------------------------------------
100 |
101 | "GetModuleDirectory"
102 | };
103 |
104 | public static void Execute(IntPtr client, string args, DebuggingMethod callback)
105 | {
106 | if (!callback.Method.IsStatic)
107 | {
108 | Console.WriteLine("The callback given to DebuggingContext.Execute needs to be a static method");
109 | return;
110 | }
111 |
112 | if (IsWinDbg)
113 | {
114 | ExecuteWinDbg(client, args, callback);
115 | }
116 | else
117 | {
118 | if (Runtime == null)
119 | {
120 | Initialize(client, false);
121 | }
122 |
123 | callback(Runtime, args);
124 | }
125 | }
126 |
127 | [MethodImpl(MethodImplOptions.NoInlining)]
128 | private static void ExecuteWinDbg(IntPtr client, string args, DebuggingMethod callback)
129 | {
130 | if (ChildDomain == null)
131 | {
132 | var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
133 |
134 | ChildDomain = AppDomain.CreateDomain("WinDbgExtension", AppDomain.CurrentDomain.Evidence, assemblyPath, ".", false);
135 | }
136 |
137 | var invoker = new CrossDomainInvoker(client, args, callback.Method.DeclaringType.AssemblyQualifiedName, callback.Method.MetadataToken);
138 |
139 | ChildDomain.DoCallBack(invoker.Invoke);
140 | }
141 |
142 | internal static void Initialize(IntPtr ptrClient, bool isWinDbg)
143 | {
144 | // On our first call to the API:
145 | // 1. Store a copy of IDebugClient in DebugClient.
146 | // 2. Replace Console's output stream to be the debugger window.
147 | // 3. Create an instance of DataTarget using the IDebugClient.
148 | if (DataTarget == null)
149 | {
150 | if (!isWinDbg)
151 | {
152 | DebugClient = NativeInvoker.GetInstance(ptrClient, vtable);
153 |
154 | var linuxFunctionsType = Type.GetType("Microsoft.Diagnostics.Runtime.LinuxFunctions, Microsoft.Diagnostics.Runtime");
155 |
156 | var field = typeof(DataTarget).GetField("k__BackingField", BindingFlags.Static | BindingFlags.NonPublic);
157 |
158 | field.SetValue(null, Activator.CreateInstance(linuxFunctionsType));
159 |
160 | Console.SetOut(new StripDmlWriter(Console.Out));
161 | }
162 | else
163 | {
164 | DebugClient = (IDebugClient)Marshal.GetUniqueObjectForIUnknown(ptrClient);
165 |
166 | var stream = new StreamWriter(new DbgEngStream(DebugClient)) { AutoFlush = true };
167 | Console.SetOut(stream);
168 | }
169 |
170 | DataTarget = DataTarget.CreateFromDbgEng(ptrClient);
171 | }
172 |
173 | // If our ClrRuntime instance is null, it means that this is our first call, or
174 | // that the dac wasn't loaded on any previous call.
175 | if (Runtime == null)
176 | {
177 | Runtime = DataTarget.ClrVersions.Single().CreateRuntime();
178 | }
179 | }
180 | }
181 | }
--------------------------------------------------------------------------------
/src/ClrMDExports/DelegateBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Reflection.Emit;
4 | using System.Runtime.InteropServices;
5 |
6 | namespace ClrMDExports
7 | {
8 | public class DelegateBuilder
9 | {
10 | public static Type GenerateDelegateType(MethodInfo targetMethod)
11 | {
12 | var assembly = new AssemblyName
13 | {
14 | Version = new Version(1, 0, 0, 0),
15 | Name = Guid.NewGuid().ToString().Replace("-", string.Empty)
16 | };
17 |
18 | var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.Run);
19 | var modbuilder = assemblyBuilder.DefineDynamicModule("MyModule");
20 |
21 | // Create a delegate that has the same signature as the method we would like to hook up to
22 | var typeBuilder = modbuilder.DefineType("MyDelegateType", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));
23 |
24 | var unmanagedFunctionPointerAttributeBuilder = new CustomAttributeBuilder(typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new Type[] { typeof(CallingConvention) }), new object[] { CallingConvention.StdCall });
25 | typeBuilder.SetCustomAttribute(unmanagedFunctionPointerAttributeBuilder);
26 |
27 | var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });
28 | constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
29 |
30 | // Grab the parameters of the method
31 | var parameters = targetMethod.GetParameters();
32 |
33 | var paramTypes = new Type[parameters.Length + 1];
34 |
35 | paramTypes[0] = typeof(IntPtr);
36 |
37 | for (int i = 0; i < parameters.Length; i++)
38 | {
39 | paramTypes[i + 1] = parameters[i].ParameterType;
40 | }
41 |
42 | // Define the Invoke method for the delegate
43 | var methodBuilder = typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, targetMethod.ReturnType, paramTypes);
44 |
45 | for (int i = 0; i < parameters.Length; i++)
46 | {
47 | var parameter = parameters[i];
48 |
49 | var attributes = ParameterAttributes.None;
50 |
51 | UnmanagedType? unmanagedType = null;
52 |
53 | bool outAttribute = false;
54 |
55 | foreach (var customAttribute in parameter.CustomAttributes)
56 | {
57 | if (customAttribute.AttributeType == typeof(MarshalAsAttribute))
58 | {
59 | attributes |= ParameterAttributes.HasFieldMarshal;
60 | unmanagedType = (UnmanagedType)customAttribute.ConstructorArguments[0].Value;
61 | }
62 |
63 | if (customAttribute.AttributeType == typeof(InAttribute))
64 | {
65 | attributes |= ParameterAttributes.In;
66 | }
67 |
68 | if (customAttribute.AttributeType == typeof(OutAttribute))
69 | {
70 | attributes |= ParameterAttributes.Out;
71 | outAttribute = true;
72 | }
73 | }
74 |
75 | var pbr = methodBuilder.DefineParameter(i + 2, attributes, null);
76 |
77 | if (outAttribute)
78 | {
79 | var outAttributeBuilder = new CustomAttributeBuilder(typeof(OutAttribute).GetConstructor(new Type[0]), new object[0]);
80 | pbr.SetCustomAttribute(outAttributeBuilder);
81 | }
82 |
83 | if (unmanagedType != null)
84 | {
85 | var marshalAsAttributeBuilder = new CustomAttributeBuilder(typeof(MarshalAsAttribute).GetConstructor(new Type[] { typeof(UnmanagedType) }), new object[] { unmanagedType.Value });
86 | pbr.SetCustomAttribute(marshalAsAttributeBuilder);
87 | }
88 | }
89 |
90 | methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
91 |
92 | return typeBuilder.CreateTypeInfo();
93 | }
94 | }
95 | }
--------------------------------------------------------------------------------
/src/ClrMDExports/DispatchProxy.cs:
--------------------------------------------------------------------------------
1 | namespace System.Reflection
2 | {
3 | ///
4 | /// DispatchProxy provides a mechanism for the instantiation of proxy objects and handling of
5 | /// their method dispatch.
6 | ///
7 | internal abstract class DispatchProxy
8 | {
9 | protected DispatchProxy()
10 | {
11 | }
12 |
13 | ///
14 | /// Whenever any method on the generated proxy type is called, this method
15 | /// will be invoked to dispatch control.
16 | ///
17 | /// The method the caller invoked
18 | /// The arguments the caller passed to the method
19 | /// The object to return to the caller, or null for void methods
20 | protected abstract object Invoke(MethodInfo targetMethod, object[] args);
21 |
22 | ///
23 | /// Creates an object instance that derives from class
24 | /// and implements interface .
25 | ///
26 | /// The interface the proxy should implement.
27 | /// The base class to use for the proxy class.
28 | /// An object instance that implements .
29 | /// is a class,
30 | /// or is sealed or does not have a parameterless constructor
31 | public static T Create()
32 | where TProxy : DispatchProxy
33 | {
34 | return (T)DispatchProxyGenerator.CreateProxyInstance(typeof(TProxy), typeof(T));
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/src/ClrMDExports/DispatchProxyGenerator.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 | // See the LICENSE file in the project root for more information.
4 |
5 | using System.Collections.Generic;
6 | using System.Diagnostics;
7 | using System.Linq;
8 | using System.Reflection.Emit;
9 | using System.Runtime.ExceptionServices;
10 | using System.Threading;
11 |
12 | namespace System.Reflection
13 | {
14 | // Helper class to handle the IL EMIT for the generation of proxies.
15 | // Much of this code was taken directly from the Silverlight proxy generation.
16 | // Differences between this and the Silverlight version are:
17 | // 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel.
18 | // There are several notable differences between them.
19 | // 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types:
20 | // the interface type to implement, and a base type. But they behave slightly differently:
21 | // - RealProxy generates a proxy type that derives from Object and *implements" all the base type's
22 | // interfaces plus all the interface type's interfaces.
23 | // - DispatchProxy generates a proxy type that *derives* from the base type and implements all
24 | // the interface type's interfaces. This is true for both the CLR version in NET Native and this
25 | // version for CoreCLR.
26 | // 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies:
27 | // - RealProxy type hierarchy is:
28 | // proxyType : proxyBaseType : object
29 | // Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces
30 | // explicitly, preventing collision for same name methods on the base and interface types.
31 | // - DispatchProxy hierarchy is:
32 | // proxyType : baseType (where baseType : DispatchProxy)
33 | // The generated DispatchProxy proxy type does not need to generate implementation methods
34 | // for the base type's interfaces, because the base type already must have implemented them.
35 | // 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror
36 | // the .Net Remoting design that required the proxy and RealProxy to be separate instances.
37 | // But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore,
38 | // the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were
39 | // able to remove an extraneous field and ctor arg from the DispatchProxy proxies.
40 | //
41 | internal static class DispatchProxyGenerator
42 | {
43 | // Generated proxies have a private Action field that all generated methods
44 | // invoke. It is the first field in the class and the first ctor parameter.
45 | private const int InvokeActionFieldAndCtorParameterIndex = 0;
46 |
47 | // Proxies are requested for a pair of types: base type and interface type.
48 | // The generated proxy will subclass the given base type and implement the interface type.
49 | // We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type,
50 | // containing the generated proxy type for that pair. There are likely to be few (maybe only 1)
51 | // base type in use for many interface types.
52 | // Note: this differs from Silverlight's RealProxy implementation which keys strictly off the
53 | // interface type. But this does not allow the same interface type to be used with more than a
54 | // single base type. The implementation here permits multiple interface types to be used with
55 | // multiple base types, and the generated proxy types will be unique.
56 | // This cache of generated types grows unbounded, one element per unique T/ProxyT pair.
57 | // This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs,
58 | // which would ultimately be a more expensive leak.
59 | // Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create.
60 | private static readonly Dictionary> s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary>();
61 | private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly();
62 | private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke");
63 |
64 | // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType'
65 | internal static object CreateProxyInstance(Type baseType, Type interfaceType)
66 | {
67 | Debug.Assert(baseType != null);
68 | Debug.Assert(interfaceType != null);
69 |
70 | Type proxiedType = GetProxyType(baseType, interfaceType);
71 | return Activator.CreateInstance(proxiedType, (Action