Skip to content

mark file paths passed to R as utf-8 - #19640

Merged
kevinushey merged 8 commits into
mainfrom
bugfix/19627-utf8-filepath-params
Nov 17, 2026
Merged

kevinushey merged 8 commits into
mainfrom
bugfix/19627-utf8-filepath-params

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Fixes #19627.

On Windows with R 4.1 and earlier, uploading a zip in the Files pane to a folder whose path has non-ASCII characters (e.g. C:\temp\test-é) extracted it into a differently named sibling folder (test-é), or failed to find the uploaded zip when the session temp directory was under a non-ASCII profile.

Approach

RStudio's C++ strings are UTF-8, but r::sexp::create() marked the strings it made for R as native, and asString() / extract() read R's strings back as native. RFunction parameters, ListBuilder, .Call results and the code executeString() parses all go through these. Before R 4.2 on Windows the native encoding is the system code page, so R read é (C3 A9) as é. The upload handed its target folder to unzip() this way. This is the same handoff that broke the Posit Assistant install in #19625, fixed for those paths only in #19628.

  • Every create() overload that makes strings, including list and vector names, now marks them UTF-8, and asString(), safeAsString(), extract(), getNames(), fillVectorString() and fillSetString() read R strings as UTF-8. Both sides change together, so a string that goes to R and comes back (e.g. .rs.editor -> rs_editFile, rs_computeScratchPaths -> rs_addFirstRunDoc, lazy modules) still round-trips. This is the change the comment on create() deferred until its callers were audited.
  • Callers that compensated for the old defaults no longer convert: 60 utf8ToSystem() calls on values passed to R in this process (RFunction parameters, and the plot export device code run through executeString()), and 5 systemToUtf8() calls on values read back from R. utf8ToSystem() calls that build child-process commands, environment variables, or arguments to R's C API (R_SaveGlobalEnvToFile, R's startup parameters, console input) are unchanged. EmbeddedPackage::archivePath now holds UTF-8 and is converted where it goes to a child process.
  • Code that uses strings read back from R now expects UTF-8 too. Lookups by name (getBindingType(), getBindingIdentity(), isActiveBinding(), findVar(), findFunction()) install the symbol from a UTF-8 string with Rf_installTrChar(), so R translates the name to native; with Rf_install(), the Environment pane showed a variable such as café with no value. The saved search path, which RSearchPath.cpp writes as read from R, is read back with encoding = "UTF-8", and async R process output is converted from the system encoding before it reaches its R callback.
  • .Call functions that return paths, such as rs_rResourcesPath and rs_getLocalThemeDir, now return them marked UTF-8 with no changes of their own.
  • .rs.utf8ToSystem() still returns a native-marked string, and .rs.systemToUtf8() no longer converts twice. Neither has callers in this repository.
  • Reading a "bytes" string returns its bytes instead of raising an R error, which would longjmp through C++. A conversion's R_alloc() buffer is now released right away.

Behavior only changes where R's native encoding isn't UTF-8. On Windows that's R < 4.2: R 4.2 and later are UCRT builds and run rsession-utf8.exe, whose code page is UTF-8, so utf8ToSystem() and systemToUtf8() were already no-ops there. With R < 4.2, non-ASCII text the system code page can represent now reaches R intact; characters outside it still can't be used, as with #19625. On POSIX, it's a non-UTF-8 locale. In the C/POSIX locale non-ASCII text can't be translated to native, so text and file names that used to pass through as raw bytes now fail ("unable to translate ... to native encoding") or show as <U+00E9>. RStudio only runs in such a locale when ensureUtf8Charset() (SessionMain.cpp) can't switch to a UTF-8 one, which it already warns about.

Not covered: strings created or read with R's API directly (Rf_mkString(), CHAR()) rather than through r::sexp, and child-process arguments built with utf8ToSystem(), which Windows then converts with utf8ToWide() (a separate problem with R < 4.2, #19649).

Automated Tests

