Repository navigation
mark file paths passed to R as utf-8 - #19640
Conversation
Addresses #19627.
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
gtritchie
left a comment
There was a problem hiding this comment.
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.
| // 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
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.
|
Thanks. Rather than chase the remaining call sites one at a time, this now changes the defaults (a2d167f). 1 and 2 are covered by the default. 3 is too: those daa123d drops the conversions that made up for the old defaults: 60 Aside: |
gtritchie
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Thanks -- pushed 89519d1, a107cb0 and a0fe53a.
I added the |
gtritchie
left a comment
There was a problem hiding this comment.
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.
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, andasString()/extract()read R's strings back as native.RFunctionparameters,ListBuilder,.Callresults and the codeexecuteString()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 tounzip()this way. This is the same handoff that broke the Posit Assistant install in #19625, fixed for those paths only in #19628.create()overload that makes strings, including list and vector names, now marks them UTF-8, andasString(),safeAsString(),extract(),getNames(),fillVectorString()andfillSetString()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 oncreate()deferred until its callers were audited.utf8ToSystem()calls on values passed to R in this process (RFunctionparameters, and the plot export device code run throughexecuteString()), and 5systemToUtf8()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::archivePathnow holds UTF-8 and is converted where it goes to a child process.getBindingType(),getBindingIdentity(),isActiveBinding(),findVar(),findFunction()) install the symbol from a UTF-8 string withRf_installTrChar(), so R translates the name to native; withRf_install(), the Environment pane showed a variable such ascaféwith no value. The saved search path, which RSearchPath.cpp writes as read from R, is read back withencoding = "UTF-8", and async R process output is converted from the system encoding before it reaches its R callback..Callfunctions that return paths, such asrs_rResourcesPathandrs_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."bytes"string returns its bytes instead of raising an R error, which would longjmp through C++. A conversion'sR_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, soutf8ToSystem()andsystemToUtf8()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 whenensureUtf8Charset()(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 throughr::sexp, and child-process arguments built withutf8ToSystem(), which Windows then converts withutf8ToWide()(a separate problem with R < 4.2, #19649).Automated Tests
SessionRTest.StringsReachRMarkedUtf8(rsession C++ tests) passes a non-ASCII string to R as anRFunctionconstructor argument, viaaddParam(), and as a vector, and checks that R reportsEncoding()as"UTF-8".SessionRTest.StringsFromRAreReadAsUtf8(POSIX only) switches R to the C locale and checks that a UTF-8 string read back throughasString()andRFunction::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 throughgetBindingType(),findVar(),getBindingIdentity(),isActiveBinding()andhasActiveBinding(); withRf_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
RFunctionsent), R 4.1.3unzip()andpng()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
rsessionandcoreC++ tests and thertestthat scope pass on macOS.QA Notes
Windows, with RStudio configured to use R 4.1 (or earlier):
C:\temp\test-é..zipfile with Upload.test-é. Notest-é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, runcafé <- 1and 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
NEWS.md