Repository navigation
pick error categories from the code's type - #19753
Conversation
systemError(errc) and errno values now build generic-category errors, and Win32 codes (DWORD, LONG) build system-category ones. On Windows an int is ambiguous, so systemError(int) is deleted there; errno from the C runtime goes through the new genericError(int). Integer types and enums whose category can't be known are deleted on every platform, and registered Boost error code enums keep their own category. Comparisons against errc-built errors use the new Error::matches(errc), zlib and Mach return codes get their own categories, and FileSerializer's error helpers take a finished Error rather than an int that lost the code's type. Addresses #19745.
getCode() / value() == errc ignored the category, so on Windows these checks compared Win32 codes against errno numbers. Use Error::matches() or boost's ec == errc instead, and pin that Error(errc) equals systemError(errc). Addresses #18946.
isNotFoundError() on Windows and the socket error classifiers compared against native codes exactly, which errc-built errors only matched while they were in the system category. Accept the generic forms too, and keep friendlySaveError() in the original error's category. Addresses #19745.
RStudio E2E - all platformsAll tests passed!
All platforms - commit |
The using-directive for boost::asio::error made 'eof' ambiguous with the global ::eof(int) that the Windows CRT declares in <io.h> (C2872). Addresses #19745.
- iconvstrImpl() and captureCommand() read errno only after Riconv_close() / LOG_ERROR, which can overwrite it; save it first. - startHttpConnectionListenerWithTimeout() compared against a generic-category address_in_use, which an asio bind error (system category) never equals, so the retry never ran; use matches(). - isConnectionTerminatedError() on Windows again matches only ERROR_FILE_NOT_FOUND among the native not-found codes, as before; #19756 tracks whether ERROR_PATH_NOT_FOUND belongs there too. Addresses #19745, #19755.
An error built from an errc value is generic, while Boost reports the same condition in the system category, so == against systemError() / Error(errc) is quietly false, and getCode() / value() compared with an errc value ignores the category. test-linter.R now flags both forms, including ones split across lines. It found two such checks in the Posit Assistant edit-file handler, which on Windows compared ERROR_ACCESS_DENIED with EACCES; they now use matches().
systemError(::GetLastError(), ERROR_LOCATION) can read the last error after MSVC debug builds construct ERROR_LOCATION and reset it to 0, which is why LAST_SYSTEM_ERROR() exists. test-linter.R now flags the direct call, and the four remaining sites in Win32Resources.cpp and FilePath.cpp use the macro. It also flags a newly built error assigned in a condition, such as the always-true ((error = systemError(errc::timed_out, ...))) Zotero check, and shares the C++ source scan between these lint tests.
gtritchie
left a comment
There was a problem hiding this comment.
Two issues from the switch to matches(), plus a NEWS entry. Details inline:
- the
address_in_useretry at startup now runs, and each attempt leaks a listener - on Windows, Posit Assistant now reports a file that's open in another program as "Permission denied"
- NEWS.md has no entry for #19755
| if (!error) | ||
| return WaitResult(WaitSuccess, Success()); | ||
| else if (error != boost::system::error_code(boost::system::errc::address_in_use, boost::system::generic_category())) | ||
| else if (!error.matches(boost::system::errc::address_in_use)) |
There was a problem hiding this comment.
With matches() this retry now runs. Before, Error::operator== also compared category names, so asio's system-category EADDRINUSE never equaled the generic code, and every bind failure went to WaitError.
Each retry goes through startHttpConnectionListener() -> initializeHttpConnectionListener(), which news a listener and overwrites s_pHttpConnectionListener without deleting the previous one (SessionWin32HttpConnectionListener.cpp:81, SessionPosixHttpConnectionListener.cpp:81 and :93). The failed listener's acceptor was already opened (TcpIpSocketUtils.hpp:99) before bind failed (:151). So with waitWithTimeout(..., 0, 100, 1) (SessionMain.cpp:3051), a restart that hits a busy port leaks up to ~10 listeners, each with its own io_context and an open socket.
The local-stream listeners (SessionPosixHttpConnectionListener.cpp:157 and :188) are recreated the same way. A local stream that another process is already listening on also returns address_in_use (LocalStreamSocketUtils.hpp:257), so that case now retries for a second instead of failing right away.
Could the listener be built once and only the bind retried, or the failed listener deleted before the next attempt?
There was a problem hiding this comment.
Good catch, and you're right that this PR is what makes the retry reachable. Fixed in ec52fee: initializeHttpConnectionListener() now deletes the previous listener before building the next one, on both platforms. It's only called again after a bind that failed with address_in_use, so that listener never started and nothing else refers to it; destroying it closes the acceptor through SocketAcceptorService's destructor. The claimed session-stream listener on POSIX still returns early and is left alone.
I went with deleting the failed listener over retrying only the bind, since bindEndpoint() would otherwise have to close and reopen an acceptor that's already open.
Two caveats. There's no test for this: the retry goes through the session options and a file-static pointer. And I left the local-stream case retrying for a second. It no longer leaks, and a restarting session may be waiting on the old process to let go of the stream, but I'm happy to exclude it if you'd rather it fail right away.
| if (error) | ||
| { | ||
| if (error.getCode() == boost::system::errc::permission_denied) | ||
| if (error.matches(boost::system::errc::permission_denied)) |
There was a problem hiding this comment.
On Windows, this now matches ERROR_SHARING_VIOLATION and ERROR_WRITE_PROTECT: Boost 1.91 maps both to permission_denied (boost/system/detail/system_category_condition_win32.hpp). writeContentsToFile opens the target with share mode 0 (FileSerializer.cpp:130), so writing a file that's open in Excel fails with ERROR_SHARING_VIOLATION, and the Assistant gets "Permission denied: ". It used to get "Failed to write file", because the old getCode() == errc::permission_denied compared against 13, which is ERROR_INVALID_DATA on Windows.
"Permission denied" points the agent at file permissions when the fix is to close the file in the other program. The edit path's write (line 3148) behaves the same way, and so do the reads at 2612 and 3098 when the other program also denies read sharing.
Could Windows check for ERROR_SHARING_VIOLATION first, with an "in use by another program" message? Or match only ERROR_ACCESS_DENIED here, which is the case the PR description mentions.
There was a problem hiding this comment.
Agreed, and fixed in ec52fee with your first suggestion. There's a new core::isFileInUseError() (a Win32 ERROR_SHARING_VIOLATION, false on POSIX), and all four handlers test it before the permission check and report File is in use by another program: <path>.
The read case turns out to be broader than "the other program also denies read sharing": FilePath::openForRead opens without FILE_SHARE_WRITE, so our read fails with a sharing violation whenever another program holds a write handle. FileSerializerTest.FileHeldOpenByAnotherHandleIsInUse covers both the write and the read.
The predicate also replaces the private isFileLockedError() in FileSerializer.cpp, which checked only the code, so the write retry loop no longer treats errno 32 (EPIPE) as a sharing violation.
ERROR_WRITE_PROTECT still reports "Permission denied", which seemed right for write-protected media.
| - ([#19661](https://github.com/rstudio/rstudio/issues/19661)): RStudio Desktop can now switch to another installed version of R on macOS and Linux as well as Windows, from Tools > Global Options > General or Session > Switch R Version, restarting only the R session rather than RStudio. The version of R switched to, including from the renv R version notice in the Console, is kept for later launches; it takes precedence over `RSTUDIO_WHICH_R` until that variable changes (as it does when rig's default R changes), and is forgotten then. If the chosen R can't be used at startup, RStudio starts with the default R and asks whether to keep the choice (on Windows, the Choose R dialog is shown, as before), and if a session fails to start with the chosen R, the error page offers to go back to the previous or the default version of R. | ||
|
|
||
| ### Fixed | ||
| - ([#19745](https://github.com/rstudio/rstudio/issues/19745)): Fixed an issue on Windows where some error messages described an unrelated Windows error, e.g. an input/output error reported as "Access is denied". |
There was a problem hiding this comment.
The PR fixes #19755 (iconvstrImpl() and captureCommand() reading errno after cleanup), but this is the only new entry. That code is in released versions, so per .claude/CLAUDE.md it needs its own ### Fixed entry.
On POSIX the system and generic categories both hold errno values, and which one an errno value arrives in depends only on who reported it: our own errors are generic, while Boost (asio, filesystem) reports errno in the system category. The same ENOENT was then two unequal errors. Error now stores a system-category code as generic on POSIX, and operator==(error_code) treats its argument the same way, so errors for the same errno value are equal. On Windows nothing changes: a Win32 code and an errno value are different codes and stay distinct. Logs and messages keep the "system error N" form on POSIX. The new Error::getDisplayName() gives the name to show, and getSummary(), the JSON log's type field and errorMessage() use it. getName(), ==, matches(), writeJson() and the RPC category field keep the stored name. hasNativeCode() in FileSerializer.cpp is now one check per platform, and the system branch of matches() is Windows-only. matches() also documents that a Win32 code matches by Boost's many-to-one mapping. Addresses #19745.
Review feedback on the switch to matches(): - The address_in_use retry in startHttpConnectionListenerWithTimeout() now runs, and each attempt built a new listener without freeing the one whose bind had failed, leaking it and the socket it had opened. initializeHttpConnectionListener() now deletes that listener first; it never started, so nothing else refers to it. - On Windows, matches(permission_denied) is also true for ERROR_SHARING_VIOLATION, so Posit Assistant reported a file that was open in another program as "Permission denied". The new core::isFileInUseError() recognizes the sharing violation, and the Assistant's read, write and edit handlers test for it first and say the file is in use by another program. isFileInUseError() replaces FileSerializer.cpp's isFileLockedError(), which checked only the code; the write retry loop no longer takes an errno 32 (EPIPE) for a sharing violation. - NEWS.md gains an entry for #19755. Addresses #19745, #19755.
Review feedback: - getDisplayName() returned a function-local static string, which exit() destroys while a detached thread may still log an error. It is now leaked with make_leaked(). - iconvstrImpl() read errno after output.insert(), which can allocate, had run. It now reads it once, right after Riconv(). - The condition-comparison lint missed an Error compared with a boost::system::error_code built from an errc value, the form of the original listener retry check. It now flags that too. - ClassifiesResourceErrors gains generic-category positive cases, and the unusable-manifest test checks matches(protocol_not_supported), as the update check does, rather than the bare code. Addresses #19745.
gtritchie
left a comment
There was a problem hiding this comment.
Thanks, all three are addressed. The listener fix, isFileInUseError() and the NEWS entry look good, as does the errno-as-generic change on POSIX.
Intent
On Windows, errors that RStudio builds from an errno value or a portable
errcvalue reported the message of an unrelated Win32 error with the same number. For example,errc::io_error(5) read as "Access is denied", anderrc::is_a_directory(21) as "The device is not ready".systemError(int)put every integer insystem_category(), which on Windows means Win32 codes, andsystemError(errc::X)reached it through the enum's conversion toint.Fixes #19745.
Fixes #19755.
Addresses #18946.
This replaces #19749, which fixed the same bug by rejecting bare integers on every platform. This version keeps
systemError(errno)working where anintcan only be errno, and only requires the caller to say which kind of code it has on Windows.Approach
The guideline: errno values and portable
errccodes usegeneric_category(); native OS errors (Win32 codes) usesystem_category(); and tests for a particular condition compare against anerrcvalue, not a raw number.The code's type picks the category.
boost::system::errcvalueinton POSIX (errno, or an error number a call returns)DWORD(GetLastError()) orLONG(Reg*,ERROR_*constants) on Windowsjson::errc,windows_error)inton WindowsDWORDisunsigned longandLONGislong, which are distinct types fromintfor overload resolution, so the Win32 callers compile unchanged. On Windows, errno set by the C runtime goes through the newgenericError(int), which also rejects other integer types and enums (sogenericError(GetLastError())doesn't compile).systemCallError()is POSIX-only, and generic.On POSIX, an errno value is one error whoever reports it. The system and generic categories both hold errno values there, and Boost (asio, filesystem) reports errno in the system category, so the same
ENOENTwould otherwise be two unequal errors depending on which library made the call.Errorstores a system-category code as generic on POSIX, in every constructor, andoperator==(error_code)treats its argument the same way. On Windows nothing is folded: a Win32 code and an errno value are different codes.Logs and messages keep the
system error N (...)form on POSIX. The newError::getDisplayName()gives the name to show (systemfor a generic error on POSIX, otherwise the stored name), andgetSummary(), the JSON log'stypefield anderrorMessage()use it.getName(),==,matches(),writeJson()and the RPCcategoryfield keep the stored name. On Windows a generic error is shown asgeneric error N, since there the name says which set of codes the number belongs to.Condition tests use
Error::matches(errc). Errors built fromerrcvalues are now generic, while on Windows Boost reports the same conditions as Win32 codes in the system category, so there the 13error == systemError(errc::X, ErrorLocation())checks can never equal one of Boost's errors (before, they did only where the errno number happened to equal the Win32 one). They now callerror.matches(errc::X), which uses Boost's condition mapping for Win32 codes. On POSIX the equality would still hold, since both sides are errno values, sotest-linter.Rrejects the==form to keep a check that passes on POSIX from being quietly false on Windows. On Windows this means, for example, that bothERROR_FILE_NOT_FOUNDandERROR_PATH_NOT_FOUNDmatchno_such_file_or_directory, and thatERROR_NOT_READYno longer matchesis_a_directoryby sharing its number.operator==still compares the code and category name exactly.The 9 checks that compared
getCode()orvalue()against anerrcvalue ignored the category entirely, so on Windows they compared Win32 codes against errno numbers. They now usematches(), or Boost'sec == errc::Xfor a rawerror_code. Where they compile on Windows, this changes behavior:ERROR_ACCESS_DENIED(5), which never equaledEACCES(13), instead of a generic failure. Boost also mapsERROR_SHARING_VIOLATIONtopermission_denied, so a file that another program holds open is checked for first, with the newcore::isFileInUseError(), and reported as "File is in use by another program". That covers reads too: our readers don't share writes, so a read fails the same way while another program has the file open for writing.isResourceExhaustionError()now runs on Windows, where asio reportsWSAEMFILEandERROR_OUTOFMEMORYrather than 24 and 12. Its system-category guard is gone, since a condition comparison can't match another category's number.SocketAcceptorService's destructor no longer logsWSAEBADFfrom closing an already-closed acceptor.The rest (
LocalStreamAsyncServer,LocalStreamAsyncClient,SocketOwnership) are POSIX-only and only get shorter.Checks that compared native codes exactly. Some checks only recognized our
errc-built errors because those used to be in the system category:isNotFoundError()on Windows compared againstERROR_FILE_NOT_FOUNDandERROR_PATH_NOT_FOUND, andsystemError(errc::no_such_file_or_directory)matched the first only because both are 2. It now also accepts the generic error, while native errors still match only those two codes.http::isConnectionTerminatedError()andisConnectionUnavailableError()compared against asio'stimed_out,connection_reset,bad_descriptor,broken_pipeandconnection_refused. On POSIX our ownsystemError(errc::timed_out)(request deadlines, connect timeouts) andsystemError(errc::connection_refused)(a refused proxy CONNECT) matched them exactly; they now compare as conditions.isConnectionUnavailableError()still retries only the native Windows pipe errors it did before (ERROR_FILE_NOT_FOUND,ERROR_BROKEN_PIPE,ERROR_PIPE_BUSY), plus a generic not-found error. Likewise,isConnectionTerminatedError()on Windows still treats onlyERROR_FILE_NOT_FOUNDamong the native not-found codes as a client hang-up, plus a generic not-found error; Check which Windows not-found codes isConnectionTerminatedError() should treat as a client hang-up #19756 asks whetherERROR_PATH_NOT_FOUNDbelongs there too.friendlySaveError()inSessionSource.cpprebuilt the disk-full error in the system category; it now keeps the original category and code.Call sites.
genericError()or anerrcvalue (Win32OutputCapture.cpp,Win32System.cpp,RUtil.cpp,SessionContentUrls.cpp).FileSerializer.cpp'sfileError()andatomicWriteError()took anintcode, and Windows callers passedGetLastError()through it, losing theDWORDtype. They now take the finishedError, built where the code is read (LAST_SYSTEM_ERROR()on Windows, which also captures it beforeERROR_LOCATIONis constructed).isDiskSpaceError(),isPermissionError()andisMountPointError()required the system category. On POSIX they now require generic, which is how anErrorstores every errno value there, so both our errno errors and Boost's classify; on Windows they still require a Win32 code.ZlibUtil.cpp,Response.cpp) and Machkern_return_tvalues (MacResources.cpp) getzlibandmachcategories with their own messages, since they're neither errno values nor Win32 codes.error_code(errc::X, system_category())now use the generic category, andPosixChildProcess.cppkeeps the asio error's category instead of rebuilding it fromvalue().RConsoleHistory.cppdrops thestd::make_error_codeworkaround from report savehistory() / loadhistory() failures as errors on windows #19689 in favor ofsystemError(errc::...).ZoteroBetterBibTeX.cpp's timeout check assigned instead of comparing,(error = systemError(errc::timed_out, ErrorLocation())), which was always true. Every error other than an unavailable connection was replaced with a fake timeout and reported as "Zotero isn't running", and the branch that logs unexpected errors never ran. It's nowerror.matches(errc::timed_out)(from compare, don't assign, when checking for a better bibtex timeout #19752).startHttpConnectionListenerWithTimeout()(SessionHttpMethods.cpp) compared the listener error against a genericaddress_in_use, which asio's system-category bind error never equals, so the busy-port retry after an rsession restart never ran. It now usesmatches(). Each attempt builds a new listener, soinitializeHttpConnectionListener()now frees the one whose bind failed, and with it the socket it had opened, before building the next; otherwise a restart onto a busy port would leak a listener per attempt (about ten in the one-second retry window). A local stream that another process is already listening on also reportsaddress_in_use, so that case now retries for a second before failing.isFileInUseError()replacesFileSerializer.cpp's privateisFileLockedError(), which checked only the code. The write retry loop no longer takes an errno 32 (EPIPE) for a sharing violation.iconvstrImpl()(RUtil.cpp) andcaptureCommand()(Win32System.cpp) now save errno beforeRiconv_close()orLOG_ERRORcan overwrite it, so the error reports the failed call (iconvstrImpl() reads errno after Riconv_close(), which can change it #19755).Visible changes besides Windows messages: on POSIX, log lines and error messages are unchanged (
system error N), but the RPCcategoryfield andError::writeJson()now carrygenericfor errno errors, including the ones Boost reports. The client only checks the category for a Win32 sharing violation, which is stillsystem. On Windows, errno errors now log asgeneric error Nwith the errno message.For #18946, this covers its first group (
Error(errc::X)andsystemError(errc::X)now build the same generic error, whichErrorTestspins) and its third (the value comparisons above;RToolsInfo.cppandhttp/Util.cppwere fixed earlier). Not included:AsyncConnectionImpl::handleStreamError()rebuilding a stream write's error in the generic category.Automated Tests
src/cpp/shared_core/ErrorTests.cpp(new): compile-time checks of which types each factory accepts on each platform, plus the categories, messages, descriptions and causes forerrcvalues, errno values, registered enums and (on Windows)DWORD/LONGcodes,LAST_SYSTEM_ERROR()on both platforms, andmatches(). On POSIX it also checks that an errno value is the same error from the generic category, Boost's system category, a category name or astd::error_code, and that such errors are shown assystem error N; on Windows, that errno 5 and Win32 code 5 stay distinct and are shown asgenericandsystem.FileSerializerTest.IsDiskSpaceErrorClassifiesalso covers an errno value in the system category, as Boost reports it.FileSerializerTest.FileHeldOpenByAnotherHandleIsInUse(new, Windows) holds a file open with a write handle and checks that both our write and our read fail with an error thatisFileInUseError()recognizes and that also matchespermission_denied.FileSerializerTest.IsFileInUseErrorClassifies(new) covers the predicate on both platforms, including errno 32 on Windows.SocketUtilsTests.cpp(new): each connection classifier accepts both the asio code and the generic error for the same condition, and on WindowsisConnectionUnavailableError()acceptsERROR_FILE_NOT_FOUNDbut notERROR_PATH_NOT_FOUND,ERROR_INVALID_NAMEorERROR_BAD_NETPATH, andisConnectionTerminatedError()acceptsERROR_FILE_NOT_FOUNDbut notERROR_PATH_NOT_FOUND.SharedCoreTest.NotFoundHelpersMatchFileAndPathErrorsalso covers the generic not-found error.ZlibTest.DecompressErrorsAreZlibErrors(new).AsyncServerResourceExhaustion.ClassifiesResourceErrorsnow uses the codes asio reports (no_descriptors,no_memory, ...), which are native on each platform, so on Windows it exercisesWSAEMFILEandERROR_OUTOFMEMORY.LoggingTest.CanJsonLogErrornow expects the generic message, with the logged typesystemon POSIX andgenericon Windows.test-linter.Rrejectserrcvalues paired withsystem_category()in C++ sources.On macOS, before the last two commits (folding errno categories on POSIX, and the review fixes): core 891 passed (12 skipped), shared-core 26, rsession 951, rserver 133 (11 skipped), and the R linter and history tests pass.
With those two commits:
ErrorTestsuite passes (8 tests) in a standalone g++ build ofError.cppandErrorTests.cpp, andFileSerializer.cpp,FileSerializerTests.cppandLoggingTests.cppcompile. The full POSIX suites weren't rerun locally, so CI is the first run of thesystemexpectation inLoggingTest.CanJsonLogError, and the first compile of the edit toSessionPosixHttpConnectionListener.cpp.test-linter.Rpass.QA Notes
On Windows:
loadhistory(tempdir())should report "is a directory".rsessionlog entries for internal errors should read like errno messages ("Input/output error", "Invalid argument") rather than unrelated Win32 messages ("Access is denied")..csvopen in Excel), asking Posit Assistant to edit that file should fail with "File is in use by another program", not "Permission denied".On Linux or macOS,
rsessionandrserverlog entries for errno errors should still readsystem error N (...), as before.On any platform, with Zotero closed, the Better BibTeX warning should still say Zotero isn't running.
Documentation
None needed.
Checklist
NEWS.md