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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Remoting.Internal;
using System.Management.Automation.Runspaces;
using System.Threading;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// This cmdlet takes a Runspace object and checks to see if it is debuggable (i.e, if
    /// it is running a script or is currently stopped in the debugger.
    /// If it is debuggable then it breaks into the Runspace debugger in step mode.
    /// </summary>
    [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")]
    [Cmdlet(VerbsDiagnostic.Debug, "Runspace", SupportsShouldProcess = true, DefaultParameterSetName = DebugRunspaceCommand.RunspaceParameterSet,
        HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096917")]
    public sealed class DebugRunspaceCommand : PSCmdlet
    {
        #region Strings

        private const string RunspaceParameterSet = "RunspaceParameterSet";
        private const string NameParameterSet = "NameParameterSet";
        private const string IdParameterSet = "IdParameterSet";
        private const string InstanceIdParameterSet = "InstanceIdParameterSet";

        #endregion

        #region Private members

        private Runspace _runspace;
        private System.Management.Automation.Debugger _debugger;
        private PSDataCollection<PSStreamObject> _debugBlockingCollection;
        private PSDataCollection<PSStreamObject> _debugAccumulateCollection;
        private Pipeline _runningPipeline;
        private System.Management.Automation.PowerShell _runningPowerShell;

        // Debugging to persist until Ctrl+C or Debugger 'Exit' stops cmdlet.
        private bool _debugging;
        private readonly ManualResetEventSlim _newRunningScriptEvent = new(true);
        private RunspaceAvailability _previousRunspaceAvailability = RunspaceAvailability.None;

        #endregion

        #region Parameters

        /// <summary>
        /// The Runspace to be debugged.
        /// </summary>
        [Parameter(Position = 0,
                   Mandatory = true,
                   ValueFromPipelineByPropertyName = true,
                   ValueFromPipeline = true,
                   ParameterSetName = DebugRunspaceCommand.RunspaceParameterSet)]
        public Runspace Runspace
        {
            get;
            set;
        }

        /// <summary>
        /// The name of a Runspace to be debugged.
        /// </summary>
        [Parameter(Position = 0,
                   Mandatory = true,
                   ParameterSetName = DebugRunspaceCommand.NameParameterSet)]
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// The Id of a Runspace to be debugged.
        /// </summary>
        [Parameter(Position = 0,
                   Mandatory = true,
                   ParameterSetName = DebugRunspaceCommand.IdParameterSet)]
        public int Id
        {
            get;
            set;
        }

        /// <summary>
        /// The InstanceId of a Runspace to be debugged.
        /// </summary>
        [Parameter(Position = 0,
                   Mandatory = true,
                   ParameterSetName = DebugRunspaceCommand.InstanceIdParameterSet)]
        public Guid InstanceId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target.
        /// </summary>
        [Parameter]
        public SwitchParameter BreakAll { get; set; }

        #endregion

        #region Overrides

        /// <summary>
        /// End processing.  Do work.
        /// </summary>
        protected override void EndProcessing()
        {
            if (ParameterSetName == DebugRunspaceCommand.RunspaceParameterSet)
            {
                _runspace = Runspace;
            }
            else
            {
                IReadOnlyList<Runspace> runspaces = null;

                switch (ParameterSetName)
                {
                    case DebugRunspaceCommand.NameParameterSet:
                        runspaces = GetRunspaceUtils.GetRunspacesByName(new string[] { Name });
                        break;

                    case DebugRunspaceCommand.IdParameterSet:
                        runspaces = GetRunspaceUtils.GetRunspacesById(new int[] { Id });
                        break;

                    case DebugRunspaceCommand.InstanceIdParameterSet:
                        runspaces = GetRunspaceUtils.GetRunspacesByInstanceId(new Guid[] { InstanceId });
                        break;
                }

                if (runspaces.Count > 1)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            new PSArgumentException(Debugger.RunspaceDebuggingTooManyRunspacesFound),
                            "DebugRunspaceTooManyRunspaceFound",
                            ErrorCategory.InvalidOperation,
                            this)
                        );
                }

                if (runspaces.Count == 1)
                {
                    _runspace = runspaces[0];
                }
            }

            if (_runspace == null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSArgumentNullException(Debugger.RunspaceDebuggingNoRunspaceFound),
                        "DebugRunspaceNoRunspaceFound",
                        ErrorCategory.InvalidOperation,
                        this)
                    );
            }

            Runspace defaultRunspace = LocalRunspace.DefaultRunspace;
            if (defaultRunspace == null || defaultRunspace.Debugger == null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(Debugger.RunspaceDebuggingNoHostRunspaceOrDebugger),
                        "DebugRunspaceNoHostDebugger",
                        ErrorCategory.InvalidOperation,
                        this)
                    );
            }

            if (_runspace == defaultRunspace)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(Debugger.RunspaceDebuggingCannotDebugDefaultRunspace),
                        "DebugRunspaceCannotDebugHostRunspace",
                        ErrorCategory.InvalidOperation,
                        this)
                    );
            }

            if (this.Host == null || this.Host.UI == null)
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSInvalidOperationException(Debugger.RunspaceDebuggingNoHost),
                        "DebugRunspaceNoHostAvailable",
                        ErrorCategory.InvalidOperation,
                        this)
                    );
            }

            if (!ShouldProcess(_runspace.Name, VerbsDiagnostic.Debug))
            {
                return;
            }

            _debugger = defaultRunspace.Debugger;

            try
            {
                PrepareRunspace(_runspace);

                // Blocking call.  Send runspace/command output to host UI while debugging and wait for runspace/command completion.
                WaitAndReceiveRunspaceOutput();
            }
            finally
            {
                RestoreRunspace(_runspace);
            }
        }

        /// <summary>
        /// Stop processing.
        /// </summary>
        protected override void StopProcessing()
        {
            _debugging = false;

            // Cancel runspace debugging.
            System.Management.Automation.Debugger debugger = _debugger;
            if ((debugger != null) && (_runspace != null))
            {
                debugger.StopDebugRunspace(_runspace);
            }

            // Unblock the data collection.
            PSDataCollection<PSStreamObject> debugCollection = _debugBlockingCollection;
            debugCollection?.Complete();

            // Unblock any new command wait.
            _newRunningScriptEvent.Set();
        }

        #endregion

        #region Private methods

        private void WaitAndReceiveRunspaceOutput()
        {
            _debugging = true;

            try
            {
                HostWriteLine(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceDebuggingStarted, _runspace.Name));
                HostWriteLine(Debugger.RunspaceDebuggingEndSession);
                HostWriteLine(string.Empty);

                _runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged;
                _debugger.NestedDebuggingCancelledEvent += HandleDebuggerNestedDebuggingCancelledEvent;

                // Make sure host debugger has debugging turned on.
                _debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);

                // Set up host script debugger to debug the runspace.
                _debugger.DebugRunspace(_runspace, breakAll: BreakAll);

                _runspace.IsRemoteDebuggerAttached = true;
                _runspace.Events?.GenerateEvent(
                    PSEngineEvent.OnDebugAttach,
                    sender: null,
                    args: Array.Empty<object>(),
                    extraData: null,
                    processInCurrentThread: true,
                    waitForCompletionInCurrentThread: false);

                while (_debugging)
                {
                    // Wait for running script.
                    _newRunningScriptEvent.Wait();

                    if (!_debugging)
                    {
                        return;
                    }

                    AddDataEventHandlers();

                    try
                    {
                        // Block cmdlet during debugging until either the command finishes
                        // or the user terminates the debugging session.
                        foreach (var streamItem in _debugBlockingCollection)
                        {
                            streamItem.WriteStreamObject(this);
                        }
                    }
                    finally
                    {
                        RemoveDataEventHandlers();
                    }

                    if (_debugging &&
                        (!_runspace.InNestedPrompt))
                    {
                        HostWriteLine(string.Empty);
                        HostWriteLine(Debugger.RunspaceDebuggingScriptCompleted);
                        HostWriteLine(Debugger.RunspaceDebuggingEndSession);
                        HostWriteLine(string.Empty);
                    }

                    _newRunningScriptEvent.Reset();
                }
            }
            finally
            {
                _runspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged;
                _debugger.NestedDebuggingCancelledEvent -= HandleDebuggerNestedDebuggingCancelledEvent;
                _runspace.IsRemoteDebuggerAttached = false;
                _debugger.StopDebugRunspace(_runspace);
                _newRunningScriptEvent.Dispose();
            }
        }

        private void HostWriteLine(string line)
        {
            if ((this.Host != null) && (this.Host.UI != null))
            {
                try
                {
                    if (this.Host.UI.RawUI != null)
                    {
                        this.Host.UI.WriteLine(ConsoleColor.Yellow, this.Host.UI.RawUI.BackgroundColor, line);
                    }
                    else
                    {
                        this.Host.UI.WriteLine(line);
                    }
                }
                catch (System.Management.Automation.Host.HostException) { }
            }
        }

        private void AddDataEventHandlers()
        {
            // Create new collection objects.
            _debugBlockingCollection?.Dispose();
            _debugAccumulateCollection?.Dispose();

            _debugBlockingCollection = new PSDataCollection<PSStreamObject>();
            _debugBlockingCollection.BlockingEnumerator = true;
            _debugAccumulateCollection = new PSDataCollection<PSStreamObject>();

            _runningPowerShell = _runspace.GetCurrentBasePowerShell();
            if (_runningPowerShell != null)
            {
                if (_runningPowerShell.OutputBuffer != null)
                {
                    _runningPowerShell.OutputBuffer.DataAdding += HandlePowerShellOutputBufferDataAdding;
                }

                if (_runningPowerShell.ErrorBuffer != null)
                {
                    _runningPowerShell.ErrorBuffer.DataAdding += HandlePowerShellErrorBufferDataAdding;
                }
            }
            else
            {
                _runningPipeline = _runspace.GetCurrentlyRunningPipeline();
                if (_runningPipeline != null)
                {
                    if (_runningPipeline.Output != null)
                    {
                        _runningPipeline.Output.DataReady += HandlePipelineOutputDataReady;
                    }

                    if (_runningPipeline.Error != null)
                    {
                        _runningPipeline.Error.DataReady += HandlePipelineErrorDataReady;
                    }
                }
            }
        }

        private void RemoveDataEventHandlers()
        {
            if (_runningPowerShell != null)
            {
                if (_runningPowerShell.OutputBuffer != null)
                {
                    _runningPowerShell.OutputBuffer.DataAdding -= HandlePowerShellOutputBufferDataAdding;
                }

                if (_runningPowerShell.ErrorBuffer != null)
                {
                    _runningPowerShell.ErrorBuffer.DataAdding -= HandlePowerShellErrorBufferDataAdding;
                }

                _runningPowerShell = null;
            }
            else if (_runningPipeline != null)
            {
                if (_runningPipeline.Output != null)
                {
                    _runningPipeline.Output.DataReady -= HandlePipelineOutputDataReady;
                }

                if (_runningPipeline.Error != null)
                {
                    _runningPipeline.Error.DataReady -= HandlePipelineErrorDataReady;
                }

                _runningPipeline = null;
            }
        }

        private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e)
        {
            // Ignore nested commands.
            if (sender is LocalRunspace localRunspace)
            {
                var basePowerShell = localRunspace.GetCurrentBasePowerShell();
                if ((basePowerShell != null) && (basePowerShell.IsNested))
                {
                    return;
                }
            }

            RunspaceAvailability prevAvailability = _previousRunspaceAvailability;
            _previousRunspaceAvailability = e.RunspaceAvailability;

            if ((e.RunspaceAvailability == RunspaceAvailability.Available) || (e.RunspaceAvailability == RunspaceAvailability.None))
            {
                _debugBlockingCollection.Complete();
            }
            else if ((e.RunspaceAvailability == RunspaceAvailability.Busy) &&
                     ((prevAvailability == RunspaceAvailability.Available) || (prevAvailability == RunspaceAvailability.None)))
            {
                _newRunningScriptEvent.Set();
            }
        }

        private void HandleDebuggerNestedDebuggingCancelledEvent(object sender, EventArgs e)
        {
            StopProcessing();
        }

        private void HandlePipelineOutputDataReady(object sender, EventArgs e)
        {
            if (sender is PipelineReader<PSObject> reader && reader.IsOpen)
            {
                WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output);
            }
        }

        private void HandlePipelineErrorDataReady(object sender, EventArgs e)
        {
            if (sender is PipelineReader<object> reader && reader.IsOpen)
            {
                WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error);
            }
        }

        private void WritePipelineCollection<T>(Collection<T> collection, PSStreamObjectType psStreamType)
        {
            foreach (var item in collection)
            {
                if (item != null)
                {
                    AddToDebugBlockingCollection(new PSStreamObject(psStreamType, item));
                }
            }
        }

        private void HandlePowerShellOutputBufferDataAdding(object sender, DataAddingEventArgs e)
        {
            if (e.ItemAdded != null)
            {
                HandlePowerShellPStreamItem(new PSStreamObject(PSStreamObjectType.Output, e.ItemAdded));
            }
        }

        private void HandlePowerShellErrorBufferDataAdding(object sender, DataAddingEventArgs e)
        {
            if (e.ItemAdded != null)
            {
                HandlePowerShellPStreamItem(new PSStreamObject(PSStreamObjectType.Error, e.ItemAdded));
            }
        }

        private void HandlePowerShellPStreamItem(PSStreamObject streamItem)
        {
            if (!_debugger.InBreakpoint)
            {
                // First write any accumulated items.
                foreach (var item in _debugAccumulateCollection.ReadAll())
                {
                    AddToDebugBlockingCollection(item);
                }

                // Handle new item.
                if ((_debugBlockingCollection != null) && (_debugBlockingCollection.IsOpen))
                {
                    AddToDebugBlockingCollection(streamItem);
                }
            }
            else if (_debugAccumulateCollection.IsOpen)
            {
                // Add to accumulator if debugger is stopped in breakpoint.
                _debugAccumulateCollection.Add(streamItem);
            }
        }

        private void AddToDebugBlockingCollection(PSStreamObject streamItem)
        {
            if (!_debugBlockingCollection.IsOpen)
            {
                return;
            }

            if (streamItem != null)
            {
                try
                {
                    _debugBlockingCollection.Add(streamItem);
                }
                catch (PSInvalidOperationException) { }
            }
        }

        private void PrepareRunspace(Runspace runspace)
        {
            SetLocalMode(runspace.Debugger, true);
            EnableHostDebugger(runspace, false);
        }

        private void RestoreRunspace(Runspace runspace)
        {
            SetLocalMode(runspace.Debugger, false);
            EnableHostDebugger(runspace, true);
        }

        private void EnableHostDebugger(Runspace runspace, bool enabled)
        {
            // Only enable and disable the host's runspace if we are in process attach mode.
            if (_debugger is ServerRemoteDebugger)
            {
                if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null))
                {
                    try
                    {
                        localRunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled = enabled;
                    }
                    catch (PSNotImplementedException) { }
                }
            }
        }

        private static void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode)
        {
            if (debugger is ServerRemoteDebugger remoteDebugger)
            {
                remoteDebugger.LocalDebugMode = localMode;
            }
        }

        #endregion
    }
}