public async Task StepOutFromGlobal() { const string code = @"x <- 1 y <- 2"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp1 = await debugSession.CreateBreakpointAsync(sf, 1); var bp2 = await debugSession.CreateBreakpointAsync(sf, 2); var bp1Hit = new BreakpointHitDetector(bp1); await sf.Source(_session); await bp1Hit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { bp1.Location } }); (await debugSession.StepOutAsync()).Should().Be(false); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { bp2.Location } }); } }
public static int WriteLogEntries(this DebugSession debugSession, int lastLogMessageId = -1) { int startId = -1; if (lastLogMessageId != -1) { startId = lastLogMessageId + 1; } if (debugSession != null) { XElement logXml = XElement.Parse(debugSession.GetLogMessagesXml(-1, startId, -1)); foreach (XElement logEntry in logXml.Descendants(templateDebuggingNamespace + "log")) { startId = int.Parse(logEntry.Attribute("id").Value); TraceEventType logType; Enum.TryParse <TraceEventType>(logEntry.Attribute("type").Value, true, out logType); Logger.Log(logType, logEntry.Value); } } return(startId); }
public async Task InteractDuringBrowse() { using (var debugSession = new DebugSession(_session)) { using (var sf = new SourceFile("x <- 'old'; browser()")) { var browse = new TaskCompletionSource<bool>(); debugSession.Browse += (s, e) => { browse.TrySetResult(true); }; await sf.Source(_session); await browse.Task; using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("x <- 'new'\n"); } REvaluationResult x; using (var eval = await _session.BeginEvaluationAsync()) { x = await eval.EvaluateAsync("x"); } x.StringResult.Should().Be("new"); } } }
public static IEnumerable <VersionInfo> EnumerateClrVersions(IProcessInfo info) { using (var session = DebugSession.Create(info)) { return(session.DataTarget.ClrVersions.Select(v => v.Version)); } }
public async Task StepOntoBreakpoint() { const string code = @"x <- 1 y <- 2"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp1 = await debugSession.CreateBreakpointAsync(sf, 1); var bp2 = await debugSession.CreateBreakpointAsync(sf, 2); var bp1Hit = new BreakpointHitDetector(bp1); var bp2Hit = new BreakpointHitDetector(bp2); await sf.Source(_session); await bp1Hit.ShouldBeHitAtNextPromptAsync(); (await debugSession.StepOverAsync()).Should().Be(false); await bp2Hit.ShouldBeHitAtNextPromptAsync(); } }
private int Continue(IDebugThread2 pThread) { ThrowIfDisposed(); if (_firstContinue) { _firstContinue = false; } else { // If _sentContinue is true, then this is a dummy Continue issued to notify the // debugger that user has explicitly entered something at the Browse prompt, and // we don't actually need to issue the command to R debugger. Func <CancellationToken, Task> continueMethod = null; lock (_browseLock) { if (_sentContinue != true) { _sentContinue = true; continueMethod = ct => DebugSession.ContinueAsync(ct); } } if (continueMethod != null) { TaskExtensions.RunSynchronouslyOnUIThread(continueMethod); } } return(VSConstants.S_OK); }
public async Task AddRemoveBreakpoint() { const string code = @"x <- 1 y <- 2 z <- 3"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { var bp1Loc = new DebugBreakpointLocation(sf.FilePath, 1); var bp1 = await debugSession.CreateBreakpointAsync(bp1Loc); bp1.Location.Should().Be(bp1Loc); bp1.Session.Should().Be(debugSession); debugSession.Breakpoints.Count.Should().Be(1); var bp2Loc = new DebugBreakpointLocation(sf.FilePath, 3); var bp2 = await debugSession.CreateBreakpointAsync(bp2Loc); bp2.Location.Should().Be(bp2Loc); bp2.Session.Should().Be(debugSession); debugSession.Breakpoints.Count.Should().Be(2); await bp1.DeleteAsync(); debugSession.Breakpoints.Count.Should().Be(1); debugSession.Breakpoints.First().Should().BeSameAs(bp2); } }
public async Task MultilinePromise() { const string code = @" f <- function(p, d) { force(d) browser() } x <- quote({{{}}}) eval(substitute(f(P, x), list(P = x))) "; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var browseTask = EventTaskSources.DebugSession.Browse.Create(debugSession); await sf.Source(_session); await browseTask; var stackFrames = (await debugSession.GetStackFramesAsync()).ToArray(); stackFrames.Should().NotBeEmpty(); var frame = (await stackFrames.Last().GetEnvironmentAsync()).As <DebugValueEvaluationResult>(); var children = (await frame.GetChildrenAsync(DebugEvaluationResultFields.ReprDeparse)).ToDictionary(er => er.Name); var p = children.Should().ContainKey("p").WhichValue.As <DebugPromiseEvaluationResult>(); var d = children.Should().ContainKey("d").WhichValue.As <DebugValueEvaluationResult>(); p.Code.Should().Be(d.GetRepresentation().Deparse); } }
public async Task StepInto() { const string code = @"f <- function(x) { x + 1 } x <- f(1) print(x)"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp = await debugSession.CreateBreakpointAsync(sf, 4); var bpHit = new BreakpointHitDetector(bp); await sf.Source(_session); await bpHit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { bp.Location } }); (await debugSession.StepIntoAsync()).Should().Be(true); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { sf, 4, "f(1)" }, { sf, 1, MatchAny<string>.Instance }, }); } }
private async Task PublishAllAsync() { await TaskUtilities.SwitchToBackgroundThread(); var debugSessionProvider = VsAppShell.Current.ExportProvider.GetExportedValue <IDebugSessionProvider>(); if (_debugSession == null) { _debugSession = await debugSessionProvider.GetDebugSessionAsync(RSession); if (_debugSession == null) { Debug.Fail(""); return; } } List <Task> subsribeTasks = new List <Task>(); lock (_subscribers) { foreach (var kv in _subscribers) { subsribeTasks.Add(PublishAsync(kv.Key, kv.Value)); } } await Task.WhenAll(subsribeTasks); }
public static async Task NextPromptShouldBeBrowseAsync(this DebugSession session) { // Grab the next available prompt, and verify that it's Browse> using (var inter = await session.RSession.BeginInteractionAsync()) { inter.Contexts.IsBrowser().Should().BeTrue("Next available prompt should be a Browse> prompt"); } // Now wait until session tells us that it has noticed the prompt and processed it. // Note that even if we register the handler after it has already noticed, but // before the interaction completed, it will still invoke the handler. var browseTask = EventTaskSources.DebugSession.Browse.Create(session); // Spin until either Browse is raised, or we see a different non-Browse prompt. // If the latter happens, we're not going to see Browse raised for that prompt that we've // seen initially, because something had interfered asynchronously, which shouldn't happen // in a test - and if it does, the test should be considered failed at that point, because // the state is indeterminate. while (true) { var interTask = session.RSession.BeginInteractionAsync(); var completedTask = await Task.WhenAny(browseTask, interTask); if (completedTask == browseTask) { interTask.ContinueWith(t => t.Result.Dispose(), TaskContinuationOptions.OnlyOnRanToCompletion).DoNotWait(); return; } using (var inter = await interTask) { inter.Contexts.IsBrowser().Should().BeTrue(); } } }
public async Task SetBreakpointWhileRunning() { const string code = @"browser() f <- function() { NULL } while (TRUE) f()"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); await sf.Source(_session); await debugSession.NextPromptShouldBeBrowseAsync(); await debugSession.ContinueAsync(); await Task.Delay(100); var bp = await debugSession.CreateBreakpointAsync(sf, 3); await debugSession.NextPromptShouldBeBrowseAsync(); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { bp.Location } }); } }
internal DebugStackFrame(DebugSession session, int index, DebugStackFrame callingFrame, JObject jFrame, DebugStackFrame fallbackFrame = null) { Session = session; Index = index; CallingFrame = callingFrame; FileName = jFrame.Value<string>("filename"); LineNumber = jFrame.Value<int?>("line_number"); Call = jFrame.Value<string>("call"); IsGlobal = jFrame.Value<bool?>("is_global") ?? false; var match = _doTraceRegex.Match(Call); if (match.Success) { FrameKind = DebugStackFrameKind.DoTrace; } if (fallbackFrame != null) { // If we still don't have the filename and line number, use those from the fallback frame. // This happens during breakpoint hit processing after the context is unwound from within // .doTrace back to the function that called it - because we no longer have .doTrace call, // we don't have the file/line information that came from it. But DebugSession will have // stashed it away when it had it, and then pass it as a fallback frame if index matches. FileName = FileName ?? fallbackFrame.FileName; LineNumber = LineNumber ?? fallbackFrame.LineNumber; } }
public async Task MultilinePromise() { const string code = @" f <- function(p, d) { force(d) browser() } x <- quote({{{}}}) eval(substitute(f(P, x), list(P = x))) "; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var browseTask = EventTaskSources.DebugSession.Browse.Create(debugSession); await sf.Source(_session); await browseTask; var stackFrames = (await debugSession.GetStackFramesAsync()).ToArray(); stackFrames.Should().NotBeEmpty(); var frame = (await stackFrames.Last().GetEnvironmentAsync()).As<DebugValueEvaluationResult>(); var children = (await frame.GetChildrenAsync()).ToDictionary(er => er.Name); var p = children.Should().ContainKey("p").WhichValue.As<DebugPromiseEvaluationResult>(); var d = children.Should().ContainKey("d").WhichValue.As<DebugValueEvaluationResult>(); p.Code.Should().Be(d.GetRepresentation(DebugValueRepresentationKind.Raw).Deparse); } }
public async Task InteractDuringBrowse() { using (var debugSession = new DebugSession(_session)) { using (var sf = new SourceFile("x <- 'old'; browser()")) { var browse = new TaskCompletionSource <bool>(); debugSession.Browse += (s, e) => { browse.TrySetResult(true); }; await sf.Source(_session); await browse.Task; using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("x <- 'new'\n"); } REvaluationResult x; using (var eval = await _session.BeginEvaluationAsync()) { x = await eval.EvaluateAsync("x"); } x.StringResult.Should().Be("new"); } } }
public async Task StepOver() { const string code = @"f <- function(x) { x + 1 } x <- f(1) print(x)"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp = await debugSession.CreateBreakpointAsync(sf, 4); var bpHit = new BreakpointHitDetector(bp); await sf.Source(_session); await bpHit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { bp.Location } }); (await debugSession.StepOverAsync()).Should().Be(true); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { bp.Location, +1 } }); } }
public async Task OverlappingBreakpoints() { const string code = @"f <- function() { 1 }"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); await sf.Source(_session); var bp1 = await debugSession.CreateBreakpointAsync(sf, 1); var bp2 = await debugSession.CreateBreakpointAsync(sf, 1); bp1.Should().BeSameAs(bp2); debugSession.Breakpoints.Should().HaveCount(1); var bp1Hit = new BreakpointHitDetector(bp1); var bp2Hit = new BreakpointHitDetector(bp2); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } await bp1Hit.ShouldBeHitAtNextPromptAsync(); bp2Hit.WasHit.Should().BeTrue(); await bp1.DeleteAsync(); debugSession.Breakpoints.Should().HaveCount(1); debugSession.Breakpoints.Should().Contain(bp2); await debugSession.ContinueAsync(); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } await bp2Hit.ShouldBeHitAtNextPromptAsync(); await bp2.DeleteAsync(); debugSession.Breakpoints.Should().HaveCount(0); await debugSession.ContinueAsync(); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } using (var inter = await _session.BeginInteractionAsync()) { inter.Contexts.IsBrowser().Should().BeFalse(); } } }
private static async Task <DebugSession> CreateDebugSession(DisposableTracker tracker) { var taskTarget = tracker.Track(new HeapAnalysisTargetProcess()); var process = taskTarget.Start(); await taskTarget.WaitForTask(); return(tracker.Track(DebugSession.Create(ProcessInfo.FromProcess(process), DebugMode.Snapshot))); }
internal async Task AttachDebugger(DebugOptions debugOptions) { string appHash = ComputeHash(debugOptions.StartupAssemblyPath); Project startup = GetStartupProject(); bool isWeb = ((object[])startup.ExtenderNames).Any(x => x.ToString() == "WebApplication"); ApplicationType appType = isWeb ? ApplicationType.Webapplication : ApplicationType.Desktopapplication; if (appType == ApplicationType.Webapplication) { debugOptions.OutputDirectory += @"\..\..\"; } var client = new DebugClient(appType, debugOptions.TargetExeFileName, debugOptions.StartArguments, debugOptions.OutputDirectory, appHash); DebugSession session = await client.ConnectToServerAsync(debugOptions.UserSettings.LastIp); var debugSessionStarted = await session.RestartDebuggingAsync(debugOptions.UserSettings.LastTimeout); if (!debugSessionStarted) { await session.TransferFilesAsync(); await session.WaitForAnswerAsync(debugOptions.UserSettings.LastTimeout); } IntPtr pInfo = GetDebugInfo(debugOptions); var sp = new ServiceProvider((IServiceProvider)_dte); try { var dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger)); int hr = dbg.LaunchDebugTargets(1, pInfo); Marshal.ThrowExceptionForHR(hr); DebuggedProcess.Instance.AssociateDebugSession(session); } catch (Exception ex) { logger.Error(ex); string msg; var sh = (IVsUIShell)sp.GetService(typeof(SVsUIShell)); sh.GetErrorInfo(out msg); if (!string.IsNullOrWhiteSpace(msg)) { logger.Error(msg); } throw; } finally { if (pInfo != IntPtr.Zero) { Marshal.FreeCoTaskMem(pInfo); } } }
/// <summary> /// Execute the template transformation with the given parameters /// </summary> /// <param name="itemUri">Tridion item URI.</param> /// <param name="templateUri">Tridion template URI.</param> /// <param name="publicationTargetUri">Tridion publication target URI.</param> /// <param name="logLevel">Log level.</param> /// <returns>Package "Output" item as <see cref="T:System.String" /></returns> public override String Execute(String itemUri, String templateUri, String publicationTargetUri = null) { String sessionId = Guid.NewGuid().ToString(); DebugSession debugSession = null; try { String templateXml = mCompoundService.GetCompoundTemplateXml(templateUri); debugSession = new DebugSession(sessionId, templateUri, templateXml, itemUri, null, true, publicationTargetUri, DebuggerConfig.Instance.Templating.EnableImpersonation && !String.IsNullOrEmpty(DebuggerConfig.Instance.Templating.ImpersonationIdentity) ? DebuggerConfig.Instance.Templating.ImpersonationIdentity : WindowsIdentity.GetCurrent().Name, DebuggerConfig.Instance.Logging.IncludeTridionClasses, DebuggerConfig.Instance.Logging.Level); debugSession.SetPreviewLocations( DebuggerConfig.Instance.CMS.PreviewDirectory, PreviewServer.PreviewUrl); // Signal for any debuggers DebuggerHook(); debugSession.Start(); int lastMessageId = -1; while (debugSession.IsRunning()) { Thread.Sleep(1000); lastMessageId = debugSession.WriteLogEntries(lastMessageId); } String postPackage = debugSession.GetPostPackageName(); String outputItemDataId = debugSession.GetPackageItemDataId(postPackage, "Output"); return(debugSession.GetPackageItemString(outputItemDataId)); } catch (Exception ex) { Logger.Log(System.Diagnostics.TraceEventType.Error, "Exception while executing DebugEngine for item {0}, template {1}: {2}", itemUri, templateUri, LoggerExtensions.TraceException(ex)); } finally { if (debugSession != null) { debugSession.Stop(); } } return(String.Empty); }
private static ClrClassObject GetSubjectFromSession(DebugSession session) { var runtime = session.CreateRuntime(); return(runtime.Heap .EnumerateAllClrObjects() .OfType <ClrClassObject>() .Single(i => i.Type.CanBeAssignedTo <HeapAnalysisTarget.Program>())); }
int IDebugEngine2.CauseBreak() { ThrowIfDisposed(); DebugSession.BreakAsync() .SilenceException <MessageTransportException>() .SilenceException <RException>() .DoNotWait(); return(VSConstants.S_OK); }
public static String GetPackageItemString(this DebugSession debugSession, String itemDataId) { if (debugSession != null) { XElement itemXml = XElement.Parse(debugSession.GetPackageItemXml(itemDataId)); return(HttpUtility.UrlDecode(itemXml.Value)); } return(String.Empty); }
private static void ExecuteRepl(string JsStatement, DebugSession session) { var old = session.JsEngine.SetDebugHandlerMode(Jint.Runtime.Debugger.StepMode.None); session.JsEngine.ExecuteWithErrorHandle(JsStatement, new Jint.Parser.ParserOptions() { Tolerant = true }); session.JsEngine.SetDebugHandlerMode(old); }
public static HeapAnalysisScope LoadMemoryDump(string filePath) { using (var tracker = new DisposableTracker()) { var session = tracker.Track(DebugSession.Load(filePath)); var subject = GetSubjectFromSession(session); return(tracker.TransferOwnershipTo(t => new HeapAnalysisScope(t, subject))); } }
internal async Task AttachDebugger(string ipAddress) { string path = GetStartupAssemblyPath(); string targetExe = Path.GetFileName(path); string outputDirectory = Path.GetDirectoryName(path); Project startup = GetStartupProject(); bool isWeb = ((object[])startup.ExtenderNames).Any(x => x.ToString() == "WebApplication"); ApplicationType appType = isWeb ? ApplicationType.Webapplication : ApplicationType.Desktopapplication; if (appType == ApplicationType.Webapplication) { outputDirectory += @"\..\..\"; } var client = new DebugClient(appType, targetExe, outputDirectory); DebugSession session = await client.ConnectToServerAsync(ipAddress); await session.TransferFilesAsync(); await session.WaitForAnswerAsync(); IntPtr pInfo = GetDebugInfo(ipAddress, targetExe, outputDirectory); var sp = new ServiceProvider((IServiceProvider)_dte); try { var dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger)); int hr = dbg.LaunchDebugTargets(1, pInfo); Marshal.ThrowExceptionForHR(hr); DebuggedProcess.Instance.AssociateDebugSession(session); } catch (Exception ex) { logger.Error(ex); string msg; var sh = (IVsUIShell)sp.GetService(typeof(SVsUIShell)); sh.GetErrorInfo(out msg); if (!string.IsNullOrWhiteSpace(msg)) { logger.Error(msg); } throw; } finally { if (pInfo != IntPtr.Zero) { Marshal.FreeCoTaskMem(pInfo); } } }
public async Task Representation(string expr, string deparse, string str, string toString) { using (var debugSession = new DebugSession(_session)) { var res = (await debugSession.EvaluateAsync(expr)).Should().BeAssignableTo <DebugValueEvaluationResult>().Which; var repr = res.GetRepresentation(); repr.Deparse.Should().Be(deparse); repr.Str.Should().Be(str); repr.ToString.Should().Be(toString); } }
public static void DumpSession(DebugSession session, string filePath, ConsoleLog console = null) { if (session.DataTarget.DebuggerInterface is IDebugClient2 clientInterface) { // Record complete dump, including binaries and symbols if possible. clientInterface.WriteDumpFile2(filePath, DEBUG_DUMP.SMALL, DEBUG_FORMAT.USER_SMALL_FULL_MEMORY | DEBUG_FORMAT.CAB_SECONDARY_ALL_IMAGES, ""); return; } console?.WriteLine("WARNING: API only supports old-style dump? Recording minidump instead."); session.DataTarget.DebuggerInterface.WriteDumpFile(filePath, DEBUG_DUMP.SMALL); }
public async Task MultilinePromise() { const string code = @" f <- function(p, d) { force(d) browser() } x <- quote({{{}}}) eval(substitute(f(P, x), list(P = x))) "; using (var sessionProvider = new RSessionProvider()) { var session = sessionProvider.GetOrCreate(Guid.NewGuid(), new RHostClientTestApp()); await session.StartHostAsync(new RHostStartupInfo { Name = _testMethod.Name, RBasePath = RUtilities.FindExistingRBasePath() }, 50000); using (var debugSession = new DebugSession(session)) { using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var paused = new TaskCompletionSource<bool>(); debugSession.Browse += delegate { paused.SetResult(true); }; await sf.Source(session); await paused.Task; var stackFrames = (await debugSession.GetStackFramesAsync()).Reverse().ToArray(); stackFrames.Should().NotBeEmpty(); var evalResult = await stackFrames[0].GetEnvironmentAsync(); evalResult.Should().BeAssignableTo<DebugValueEvaluationResult>(); var frame = (DebugValueEvaluationResult)evalResult; var children = (await frame.GetChildrenAsync()).ToDictionary(er => er.Name); children.Should().ContainKey("p"); children["p"].Should().BeAssignableTo<DebugPromiseEvaluationResult>(); var p = (DebugPromiseEvaluationResult)children["p"]; children.Should().ContainKey("d"); children["d"].Should().BeAssignableTo<DebugValueEvaluationResult>(); var d = (DebugValueEvaluationResult)children["d"]; p.Code.Should().Be(d.GetRepresentation(DebugValueRepresentationKind.Raw).Deparse); } } await session.StopHostAsync(); } }
public static void ExchangeDebugInfo(Guid CodeId, DebugSession debugsession, Jint.Engine engine) { engine.BreakPoints.Clear(); foreach (var item in debugsession.BreakLines.Where(w => w.codeId == CodeId)) { engine.BreakPoints.Add(new Jint.Runtime.Debugger.BreakPoint(item.Line, 0)); } debugsession.JsEngine = engine; debugsession.CurrentCodeId = CodeId; debugsession.End = false; }
public async Task BrowseOnNewPrompt() { using (var debugSession = new DebugSession(_session)) { var browseTask = EventTaskSources.DebugSession.Browse.Create(debugSession); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("browser()\n"); } await debugSession.NextPromptShouldBeBrowseAsync(); await browseTask; } }
int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 pCallback, enum_ATTACH_REASON dwReason) { ThrowIfDisposed(); if (rgpPrograms.Length != 1) { throw new ArgumentException("Zero or more than one programs", "rgpPrograms"); } _program = rgpPrograms[0] as RDebugPortSupplier.DebugProgram; if (_program == null) { throw new ArgumentException("rgpPrograms[0] must be an " + nameof(RDebugPortSupplier.DebugProgram), "rgpPrograms"); } Marshal.ThrowExceptionForHR(_program.GetProgramId(out _programId)); _events = pCallback; DebugSession = TaskExtensions.RunSynchronouslyOnUIThread(ct => DebugSessionProvider.GetDebugSessionAsync(_program.Session, ct)); MainThread = new AD7Thread(this); IsConnected = true; // Enable breakpoint instrumentation. TaskExtensions.RunSynchronouslyOnUIThread(ct => DebugSession.EnableBreakpointsAsync(true, ct)); // Send notification after acquiring the session - we need it in case there were any breakpoints pending before // the attach, in which case we'll immediately get breakpoint creation requests as soon as we send these, and // we will need the session to process them. AD7EngineCreateEvent.Send(this); AD7ProgramCreateEvent.Send(this); Send(new AD7LoadCompleteEvent(), AD7LoadCompleteEvent.IID); // Register event handlers after notifying VS that debug engine has loaded. This order is important because // we may get a Browse event immediately, and we want to raise a breakpoint notification in response to that // to pause the debugger - but it will be ignored unless the engine has reported its creation. // Also, AfterRequest must be registered before Browse, so that we never get in a situation where we get // Browse but not AfterRequest that follows it because of a race between raising and registration. DebugSession.RSession.AfterRequest += RSession_AfterRequest; DebugSession.RSession.Disconnected += RSession_Disconnected; // If we're already at the Browse prompt, registering the handler will result in its immediate invocation. // We want to handle that fully before we process any following AfterRequest event to avoid concurrency issues // where we pause and never resume, so hold the lock while adding the handler. lock (_browseLock) { DebugSession.Browse += Session_Browse; } return(VSConstants.S_OK); }
public async Task CallStack() { using (var debugSession = new DebugSession(_session)) { const string code1 = @"f <- function(n) { if (n > 0) { g(n - 1) } else { return() } }"; const string code2 = @"g <- function(n) { if (n > 0) { f(n - 1) } else { return() } }"; using (var sf1 = new SourceFile(code1)) using (var sf2 = new SourceFile(code2)) { await debugSession.EnableBreakpointsAsync(true); await sf1.Source(_session); await sf2.Source(_session); var bp = await debugSession.CreateBreakpointAsync(sf1, 5); var bpHit = new BreakpointHitDetector(bp); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f(4)\n"); } await bpHit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { (string)null, null, "f(4)" }, { sf1, 3, "g(n - 1)" }, { sf2, 3, "f(n - 1)" }, { sf1, 3, "g(n - 1)" }, { sf2, 3, "f(n - 1)" }, { sf1, 5, MatchAny <string> .Instance }, }); } } }
public void StartDebugExperimentFromButton() { if (fileLocationSettings == null) { Debug.LogError($"{TuxLog.Prefix} fileLocationSettings null when debug started"); } Session session = new DebugSession(fileLocationSettings); foreach (ParticipantVariable variable in runner.DesignFile.GetVariables.ParticipantVariables) { variable.SetValueDefaultValue(); } StartRunningExperiment(session); }
public async Task BrowseOnExistingPrompt() { using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("browser()\n"); } using (var inter = await _session.BeginInteractionAsync()) { inter.Contexts.IsBrowser().Should().BeTrue(); } using (var debugSession = new DebugSession(_session)) { await debugSession.InitializeAsync(); await EventTaskSources.DebugSession.Browse.Create(debugSession); } }
public async Task SetAndHitToplevelBreakpoint() { const string code = @"x <- 1 y <- 2 z <- 3"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp = await debugSession.CreateBreakpointAsync(new DebugBreakpointLocation(sf.FilePath, 2)); var bpHit = new BreakpointHitDetector(bp); await sf.Source(_session); await bpHit.ShouldBeHitAtNextPromptAsync(); } }
public async Task CallStack() { using (var debugSession = new DebugSession(_session)) { const string code1 = @"f <- function(n) { if (n > 0) { g(n - 1) } else { return() } }"; const string code2 = @"g <- function(n) { if (n > 0) { f(n - 1) } else { return() } }"; using (var sf1 = new SourceFile(code1)) using (var sf2 = new SourceFile(code2)) { await debugSession.EnableBreakpointsAsync(true); await sf1.Source(_session); await sf2.Source(_session); var bp = await debugSession.CreateBreakpointAsync(sf1, 5); var bpHit = new BreakpointHitDetector(bp); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f(4)\n"); } await bpHit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should().HaveTail(new MatchDebugStackFrames { { (string)null, null, "f(4)" }, { sf1, 3, "g(n - 1)" }, { sf2, 3, "f(n - 1)" }, { sf1, 3, "g(n - 1)" }, { sf2, 3, "f(n - 1)" }, { sf1, 5, MatchAny<string>.Instance }, }); } } }
public async Task<DebugSession> GetDebugSessionAsync(IRSession session, CancellationToken cancellationToken = default(CancellationToken)) { DebugSession debugSession; await _sem.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (!_debugSessions.TryGetValue(session, out debugSession)) { debugSession = new DebugSession(session); await debugSession.InitializeAsync(cancellationToken).ConfigureAwait(false); _debugSessions.Add(session, debugSession); } session.Disposed += Session_Disposed; } finally { _sem.Release(); } return debugSession; }
public async Task StepOver() { const string code = @"f <- function(x) { x + 1 } x <- f(1) print(x)"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp = await debugSession.CreateBreakpointAsync(sf, 4); var bpHit = new BreakpointHitDetector(bp); await sf.Source(_session); await bpHit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should().BeAt(bp.Location); (await debugSession.StepOverAsync()).Should().Be(true); (await debugSession.GetStackFramesAsync()).Should().BeAt(bp.Location, +1); } }
/// <summary> /// Execute the template transformation with the given parameters /// </summary> /// <param name="itemUri">Tridion item URI.</param> /// <param name="templateUri">Tridion template URI.</param> /// <param name="publicationTargetUri">Tridion publication target URI.</param> /// <param name="logLevel">Log level.</param> /// <returns>Package "Output" item as <see cref="T:System.String" /></returns> public override String Execute(String itemUri, String templateUri, String publicationTargetUri = null) { String sessionId = Guid.NewGuid().ToString(); DebugSession debugSession = null; try { String templateXml = mCompoundService.GetCompoundTemplateXml(templateUri); debugSession = new DebugSession(sessionId, templateUri, templateXml, itemUri, null, true, publicationTargetUri, DebuggerConfig.Instance.Templating.EnableImpersonation && !String.IsNullOrEmpty(DebuggerConfig.Instance.Templating.ImpersonationIdentity) ? DebuggerConfig.Instance.Templating.ImpersonationIdentity : WindowsIdentity.GetCurrent().Name, DebuggerConfig.Instance.Logging.IncludeTridionClasses, DebuggerConfig.Instance.Logging.Level); debugSession.SetPreviewLocations( DebuggerConfig.Instance.CMS.PreviewDirectory, PreviewServer.PreviewUrl); // Signal for any debuggers DebuggerHook(); debugSession.Start(); int lastMessageId = -1; while (debugSession.IsRunning()) { Thread.Sleep(1000); lastMessageId = debugSession.WriteLogEntries(lastMessageId); } String postPackage = debugSession.GetPostPackageName(); String outputItemDataId = debugSession.GetPackageItemDataId(postPackage, "Output"); return debugSession.GetPackageItemString(outputItemDataId); } catch (Exception ex) { Logger.Log(System.Diagnostics.TraceEventType.Error, "Exception while executing DebugEngine for item {0}, template {1}: {2}", itemUri, templateUri, LoggerExtensions.TraceException(ex)); } finally { if (debugSession != null) debugSession.Stop(); } return String.Empty; }
private async Task PublishAllAsync() { await TaskUtilities.SwitchToBackgroundThread(); var debugSessionProvider = VsAppShell.Current.ExportProvider.GetExportedValue<IDebugSessionProvider>(); if (_debugSession == null) { _debugSession = await debugSessionProvider.GetDebugSessionAsync(RSession); if (_debugSession == null) { Debug.Fail(""); return; } } List<Task> subsribeTasks = new List<Task>(); lock (_subscribers) { foreach (var kv in _subscribers) { subsribeTasks.Add(PublishAsync(kv.Key, kv.Value)); } } await Task.WhenAll(subsribeTasks); }
public async Task StepOutToFunction() { const string code = @"f <- function() { 1 } g <- function() { f() 1 } g()"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp = await debugSession.CreateBreakpointAsync(sf, 2); var bpHit = new BreakpointHitDetector(bp); await sf.Source(_session); await bpHit.ShouldBeHitAtNextPromptAsync(); (await debugSession.GetStackFramesAsync()).Should() .BeAt(bp.Location, "f()") .At(sf, 5, "g()"); (await debugSession.StepOutAsync()).Should().Be(true); (await debugSession.GetStackFramesAsync()).Should().BeAt(sf, 6, "g()"); } }
//[InlineData(@"'\u2260'", @"""≠""", @"""≠""", "≠")] public async Task Representation(string expr, string deparse, string str, string toString) { using (var debugSession = new DebugSession(_session)) { var res = (await debugSession.EvaluateAsync(expr)).As<DebugValueEvaluationResult>(); var repr = res.GetRepresentation(DebugValueRepresentationKind.Normal); repr.Deparse.Should().Be(deparse); repr.Str.Should().Be(str); repr.ToString.Should().Be(toString); } }
public async Task BreakpointsInDifferentFiles() { using (var debugSession = new DebugSession(_session)) using (var sf1 = new SourceFile("1")) using (var sf2 = new SourceFile($"eval(parse({sf1.FilePath.ToRStringLiteral()}))")) { await debugSession.EnableBreakpointsAsync(true); var bp1Loc = new DebugBreakpointLocation(sf1.FilePath, 1); var bp1 = await debugSession.CreateBreakpointAsync(bp1Loc); bp1.Location.Should().Be(bp1Loc); var bp2Loc = new DebugBreakpointLocation(sf2.FilePath, 1); var bp2 = await debugSession.CreateBreakpointAsync(bp2Loc); bp2.Location.Should().Be(bp2Loc); debugSession.Breakpoints.Should().HaveCount(2); var bp1Hit = new BreakpointHitDetector(bp1); var bp2Hit = new BreakpointHitDetector(bp2); await sf2.Source(_session); await bp2Hit.ShouldBeHitAtNextPromptAsync(); bp1Hit.WasHit.Should().BeFalse(); bp2Hit.Reset(); await debugSession.ContinueAsync(); await bp1Hit.ShouldBeHitAtNextPromptAsync(); bp2Hit.WasHit.Should().BeFalse(); } }
public async Task RemovedBreakpointNotHit() { const string code = @"f <- function() { 0 }"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); await sf.Source(_session); var bp = await debugSession.CreateBreakpointAsync(new DebugBreakpointLocation(sf.FilePath, 2)); var bpHit = new BreakpointHitDetector(bp); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } await bpHit.ShouldBeHitAtNextPromptAsync(); await bp.DeleteAsync(); await debugSession.ContinueAsync(); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } using (var inter = await _session.BeginInteractionAsync()) { inter.Contexts.IsBrowser().Should().BeFalse(); } } }
public async Task OverlappingBreakpoints() { const string code = @"f <- function() { 1 }"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); await sf.Source(_session); var bp1 = await debugSession.CreateBreakpointAsync(sf, 1); var bp2 = await debugSession.CreateBreakpointAsync(sf, 1); bp1.Should().BeSameAs(bp2); debugSession.Breakpoints.Should().HaveCount(1); var bp1Hit = new BreakpointHitDetector(bp1); var bp2Hit = new BreakpointHitDetector(bp2); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } await bp1Hit.ShouldBeHitAtNextPromptAsync(); bp2Hit.WasHit.Should().BeTrue(); await debugSession.ContinueAsync(); await bp1.DeleteAsync(); debugSession.Breakpoints.Should().HaveCount(1); debugSession.Breakpoints.Should().Contain(bp2); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } await bp2Hit.ShouldBeHitAtNextPromptAsync(); await debugSession.ContinueAsync(); await bp2.DeleteAsync(); debugSession.Breakpoints.Should().HaveCount(0); using (var inter = await _session.BeginInteractionAsync()) { await inter.RespondAsync("f()\n"); } using (var inter = await _session.BeginInteractionAsync()) { inter.Contexts.IsBrowser().Should().BeFalse(); } } }
public DebuggingStatusResult StartDebuggingWithPackage(String compoundTemplateId, String compoundTemplateXml, String packageXml, bool includeSystemLog, System.Diagnostics.TraceEventType logLevel) { try { mDebugSession = new DebugSession(mSessionId, compoundTemplateId, compoundTemplateXml, null, packageXml, true, "tcm:0-0-0", DebuggerConfig.Instance.Templating.EnableImpersonation && !String.IsNullOrEmpty(DebuggerConfig.Instance.Templating.ImpersonationIdentity) ? DebuggerConfig.Instance.Templating.ImpersonationIdentity : WindowsIdentity.GetCurrent().Name, DebuggerConfig.Instance.Logging.IncludeTridionClasses, logLevel); // Signal for any debuggers DebuggerHook(); mDebugSession.SetPreviewLocations( DebuggerConfig.Instance.CMS.PreviewDirectory, PreviewServer.PreviewUrl); mDebugSession.Start(); } catch (Exception ex) { Logger.Log(System.Diagnostics.TraceEventType.Error, LoggerExtensions.TraceException(ex)); } String logMessages = mDebugSession.GetLogMessagesXml(-1, -1, -1); WriteLog(logMessages); return new DebuggingStatusResult() { SessionId = mSessionId, IsRunning = mDebugSession.IsRunning(), ExecutionStatus = StripXmlDeclaration(mDebugSession.GetExecutionStatusXml()), Log = StripXmlDeclaration(logMessages), Error = mDebugSession.GetLastException() }; }
public async Task SetBreakpointOnNull() { const string code = @"f <- function() { NULL }"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { var bp = await debugSession.CreateBreakpointAsync(new DebugBreakpointLocation(sf.FilePath, 2)); debugSession.Breakpoints.Count.Should().Be(1); await sf.Source(_session); var res = (await debugSession.EvaluateAsync("is.function(f)")).As<DebugValueEvaluationResult>(); res.GetRepresentation(DebugValueRepresentationKind.Normal).Deparse .Should().Be("TRUE"); } }
public async Task SetAndHitBreakpointInsideUnloadedFunction() { const string code = @"f <- function() { 0 } f()"; using (var debugSession = new DebugSession(_session)) using (var sf = new SourceFile(code)) { await debugSession.EnableBreakpointsAsync(true); var bp = await debugSession.CreateBreakpointAsync(new DebugBreakpointLocation(sf.FilePath, 2)); var bpHit = new BreakpointHitDetector(bp); await sf.Source(_session); await bpHit.ShouldBeHitAtNextPromptAsync(); } }