SessionRTest.StringsReachRMarkedUtf8 (rsession C++ tests) passes a non-ASCII string to R as an RFunction constructor argument, via addParam(), and as a vector, and checks that R reports Encoding() as "UTF-8". SessionRTest.StringsFromRAreReadAsUtf8 (POSIX only) switches R to the C locale and checks that a UTF-8 string read back through asString() and RFunction::call() keeps its bytes. With the old native defaults, the first reports "unknown" and the second gets <U+00E9>. SessionRTest.NamesReadFromRFindTheirBindings (POSIX only, skipped where no Latin-1 locale is installed) binds a Latin-1 name in R and checks that the UTF-8 name read back finds the binding through getBindingType(), findVar(), getBindingIdentity(), isActiveBinding() and hasActiveBinding(); with Rf_install(), the binding is reported unbound.

The R side was checked separately on Windows in plain R, outside RStudio. Given the UTF-8 bytes marked native (what RFunction sent), R 4.1.3 unzip() and png() wrote into a sibling -é directory and left the intended one empty. Given the same bytes marked UTF-8, they wrote into the intended directory. R 4.5.1 handled both.

All rsession and core C++ tests and the r testthat scope pass on macOS.

QA Notes

Windows, with RStudio configured to use R 4.1 (or earlier):

  1. Create a folder such as C:\temp\test-é.
  2. In the Files pane, go to that folder and upload a .zip file with Upload.
  3. The zip's contents appear in test-é. No test-é folder is created next to it.

Optionally, with the AGG graphics backend selected (Tools > Global Options > General > Graphics), make a plot and use Export > Save as Image to save a PNG into the same folder; it should land there.

Because this changes how all text passes between RStudio and R, also smoke-test with R 4.1 in a project whose folder name contains é: open the project, view the Packages pane, run café <- 1 and check that the Environment pane shows its value, export a plot as PDF, and knit an R Markdown document.

With R 4.2 or later the upload already worked; it should keep working.

Documentation

None needed.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards (no UI changes)
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 15, 2026
@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
5679 0 256 0
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1424 0 46 0
✅ desktop-macos 1420 0 51 0
✅ desktop-windows 1419 0 57 0
✅ server-linux 1364 0 54 0
✅ setup 48 0 32 0

View report online


All platforms - commit a0fe53a9d10f308da6f00451269bfb15ea96b1b4 - Run #2317

@kevinushey
kevinushey requested a review from gtritchie November 15, 2026 23:57

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two more call sites with the same bug, outside the diff, plus a few notes inline. Nothing here is blocking; the request-changes state is procedural.

1. Search-path environment save still passes the path marked native — RSearchPath.cpp:163-165

.rs.saveEnvironment gets dataFilePath.getAbsolutePath() and hands it to save(file = ). The restore side already gets environmentDataPath via addUtf8Param (line 292), and this PR fixed base:::load in the same file. With R 4.1 on Windows, a non-ASCII profile, and a user-attach()ed environment, a full-state restart (SuspendOptions.createSaveAll, e.g. Install and Restart from the Build pane) saves to ...é...\environment_data\N. Either the save fails or the data goes to a different folder, and restore finds nothing at the real path. Fix: pass dataFilePath.

2. User-command keybindings path — SessionUserCommands.cpp:113-114

userConfigDir() is under %APPDATA% on Windows, and .rs.loadUserCommands runs list.files(file.path(path, "R")) / source() on it directly (SessionUserCommands.R:94-100). Under a non-ASCII profile with R 4.1, registered user commands silently don't load. Fix: drop .getAbsolutePath().

3. .Call functions that return paths (follow-up, not necessarily this PR)

Ten .Call entry points still return r::sexp::create(<FilePath>.getAbsolutePath(), ...), so the result reaches R marked native. Some feed R file operations, e.g. rs_rResourcesPath is opened via file() at SessionThemes.R:392 (per-user install under a non-ASCII profile), and rs_getLocalThemeDir. These can now pass the FilePath to create(). A blanket sweep isn't safe, though: some paths only travel back to C++ through asString(), e.g. rs_computeScratchPaths → rs_addFirstRunDoc. They round-trip correctly today and would break if marked UTF-8 alone. The same goes for .rs.editor → rs_editFile.

