Repository navigation
reduce reliance on R_GlobalContext in debugger - #17288
Conversation
…inery
Add RContext.hpp, a lightweight header that depends only on the stable
{nextcontext, callflag} prefix of the RCNTXT struct. Migrate call sites
that only need callflag checks (busy detection, top-level checks,
browser context detection) to use it instead of the full RCntxt class.
Replace the C++ rs_chatCallStackFunctions() with R-side
lapply(seq_len(sys.nframe()), sys.function), and replace
rs_dumpContexts() with a direct call to sys.status().
The remaining RCntxt usage in SessionEnvironment.cpp (debugger call
frame introspection) is left for a follow-up.
Move the debugger call frame introspection from C++ (walking the RCNTXT linked list) to R using sys.call/sys.function/sys.frame/sys.parents. The new .rs.callFrames() R function builds the same frame descriptor list that the old C++ callFramesAsJson() produced, using only public R APIs for most of the work. The browser environment is tracked as a global (s_browserEnv) set from onConsolePrompt, to handle the promise forcing case where the browser's environment doesn't correspond to any sys.frame() visible from R. Use R_GetCurrentSrcref(NA_INTEGER) (public R API) instead of accessing the RCNTXT srcref field directly for debug stepping line detection. Also update functionIsOutOfSync() to accept the CallFrameResult struct instead of an RCntxt object.
Pass R_GetCurrentSrcref(NA_INTEGER) from C++ into .rs.callFrames so the innermost frame can use the evaluator's runtime srcref (the current stepping position), which is not accessible from R's sys.*() functions. Track the browser environment as a global (s_browserEnv) set from onConsolePrompt, and expose it via rs_getBrowserEnv so the R function can correctly identify the browsed frame during promise forcing. Also fix the Phase 3 iteration order to go inner-to-outer (rev(seq_len(nframe))), matching the old C++ RCNTXT convention where depth 1 is the innermost function context.
Replace the shared RCntxt object used for change detection with a plain
SEXP environment pointer. Reimplement getFunctionContext and
inDebugHiddenContext as R helpers (.rs.getFunctionContext,
.rs.inDebugHiddenContext).
SessionEnvironment.cpp no longer includes RCntxt.hpp or RCntxtUtils.hpp.
The only remaining context access is via RContext.hpp (the lightweight
{nextcontext, callflag} walker for inActiveBrowseContext).
Also fix two bugs from the prior commit:
- Phase 1 envSrcrefMap now iterates inner-to-outer (rev(seq_len(nframe)))
so first-match-wins selects the innermost srcref
- lastDebugLine is now propagated back from R to C++ via the return value
instead of dead code mutating a local R list copy
All context introspection now uses either the lightweight RContext.hpp (for signal-safe callflag checks) or R-side sys.*() functions (for full frame introspection). The version-dispatched RCntxt class hierarchy, its five RCNTXT_* struct definitions, and supporting files are no longer referenced and can be removed. Addresses review feedback: clean up dead code, fix copyright years, add clarifying comment on evaldepth equivalence.
Extend the RContext struct to include the stable prefix of RCNTXT through cloenv, enabling direct context stack walks for browser detection and debug-hidden checks without the old RCntxt class. These must run in C++ (not R) because onConsolePrompt is called from the R console read callback, where sys.*() functions don't see the browser's call stack. Also rename contextStack() to globalContext() and use R_NO_REMAP to avoid Rinternals.h macro conflicts with C++ standard headers.
Replace the C++ context stack walk in getFunctionContext with a call to the R-side .rs.getFunctionContext(), which uses sys.frame() / sys.nframe() (public R API) instead of walking RCNTXT directly. The browser context's cloenv is passed from C++ via a new browserContextEnv() helper, since browserText() / do_sysbrowser are unreliable when called through R_tryEval (R_ToplevelExec resets R_ToplevelContext, hiding the CTXT_BROWSER context). Also fix Rf_asLogical check in inDebugHiddenContext to compare against TRUE explicitly, avoiding NA_LOGICAL being treated as truthy.
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
Enable dark theme styling for the New Connection Wizard and all its sub-pages (snippet, Shiny, ODBC install/pre-install). GWT changes: - Call setThemeAware(true) in NewConnectionWizard constructor - Add dark CSS overrides for wizardBodyPanel border, warning panels, code viewer, and ODBC console areas - Remove newConnectionWizardBackground sprite in dark mode (all connection pages override getWizardPageBackgroundStyle with this custom sprite, which was not covered by the base Wizard.css dark override) - Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css Shiny iframe dark mode (Spark Connection, etc.): - Inject dark-mode CSS into the Shiny mini-UI iframe for labels, form controls, and select option elements - In Server, use native JSNI to inject styles into the same-origin iframe document - In Desktop, add an Electron bridge method (injectShinyDialogCss) that uses WebFrameMain.executeJavaScript() to inject CSS into cross-origin iframes, matching the Shiny dialog frame by its full URL (origin + pathname)
Enable dark theme styling for the New Connection Wizard and all its sub-pages (snippet, Shiny, ODBC install/pre-install). GWT changes: - Call setThemeAware(true) in NewConnectionWizard constructor - Add dark CSS overrides for wizardBodyPanel border, warning panels, code viewer, and ODBC console areas - Remove newConnectionWizardBackground sprite in dark mode (all connection pages override getWizardPageBackgroundStyle with this custom sprite, which was not covered by the base Wizard.css dark override) - Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css Shiny iframe dark mode (Spark Connection, etc.): - Inject dark-mode CSS into the Shiny mini-UI iframe for labels, form controls, and select option elements - In Server, use native JSNI to inject styles into the same-origin iframe document - In Desktop, add an Electron bridge method (injectShinyDialogCss) that uses WebFrameMain.executeJavaScript() to inject CSS into cross-origin iframes, matching the Shiny dialog frame by its full URL (origin + pathname)
Enable dark theme styling for the New Connection Wizard and all its sub-pages (snippet, Shiny, ODBC install/pre-install). GWT changes: - Call setThemeAware(true) in NewConnectionWizard constructor - Add dark CSS overrides for wizardBodyPanel border, warning panels, code viewer, and ODBC console areas - Remove newConnectionWizardBackground sprite in dark mode (all connection pages override getWizardPageBackgroundStyle with this custom sprite, which was not covered by the base Wizard.css dark override) - Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css Shiny iframe dark mode (Spark Connection, etc.): - Inject dark-mode CSS into the Shiny mini-UI iframe for labels, form controls, and select option elements - In Server, use native JSNI to inject styles into the same-origin iframe document - In Desktop, add an Electron bridge method (injectShinyDialogCss) that uses WebFrameMain.executeJavaScript() to inject CSS into cross-origin iframes, matching the Shiny dialog frame by its full URL (origin + pathname)
Enable dark theme styling for the New Connection Wizard and all its sub-pages (snippet, Shiny, ODBC install/pre-install). GWT changes: - Call setThemeAware(true) in NewConnectionWizard constructor - Add dark CSS overrides for wizardBodyPanel border, warning panels, code viewer, and ODBC console areas - Remove newConnectionWizardBackground sprite in dark mode (all connection pages override getWizardPageBackgroundStyle with this custom sprite, which was not covered by the base Wizard.css dark override) - Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css Shiny iframe dark mode (Spark Connection, etc.): - Inject dark-mode CSS into the Shiny mini-UI iframe for labels, form controls, and select option elements - In Server, use native JSNI to inject styles into the same-origin iframe document - In Desktop, add an Electron bridge method (injectShinyDialogCss) that uses WebFrameMain.executeJavaScript() to inject CSS into cross-origin iframes, matching the Shiny dialog frame by its full URL (origin + pathname)
Enable dark theme styling for the New Connection Wizard and all its sub-pages (snippet, Shiny, ODBC install/pre-install). GWT changes: - Call setThemeAware(true) in NewConnectionWizard constructor - Add dark CSS overrides for wizardBodyPanel border, warning panels, code viewer, and ODBC console areas - Remove newConnectionWizardBackground sprite in dark mode (all connection pages override getWizardPageBackgroundStyle with this custom sprite, which was not covered by the base Wizard.css dark override) - Remove duplicate .codeViewer CSS block in NewConnectionShinyHost.css Shiny iframe dark mode (Spark Connection, etc.): - Inject dark-mode CSS into the Shiny mini-UI iframe for labels, form controls, and select option elements - In Server, use native JSNI to inject styles into the same-origin iframe document - In Desktop, add an Electron bridge method (injectShinyDialogCss) that uses WebFrameMain.executeJavaScript() to inject CSS into cross-origin iframes, matching the Shiny dialog frame by its full URL (origin + pathname)
R only added special NA_INTEGER handling to R_GetCurrentSrcref in R 4.5. On older versions, NA_INTEGER is treated as a large negative skip value and always returns R_NilValue, causing the debug source highlight to break during stepping.
…t/hasBrowserContext - isBusy() now uses !isTopLevelContext() so it correctly reports busy for non-function contexts like top-level for loops - isTopLevelContext() now checks nextcontext == nullptr to distinguish the real top-level from R_ToplevelExec contexts - browserContextActive() is now prompt-based (Browse[N]>) instead of walking R_GlobalContext - Remove hasFunctionContext() and hasBrowserContext() (no remaining callers)
gtritchie
left a comment
There was a problem hiding this comment.
PR Review: reduce reliance on R_GlobalContext in debugger
Reviewed +908/-1448 across 24 files. Well-structured refactoring that consolidates all R_GlobalContext access into a single file behind a narrow API, replacing version-fragile struct overlays with R's public sys.*() API. Net deletion of ~540 lines.
Critical (2)
1. s_browserEnv is not GC-protected
src/cpp/session/modules/environment/SessionEnvironment.cpp
The static SEXP s_browserEnv is assigned from environmentTop without R_PreserveObject, but read from R via .Call("rs_getBrowserEnv"). If the browser context is unwound between assignment and use, GC could collect it. By contrast, pCurrentEnv in the same file correctly uses preserve/release.
// Suggested fix:
if (s_browserEnv != R_NilValue)
R_ReleaseObject(s_browserEnv);
s_browserEnv = environmentTop;
if (s_browserEnv != R_NilValue)
R_PreserveObject(s_browserEnv);2. No bounds check on VECTOR_ELT in getFunctionContext()
src/cpp/r/RContext.cpp:110-111
int foundDepth = r::sexp::asInteger(VECTOR_ELT(resultSEXP, 0));
SEXP foundEnv = VECTOR_ELT(resultSEXP, 1);If .rs.getFunctionContext() returns something other than a 2-element VECSXP (due to a bug or unexpected R state), this will crash. No type/length validation on resultSEXP. Also, the Error from the R call is silently discarded without LOG_ERROR.
Important (5)
3. rs_getBrowserEnv() misleading null check
SessionEnvironment.cpp
return s_browserEnv ? s_browserEnv : R_NilValue;s_browserEnv is initialized to R_NilValue (a valid non-null SEXP pointer), so the C boolean test always evaluates true. The ternary fallback is dead code. Simplify to return s_browserEnv;.
4. isBusy() semantic broadening
src/cpp/r/session/RBusy.cpp
Old code checked callflag & CTXT_FUNCTION (any function on stack). New code checks !isTopLevelContext() (any context at all, including loops, ccode, browser). This broadens what's considered "busy." If intentional, worth a comment; if not, consider preserving the old CTXT_FUNCTION check.
5. boost::regex_match can throw in RReadConsole
src/cpp/r/session/RStdCallbacks.cpp:277-278
static const boost::regex reBrowsePrompt("Browse\\[\\d+\\]> ");
setBrowserActive(boost::regex_match(prompt, reBrowsePrompt));boost::regex_match can throw boost::regex_error. No try-catch, and this runs inside RReadConsole. An exception could terminate the session.
6. Unchecked getNamedListSEXP inner calls in callFramesFromR()
SessionEnvironment.cpp
Four getNamedListSEXP calls inside the context extraction block silently discard their Error return values. If the R function changes its return structure, these failures would be invisible. At minimum, add LOG_ERROR.
7. R-side tryCatch swallows errors silently
SessionEnvironment.R (.rs.callFrames)
At least 5 places use tryCatch(..., error = function(e) "") with zero logging. Bugs in helpers like .rs.functionNameFromCall, .rs.sourceFileFromRef, .rs.simulateSourceRefs would produce blank/zero values indistinguishable from legitimately absent data. The old C++ code had LOG_ERROR on some of these paths.
Suggestions (5)
8. chat.hasTrustedCaller now includes its own frame
src/cpp/session/modules/SessionChat.R:293 — Old .Call returned only callfun from CTXT_FUNCTION contexts. New lapply(seq_len(sys.nframe()), sys.function) includes .rs.chat.hasTrustedCaller itself. Verify the trusted caller check doesn't match .rs. internal functions.
9. .rs.callFrames docstring doesn't match return value
The @return documents flat components (context_callfun, context_cloenv, src_context_callfun, src_context_call). Actual return is nested (context is a list with sub-elements, src_context is a list with sub-elements, and lastDebugLine is undocumented).
10. rs_dumpContexts() silently discards error — Add LOG_ERROR.
11. RContext struct "stable prefix" comment — Worth explaining why these fields are stable (same order across R 3.2-4.4+) and what R version range this is validated for. Aids future maintainers when a new R version ships.
12. CMake libgit2 timestamp workaround — Orthogonal to this PR's purpose. Consider splitting into a separate commit for cleaner history.
Strengths
- Major reduction in R-internal dependency surface — deletes 5 header/source files maintaining version-specific RCNTXT struct layouts
- Clean encapsulation — all
R_GlobalContextaccess behind a narrow API in one file - Good use of stable R public APIs (
sys.frame(),sys.nframe(),sys.call(),R_GetCurrentSrcref()) - High-quality comments in key areas: context type flag binary literals, browser env promise-forcing rationale,
browserEnvparam explainingR_ToplevelExecbehavior inActiveBrowseContext()rename improves precision- Defensive null check in
SessionBreakpoints.R
Instead of walking R_GlobalContext to find the browser context's environment, inject .rs.captureCurrentEnvironment() into the browser REPL. R evaluates this in the browser's rho, so parent.frame() correctly returns the environment being debugged -- even during promise forcing where the browser env doesn't correspond to any sys.frame() visible from R. Also adds dumpContexts() for debugging/testing the context stack, and rs_setCapturedBrowserEnv .Call method for the R-to-C++ bridge.
inActiveBrowseContext() now checks browserContextActive() (prompt-based) and browserEnv() != R_GlobalEnv (captured via REPL injection) instead of walking the C context stack.
…textEnv inDebugHiddenContext() now calls .rs.inDebugHiddenContext() in R instead of walking the C context stack. The R version also correctly handles S4 trace wrappers via .rs.originalFunction(). browserContextEnv() has no remaining callers (getFunctionContext now uses the browser env captured via the injected REPL command) and is removed. The only remaining globalContext() uses are isTopLevelContext() (needs async-signal safety) and dumpContexts() (diagnostic tool).
… tracking isTopLevelContext() now uses atDefaultPrompt() (set from RReadConsole when hist==1 and the prompt matches the default) combined with !r::exec::isExecuting() (tracks internal R code execution). This removes the last production use of R_GlobalContext. Only the dumpContexts() diagnostic tool still accesses the C context stack.
RContext.cpp no longer accesses R_GlobalContext or the RCNTXT struct directly. Remove the internal struct definition, context type flags, globalContext() accessor, contextTypeName() helper, and dumpContexts() diagnostic function. Revert rs_dumpContexts to use sys.status().
…xt result - Use PreservedSEXP for s_browserEnv in both SessionEnvironment.cpp and RSession.cpp to ensure proper R_PreserveObject/R_ReleaseObject lifecycle - Add type/length validation on the VECTOR_ELT calls in getFunctionContext() to guard against malformed R results
- Add LOG_ERROR to unchecked getNamedListSEXP calls in callFramesFromR - Add LOG_ERROR to rs_dumpContexts - Use regex_utils::match instead of boost::regex_match for browse prompt detection (catches exceptions instead of propagating) - Document isBusy() semantic broadening - Exclude own frame in .rs.chat.hasTrustedCaller
Move isTopLevelContext, inActiveBrowseContext, getFunctionContext, and inDebugHiddenContext from the r::context namespace (RContext.cpp) to r::session (RSession.cpp). These functions now operate entirely on tracked session state and R-side calls, so r::session is their natural home. Rename for clarity: - isTopLevelContext -> isAtTopLevel - inActiveBrowseContext -> isBrowseActive Delete RContext.cpp and RContext.hpp — no longer needed.
|
Review #210 /Users/gary/alt/rstudio 6ccb5be..ac1f205 Review Findings
SummaryThis change replaces direct |
- pass caller's Protect into callFramesFromR() so returned SEXPs stay protected for the lifetime of their use - only update browser state on REPL prompts (hist == 1) so that readline()/scan() inside the browser don't clear debug state - simplify capture-env injection flag logic and rename to s_captureInjected for clarity - remove redundant environmentTop assignment in onConsolePrompt
Continuation prompts ("+ ") share the hist == 1 path with fresh REPL
prompts in RReadConsole, so they were calling setBrowserActive(false)
mid-parse on every line of a multi-line expression entered at the
Browse[N]> prompt. That cleared the captured browser environment,
flipped the cached browser-active flag to false, and could prevent the
client from receiving a kContextDepthChanged event when state didn't
appear to change after the multi-line eval — leaving the call stack
pane empty and the source-editor debug highlight stale.
Detect continuation prompts via getOption("continue") and skip the
setAtTopLevelPrompt / setBrowserActive updates in that case. The
underlying REPL (browser or top-level) hasn't changed across a
continuation, so the cached state should be preserved from the prior
fresh prompt.
Regression introduced by #17288.
isBrowseActive() in RSession.cpp excluded R_GlobalEnv as a valid captured browser environment. For top-level debugging (debugSource() of a script with breakpoints, or browser() at top level), the inject's parent.frame() correctly captures R_GlobalEnv — so the !=R_GlobalEnv clause then rejected the legitimate state, isBrowseActive() returned FALSE, and onConsolePrompt's early-return path fired before any kContextDepthChanged event reached the client. The debug highlight and debugger toolbar therefore never appeared. Test the right invariant — that the env was captured (non-nil) — rather than excluding R_GlobalEnv specifically. R_GlobalEnv is a perfectly valid captured env when debugging at the top level of a sourced script. Adds a top-level breakpoint regression test that mirrors the reproducer from #17481. preserve browser state across continuation prompts in the debugger Continuation prompts ("+ ") share the hist == 1 path with fresh REPL prompts in RReadConsole, so they were calling setBrowserActive(false) mid-parse on every line of a multi-line expression entered at the Browse[N]> prompt. That cleared the captured browser environment, flipped the cached browser-active flag to false, and could prevent the client from receiving a kContextDepthChanged event when state didn't appear to change after the multi-line eval — leaving the call stack pane empty and the source-editor debug highlight stale. Detect continuation prompts via getOption("continue") and skip the setAtTopLevelPrompt / setBrowserActive updates in that case. The underlying REPL (browser or top-level) hasn't changed across a continuation, so the cached state should be preserved from the prior fresh prompt. Regression introduced by #17288. replace em-dashes with ascii dashes in debugger test handle nested debugger in test still update top-level prompt flag at continuation prompts The previous commit skipped both setAtTopLevelPrompt and setBrowserActive at continuation prompts on the theory that the underlying REPL state had not changed. But setAtTopLevelPrompt(false) is called right before each line of input is returned to R (RStdCallbacks.cpp:440), so when R issued the "+ " prompt for the next line of a multi-line expression, the flag remained false instead of bouncing back to true. NotebookQueue::process() bails out when isAtTopLevel() is false, so it deferred the next line of any multi-line chunk expression and never resumed -- leaving R hung at the "+ " prompt. This regressed the "multiline expressions in chunks execute without hanging" automation test. Restore the atTopLevelPrompt update at continuation prompts, but key it off browserContextActive() instead of the (always-false) `browsing` flag derived from the prompt regex -- the "+ " prompt itself doesn't reveal whether we're inside a browser. browserActive remains untouched at continuation prompts, preserving the original fix for multi-line input at Browse[N]>.
…17491) * debugger fixes isBrowseActive() in RSession.cpp excluded R_GlobalEnv as a valid captured browser environment. For top-level debugging (debugSource() of a script with breakpoints, or browser() at top level), the inject's parent.frame() correctly captures R_GlobalEnv — so the !=R_GlobalEnv clause then rejected the legitimate state, isBrowseActive() returned FALSE, and onConsolePrompt's early-return path fired before any kContextDepthChanged event reached the client. The debug highlight and debugger toolbar therefore never appeared. Test the right invariant — that the env was captured (non-nil) — rather than excluding R_GlobalEnv specifically. R_GlobalEnv is a perfectly valid captured env when debugging at the top level of a sourced script. Adds a top-level breakpoint regression test that mirrors the reproducer from #17481. preserve browser state across continuation prompts in the debugger Continuation prompts ("+ ") share the hist == 1 path with fresh REPL prompts in RReadConsole, so they were calling setBrowserActive(false) mid-parse on every line of a multi-line expression entered at the Browse[N]> prompt. That cleared the captured browser environment, flipped the cached browser-active flag to false, and could prevent the client from receiving a kContextDepthChanged event when state didn't appear to change after the multi-line eval — leaving the call stack pane empty and the source-editor debug highlight stale. Detect continuation prompts via getOption("continue") and skip the setAtTopLevelPrompt / setBrowserActive updates in that case. The underlying REPL (browser or top-level) hasn't changed across a continuation, so the cached state should be preserved from the prior fresh prompt. Regression introduced by #17288. replace em-dashes with ascii dashes in debugger test handle nested debugger in test still update top-level prompt flag at continuation prompts The previous commit skipped both setAtTopLevelPrompt and setBrowserActive at continuation prompts on the theory that the underlying REPL state had not changed. But setAtTopLevelPrompt(false) is called right before each line of input is returned to R (RStdCallbacks.cpp:440), so when R issued the "+ " prompt for the next line of a multi-line expression, the flag remained false instead of bouncing back to true. NotebookQueue::process() bails out when isAtTopLevel() is false, so it deferred the next line of any multi-line chunk expression and never resumed -- leaving R hung at the "+ " prompt. This regressed the "multiline expressions in chunks execute without hanging" automation test. Restore the atTopLevelPrompt update at continuation prompts, but key it off browserContextActive() instead of the (always-false) `browsing` flag derived from the prompt regex -- the "+ " prompt itself doesn't reveal whether we're inside a browser. browserActive remains untouched at continuation prompts, preserving the original fix for multi-line input at Browse[N]>. * harden top-level breakpoint test against transient highlight state The waitUntil only checked element existence, so it could fire on a transient highlight before the post-step events from the .doTrace auto-step settled. Wait for the line number to match and add a brief flush before asserting. * line number is 3, even though 0-based index is 2 * address pr review feedback for debugger continuation fixup - replace utf-8 em-dashes with -- in RStdCallbacks.cpp - fix inaccurate NotebookQueue reference in atTopLevelPrompt comment - tighten isBrowseActive comment with C++-side capture details and precise window boundaries - replace fixed Sys.sleep waits in tests with waitUntil predicates that poll for the actual condition (function defined, line number, console output) rather than time - clarify that gutter children use 0-based indexing in BRAT, and that the breakpoint lands on the print() line - assert "[1] 23" appears after the debugger exits so a hung session would fail the test
Summary
RCntxtinfrastructure (which overlaid an internal R struct onR_GlobalContext) with targeted, minimal uses of the context stackcallFramesAsJsonin R usingsys.frame()/sys.nframe()/sys.call()(public R API) instead of walkingRCNTXTdirectlygetFunctionContextin R usingsys.frame(), with the browser context'scloenvpassed from a small C++ helper (browserContextEnv())RContext.cppwith a file-local struct, reducing the surface area that depends on R internalsThe remaining uses of
R_GlobalContextare limited to simple boolean queries (isTopLevelContext,hasFunctionContext,hasBrowserContext,inActiveBrowseContext,inDebugHiddenContext) andbrowserContextEnv().Test plan
debugging-cmd-enter.R)debugging-14306.R)debugging-*.Rtest scripts insrc/cpp/tests/debugger/