-
Notifications
You must be signed in to change notification settings - Fork 219
/
MIDebugPackagePackage.cs
481 lines (413 loc) · 18.9 KB
/
MIDebugPackagePackage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.IO;
using Microsoft.MIDebugEngine;
using System.Collections.Generic;
using MICore;
using System.Threading.Tasks;
namespace Microsoft.MIDebugPackage
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
///
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
// a package.
[PackageRegistration(UseManagedResourcesOnly = true)]
// This attribute is needed to let the shell know that this package exposes some menus.
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(GuidList.guidMIDebugPackagePkgString)]
#if LAB
// Adding this dll location to VS probe path. Custom launcher types are referenced by Linux/Azure Sphere workloads.
[ProvideBindingPath]
#endif
public sealed class MIDebugPackagePackage : Package, IOleCommandTarget
{
private IOleCommandTarget _packageCommandTarget;
/// <summary>
/// Default constructor of the package.
/// Inside this method you can place any initialization code that does not require
/// any Visual Studio service because at this point the package object is created but
/// not sited yet inside Visual Studio environment. The place to do all the other
/// initialization is the Initialize method.
/// </summary>
public MIDebugPackagePackage()
{
}
/////////////////////////////////////////////////////////////////////////////
// Overridden Package Implementation
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
protected override void Initialize()
{
ThreadHelper.ThrowIfNotOnUIThread();
base.Initialize();
_packageCommandTarget = GetService(typeof(IOleCommandTarget)) as IOleCommandTarget;
Assumes.Present(_packageCommandTarget);
}
#endregion
int IOleCommandTarget.Exec(ref Guid cmdGroup, uint nCmdID, uint nCmdExecOpt, IntPtr pvaIn, IntPtr pvaOut)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (cmdGroup == GuidList.guidMIDebugPackageCmdSet)
{
switch (nCmdID)
{
case PkgCmdIDList.cmdidLaunchMIDebug:
return LaunchMIDebug(nCmdExecOpt, pvaIn, pvaOut);
case PkgCmdIDList.cmdidMIDebugExec:
return MIDebugExec(nCmdExecOpt, pvaIn, pvaOut);
case PkgCmdIDList.cmdidMIDebugLog:
return MIDebugLog(nCmdExecOpt, pvaIn, pvaOut);
default:
Debug.Fail("Unknown command id");
return VSConstants.E_NOTIMPL;
}
}
return _packageCommandTarget.Exec(cmdGroup, nCmdID, nCmdExecOpt, pvaIn, pvaOut);
}
int IOleCommandTarget.QueryStatus(ref Guid cmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (cmdGroup == GuidList.guidMIDebugPackageCmdSet)
{
switch (prgCmds[0].cmdID)
{
case PkgCmdIDList.cmdidLaunchMIDebug:
case PkgCmdIDList.cmdidMIDebugExec:
case PkgCmdIDList.cmdidMIDebugLog:
prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_INVISIBLE);
return VSConstants.S_OK;
default:
Debug.Fail("Unknown command id");
return VSConstants.E_NOTIMPL;
}
}
return _packageCommandTarget.QueryStatus(ref cmdGroup, cCmds, prgCmds, pCmdText);
}
/// <summary>
/// The syntax for the MIDebugLaunch command. Notes:
/// ':' : The switch takes a value
/// '!' : The value is required
/// '(' ... ')' : Auto complete list for the switch (I don't know what is valid here except for 'd')
/// d : A path
/// </summary>
private const string LaunchMIDebugCommandSyntax = "E,Executable:!(d) O,OptionsFile:!(d)";
// NOTE: This must be in the same order as the syntax string
private enum LaunchMIDebugCommandSwitchEnum
{
Executable,
OptionsFile
}
private int LaunchMIDebug(uint nCmdExecOpt, IntPtr pvaIn, IntPtr pvaOut)
{
ThreadHelper.ThrowIfNotOnUIThread("Microsoft.MIDebugPackage.LaunchMIDebug");
int hr;
if (IsQueryParameterList(pvaIn, pvaOut, nCmdExecOpt))
{
Marshal.GetNativeVariantForObject("$ /switchdefs:\"" + LaunchMIDebugCommandSyntax + "\"", pvaOut);
return VSConstants.S_OK;
}
string arguments;
hr = EnsureString(pvaIn, out arguments);
if (hr != VSConstants.S_OK)
return hr;
IVsParseCommandLine parseCommandLine = (IVsParseCommandLine)GetService(typeof(SVsParseCommandLine));
if (parseCommandLine == null)
{
throw new InvalidOperationException("Why is IVsParseCommandLine null?");
}
hr = parseCommandLine.ParseCommandTail(arguments, iMaxParams: -1);
if (ErrorHandler.Failed(hr))
return hr;
hr = parseCommandLine.HasParams();
if (ErrorHandler.Failed(hr))
return hr;
if (hr == VSConstants.S_OK || parseCommandLine.HasSwitches() != VSConstants.S_OK)
{
string message = string.Concat("Unexpected syntax for MIDebugLaunch command. Expected:\n",
"Debug.MIDebugLaunch /Executable:<path_or_logical_name> /OptionsFile:<path>");
throw new ApplicationException(message);
}
hr = parseCommandLine.EvaluateSwitches(LaunchMIDebugCommandSyntax);
if (ErrorHandler.Failed(hr))
return hr;
string executable;
if (parseCommandLine.GetSwitchValue((int)LaunchMIDebugCommandSwitchEnum.Executable, out executable) != VSConstants.S_OK ||
string.IsNullOrWhiteSpace(executable))
{
throw new ArgumentException("Executable must be specified");
}
bool checkExecutableExists = false;
string options = string.Empty;
string optionsFilePath;
if (parseCommandLine.GetSwitchValue((int)LaunchMIDebugCommandSwitchEnum.OptionsFile, out optionsFilePath) == 0)
{
// When using the options file, we want to allow the executable to be just a logical name, but if
// one enters a real path, we should make sure it isn't mistyped. If the path contains a slash, we assume it
// is meant to be a real path so enforce that it exists
checkExecutableExists = (executable.IndexOf('\\') >= 0);
if (string.IsNullOrWhiteSpace(optionsFilePath))
throw new ArgumentException("Value expected for '/OptionsFile' option");
if (!File.Exists(optionsFilePath))
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Options file '{0}' does not exist", optionsFilePath));
options = File.ReadAllText(optionsFilePath);
}
if (checkExecutableExists)
{
if (!File.Exists(executable))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Executable '{0}' does not exist", executable));
}
executable = Path.GetFullPath(executable);
}
LaunchDebugTarget(executable, options);
return 0;
}
private int MIDebugExec(uint nCmdExecOpt, IntPtr pvaIn, IntPtr pvaOut)
{
int hr;
if (IsQueryParameterList(pvaIn, pvaOut, nCmdExecOpt))
{
Marshal.GetNativeVariantForObject("$", pvaOut);
return VSConstants.S_OK;
}
string arguments;
hr = EnsureString(pvaIn, out arguments);
if (hr != VSConstants.S_OK)
return hr;
if (string.IsNullOrWhiteSpace(arguments))
throw new ArgumentException("Expected an MI command to execute (ex: Debug.MIDebugExec info sharedlibrary)");
_ = MIDebugExecAsync(arguments);
return VSConstants.S_OK;
}
/// <summary>
/// The syntax for the MIDebugLog command. Notes:
/// ':' : The switch takes a value
/// '!' : The value is required
/// '(' ... ')' : Auto complete list for the switch (I don't know what is valid here except for 'd')
/// d : A path
/// </summary>
private const string LogMIDebugCommandSyntax = "O,On:(d) OutputWindow Off";
private enum LogMIDebugCommandSwitchEnum
{
On,
OutputWindow,
Off
}
private int MIDebugLog(uint nCmdLogOpt, IntPtr pvaIn, IntPtr pvaOut)
{
ThreadHelper.ThrowIfNotOnUIThread("Microsoft.MIDebugPackage.MIDebugLog");
int hr;
if (IsQueryParameterList(pvaIn, pvaOut, nCmdLogOpt))
{
Marshal.GetNativeVariantForObject("$ /switchdefs:\"" + LogMIDebugCommandSyntax + "\"", pvaOut);
return VSConstants.S_OK;
}
string arguments;
hr = EnsureString(pvaIn, out arguments);
if (hr != VSConstants.S_OK)
return hr;
IVsParseCommandLine parseCommandLine = (IVsParseCommandLine)GetService(typeof(SVsParseCommandLine));
if (parseCommandLine == null)
{
throw new InvalidOperationException("Why is IVsParseCommandLine null?");
}
hr = parseCommandLine.ParseCommandTail(arguments, iMaxParams: -1);
if (ErrorHandler.Failed(hr))
return hr;
hr = parseCommandLine.HasParams();
if (ErrorHandler.Failed(hr))
return hr;
if (hr == VSConstants.S_OK || parseCommandLine.HasSwitches() != VSConstants.S_OK)
{
string message = string.Concat("Unexpected syntax for MIDebugLaunch command. Expected:\n",
"Debug.MIDebugLog [/On:<optional_path> [/OutputWindow] | /Off]");
throw new ApplicationException(message);
}
hr = parseCommandLine.EvaluateSwitches(LogMIDebugCommandSyntax);
if (ErrorHandler.Failed(hr))
return hr;
string logPath = string.Empty;
bool logToOutput = false;
if (parseCommandLine.GetSwitchValue((int)LogMIDebugCommandSwitchEnum.On, out logPath) == VSConstants.S_OK)
{
logToOutput = parseCommandLine.IsSwitchPresent((int)LogMIDebugCommandSwitchEnum.OutputWindow) == VSConstants.S_OK;
if (parseCommandLine.IsSwitchPresent((int)LogMIDebugCommandSwitchEnum.Off) == VSConstants.S_OK)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "/On and /Off cannot both appear on command line"));
}
if (!logToOutput && string.IsNullOrEmpty(logPath))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Must specify a log file (/On:<path>) or /OutputWindow"));
}
}
else if (parseCommandLine.IsSwitchPresent((int)LogMIDebugCommandSwitchEnum.Off) != VSConstants.S_OK)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "One of /On or /Off must be present on command line"));
}
EnableLogging(logToOutput, logPath);
return 0;
}
private async Task MIDebugExecAsync(string command)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var commandWindow = (IVsCommandWindow)GetService(typeof(SVsCommandWindow));
if (commandWindow == null)
{
throw new InvalidOperationException("Why is IVsCommandWindow null?");
}
bool atBreak = false;
var debugger = GetService(typeof(SVsShellDebugger)) as IVsDebugger;
if (debugger != null)
{
DBGMODE[] mode = new DBGMODE[1];
if (debugger.GetMode(mode) == MIDebugEngine.Constants.S_OK)
{
atBreak = mode[0] == DBGMODE.DBGMODE_Break;
}
}
string results = null;
try
{
if (atBreak)
{
commandWindow.ExecuteCommand(String.Format(CultureInfo.InvariantCulture, "Debug.EvaluateStatement -exec {0}", command));
}
else
{
results = await MIDebugCommandDispatcher.ExecuteCommand(command);
}
}
catch (Exception e)
{
if (e.InnerException != null)
e = e.InnerException;
UnexpectedMIResultException miException = e as UnexpectedMIResultException;
string message;
if (miException != null && miException.MIError != null)
message = miException.MIError;
else
message = e.Message;
commandWindow.Print(string.Format(CultureInfo.CurrentCulture, "Error: {0}\r\n", message));
return;
}
if (results != null && results.Length > 0)
{
// Make sure that we are printing whole lines
if (!results.EndsWith("\n", StringComparison.Ordinal) && !results.EndsWith("\r\n", StringComparison.Ordinal))
{
results = results + "\n";
}
commandWindow.Print(results);
}
}
private void LaunchDebugTarget(string filePath, string options)
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsDebugger4 debugger = (IVsDebugger4)GetService(typeof(IVsDebugger));
if (debugger != null)
{
VsDebugTargetInfo4[] debugTargets = new VsDebugTargetInfo4[1];
debugTargets[0].dlo = (uint)DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
debugTargets[0].bstrExe = filePath;
debugTargets[0].bstrOptions = options;
debugTargets[0].guidLaunchDebugEngine = Microsoft.MIDebugEngine.EngineConstants.EngineId;
VsDebugTargetProcessInfo[] processInfo = new VsDebugTargetProcessInfo[debugTargets.Length];
debugger.LaunchDebugTargets4(1, debugTargets, processInfo);
}
else
{
throw new InvalidOperationException("Why is IVsDebugger4 null?");
}
}
private void EnableLogging(bool sendToOutputWindow, string logFile)
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsDebugger debugger = (IVsDebugger)GetService(typeof(IVsDebugger));
if (debugger != null)
{
DBGMODE[] mode = new DBGMODE[] { DBGMODE.DBGMODE_Design };
int hr = debugger.GetMode(mode);
if (hr == VSConstants.S_OK && mode[0] != DBGMODE.DBGMODE_Design)
{
throw new ArgumentException("Unable to update MIDebugLog while debugging.");
}
try
{
MIDebugCommandDispatcher.EnableLogging(sendToOutputWindow, logFile);
}
catch (Exception e)
{
var commandWindow = (IVsCommandWindow)GetService(typeof(SVsCommandWindow));
if (commandWindow != null)
{
commandWindow.Print(string.Format(CultureInfo.CurrentCulture, "Error: {0}\r\n", e.Message));
}
else
{
throw new InvalidOperationException("Why is IVsCommandWindow null?");
}
}
}
else
{
throw new InvalidOperationException("Why is IVsDebugger null?");
}
}
static private int EnsureString(IntPtr pvaIn, out string arguments)
{
arguments = null;
if (pvaIn == IntPtr.Zero)
{
// No arguments.
return VSConstants.E_INVALIDARG;
}
object vaInObject = Marshal.GetObjectForNativeVariant(pvaIn);
if (vaInObject == null || vaInObject.GetType() != typeof(string))
{
return VSConstants.E_INVALIDARG;
}
arguments = vaInObject as string;
return VSConstants.S_OK;
}
/// <summary>
/// Used to determine if the shell is querying for the parameter list.
/// </summary>
static private bool IsQueryParameterList(System.IntPtr pvaIn, System.IntPtr pvaOut, uint nCmdexecopt)
{
ushort lo = (ushort)(nCmdexecopt & (uint)0xffff);
ushort hi = (ushort)(nCmdexecopt >> 16);
if (lo == (ushort)OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP)
{
if (hi == VsMenus.VSCmdOptQueryParameterList)
{
if (pvaOut != IntPtr.Zero)
{
return true;
}
}
}
return false;
}
}
}