Comment thread src/cpp/r/RSexp.cpp Outdated
// unlike std::string, a FilePath's path is always UTF-8, so mark it as such.
// marked native, R would misread a non-ASCII path wherever the native encoding
// is not UTF-8 (e.g. Windows with R < 4.2) and name a different file
SEXP create(const FilePath& value, Protect* pProtect)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Under a non-UTF-8 POSIX locale this turns paths that used to work into failures. R now has to translate the path to native, and in C/POSIX that translation fails for any non-ASCII character. Reproduced with LC_ALL=C Rscript (R 4.6): a native-marked .../test-é/f gives file.exists() TRUE; the same bytes marked UTF-8 give FALSE with "unable to translate ... to native encoding", and load() errors.

In practice this only bites when ensureUtf8Charset() (SessionMain.cpp:2181) can't switch to a UTF-8 locale, e.g. a Linux host with none installed, which already warns. The PR description says "Under a non-UTF-8 POSIX locale, R now converts these paths". Worth adding that under C/POSIX the conversion fails for non-ASCII paths, so the tradeoff is on record.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. With the new default this applies to all text, not just paths, and the description now says so: under C/POSIX, non-ASCII text that used to pass through as raw bytes fails to translate. RStudio only ends up there when ensureUtf8Charset() can't switch to a UTF-8 locale.

