-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathgdb.cs
More file actions
424 lines (375 loc) · 16.8 KB
/
gdb.cs
File metadata and controls
424 lines (375 loc) · 16.8 KB
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
// 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.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using System.Collections.ObjectModel;
using System.Linq;
using System.Globalization;
using Microsoft.DebugEngineHost;
namespace MICore
{
internal class GdbMICommandFactory : MICommandFactory
{
private int _currentThreadId = 0;
private uint _currentFrameLevel = 0;
public override string Name
{
get { return "GDB"; }
}
public override void DefineCurrentThread(int threadId)
{
_currentThreadId = threadId;
// If current threadId is changed, reset _currentFrameLevel
_currentFrameLevel = 0;
}
public override int CurrentThread { get { return _currentThreadId; } }
public override bool SupportsStopOnDynamicLibLoad()
{
return true;
}
public override bool SupportsChildProcessDebugging()
{
return true;
}
public override bool AllowCommandsWhileRunning()
{
return false;
}
protected override async Task<Results> ThreadFrameCmdAsync(string command, string args, ResultClass expectedResultClass, int threadId, uint frameLevel)
{
// first aquire an exclusive lock. This is used as we don't want to fight with other commands that also require the current
// thread to be set to a particular value
ExclusiveLockToken lockToken = await _debugger.CommandLock.AquireExclusive();
try
{
string threadFrameCommand;
// With source code of gdb 7.0.0, the --thread and --frame options were introduced and -thread-select and
// -stack-select-frame were deprecated
if (MajorVersion < 7)
{
await ThreadSelect(threadId, lockToken);
await StackSelectFrame(frameLevel, lockToken);
threadFrameCommand = string.Format(CultureInfo.InvariantCulture, $@"{command} {args}");
}
else
{
threadFrameCommand = string.Format(CultureInfo.InvariantCulture, $@"{command} --thread {threadId} --frame {frameLevel} {args}");
}
// Before we execute the provided command, we need to switch to a shared lock. This is because the provided
// command may be an expression evaluation command which could be long running, and we don't want to hold the
// exclusive lock during this.
lockToken.ConvertToSharedLock();
lockToken = null;
return await _debugger.CmdAsync(threadFrameCommand, expectedResultClass);
}
finally
{
if (lockToken != null)
{
// finally is executing before we called 'ConvertToSharedLock'
lockToken.Close();
}
else
{
// finally is called after we called ConvertToSharedLock, we need to decerement the shared lock count
_debugger.CommandLock.ReleaseShared();
}
}
}
protected override async Task<Results> ThreadCmdAsync(string command, string args, ResultClass expectedResultClass, int threadId)
{
// first aquire an exclusive lock. This is used as we don't want to fight with other commands that also require the current
// thread to be set to a particular value
ExclusiveLockToken lockToken = await _debugger.CommandLock.AquireExclusive();
try
{
string threadCommand;
// With source code of gdb 7.0.0, the --thread option was introduced and -thread-select
// was deprecated
if (MajorVersion < 7)
{
await ThreadSelect(threadId, lockToken);
threadCommand = string.Format(CultureInfo.InvariantCulture, $@"{command} {args}");
}
else
{
threadCommand = string.Format(CultureInfo.InvariantCulture, $@"{command} --thread {threadId} {args}"); ;
}
// Before we execute the provided command, we need to switch to a shared lock. This is because the provided
// command may be an expression evaluation command which could be long running, and we don't want to hold the
// exclusive lock during this.
lockToken.ConvertToSharedLock();
lockToken = null;
return await _debugger.CmdAsync(threadCommand, expectedResultClass);
}
finally
{
if (lockToken != null)
{
// finally is executing before we called 'ConvertToSharedLock'
lockToken.Close();
}
else
{
// finally is called after we called ConvertToSharedLock, we need to decerement the shared lock count
_debugger.CommandLock.ReleaseShared();
}
}
}
private async Task ThreadSelect(int threadId, ExclusiveLockToken lockToken)
{
if (ExclusiveLockToken.IsNullOrClosed(lockToken))
{
throw new ArgumentNullException(nameof(lockToken));
}
if (threadId != _currentThreadId)
{
string command = string.Format(CultureInfo.InvariantCulture, "-thread-select {0}", threadId);
await _debugger.ExclusiveCmdAsync(command, ResultClass.done, lockToken);
_currentThreadId = threadId;
_currentFrameLevel = 0;
}
}
private async Task StackSelectFrame(uint frameLevel, ExclusiveLockToken lockToken)
{
if (ExclusiveLockToken.IsNullOrClosed(lockToken))
{
throw new ArgumentNullException(nameof(lockToken));
}
if (frameLevel != _currentFrameLevel)
{
string command = string.Format(CultureInfo.InvariantCulture, "-stack-select-frame {0}", frameLevel);
await _debugger.ExclusiveCmdAsync(command, ResultClass.done, lockToken);
_currentFrameLevel = frameLevel;
}
}
public override async Task<Results> ThreadInfo(uint? threadId = null)
{
Results results = await base.ThreadInfo(threadId);
if (results.ResultClass == ResultClass.done && results.Contains("current-thread-id"))
{
_currentThreadId = results.FindInt("current-thread-id");
}
var tlist = results.Find<ValueListValue>("threads");
foreach (var tVal in tlist.Content)
{
if (tVal.Contains("details"))
{
string details = tVal.FindString("details");
var keyValuePairs = details.Split(',')
.Select(part => part.Split(new[] { ':' }, 2))
.Where(part => part.Length == 2)
.ToDictionary(
part => part[0].Trim(),
part => part[1].Trim()
);
if (keyValuePairs.TryGetValue("Name", out string name))
{
if (tVal is TupleValue tupleValue)
{
tupleValue.Content.Add(new NamedResultValue("name", new ConstValue(name)));
}
}
}
}
return results;
}
public override async Task<List<ulong>> StartAddressesForLine(string file, uint line)
{
string cmd = "info line " + file + ":" + line;
var result = await _debugger.ConsoleCmdAsync(cmd, allowWhileRunning: false);
List<ulong> addresses = new List<ulong>();
using (StringReader stringReader = new StringReader(result))
{
while (true)
{
string resultLine = stringReader.ReadLine();
if (resultLine == null)
break;
int pos = resultLine.IndexOf("starts at address ", StringComparison.Ordinal);
if (pos > 0)
{
ulong address;
string addrStr = resultLine.Substring(pos + 18);
if (MICommandFactory.SpanNextAddr(addrStr, out address) != null)
{
addresses.Add(address);
}
}
}
}
return addresses;
}
public override async Task EnableTargetAsyncOption()
{
// Linux attach TODO: GDB will fail this command when attaching. This is worked around
// by using signals for that case.
Results result = await _debugger.CmdAsync("-gdb-set mi-async on", ResultClass.None);
// 'set mi-async on' will error on older versions of gdb (older than 11.x)
// Try enabling with the older 'target-async' keyword.
if (result.ResultClass == ResultClass.error)
{
await _debugger.CmdAsync("-gdb-set target-async on", ResultClass.None);
}
}
public override async Task<HashSet<string>> GetFeatures()
{
Results results = await _debugger.CmdAsync("-list-features", ResultClass.done);
return new HashSet<string>(results.Find<ValueListValue>("features").AsStrings);
}
public override async Task<bool> SupportsSimpleValuesExcludesRefTypes()
{
HashSet<string> features = await GetFeatures();
return features.Contains("simple-values-ref-types");
}
public override async Task Terminate()
{
// Although the mi documentation states that the correct command to terminate is -exec-abort
// that isn't actually supported by gdb.
await _debugger.CmdAsync("kill", ResultClass.None);
}
private static string TypeBySize(uint size)
{
switch (size)
{
case 1:
return "char";
case 2:
return "short";
case 4:
return "int";
case 8:
return "double";
default:
throw new ArgumentException(null, nameof(size));
}
}
public override async Task<Results> BreakWatch(string address, uint size, ResultClass resultClass = ResultClass.done)
{
string cmd = string.Format(CultureInfo.InvariantCulture, "-break-watch *({0}*)({1})", TypeBySize(size), address);
return await _debugger.CmdAsync(cmd.ToString(), resultClass);
}
public override bool SupportsDataBreakpoints { get { return true; } }
public override string GetTargetArchitectureCommand()
{
return "show architecture";
}
public override TargetArchitecture ParseTargetArchitectureResult(string result)
{
using (StringReader stringReader = new StringReader(result))
{
while (true)
{
string resultLine = stringReader.ReadLine();
if (resultLine == null)
break;
if (resultLine.IndexOf("x86-64", StringComparison.OrdinalIgnoreCase) >= 0)
{
return TargetArchitecture.X64;
}
else if (resultLine.IndexOf("i386", StringComparison.OrdinalIgnoreCase) >= 0)
{
return TargetArchitecture.X86;
}
else if (resultLine.IndexOf("arm64", StringComparison.OrdinalIgnoreCase) >= 0)
{
return TargetArchitecture.ARM64;
}
else if (resultLine.IndexOf("aarch64", StringComparison.OrdinalIgnoreCase) >= 0)
{
return TargetArchitecture.ARM64;
}
else if (resultLine.IndexOf("arm", StringComparison.OrdinalIgnoreCase) >= 0)
{
return TargetArchitecture.ARM;
}
}
}
return TargetArchitecture.Unknown;
}
public override string GetSetEnvironmentVariableCommand(string name, string value)
{
return string.Format(CultureInfo.InvariantCulture, "set env {0} {1}", name, value);
}
public override async Task Signal(string sig)
{
string command = String.Format(CultureInfo.InvariantCulture, "-interpreter-exec console \"signal {0}\"", sig);
await _debugger.CmdAsync(command, ResultClass.running);
}
public override async Task Catch(string name, bool onlyOnce = false, ResultClass resultClass = ResultClass.done)
{
string command = onlyOnce ? "tcatch " : "catch ";
await _debugger.ConsoleCmdAsync(command + name, allowWhileRunning: false);
}
public override async Task<string[]> AutoComplete(string command, int threadId, uint frameLevel)
{
string cmd = "-complete";
string args = $"\"{command}\"";
Results res;
if (threadId == -1)
res = await _debugger.CmdAsync($"{cmd} {args}", ResultClass.done);
else
res = await ThreadFrameCmdAsync(cmd, args, ResultClass.done, threadId, frameLevel);
var matchlist = res.Find<ValueListValue>("matches");
if (int.Parse(res.FindString("max_completions_reached"), CultureInfo.InvariantCulture) != 0)
_debugger.Logger.WriteLine(LogLevel.Verbose, "We reached max-completions!");
return matchlist?.AsStrings;
}
public override IEnumerable<Guid> GetSupportedExceptionCategories()
{
const string CppExceptionCategoryString = "{3A12D0B7-C26C-11D0-B442-00A0244A1DD2}";
return new Guid[] { new Guid(CppExceptionCategoryString) };
}
public override async Task<IEnumerable<long>> SetExceptionBreakpoints(Guid exceptionCategory, IEnumerable<string> exceptionNames, ExceptionBreakpointStates exceptionBreakpointStates)
{
string command;
Results result;
List<long> breakpointNumbers = new List<long>();
if (exceptionNames == null) // set breakpoint for all exceptions in exceptionCategory
{
command = "-catch-throw";
result = await _debugger.CmdAsync(command, ResultClass.None);
switch (result.ResultClass)
{
case ResultClass.done:
var breakpointNumber = result.Find("bkpt").FindUint("number");
breakpointNumbers.Add(breakpointNumber);
break;
case ResultClass.error:
default:
throw new NotSupportedException();
}
}
else // set breakpoint for each exceptionName in exceptionNames
{
command = "-catch-throw -r \\b";
foreach (string exceptionName in exceptionNames)
{
result = await _debugger.CmdAsync(command + exceptionName + "\\b", ResultClass.None);
switch (result.ResultClass)
{
case ResultClass.done:
var breakpointNumber = result.Find("bkpt").FindUint("number");
breakpointNumbers.Add(breakpointNumber);
break;
case ResultClass.error:
default:
throw new NotSupportedException();
}
}
}
return breakpointNumbers;
}
public override async Task RemoveExceptionBreakpoint(Guid exceptionCategory, IEnumerable<long> exceptionBreakpoints)
{
foreach (long breakpointNumber in exceptionBreakpoints)
{
await BreakDelete(breakpointNumber.ToString(CultureInfo.InvariantCulture));
}
}
}
}