Repository navigation
keep r errors from longjmping past rpc handlers and r::sexp callers - #19712
Conversation
…filepath round trip
RFunction::addParam() checks names and string-bearing values with sexp::containsNul() and records the first problem for call() to return, so a NUL from a C++ RPC handler's client string no longer raises R's error outside the protected call. This replaces the callRHandler() check. Every string create() builds now goes through one mkChar helper, which raises R's error on a NUL instead of cutting the string off. Addresses #19697.
…n containsNul() Raising R's error on a NUL in every create() overload added longjmps where r::sexp promises none (findVar() on a user command name, a _quarto.yml editor key, rs_readLines), so create() keeps erroring for std::string and truncating elsewhere; unifying it is a follow-up. containsNul() now has one overload per create() overload instead of a catch-all template, which won for a YAML sequence iterator's element and skipped the check. The test covers the remaining overloads and keeps fixtures and protection out of the protected callbacks. Addresses #19697.
call() passes each name to Rf_install(), which raises 'variable names are limited to 10000 bytes' outside the protected call, so a long JSON-RPC kwparams name longjmped past the handler just as a NUL did. acceptParam() now refuses names over 10000 bytes too. Addresses #19697.
A default-constructed core::Error allocates its implementation, which every RFunction would have paid for; call() now builds the error from the recorded reason. Addresses #19697.
Callers such as the connection handlers pass the result on before checking the error, so a refused call now leaves it as R_NilValue instead of untouched. Addresses #19697.
The refused requests must not run the handler at all; the control request runs it once. Addresses #19697.
The IDE's own client doesn't send these requests in normal use. Addresses #19697.
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
- r::sexp lookups by name treat a name R can't make a symbol from (empty, over 10000 bytes, or containing a nul) as unbound, instead of raising R's error or looking up the name cut off at the nul; the Object Explorer checks a View() title the same way before Rf_install(). - findVar() / findVarInFrame() read an active binding, or a promise R_getVarEx() forces, with errors and interrupts caught (R_tryCatch, silently); forcePromise() and findFunction()'s promise forcing likewise. - create(json::Array / json::Object) protects each element only until it's stored, so a long array can't overflow R's protection stack. - parseString() refuses code with a nul; the _quarto.yml editor options, document hooks, and notebook chunks skip or report strings with a nul instead of handing them to create(). - RPC dispatch runs each handler under R_ToplevelExec() as a backstop, answering a request an R error interrupted. Addresses #19697.
- invokeRpcHandler() runs offline requests' handlers directly, off the main thread, rather than entering R_ToplevelExec() while the main thread runs R. - A shared RpcDelivery records when a response is claimed and when it's sent: the backstop answers only if nothing was sent (also when the continuation failed before sending), and a continuation an async handler kept is dropped once the backstop answered. - installUtf8() checks the symbol length R checks, of the native name. - findFunction() reads each binding once and stops when one's R code fails, rather than reading a failing getter twice and returning a function further out. - A cyclic YAML alias becomes NULL in create() and is skipped by containsNul(), instead of recursing until the stack overflows. - A notebook chunk with a nul runs its error in R even when the document's default engine isn't R. - Tests: per-version promise forcing, getter call counts, shadowed functions, cyclic aliases, the Quarto editor guard, and the delivery protocol. Addresses #19697.
…evelExec - R_ToplevelExec() ran each handler in a top-level context of its own, discarding calling handlers R code registered meanwhile (a notebook's first chunk installs its condition handlers so) and catching interrupts meant for running R code. R_UnwindProtect() answers the request from its cleanup and lets the unwinding continue as before. - An RpcDelivery claim records whether the main thread made it; the backstop releases only a main-thread claim, leaving a response another thread is delivering to it. claimRpcDelivery() / markRpcDeliverySent() are shared by the end functions and the test. - Before R 3.6.2, R_tryCatch() transferred control for every condition, so caught lookups use R_ToplevelExec() there. - findVar() reads a found binding from its frame instead of repeating the inherited lookup; findFunction() classifies each binding once. - containsNul() reads YAML map keys as scalars, as create() does, instead of traversing composite keys. - The Object Explorer skips a cached View() title that isn't a string; the notebook NUL error calls base::stop(). - NEWS entry for the user-visible cases. Addresses #19697.
…interrupts - R restores its handler stack when any context ends, R_UnwindProtect()'s included, so after-response work (a notebook's first chunk registers its condition handlers there) is held while the handler runs and done once invokeRpcHandler()'s context has ended. - A caught lookup re-arms an interrupt, so R code running meanwhile still sees it. - The R_tryCatch() version check uses base::getRversion(), and is cached only once it succeeds. - findFunction() stops at a missing argument; containsNul() stops at a composite YAML key; the Object Explorer reads the title's length with Rf_xlength(); a notebook chunk whose metadata holds a NUL takes the same error path as one whose code does. - Tests: after-response ordering, a paused worker's claim, warning and interrupting bindings, a missing binding shadowing a function, and the promise check by behavior rather than R version. Addresses #19697.
…old only after-response work - docType() was declared but never defined; macOS's dynamic lookup hid it, other platforms wouldn't link. - A notebook unit whose document ID or type holds a NUL is skipped before its paths are touched (read up to the NUL, they could name another document's cached output); the code scan runs only when options failed. - After-response deferral keeps only the callback and its change-detection flag (JsonRpcResponse::afterResponse()), not a copy of the response. - The YAML check reads keys as create() does: a null key as "null", and a composite key ends the whole check. - The R_tryCatch() version probe calls base's >= as well as getRversion(); the pre-3.6.2 fallback uses executeSafely(), so a caught error can't start options(error). - runtime::lookupsForcePromises() tells the promise test which lookup R uses; the Quarto test puts the bad editor options first. Addresses #19697.
…n-nul-params # Conflicts: # src/cpp/r/RSexp.cpp # src/cpp/r/include/r/RSexp.hpp # src/cpp/session/modules/SessionRTests.cpp
gtritchie
left a comment
There was a problem hiding this comment.
Thanks for closing these longjmp paths. A few problems with how it's done, most serious first:
- The notebook nul check doesn't cover the queue's own
doc_id, andevaluateRmdParams()reads that id before the check. - When an interrupt unwinds through the RPC backstop, the reply quotes the previous R error.
- The new lookups slow down the linter's hot path:
findVar()no longer uses R's global cache, and on R < 4.6 bindings that run no code still go throughtryCatch.
The rest are smaller: re-arming an interrupt outside running code, the size of the containsNul() overload set, a duplicated version check, and one comment.
| // (the client never sends one); skip it before its document's paths, | ||
| // which would be read up to the nul and so name another document's | ||
| // output, are touched | ||
| if (r::sexp::containsNul(unit->docId()) || r::sexp::containsNul(unit->docType())) |
There was a problem hiding this comment.
This checks unit->docId(), but the queue has its own docId (NotebookDocQueue::fromJson() reads it from kDocQueueId, separately from each unit's). Nothing checks that one, and evaluateRmdParams(docQueue->docId()) passes it to source_database::get() a few lines above, before this check runs.
With a queue doc_id of "<otherId>\0x" and clean unit doc_ids, completePath(id) stops at the nul, so get() reads <otherId>'s files. The contents path even resolves to the properties file. Then another document's params are evaluated, and this skip never fires. Could the queue's docId be checked once, in fromJson() or before the evaluateRmdParams block?
There was a problem hiding this comment.
Fixed in 8850c8d. NotebookDocQueue::fromJson() now refuses a queue doc_id with a nul before the constructor runs. The constructor's getPath() / getChunkValues() read the ID too, not just evaluateRmdParams(). I also moved the unit check into NotebookQueueUnit::fromJson(): when doc_type is missing, it falls back to source_database::get(docId), so the check in executeNextUnit() came too late there as well. Both now return ParamInvalid. Test: SessionRMarkdownTest.NotebookQueuesRefuseDocumentIdsWithANul.
| { | ||
| Error error = r::rCodeExecutionError( | ||
| "R error while handling '" + pInvocation->pRequest->method + "': " + | ||
| r::exec::getErrorMessage(), |
There was a problem hiding this comment.
getErrorMessage() returns R_curErrorBuf, which an interrupt doesn't write. So when an interrupt unwinds through the backstop, the reply quotes whatever error came before. In R:
try(stop("stale old error"), silent = TRUE)
tryCatch({ tools::pskill(Sys.getpid(), tools::SIGINT); Sys.sleep(2) },
interrupt = function(e) geterrmessage())
#> "Error in try(stop(\"stale old error\"), silent = TRUE) : stale old error\n"The client would get R error while handling 'foo': Error in ... : stale old error. Could this use a fixed "interrupted" message when the jump was an interrupt (getWasInterrupted() / interruptsPending())?
There was a problem hiding this comment.
Confirmed, but neither flag survives to the cleanup. onintrEx() clears R_interrupts_pending first (errors.c:170). Before jump_to_top_ex() it does REprintf("\n") (errors.c:197), and that newline is the one RWriteConsoleEx() consumes to reset wasInterrupted.
So the backstop now saves R's error message from before the handler ran. If the message is unchanged when the backstop runs, the reply says R code was interrupted while handling '<method>' instead of quoting it. Fixed in 0e5af28. InvokeRpcHandlerAnswersARequestAnRErrorInterrupted now covers this: it runs a real Rf_onintr() after a stale stop().
| // whether reading this binding can run R code: an active binding calls its | ||
| // function, R_getVarEx() (R >= 4.6) forces a promise, and it raises an error | ||
| // for a missing argument | ||
| bool readingRunsCode(SEXP symSEXP, SEXP envSEXP) |
There was a problem hiding this comment.
On R < 4.6, runtime::findVarInFrame is Rf_findVarInFrame. It doesn't force a promise, and it returns R_MissingArg without an error, so reading a Delayed or Missing binding there runs no R code. It still goes through evaluateCaught(), which costs an R-level tryCatch. findFunction() and forcePromise() also send promises that are already forced through evaluateCaught().
This sits on the linter's path. findFunction(symbol, package) (SessionRParser.cpp:281) hits lazy-loaded namespace functions, which are unforced promises, so each lookup does two tryCatch round trips: one for the read, which runs nothing, and one for the force. runtime::lookupsForcePromises() is only used by the tests right now. Could Delayed/Missing be checked against it here, and could evaluateCaught() be skipped when a promise's value is already bound?
There was a problem hiding this comment.
Agreed on both, fixed in 0e5af28:
readingRunsCode()countsDelayed/Missingonly whenruntime::lookupsForcePromises()is true. On R < 4.6 the plain read returns the promise orR_MissingArg, andfindFunction()still ends its search onR_MissingArg.findFunction()andforcePromise()now read a promise that's already forced through a newruntime::forcedPromiseValue()(PRVALUE), notRf_eval(). Evaluating a forced promise can still runR_CheckUserInterrupt()and finalizers (eval.c:1090), so it isn't free of longjmps.
For scale, an R-level tryCatch round trip costs about 4.5 us here.
| return runtime::findVar(nameSEXP, envSEXP); | ||
| // find the binding's frame without reading it, to see whether reading it | ||
| // can run R code, then read it there; most bindings can't run code | ||
| SEXP frameSEXP = findBindingFrame(nameSEXP, envSEXP); |
There was a problem hiding this comment.
Before, this was one Rf_findVar / R_getVarEx call, which answers a lookup from R_GlobalEnv through R's global cache. Now findBindingFrame() calls getBindingType() on every frame up the search path, and findVarInFrame() classifies the frame it finds a second time. findFunction() loses its global-env fast path the same way.
The linter calls findVar(symbol) / findFunction(symbol) from the global env for every simple call it lints (SessionRParser.cpp:256-258), so each base or package function lookup grows from one hash lookup to O(search path). Could it try a plain runtime::findVar() first and classify only the frame that binds the name, or pass the type findBindingFrame() found into the read?
There was a problem hiding this comment.
The first option doesn't work. R's lookup, global cache included, reads the binding, and reading it is what runs the getter (or, on 4.6, forces the promise). The cache can't tell us where a binding is without reading it.
I did the second: findBindingFrame() now returns the type it found, so the frame isn't classified twice (0e5af28). I measured what's left (R 4.6.1, 11 entries on the search path):
findVar(lapply)from global, by symbol: 14 ns -> 128 nsfindFunction("lapply"): ~35 ns -> 390 ns- linting
SessionRCompletions.R(4561 lines, 1872 calls) takes 150 ms in total, so about 0.5 us per call adds roughly 1 ms
The namespace-qualified lookups at SessionRParser.cpp:279-281 take ~9-10 us each. That's findNamespace()'s R-level tryCatch(getNamespace(...)), run twice (once through ensureNamespaceLoaded()), and this PR doesn't change it.
| // handled while the user's code runs), not for the lookup; re-arm it, so | ||
| // that code sees it when it next checks | ||
| if (evaluation.interrupted) | ||
| r::exec::setInterruptsPending(true); |
There was a problem hiding this comment.
This re-arms the interrupt even when no user R code is running, as when Object Explorer or Data Viewer change detection reads an active binding at the prompt. RStudio only sets an interrupt while code runs, so this takes a race. The user presses Stop as a command finishes, and the interrupt is still pending when a prompt hook's getter checks for it. Before this change, the jump to top level used it up. Now it's re-armed, which also sets wasInterrupted, so the next protected RFunction call in the same detect-changes pass, or the user's next command, is interrupted instead. Could the re-arm be limited to when R code is actually running?
There was a problem hiding this comment.
Agreed. The re-arm is now skipped at the top-level prompt (r::session::atTopLevelPrompt(), which is set before the prompt's change detection runs). There the lookup uses the interrupt up, as the jump to top level did. While input runs, or when a request is handled under the user's code, the interrupt is still re-armed. Fixed in 0e5af28; LookupsCatchErrorsFromBindings checks both cases.
| // parameter type, so that a call resolves to the overload create() would use | ||
| // (a catch-all template would instead win for a type derived from one of | ||
| // these, e.g. a YAML iterator's element); a new create() overload needs one | ||
| bool containsNul(const std::string& value); |
There was a problem hiding this comment.
The 22 containsNul() overloads match the 22 create() overloads today, but every new create() overload now needs a twin. Every JSON parameter is scanned twice (containsNul(), then create()). The direct callers (Quarto, document hooks, notebooks, parseString()) each needed their own check too. The root problem is that create(std::string) can raise an R error outside protection. Did you consider having RFunction build its parameter SEXPs inside the protected evaluation, or giving create() a non-raising path that reports the nul? Either would replace this overload set and the separate checks.
There was a problem hiding this comment.
I went with your second option, in 932ad80. Every string create() makes goes through one of two places: mkCharUtf8() (names, and the vector, set and map overloads) or create(std::string) (values, including the FilePath, JSON and YAML ones). Under a new r::sexp::NulCheckScope, those two make NA for a string with a nul, instead of raising R's error or cutting the string off, and the scope records it.
addParam() creates each value inside a scope and refuses it if the scope saw a nul. The Quarto reader and the document hooks do the same around their create() / ListBuilder calls. That removes the 22 overloads and the separate YAML walk. Each string is now scanned once, as it's made, and a new create() overload is covered as long as it makes its strings through those two places.
Outside a scope, create() behaves as before. containsNul(std::string) stays for the callers that check a single string: parseString(), and the notebook IDs and code. The scope keeps its state in statics rather than a pointer to itself, so an R error that longjmps past one can't leave a dangling pointer behind. Test: CreateMakesNaForANulInANulCheckScope.
| // warning or message would read as a failure; executeSafely() has the right | ||
| // semantics there, at the cost of printing a caught error. the answer is | ||
| // cached only once the check succeeds | ||
| bool tryCatchIsSelective() |
There was a problem hiding this comment.
r::util::hasRequiredVersion() (RUtil.cpp:191) already does this comparison, though its versionTest() evaluates an unqualified getRversion() >= .... That makes the base:: qualification here the more careful of the two. Rather than keep a second implementation, could versionTest() get the base:: qualification, with this function caching hasRequiredVersion("3.6.2")?
There was a problem hiding this comment.
Done in 0e5af28. versionTest() now evaluates base::`>=`(base::getRversion(), ...), and tryCatchIsSelective() caches hasRequiredVersion("3.6.2").
One difference: hasRequiredVersion() also returns false when the evaluation fails (an interrupt, say), so only a true answer is cached. Otherwise a single failed check would leave R >= 3.6.2 on the executeSafely() path, which prints caught errors, for the rest of the session.
| SET_STRING_ELT(s_conditionsSEXP, 1, Rf_mkChar("interrupt")); | ||
| } | ||
|
|
||
| // the result is left unprotected on return, like the value of a plain |
There was a problem hiding this comment.
An active binding's getter returns a fresh value that nothing else references, so this result isn't reachable from its binding. No caller is affected today: Object Explorer stores the value right away, and the old lookup behaved the same. But this comment tells future callers the value is GC-safe. Could it say the caller has to protect it?
There was a problem hiding this comment.
Right. Reworded in 0e5af28: the caller must protect the result, since an active binding's function can return a fresh value.
…p runs no code; use up a prompt-time interrupt
…s two string makers
gtritchie
left a comment
There was a problem hiding this comment.
Thanks for the thorough follow-ups; all eight earlier points are resolved. The notebook ids are now refused where they're parsed, NulCheckScope is a clear improvement on the overload set, and the reasoning and numbers for findVar() make sense.
The new revision raises a few smaller things:
- The interrupt-vs-error test can mistake a repeated identical error for an interrupt.
- Skipping the re-arm at the top-level prompt also covers
latercallbacks dispatched from the idle loop, where an interrupt is meant to end the callback (#19236). NulCheckScope's static depth can stay raised after an R error jumps past a scope.- On R 3.6.0 and 3.6.1, the R version check now runs on every caught lookup.
- A formatting nit.
| const std::string& method = pInvocation->pRequest->method; | ||
| std::string errorMessage = r::exec::getErrorMessage(); | ||
| Error error = r::rCodeExecutionError( | ||
| errorMessage == pInvocation->previousErrorMessage ? |
There was a problem hiding this comment.
An unchanged error buffer also happens when the handler fails with the same message as the error before it. In R 4.6.2:
f <- function() stop("boom")
try(f(), silent = TRUE); before <- geterrmessage()
try(f(), silent = TRUE); identical(before, geterrmessage())
#> TRUESo an RPC that hits the same stray R error twice in a row, like a deterministic bug the client retries, answers R code was interrupted while handling '<method>' the second time and drops the error. Could the buffer be cleared before the handler runs instead? base::.Internal(seterrmessage("")) empties it. An interrupt then leaves it empty, and an error writes it, so no comparison with the earlier message is needed.
There was a problem hiding this comment.
Good catch. Fixed in 1f5f7cf: the backstop now clears R's error buffer before the handler runs, so an empty buffer at unwind means an interrupt. It then restores the previous message unless the handler wrote one. Without the restore, an RPC served while user code runs would clobber geterrmessage() between a try() and its read. I wrote the buffer through R_curErrorBuf() (R exports no setter) instead of evaluating .Internal(seterrmessage()). That evaluation would run once before the handler is protected and again during the unwind, and an interrupt check in Rf_eval() could jump from either. The test now runs the failing handler twice in a row, and checks geterrmessage() after both an interrupted and a clean handler.
| // its change detection) none is running, and one still pending arrived as | ||
| // a command finished; the lookup uses it up, as R's jump to top level | ||
| // would have, rather than leave it for the user's next command | ||
| if (evaluation.interrupted && !r::session::atTopLevelPrompt()) |
There was a problem hiding this comment.
atTopLevelPrompt() is also true while processIdleEvents() runs a later callback or an RPC handler at the prompt: SessionHttpMethods.cpp:288 restores it around the dispatch. RStudio accepts an interrupt in that state on purpose. The comment at SessionHttpConnectionUtils.cpp:320-326 says it's what ends a long-running callback (#19236).
Suppose a callback like that calls into RStudio code that reads an active binding (View(), or another rstudioapi call), and the getter is what sees the user's Stop. The interrupt is caught, isn't re-armed here, and the callback keeps running, which is the swallowed interrupt #19236 fixed. The window is narrow, but could this check rule out idle-event processing as well as the prompt flag? A flag set around processIdleEvents() that the r library can read would do it.
There was a problem hiding this comment.
Agreed. Fixed in 1f5f7cf: setIdleEvents() now sets a new r::session::inputHandlersRunning() flag, and a caught interrupt is re-armed while it's set, even with atTopLevelPrompt() true. I passed on isAtTopLevel() (which also checks isExecuting()) because rsession tests run inside executeSafely(), so the prompt case couldn't be tested. The test now covers a lookup while input handlers run.
| NulCheckScope::NulCheckScope() | ||
| : enclosingFoundNul_(s_nulFound) | ||
| { | ||
| s_nulCheckDepth++; |
There was a problem hiding this comment.
Only the destructor decrements s_nulCheckDepth, and nothing resets it. create(std::string) can still raise an R error inside a scope: Rf_allocVector() fails with "cannot allocate vector". If that error longjmps past RFunction::addParam's scope, the depth stays at 1. For the rest of the session, a create() outside any scope then quietly makes NA for a string with a nul where it used to raise an error, and nothing is logged. The header comment mentions this effect. It's rare, but could the depth be reset at a known top-level point (the prompt, say) so a stray jump can't leave it on?
There was a problem hiding this comment.
Fixed in 1f5f7cf: RReadConsole() calls r::sexp::endStrayNulCheckScopes() at a top-level prompt. Scopes are held only around create() calls, which run no R code, so none can still be active there. One that is gets reset, and a warning is logged. New test: StrayNulCheckScopesAreEnded.
| { | ||
| static bool s_selective = false; | ||
| if (!s_selective) | ||
| s_selective = r::util::hasRequiredVersion("3.6.2"); |
There was a problem hiding this comment.
On R 3.6.0 and 3.6.1, where the answer is always false, this re-runs hasRequiredVersion(), an R evaluation, on every evaluateCaught() call. The previous revision cached a successful false. Could a failed check be kept apart from a false answer, so that a successful false is cached too? A small cost, and limited to those two releases.
There was a problem hiding this comment.
Fixed in 1f5f7cf: tryCatchIsSelective() now reads r::version(), which R init computes once and caches, so no lookup re-runs an R evaluation for this.
| if (r::sexp::containsNul(docId)) | ||
| return Error(json::errc::ParamInvalid, ERROR_LOCATION); | ||
|
|
||
| *pQueue =boost::make_shared<NotebookDocQueue>(docId, jobDesc, workingDir, |
…errupt in later callbacks; end stray nul-check scopes at the prompt; cache the r version check
…id or recovered doc type; stop findFunction at a promise that's missing; evaluate versionTest in base
…oc id with a nonempty queue
gtritchie
left a comment
There was a problem hiding this comment.
Thanks for working through all of these. The fixes look right; one non-blocking note inline.
| RpcDelivery* pDelivery = pInvocation->pDelivery; | ||
|
|
||
| std::string errorMessage = r::exec::getErrorMessage(); | ||
| bool interrupted = errorMessage.empty(); |
There was a problem hiding this comment.
Non-blocking: a handler's own protected R call that fails also writes this buffer. R_tryEval() (RExec.cpp:244) runs R's default error handler, and evaluateExpressions() then reads the message back. So in a handler that logs a failed RFunction call and carries on, a later interrupt that unwinds through the backstop finds the buffer non-empty. The reply then says R error while handling '<method>': Error in .rs.foo() : X, quoting the error that was already handled, instead of saying it was interrupted.
Only the reply's message is affected, and interrupts reaching the backstop are rare, so I'm fine leaving it. A fix would need the backstop to learn about the interrupt some other way than the buffer, for example a flag RStudio's interrupt path sets and R's onintr doesn't clear.
There was a problem hiding this comment.
Fixed in 4d72972. I didn't use a flag on the interrupt path: an interrupt caught inside the handler, followed by a stray error, would then read as interrupted. The backstop now runs the handler under R_withCallingErrorHandler(), so R tells it when an error nothing in the handler caught is signaled, and an unwind without that signal is an interrupt. A failed RFunction call doesn't reach it, since R_tryEval() resets the handler stack. That entry point is R >= 4.0, so R 3.6.x keeps the buffer check. The test now covers a caught error followed by an interrupt.
…e error buffer A handler's own caught R error leaves its message in R's error buffer, so an interrupt that then unwound through the backstop was answered as that error. From R 4.0 the backstop has R call it as an uncaught error is signaled; before that it still reads the buffer.
…n-nul-params # Conflicts: # src/cpp/session/modules/SessionRTests.cpp
Intent
r::sexppromises that its functions never let an R error longjmp through C++ frames. The jump skips C++ destructors, and on an RPC it leaves the request unanswered. Several paths broke that promise on data a user or client can supply:RFunction::addParam().create()raisesembedded nul in stringbefore the call runs protected (getRmdPublishDetails()with a NUL intarget, for example). A parameter name over 10,000 bytes, such as a JSON-RPC kwparams name, fails the same way inRf_install().findVar(),findFunction(),getBindingType()and the rest) given a name R can't make a symbol from. The linter hit this on valid R code: a function body with a string literal over 10,000 bytes, followed by a line starting with(, fails withvariable names are limited to 10000 bytes. So did an Object Explorer refresh for a longView()title. A NUL-suffixed name instead looked up the name before the NUL, soexecute_user_commandcould run a different command.R_getVarEx()) a promise that errors when forced. One example is the data viewer re-reading an object it shows at the next prompt, after the object starts failing. The error longjmped out of the prompt hook, leaving the viewer's change detection off for the rest of the session."\0"escape in_quarto.yml'seditor:options stopped the session from starting whenever that project opened;open_documentunanswered when a package's document hook was set;parseString().a: &x [1, *x]) recursed increate(YAML::Node)until the stack overflowed.create().Fixes #19697.
This PR was stacked on #19683, whose
callRHandler()NUL check it replaces. #19683 has merged, and this PR now targetsmain.Approach
RFunction.addParam()andaddQuotedParam()refuse a name or value holding a string with an embedded NUL, and a name over R's 10,000-byte limit. The first refusal is recorded.call()returns it as a code execution error, before evaluating anything, and sets the result toR_NilValue.addParam()creates each value under a newr::sexp::NulCheckScope. Every stringcreate()makes goes throughmkCharUtf8()orcreate(std::string). Under the scope, those make NA for a string with a NUL, rather than raising R's error or cutting the string off, and the scope records it.callRHandler()'s own check from collapse the utf-8 r::sexp / RFunction variants into the defaults #19683 is removed. R-implemented RPCs now get an execution error rather thanParamInvalid.r::sexp::isSymbolName()makes the same check for the Object Explorer's directRf_install().findVar()andfindVarInFrame()first classify the binding without reading it (getBindingType()). Only a binding whose read runs R code is read underR_tryCatch(), which catches errors and interrupts silently: an active binding, plus, on R >= 4.6, a delayed or missing one (R_getVarEx()forces promises and raises an error for a missing argument; R's older lookups return either as is).R_ToplevelExec()would print an error from a lookup the IDE makes on its own. Before R 3.6.2, though,R_tryCatch()transferred control for every condition, warnings included, so those versions fall back toR_ToplevelExec(). A caught interrupt is re-armed while R code is running (as when a request is handled during the user's computation), so that code still sees it. At the top-level prompt, the lookup uses it up, as R's jump to top level would have.forcePromise()works the same way, and reads an already-forced promise's value directly.findVar()finds the binding's frame and type in one walk, since R's own lookup (and its global cache) reads the binding, which is what runs the code.findFunction()now reads each frame once, and stops when a binding's code fails or the binding is a missing argument, as R's lookup would. Previously it could read a failing getter twice and then return a same-named function from further out.NulCheckScope,create()keeps its behavior: thestd::stringoverload raises R's error on a NUL, and the other overloads cut the string off there. The callers that can hand it client or file data use a scope or check the string first:editor:options containing a NUL, with a warning;stop()with an explanation, rather than running with the default engine;parseString()returns a parse error.create(json::Array)andcreate(json::Object)protect each element only until it's stored in the protected list.create(YAML::Node)tracks ancestor nodes, and a cyclic alias becomesNULL.invokeRpcHandler()runs each handler underR_UnwindProtect()(R >= 3.5; RStudio requires 3.6). If a stray R error or interrupt unwinds through the handler before a response was sent, the cleanup answers the request with the error, and the unwinding then continues as it would have.R_UnwindProtect()rather thanR_ToplevelExec(), which would stop the unwinding and so catch interrupts meant for R code that's running.RpcDeliveryrecords who claimed a response and when it was sent. This avoids a second response on an answered connection, leaves a response another thread is delivering to that thread, and drops a continuation an async handler kept after the backstop answered.R_UnwindProtect()returns, so they never unwind through R.The NEWS entry covers the cases users can reach: the
_quarto.ymlstartup failure, the linter, and the data viewer. The rest need a client sending malformed requests.Automated Tests
New rsession gtests in
SessionRTests.cpp. Each runs its calls insideexecuteSafely, so an R error that escapes fails the test instead of ending the run:RFunctionRefusesStringsWithEmbeddedNulandJsonRpcRefusesStringsWithEmbeddedNulcover every string-bearing parameter kind and names over 10,000 bytes, plus a handler that counts its calls to show refused requests never run.LookupsTreatNamesRCantInstallAsUnboundcovers empty, NUL-containing and 10,001-byte names across every lookup.LookupsCatchErrorsFromBindingscovers active bindings that fail, warn, or signal an interrupt (checking the interrupt is re-armed while code runs, but not at the top-level prompt), plus a failing promise and a missing argument. It asserts one getter call per lookup, that forcing a promise agrees with what the lookup returned, that a promise is forced once and found again after, and thatfindFunction()doesn't return a same-named function attached further out.CreateMakesNaForANulInANulCheckScopecovers values, names, YAML and nested scopes.ParseStringRefusesEmbeddedNul,CreateKeepsTheProtectionStackShortForLongJson(600,000 elements), andCreateTurnsACyclicYamlAliasIntoNull.InvokeRpcHandlerAnswersARequestAnRErrorInterruptedcovers handlers that fail before responding, after responding, and inside the continuation before it sends. It also covers after-response work running once the handler has returned, and a response another thread has claimed and sends after the main thread's request fails. Async handlers that respond later, or keep their continuation and then fail, are covered too, along with off-main-thread dispatch and C++ exceptions. On Unix, it also runs a real interrupt (Rf_onintr()) through a handler, after a stale error, and checks that the reply doesn't quote that error.In
SessionQuartoTests.cpp,ProjectTypeResolution.EditorOptionsWithANulAreSkippedchecks that the NUL editor options are skipped and valid ones are still read. InSessionRMarkdownTests.cpp,NotebookQueuesRefuseDocumentIdsWithANulcovers the notebook queue's and units' document IDs.Before the fix, each case failed with the escaping R error (
embedded nul in string,variable names are limited to 10000 bytes,attempt to use zero-length variable name,binding failed,protect(): protection stack overflow), or with R getting a string cut off at the NUL.The full rsession gtest suite (929) and the R testthat suite (4822) pass locally (macOS, R 4.6.1). I also ran the startup, linter and YAML cases in a real session:
_quarto.ymlhaseditor:thenmode: "source\0"failed to start (segfault, exit 139) and now opens;.rs.lintRFile()on the long-string-literal file returnedvariable names are limited to 10000 bytesand now lints;rs_fromYAML("a: &x [1, *x]")segfaulted and now returns a list.QA Notes
_quarto.ymlcontainingproject:/type: default/editor:/mode: "source\0", and open it. The session should start normally, and its log should say the editor options were ignored. Before this change, the session failed to start.(x), and save it. Linting should complete. Before this change, the lint request failed withvariable names are limited to 10000 bytes.makeActiveBinding("x", local({ok <- TRUE; function() if (ok) { ok <<- FALSE; mtcars } else stop("gone")}), globalenv()); View(x), then run anything at the console. No error should appear at the prompt, and the viewer should keep working for other objects.Documentation
None needed.
Checklist
NEWS.md