{
Error error = sourceModuleRFile(r::sexp::asString(moduleSEXP));
// the path came from sourceModuleRFileOnDemand(), marked as UTF-8
Error error = sourceModuleRFile(r::sexp::asUtf8String(moduleSEXP));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test covers this switch to asUtf8String: tests/testthat/test-lazy-modules.R has no non-ASCII module path. Reverting it to asString would still pass CI, but on Windows with R 4.1 it would break lazy modules for per-user installs under a non-ASCII profile. A testthat case that adds a lazy module from a path with é and calls one of its proxies would pin it.

(Minor: the PR description mentions ListBuilder::add() taking a FilePath, but no call site in the PR uses that, and nothing tests it.)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The asUtf8String switch is gone. asString() now reads UTF-8 by default, so rs_sourceModule is back to its original asString(). SessionRTest.StringsFromRAreReadAsUtf8 pins the decoding: it reads a UTF-8 string back under the C locale, where the old native read gives <U+00E9>. StringsReachRMarkedUtf8 pins the write side. I left out a lazy-module testthat case, since in a UTF-8 locale it passes either way. The ListBuilder line in the description is gone along with create(FilePath).

r::sexp::create() now marks strings UTF-8 and asString() / extract() read them as UTF-8, so the per-site FilePath changes are no longer needed.

Addresses #19627.
Values passed to R in this process no longer go through utf8ToSystem(), and values read back from R no longer go through systemToUtf8(). Conversions for child processes, environment variables, and R's C API are unchanged.

Addresses #19627.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks. Rather than chase the remaining call sites one at a time, this now changes the defaults (a2d167f). r::sexp::create() marks strings UTF-8 and asString()/extract() read them as UTF-8, so every RFunction param, list name and parsed code string reaches R as UTF-8, and round trips still work. The per-site FilePath edits and create(FilePath) are reverted.

1 and 2 are covered by the default. 3 is too: those .Call functions return create(path.getAbsolutePath()), now UTF-8. The round trips you flagged (rs_computeScratchPaths -> rs_addFirstRunDoc, .rs.editor -> rs_editFile) keep working because the read side is UTF-8 too.

daa123d drops the conversions that made up for the old defaults: 60 utf8ToSystem() calls on values passed to R in this process, and 5 systemToUtf8() calls on values read back. Conversions for child processes, env vars and R's C API are unchanged. The description has the details.

Aside: run-tests.R adds up df$failed, which is 0 for a test that errors, so an erroring testthat case doesn't fail rstudio-tests (#19648).

@kevinushey
kevinushey requested a review from gtritchie November 16, 2026 17:55

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new defaults resolve everything from the first round, and I checked the 77 remaining utf8ToSystem() calls: each feeds a child process, an environment variable or R's C API, so none converts twice. The flip creates two new mismatches where R-derived strings now come back as UTF-8 but meet a native-only consumer. Both apply only where native isn't UTF-8 (Windows R < 4.2, non-UTF-8 POSIX locales). One is inline (Rf_install); the other is below, with two smaller notes.

1. Saved search path is written as UTF-8 but read back as native — RSearchPath.cpp:145, 190-193

Search-path element names (asString) and package paths (call(&packagePath)) are now read from R as UTF-8 and written to the state files as-is. On restore, .rs.readProperties() (Tools.R:1835) and readLines() (Tools.R:1849) read them as native. Before, both sides were native. On Windows with R 4.1 and a user library under a non-ASCII profile, a full-state restart (e.g. Install and Restart) calls loadNamespace(pkg, lib.loc = dirname(path)) (Tools.R:1930) with a garbled path and prints "Error restoring search paths". Non-ASCII search entries (e.g. file: attachments) also stop matching search(). Reading both files with encoding = "UTF-8" would fix it.

2. Async R process output (minor) — SessionRUtil.cpp:302

Child-process stdout/stderr goes to the R callback via addParam(output), which is now marked UTF-8. With R < 4.2 the child writes in the system code page, and AsyncRProcess doesn't convert it, so é would arrive as <e9>. Nothing hits this today: the only caller (SessionPackages.R:2354) uses just onCompleted.

3. Redundant UTF-8 variants (follow-up)

asUtf8String, callUtf8, addUtf8Param, createUtf8 and the asUtf8 parameters on extract() now match the defaults (91 call sites), and nothing passes asUtf8 = false. They could be collapsed later so nobody assumes they differ.

For QA: with R 4.1, café <- 1 in the Environment pane would exercise the inline finding.

core::Error extract(SEXP valueSEXP, std::set<std::string>* pSet, bool asUtf8 = false);
core::Error extract(SEXP valueSEXP, std::map<std::string, std::set<std::string>>* pMap, bool asUtf8 = false);
core::Error extract(SEXP valueSEXP, std::string* pString, bool asUtf8 = true);
core::Error extract(SEXP valueSEXP, std::vector<std::string>* pVector, bool asUtf8 = true);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This default changes environment listing: listEnvironment() (RSexp.cpp:412) now returns variable names as UTF-8. The by-name helpers that consume them still build the symbol with Rf_install(name.c_str()), which takes native bytes: getBindingType (475), getBindingIdentity (510), isActiveBinding (631), findVar(const std::string&) (664), and the function lookup at 704.

On Windows with R 4.1, café <- 1 has the CP1252 PRINTNAME caf\xe9. The pane now gets caf\xc3\xa9, so varToJson → getBindingType (EnvironmentUtils.cpp:226) installs a different symbol and reports it Unbound. The variable shows with no value; before this PR the value showed. Posit Assistant's variable summary (SessionChat.cpp:1065) skips it. The same mechanism shows under LC_ALL=C: after assign(<UTF-8 bytes>, 1), exists(enc2utf8(ls()[1])) is FALSE.

One fix covers all of them: in those std::string overloads, build the symbol with Rf_installTrChar(Rf_mkCharCE(name.c_str(), CE_UTF8)) so R translates it to native.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 89519d1. The five std::string overloads now build the symbol from a UTF-8 CHARSXP with Rf_installTrChar(), through a small installUtf8() helper. hasActiveBindingImpl() also passed CHAR() of nested binding names (native bytes) to getBindingType(), which now takes them as UTF-8, so it reads them with translate(). The Environment monitor's snapshotBindings() is covered too, since its names also come from listEnvironment().

The LC_ALL=C repro doesn't change with this, and can't. A name bound from raw non-ASCII bytes in the C locale has no lossless UTF-8 form (enc2utf8() gives caf<c3><a9>). A UTF-8-marked name is bound as the ASCII caf<U+00E9>, which both Rf_install and Rf_installTrChar find. That's the C-locale tradeoff already in the description. The fix applies wherever native can represent the name, as with a Windows code page and R < 4.2.

EXPECT_EQ(std::vector<std::string>({ "UTF-8", "UTF-8" }), encodings);
}

