-
Notifications
You must be signed in to change notification settings - Fork 218
/
DebuggedProcess.cs
executable file
·2419 lines (2161 loc) · 107 KB
/
DebuggedProcess.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using MICore;
using Microsoft.DebugEngineHost;
using Microsoft.VisualStudio.Debugger.Interop;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Logger = MICore.Logger;
namespace Microsoft.MIDebugEngine
{
internal class DebuggedProcess : MICore.Debugger
{
public AD_PROCESS_ID Id { get; private set; }
public AD7Engine Engine { get; private set; }
public List<string> VariablesToDelete { get; private set; }
public List<string> DataBreakpointVariables { get; private set; }
public List<IVariableInformation> ActiveVariables { get; private set; }
public VariableInformation ReturnValue { get; private set; }
public SourceLineCache SourceLineCache { get; private set; }
public ThreadCache ThreadCache { get; private set; }
public Disassembly Disassembly { get; private set; }
public ExceptionManager ExceptionManager { get; private set; }
public CygwinFilePathMapper CygwinFilePathMapper { get; private set; }
private List<DebuggedModule> _moduleList;
private ISampleEngineCallback _callback;
private bool _bLastModuleLoadFailed;
private StringBuilder _pendingMessages;
private WorkerThread _worker;
private BreakpointManager _breakpointManager;
private ResultEventArgs _initialBreakArgs;
private List<string> _libraryLoaded; // unprocessed library loaded messages
private uint _loadOrder;
private HostWaitDialog _waitDialog;
public readonly Natvis.Natvis Natvis;
private ReadOnlyCollection<RegisterDescription> _registers;
private ReadOnlyCollection<RegisterGroup> _registerGroups;
private readonly EngineTelemetry _engineTelemetry = new EngineTelemetry();
private bool _needTerminalReset;
private HashSet<Tuple<string, string>> _fileTimestampWarnings;
private IProcessSequence _childProcessHandler;
private bool _deleteEntryPointBreakpoint;
private string _entryPointBreakpoint = string.Empty;
private bool? _simpleValuesExcludesRefTypes = null;
public DebuggedProcess(bool bLaunched, LaunchOptions launchOptions, ISampleEngineCallback callback, WorkerThread worker, BreakpointManager bpman, AD7Engine engine, HostConfigurationStore configStore, HostWaitLoop waitLoop = null) : base(launchOptions, engine.Logger)
{
uint processExitCode = 0;
_pendingMessages = new StringBuilder(400);
_worker = worker;
_breakpointManager = bpman;
Engine = engine;
_libraryLoaded = new List<string>();
_loadOrder = 0;
_deleteEntryPointBreakpoint = false;
MICommandFactory = MICommandFactory.GetInstance(launchOptions.DebuggerMIMode, this);
_waitDialog = (MICommandFactory.SupportsStopOnDynamicLibLoad() && launchOptions.WaitDynamicLibLoad) ? new HostWaitDialog(ResourceStrings.LoadingSymbolMessage, ResourceStrings.LoadingSymbolCaption) : null;
Natvis = new Natvis.Natvis(this, launchOptions.ShowDisplayString, configStore);
// we do NOT have real Win32 process IDs, so we use a guid
AD_PROCESS_ID pid = new AD_PROCESS_ID();
pid.ProcessIdType = (int)enum_AD_PROCESS_ID.AD_PROCESS_ID_GUID;
pid.guidProcessId = Guid.NewGuid();
this.Id = pid;
SourceLineCache = new SourceLineCache(this);
_callback = callback;
_moduleList = new List<DebuggedModule>();
ThreadCache = new ThreadCache(callback, this);
Disassembly = new Disassembly(this);
ExceptionManager = new ExceptionManager(MICommandFactory, _worker, _callback, configStore);
VariablesToDelete = new List<string>();
DataBreakpointVariables = new List<string>();
this.ActiveVariables = new List<IVariableInformation>();
_fileTimestampWarnings = new HashSet<Tuple<string, string>>();
OutputStringEvent += delegate (object o, string message)
{
// We can get messages before we have started the process
// but we can't send them on until it is
if (_connected)
{
_callback.OnOutputString(message);
}
else
{
_pendingMessages.Append(message);
}
};
LibraryLoadEvent += delegate (object o, EventArgs args)
{
ResultEventArgs results = args as MICore.Debugger.ResultEventArgs;
string file = results.Results.TryFindString("id");
if (!string.IsNullOrEmpty(file) && MICommandFactory.SupportsStopOnDynamicLibLoad())
{
_libraryLoaded.Add(file);
if (_waitDialog != null)
{
_waitDialog.ShowWaitDialog(file);
}
}
else if (!string.IsNullOrEmpty(file))
{
string addr = results.Results.TryFindString("loaded_addr");
if (string.IsNullOrEmpty(addr) || addr == "-")
{
return; // identifies the exe, not a real load
}
// generate module
string id = results.Results.TryFindString("name");
bool symsLoaded = true;
string symPath = null;
if (results.Results.Contains("symbols-path"))
{
symPath = results.Results.FindString("symbols-path");
if (string.IsNullOrEmpty(symPath))
{
symsLoaded = false;
}
}
else
{
symPath = file;
}
ulong loadAddr = results.Results.FindAddr("loaded_addr");
uint size = results.Results.FindUint("size");
if (String.IsNullOrEmpty(id))
{
id = file;
}
AddModule(id, file, loadAddr, size, symsLoaded, symPath);
}
};
if (_launchOptions is LocalLaunchOptions)
{
LocalLaunchOptions localLaunchOptions = (LocalLaunchOptions)_launchOptions;
if (!localLaunchOptions.IsValidMiDebuggerPath())
{
throw new Exception(MICoreResources.Error_InvalidMiDebuggerPath);
}
if (PlatformUtilities.IsOSX() &&
localLaunchOptions.DebuggerMIMode != MIMode.Lldb &&
!UnixUtilities.IsBinarySigned(localLaunchOptions.MIDebuggerPath, engine.Logger))
{
string message = String.Format(CultureInfo.CurrentCulture, ResourceStrings.Warning_DarwinDebuggerUnsigned, localLaunchOptions.MIDebuggerPath);
_callback.OnOutputMessage(new OutputMessage(
message + Environment.NewLine,
enum_MESSAGETYPE.MT_MESSAGEBOX,
OutputMessage.Severity.Warning));
}
ITransport localTransport;
// Attempt to support RunInTerminal first when it is a local launch and it is not debugging a coredump.
// Also since we use gdb-set new-console on in windows for external console, we don't need to RunInTerminal
if (HostRunInTerminal.IsRunInTerminalAvailable()
&& string.IsNullOrWhiteSpace(localLaunchOptions.MIDebuggerServerAddress)
&& string.IsNullOrWhiteSpace(localLaunchOptions.DebugServer)
&& IsCoreDump == false
&& (PlatformUtilities.IsWindows() ? !localLaunchOptions.UseExternalConsole : true)
&& !PlatformUtilities.IsOSX())
{
localTransport = new RunInTerminalTransport();
if (PlatformUtilities.IsLinux() || PlatformUtilities.IsOSX())
{
// Only need to clear terminal for Linux and OS X local launch
_needTerminalReset = (!localLaunchOptions.ProcessId.HasValue && _launchOptions.DebuggerMIMode == MIMode.Gdb);
}
}
else
{
localTransport = new LocalTransport();
}
if (localLaunchOptions.ShouldStartServer())
{
this.Init(
new MICore.ClientServerTransport(
localTransport,
new ServerTransport(killOnClose: true, filterStdout: localLaunchOptions.FilterStdout, filterStderr: localLaunchOptions.FilterStderr)
),
_launchOptions);
}
else
{
this.Init(localTransport, _launchOptions);
}
// Only need to know the debugger pid on Linux and OS X local launch to detect whether
// the debugger is closed. If the debugger is not running anymore, the response (^exit)
// to the -gdb-exit command is faked to allow MIEngine to shut down.
// For RunInTransport, this needs to be updated via a callback.
if (localTransport is RunInTerminalTransport)
{
((RunInTerminalTransport)localTransport).RegisterDebuggerPidCallback(SetDebuggerPid);
}
else
{
SetDebuggerPid(localTransport.DebuggerPid);
}
}
else if (_launchOptions is PipeLaunchOptions)
{
this.Init(new MICore.PipeTransport(), _launchOptions);
}
else if (_launchOptions is TcpLaunchOptions)
{
this.Init(new MICore.TcpTransport(), _launchOptions);
}
else if (_launchOptions is UnixShellPortLaunchOptions)
{
this.Init(new MICore.UnixShellPortTransport(), _launchOptions, waitLoop);
}
else
{
throw new ArgumentOutOfRangeException(nameof(launchOptions));
}
MIDebugCommandDispatcher.AddProcess(this);
// When the debuggee exits, we need to exit the debugger
ProcessExitEvent += delegate (object o, EventArgs args)
{
// NOTE: Exceptions leaked from this method may cause VS to crash, be careful
ResultEventArgs results = args as MICore.Debugger.ResultEventArgs;
if (results.Results.Contains("exit-code"))
{
// GDB sometimes returns exit codes, which don't fit into uint, like "030000000472".
// And we can't throw from here, because it crashes VS.
// Full exit code will still usually be reported in the Output window,
// but here let's return "uint.MaxValue" just to indicate that something went wrong.
if (!uint.TryParse(results.Results.FindString("exit-code"), out processExitCode))
{
processExitCode = uint.MaxValue;
}
}
// quit MI Debugger
if (!this.IsClosed)
{
_worker.PostOperation(CmdExitAsync);
}
else
{
// If we are already closed, make sure that something sends program destroy
_callback.OnProcessExit(processExitCode);
}
if (_waitDialog != null)
{
_waitDialog.EndWaitDialog();
}
};
// When the debugger exits, we tell AD7 we are done
DebuggerExitEvent += delegate (object o, EventArgs args)
{
// NOTE: Exceptions leaked from this method may cause VS to crash, be careful
// this is the last AD7 Event we can ever send
// Also the transport is closed when this returns
_callback.OnProcessExit(processExitCode);
Dispose();
};
DebuggerAbortedEvent += delegate (object o, DebuggerAbortedEventArgs eventArgs)
{
// NOTE: Exceptions leaked from this method may cause VS to crash, be careful
// The MI debugger process unexpectedly exited.
_worker.PostOperation(() =>
{
_engineTelemetry.SendDebuggerAborted(MICommandFactory, GetLastSentCommandName(), eventArgs.ExitCode);
// If the MI Debugger exits before we get a resume call, we have no way of sending program destroy. So just let start debugging fail.
if (!_connected)
{
return;
}
_callback.OnError(string.Concat(eventArgs.Message, " ", ResourceStrings.DebuggingWillAbort));
_callback.OnProcessExit(uint.MaxValue);
Dispose();
});
};
ModuleLoadEvent += async delegate (object o, EventArgs args)
{
// NOTE: This is an async void method, so make sure exceptions are caught and somehow reported
if (_needTerminalReset)
{
_needTerminalReset = false;
// This is to work around a GDB bug of warning "Failed to set controlling terminal: Operation not permitted"
// Reset debuggee terminal after the first module load.
await ResetConsole();
}
if (this.MICommandFactory.SupportsStopOnDynamicLibLoad() && !_launchOptions.WaitDynamicLibLoad)
{
await CmdAsync("-gdb-set stop-on-solib-events 0", ResultClass.None);
}
await this.EnsureModulesLoaded();
if (_waitDialog != null)
{
_waitDialog.EndWaitDialog();
}
if (MICommandFactory.SupportsStopOnDynamicLibLoad())
{
// Do not continue if debugging core dump
if (!this.IsCoreDump)
{
CmdContinueAsync();
}
}
};
// When we break we need to gather information
BreakModeEvent += async delegate (object o, EventArgs args)
{
// NOTE: This is an async void method, so make sure exceptions are caught and somehow reported
StoppingEventArgs results = args as MICore.Debugger.StoppingEventArgs;
if (_waitDialog != null)
{
_waitDialog.EndWaitDialog();
}
if (!this._connected)
{
_initialBreakArgs = results;
return;
}
try
{
await HandleBreakModeEvent(results, results.AsyncRequest);
}
catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true))
{
if (this.IsStopDebuggingInProgress)
{
return; // ignore exceptions after the process has exited
}
string exceptionDescription = EngineUtils.GetExceptionDescription(e);
string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_FailedToEnterBreakState, exceptionDescription);
_callback.OnError(message);
Terminate();
}
};
ErrorEvent += delegate (object o, EventArgs args)
{
// NOTE: Exceptions leaked from this method may cause VS to crash, be careful
ResultEventArgs result = (ResultEventArgs)args;
// In lldb, the format is ^error,message=""
// In gdb/vsdbg it is ^error,msg=""
string message = result.Results.TryFindString("msg");
if (String.IsNullOrWhiteSpace(message))
{
message = result.Results.TryFindString("message");
}
// if the command was abort (usually because of breakpoints failing to bind) then gdb writes messages into the output
if (this.MICommandFactory.Mode == MIMode.Gdb && message == "Command aborted.")
{
message = MICoreResources.Error_CommandAborted;
if (ProcessState == ProcessState.Running)
{
// assume that it was a continue command that got aborted and return to stopped state:
// this occurs when using openocd to debug embedded devices and it runs out of hardware breakpoints.
int currentThread = MICommandFactory.CurrentThread;
if (currentThread == 0)
{
currentThread = 1; // default to main thread is current doesn't have a valid value for some reason
}
ScheduleStdOutProcessing(string.Format(CultureInfo.CurrentCulture, @"*stopped,reason=""exception-received"",signal-name=""SIGINT"",thread-id=""{1}"",exception=""{0}""", MICoreResources.Info_UnableToContinue, currentThread));
}
}
_callback.OnError(message);
};
ThreadCreatedEvent += async delegate (object o, EventArgs args)
{
try
{
ResultEventArgs result = (ResultEventArgs)args;
await ThreadCache.ThreadCreatedEvent(result.Results.FindInt("id"), result.Results.TryFindString("group-id"));
_childProcessHandler?.ThreadCreatedEvent(result.Results);
}
catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true))
{
// Avoid crashing VS
}
};
ThreadExitedEvent += delegate (object o, EventArgs args)
{
ResultEventArgs result = (ResultEventArgs)args;
ThreadCache.ThreadExitedEvent(result.Results.FindInt("id"));
};
ThreadGroupExitedEvent += delegate (object o, EventArgs args)
{
ResultEventArgs result = (ResultEventArgs)args;
ThreadCache.ThreadGroupExitedEvent(result.Results.FindString("id"));
};
TelemetryEvent += (object o, ResultEventArgs args) =>
{
string eventName;
KeyValuePair<string, object>[] properties;
if (_engineTelemetry.DecodeTelemetryEvent(args.Results, out eventName, out properties))
{
HostTelemetry.SendEvent(eventName, properties);
}
};
BreakChangeEvent += async delegate (object o, EventArgs args)
{
try
{
await _breakpointManager.BreakpointModified(o, args);
}
catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true))
{ }
};
}
/// <summary>
/// GetFileName - returns all characters after the last directory separator
/// If no directory spearator is found or at least one charactar after the separator is not found
/// then return the original string.
/// </summary>
private static string GetFileName(string path)
{
int index = path.LastIndexOfAny(new char[] { '/', '\\' });
if (index >= 0 && index < path.Length - 1)
{
return path.Substring(index + 1);
}
else // no path separator or no characters after the separator, return the original string
{
return path;
}
}
private async Task EnsureModulesLoaded()
{
if (_libraryLoaded.Count != 0)
{
string moduleNames = string.Join(", ", _libraryLoaded);
try
{
// custom symbol loading?
// Lookup each file in the exception list.
// If there then
// if loadAll==false then load file
// else
// if loadAll==true then load file
if (!_launchOptions.CanAutoLoadSymbols())
{
foreach (string file in _libraryLoaded)
{
string filename = GetFileName(file);
if (_launchOptions.SymbolInfoExceptionList.Contains(filename))
{
if (!_launchOptions.SymbolInfoLoadAll)
{
await LoadSymbols(filename);
}
}
else
{
if (_launchOptions.SymbolInfoLoadAll)
{
await LoadSymbols(filename);
}
}
}
}
_libraryLoaded.Clear();
SourceLineCache.OnLibraryLoad();
await _breakpointManager.BindAsync();
await CheckModules();
_bLastModuleLoadFailed = false;
}
catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true))
{
if (this.ProcessState == MICore.ProcessState.Exited)
{
return; // ignore exceptions after the process has exited
}
string exceptionDescription = EngineUtils.GetExceptionDescription(e);
string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_ExceptionProcessingModules, moduleNames, exceptionDescription);
// to avoid spamming the user, if the last module failed, we send the next failure to the output windiw instead of a message box
if (!_bLastModuleLoadFailed)
{
_callback.OnError(message);
_bLastModuleLoadFailed = true;
}
else
{
_callback.OnOutputMessage(new OutputMessage(message, enum_MESSAGETYPE.MT_OUTPUTSTRING, OutputMessage.Severity.Warning));
}
}
}
}
public async Task Initialize(HostWaitLoop waitLoop, CancellationToken token)
{
bool success = false;
Natvis.Initialize(_launchOptions.VisualizerFiles);
int total = 1;
await this.WaitForConsoleDebuggerInitialize(token);
try
{
await this.MICommandFactory.EnableTargetAsyncOption();
await this.CheckCygwin(_launchOptions as LocalLaunchOptions);
List<LaunchCommand> commands = await GetInitializeCommands();
_childProcessHandler?.Enable();
total = commands.Count;
var i = 0;
foreach (var command in commands)
{
token.ThrowIfCancellationRequested();
waitLoop.SetProgress(total, i++, command.Description);
if (command.IsMICommand)
{
Results results = await CmdAsync(command.CommandText, ResultClass.None);
if (results.ResultClass == ResultClass.error)
{
if (command.FailureHandler != null)
{
command.FailureHandler(results.FindString("msg"));
}
else if (!command.IgnoreFailures)
{
string miError = results.FindString("msg");
throw new UnexpectedMIResultException(MICommandFactory.Name, command.CommandText, miError);
}
}
else
{
if (command.SuccessHandler != null)
{
await command.SuccessHandler(results.ToString());
}
if (command.SuccessResultsHandler != null)
{
await command.SuccessResultsHandler(results);
}
}
}
else
{
string resultString = await ConsoleCmdAsync(command.CommandText, allowWhileRunning: false, ignoreFailures: command.IgnoreFailures);
if (command.SuccessHandler != null)
{
await command.SuccessHandler(resultString);
}
}
}
success = true;
}
finally
{
if (!success)
{
Terminate();
}
}
waitLoop.SetProgress(total, total, String.Empty);
token.ThrowIfCancellationRequested();
}
private async Task<List<LaunchCommand>> GetInitializeCommands()
{
List<LaunchCommand> commands = new List<LaunchCommand>();
commands.AddRange(_launchOptions.SetupCommands);
if (_launchOptions.DebuggerMIMode == MIMode.Gdb)
{
commands.Add(new LaunchCommand("-interpreter-exec console \"set pagination off\""));
}
// When user specifies loading directives then the debugger cannot auto load symbols, the MIEngine must intervene at each solib-load event and make a determination
commands.Add(new LaunchCommand("-gdb-set auto-solib-add " + (_launchOptions.CanAutoLoadSymbols() ? "on" : "off")));
// If the absolute prefix so path has not been specified, then don't set it to null
// because the debugger might already have a default.
if (!string.IsNullOrEmpty(_launchOptions.AbsolutePrefixSOLibSearchPath))
{
commands.Add(new LaunchCommand("-gdb-set solib-absolute-prefix " + _launchOptions.AbsolutePrefixSOLibSearchPath));
}
// On Windows ';' appears to correctly works as a path seperator and from the documentation, it is ':' on unix or cygwin envrionments
string pathEntrySeperator = (_launchOptions.UseUnixSymbolPaths || IsCygwin) ? ":" : ";";
string escapedSearchPath = string.Join(pathEntrySeperator, _launchOptions.GetSOLibSearchPath().Select(path => {
return EnsureProperPathSeparators(path, ignoreSpaces: true);
}));
if (!string.IsNullOrWhiteSpace(escapedSearchPath))
{
if (_launchOptions.DebuggerMIMode == MIMode.Gdb)
{
// Do not place quotes around so paths for gdb
commands.Add(new LaunchCommand("-gdb-set solib-search-path " + escapedSearchPath + pathEntrySeperator, ResourceStrings.SettingSymbolSearchPath));
}
else
{
// surround so lib path with quotes in other cases
commands.Add(new LaunchCommand("-gdb-set solib-search-path \"" + escapedSearchPath + pathEntrySeperator + "\"", ResourceStrings.SettingSymbolSearchPath));
}
}
if (this.MICommandFactory.SupportsStopOnDynamicLibLoad())
{
// Do not stop on shared library load/unload events while debugging core dump.
// Also check _needTerminalReset because we need to work around a GDB bug and clear the terminal error message.
// This clear operation can't be done too early (because GDB only generate this message after start debugging)
// or too late (otherwise we might clear debuggee's output).
// The stop cause by first module load seems to be the perfect timing to clear the terminal,
// that's why we still need to initially turn stop-on-solib-events on then turn it off after the first stop.
if ((_needTerminalReset || _launchOptions.WaitDynamicLibLoad) && !this.IsCoreDump)
{
commands.Add(new LaunchCommand("-gdb-set stop-on-solib-events 1"));
}
}
if (MICommandFactory.SupportsChildProcessDebugging())
{
if (_launchOptions.DebugChildProcesses)
{
_childProcessHandler = new DebugUnixChild(this, this._launchOptions); // TODO: let the user enable/disable this functionality
}
}
// Custom launch options replace the built in launch steps. This is used on iOS
// and Linux attach scenarios.
if (_launchOptions.CustomLaunchSetupCommands != null)
{
commands.AddRange(_launchOptions.CustomLaunchSetupCommands);
SetTargetArch(_launchOptions.TargetArchitecture);
}
else
{
LocalLaunchOptions localLaunchOptions = _launchOptions as LocalLaunchOptions;
if (this.IsCoreDump)
{
// Load executable and core dump
this.AddExecutableAndCorePathCommand(commands);
// Important: this must occur after executable load but before anything else.
this.AddGetTargetArchitectureCommand(commands);
}
else if (_launchOptions.ProcessId.HasValue)
{
// This is an attach
if (this.MICommandFactory.Mode == MIMode.Gdb)
{
if (_launchOptions is UnixShellPortLaunchOptions)
{
// This code path is probably applicable when the ExePath is not specified and can be used to determine the full executable path.
// For now it is limited to Linux and debugger running on remote machine.
Debug.Assert(_launchOptions.ExePath == null);
DetermineAndAddExecutablePathCommand(commands, _launchOptions as UnixShellPortLaunchOptions);
}
else if (!string.IsNullOrWhiteSpace(_launchOptions.ExePath))
{
this.AddExecutablePathCommand(commands);
}
}
// Important: this must occur after file-exec-and-symbols but before anything else.
this.AddGetTargetArchitectureCommand(commands);
// check for remote
string destination = localLaunchOptions?.MIDebuggerServerAddress;
bool useExtendedRemote = localLaunchOptions?.UseExtendedRemote ?? false;
if (!string.IsNullOrWhiteSpace(destination))
{
string remoteMode = useExtendedRemote ? "extended-remote" : "remote";
commands.Add(new LaunchCommand($"-target-select {remoteMode} {destination}", string.Format(CultureInfo.CurrentCulture, ResourceStrings.ConnectingMessage, destination)));
}
// Allow attach after connection only in extended-remote mode
if (useExtendedRemote || (!useExtendedRemote && string.IsNullOrWhiteSpace(destination)))
{
Action<string> failureHandler = (string miError) =>
{
if (miError.Trim().StartsWith("ptrace:", StringComparison.OrdinalIgnoreCase))
{
string message = string.Format(CultureInfo.CurrentCulture, ResourceStrings.Error_PTraceFailure, _launchOptions.ProcessId, MICommandFactory.Name, miError);
throw new LaunchErrorException(message);
}
else
{
string message = string.Format(CultureInfo.CurrentCulture, ResourceStrings.Error_ExePathInvalid, _launchOptions.ExePath, MICommandFactory.Name, miError);
throw new LaunchErrorException(message);
}
};
commands.Add(new LaunchCommand("-target-attach " + _launchOptions.ProcessId.Value.ToString(CultureInfo.InvariantCulture), ignoreFailures: false, failureHandler: failureHandler));
}
if (_launchOptions.PostRemoteConnectCommands != null)
{
commands.AddRange(_launchOptions.PostRemoteConnectCommands);
}
if (this.MICommandFactory.Mode == MIMode.Lldb)
{
// LLDB finishes attach in break mode. Gdb does finishes in run mode. Issue a continue in lldb to match the gdb behavior
commands.Add(new LaunchCommand("-exec-continue", ignoreFailures: false));
}
return commands;
}
else
{
// The default launch is to start a new process
if (!string.IsNullOrWhiteSpace(_launchOptions.WorkingDirectory))
{
string escapedDir = this.EnsureProperPathSeparators(_launchOptions.WorkingDirectory, true);
commands.Add(new LaunchCommand("-environment-cd " + escapedDir));
}
// TODO: The last clause for LLDB may need to be changed when we support LLDB on Linux as LLDB's tty redirection doesn't work.
if (localLaunchOptions != null &&
localLaunchOptions.UseExternalConsole &&
(PlatformUtilities.IsWindows() ||
(PlatformUtilities.IsOSX() && this.MICommandFactory.Mode == MIMode.Lldb)))
{
commands.Add(new LaunchCommand("-gdb-set new-console on", ignoreFailures: true));
}
this.AddExecutablePathCommand(commands);
// Important: this must occur after file-exec-and-symbols but before anything else.
this.AddGetTargetArchitectureCommand(commands);
// LLDB requires -exec-arguments after -file-exec-and-symbols has been run, or else it errors
if (!string.IsNullOrWhiteSpace(_launchOptions.ExeArguments))
{
commands.Add(new LaunchCommand("-exec-arguments " + _launchOptions.ExeArguments));
}
Func<Results, Task> breakMainSuccessResultsHandler = (Results bkptResult) =>
{
if (bkptResult.Contains("bkpt"))
{
ResultValue b = bkptResult.Find("bkpt");
TupleValue bkpt = null;
if (b is TupleValue)
{
bkpt = b as TupleValue;
}
else if (b is ValueListValue) // Used when main breakpoint binds in more than one location
{
// Grab the first one as this is usually the <MULTIPLE> one that we can unbind them all with.
// This is usually "1" when the children manifest as "1.1", "1.2", etc
bkpt = (b as ValueListValue).Content[0] as TupleValue;
}
if (bkpt != null)
{
this._entryPointBreakpoint = bkpt.FindString("number");
this._deleteEntryPointBreakpoint = true;
}
}
return Task.FromResult(0);
};
// Builds '-break-insert' for 'main'.
StringBuilder breakInsertCommand = await this.MICommandFactory.BuildEntryBreakInsert();
breakInsertCommand.Append("main");
commands.Add(new LaunchCommand(breakInsertCommand.ToString(), ignoreFailures: true, successResultsHandler: breakMainSuccessResultsHandler));
if (null != localLaunchOptions)
{
string destination = localLaunchOptions.MIDebuggerServerAddress;
if (!string.IsNullOrWhiteSpace(destination))
{
string remoteMode = localLaunchOptions.UseExtendedRemote ? "extended-remote" : "remote";
commands.Add(new LaunchCommand($"-target-select {remoteMode} {destination}", string.Format(CultureInfo.CurrentCulture, ResourceStrings.ConnectingMessage, destination)));
if (localLaunchOptions.RequireHardwareBreakpoints && localLaunchOptions.HardwareBreakpointLimit > 0) {
commands.Add(new LaunchCommand(string.Format(CultureInfo.InvariantCulture, "-interpreter-exec console \"set remote hardware-breakpoint-limit {0}\"", localLaunchOptions.HardwareBreakpointLimit.ToString(CultureInfo.InvariantCulture))));
}
}
}
if (_launchOptions.PostRemoteConnectCommands != null)
{
commands.AddRange(_launchOptions.PostRemoteConnectCommands);
}
// Environment variables are set for the debuggee only with the modes that support that
foreach (EnvironmentEntry envEntry in _launchOptions.Environment)
{
commands.Add(new LaunchCommand(MICommandFactory.GetSetEnvironmentVariableCommand(envEntry.Name, envEntry.Value)));
}
}
}
return commands;
}
/// <summary>
/// Checks to see if we are running Cygwin or not.
/// </summary>
/// <param name="localLaunchOptions"></param>
/// <returns></returns>
private async Task CheckCygwin(LocalLaunchOptions localLaunchOptions)
{
// Checks to see if:
// 1. LocalLaunch Debugging
// 2. On Windows
// 3. With GDB
// 4. Does not have custom commands
// 5. Is not Android Debugging
// 6. Is not Dump Debugging
if (localLaunchOptions != null &&
PlatformUtilities.IsWindows() &&
this.MICommandFactory.Mode == MIMode.Gdb &&
localLaunchOptions.CustomLaunchSetupCommands == null &&
localLaunchOptions.DeviceAppLauncher == null &&
!this.IsCoreDump)
{
string resultString = await ConsoleCmdAsync("show configuration", allowWhileRunning: false, ignoreFailures: true);
// mingw will not implement this command, but to be safe, also check if the results contains the string cygwin.
// Look to see if configuration has "cywgin" within a word boundry.
// Also look for "msys" since it is a modified version of Cygwin.
if (Regex.IsMatch(resultString, "\\bcygwin\\b|\\bmsys\\b"))
{
this.IsCygwin = true;
this.CygwinFilePathMapper = new CygwinFilePathMapper(this);
_engineTelemetry.SendWindowsRuntimeEnvironment(EngineTelemetry.WindowsRuntimeEnvironment.Cygwin);
}
else
{
this.IsMinGW = true;
// Gdb on windows and not cygwin implies mingw
_engineTelemetry.SendWindowsRuntimeEnvironment(EngineTelemetry.WindowsRuntimeEnvironment.MinGW);
}
}
}
private void AddExecutablePathCommand(IList<LaunchCommand> commands)
{
string exe = this.EnsureProperPathSeparators(_launchOptions.ExePath, true);
string description = string.Format(CultureInfo.CurrentCulture, ResourceStrings.LoadingSymbolMessage, exe);
Action<string> failureHandler = (string miError) =>
{
string message = string.Format(CultureInfo.CurrentCulture, ResourceStrings.Error_ExePathInvalid, _launchOptions.ExePath, MICommandFactory.Name, miError);
throw new LaunchErrorException(message);
};
commands.Add(new LaunchCommand("-file-exec-and-symbols " + exe, description, ignoreFailures: false, failureHandler: failureHandler));
}
private void AddExecutableAndCorePathCommand(IList<LaunchCommand> commands)
{
string command;
if (_launchOptions.DebuggerMIMode == MIMode.Lldb)
{
// LLDB requires loading the executable and the core into the same target, using one command. Quotes in the path are supported.
string exePath = this.EnsureProperPathSeparators(_launchOptions.ExePath, true);
string corePath = this.EnsureProperPathSeparators(_launchOptions.CoreDumpPath, true);
command = String.Concat("file ", exePath, " -c ", corePath);
}
else
{
// GDB requires loading the executable and core separately.
// Note: Linux/mac do not support quotes around this path, but spaces in the path do work.
this.AddExecutablePathCommand(commands);
string corePathNoQuotes = this.EnsureProperPathSeparators(_launchOptions.CoreDumpPath, true, true);
command = String.Concat("-target-select core ", corePathNoQuotes);
}
// Load core dump information
string description = String.Format(CultureInfo.CurrentCulture, ResourceStrings.LoadingCoreDumpMessage, _launchOptions.CoreDumpPath);
commands.Add(new LaunchCommand(command, description, ignoreFailures: false));
}
private void DetermineAndAddExecutablePathCommand(IList<LaunchCommand> commands, UnixShellPortLaunchOptions launchOptions)
{
// TODO: connecting to OSX via SSH doesn't work yet. Show error after connection manager dialog gets dismissed.
// Runs a shell command to get the full path of the exe.
// /proc file system does not exist on OSX. And querying lsof on privilaged process fails with no output on Mac, while on Linux the command succeedes with
// embedded error text in lsof output like "(readlink error)".
string absoluteExePath;
// Must have a processId
Debug.Assert(_launchOptions.ProcessId.HasValue, "ProcessId should have a value.");
if (launchOptions.UnixPort.IsOSX())
{
// Usually the first FD=txt in the output of lsof points to the executable.
absoluteExePath = string.Format(CultureInfo.InvariantCulture, "shell lsof -p {0} | awk '$4 == \"txt\" {{ print $9 }}'|awk 'NR==1 {{print $1}}'", _launchOptions.ProcessId.Value);
}
else if (launchOptions.UnixPort.IsLinux())
{
absoluteExePath = string.Format(CultureInfo.InvariantCulture, @"shell readlink -f /proc/{0}/exe", _launchOptions.ProcessId.Value);
}
else
{
throw new LaunchErrorException(ResourceStrings.Error_UnsupportedPlatform);
}
Action<string> failureHandler = (string miError) =>
{
string message = string.Format(CultureInfo.CurrentCulture, ResourceStrings.Error_FailedToGetExePath, miError);
throw new LaunchErrorException(message);
};
Func<string, Task> successHandler = async (string exePath) =>
{
string trimmedExePath = exePath.Trim();
try
{
// If the folder contains a space, we need to quote the path.
if (trimmedExePath.Contains(' '))
{
trimmedExePath = "\"" + trimmedExePath + "\"";
}
await CmdAsync("-file-exec-and-symbols " + trimmedExePath, ResultClass.done);
}
catch (UnexpectedMIResultException miException)
{
string message = string.Format(CultureInfo.CurrentCulture, ResourceStrings.Error_ExePathInvalid, trimmedExePath, MICommandFactory.Name, miException.MIError);
throw new LaunchErrorException(message);
}
};
commands.Add(new LaunchCommand(absoluteExePath, ignoreFailures: false, failureHandler: failureHandler, successHandler: successHandler));
}
private TargetArchitecture DefaultArch()
{
if (LaunchOptions.TargetArchitecture != TargetArchitecture.Unknown)
{
return LaunchOptions.TargetArchitecture;
}
else