#ifndef _WIN32

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This read-side test only runs on POSIX, so Windows has no read-side coverage. Nothing tests the paths whose behavior changed: fillVectorString/fillSetString now translate native strings instead of copying their bytes, and C++ looks names up back in R. A test that assigns a non-ASCII variable under the C locale and checks that listEnvironment() + getBindingType() report it Normal would catch the Rf_install mismatch noted on RSexp.hpp.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added SessionRTest.NamesReadFromRFindTheirBindings in 89519d1. It uses a Latin-1 locale rather than C, because in C Rf_install and Rf_installTrChar find the same symbol and the test would pass either way. Like a Windows code page with R < 4.2, Latin-1 can represent é. The test binds caf\xe9, plus an active binding in a nested env. It checks that listEnvironment() and objects() (fillVectorString) return the UTF-8 name, and that getBindingType(), findVar(), getBindingIdentity(), isActiveBinding() and hasActiveBinding() find the bindings. It fails with Rf_install (Unbound, null findVar), and also if only the hasActiveBindingImpl change is reverted.

It skips when no Latin-1 locale is installed, and stays POSIX-only. Windows CI runs UCRT R, where native is UTF-8, and I can't verify here how R behaves after switching that to a code-page locale. fillSetString() has no callers, so it isn't covered.

Names now reach C++ as UTF-8, but getBindingType(), getBindingIdentity(), isActiveBinding(), findVar() and findFunction() installed them with Rf_install(), which takes native bytes. Where native isn't UTF-8 that named a different symbol, so the Environment pane showed non-ASCII variables with no value. They now install from a UTF-8 CHARSXP so R translates the name, and hasActiveBinding() reads nested names as UTF-8 to match.

Addresses #19627.
RSearchPath.cpp writes element names and package paths as read from R, which is now UTF-8, so restoring them as native garbled non-ASCII library paths.

Addresses #19627.
The child writes in the system encoding, and the output now reaches the R callback marked UTF-8.

Addresses #19627.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks -- pushed 89519d1, a107cb0 and a0fe53a.

  1. Search path: fixed in a107cb0. .rs.restoreSearchPathImpl() reads both files with readLines(..., encoding = "UTF-8"), and passes the package paths lines to .rs.readProperties() as text. Checked in plain R under a Latin-1 locale: the native read doesn't match the original path, the UTF-8 read does, and so does dirname() of the parsed value.
  2. Async output: fixed in a0fe53a with systemToUtf8() in onStdout()/onStderr(), as SessionRMarkdown.cpp already does for its child. It does nothing on POSIX and with UCRT R.
  3. Agreed; I filed Collapse the r::sexp / RFunction UTF-8 variants that now match the defaults #19663 to collapse the *Utf8 variants and the asUtf8 parameters.

I added the café <- 1 Environment pane check to the QA notes.

@kevinushey
kevinushey requested a review from gtritchie November 16, 2026 23:29

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All findings are addressed (the *Utf8 cleanup is tracked in #19663).

The failing snyk-code-scan check reports one issue, not from this change: "Missing Release of Memory after Effective Lifetime" (MEDIUM) for the heap-allocated IncrementalFileChangeHandler at SessionBookdownXRefs.cpp:513. That code dates from 2020. The scan covers every file the PR touches, and this PR changes only line 61 of that file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Uploading a zip in the Files pane extracts to the wrong folder on Windows with R < 4.2 when the path has non-ASCII characters

2 participants