Skip to content

fix errno values read as system error codes - #19749

Closed
kevinushey wants to merge 24 commits into
mainfrom
bugfix/19745-errc-generic-category
Closed

kevinushey wants to merge 24 commits into
mainfrom
bugfix/19745-errc-generic-category

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

On Windows, errors that RStudio builds from an errno value reported the message of an unrelated Win32 error with the same number. For example, errc::io_error (5) reported "Access is denied", and errc::is_a_directory (21) reported "The device is not ready" (the loadhistory() symptom fixed for that one call in #19689). About 364 calls are spelled systemError(boost::system::errc::X, ...), and 77 more make the same mistake another way: an errno constant (49), a C runtime errno (6, counting R_ERRNO), an errc paired with system_category() by hand (9), or a code's raw value compared against an errc (13).

The error factories now require a category for integer inputs. The compiler catches the same mistake for errno constants, saved integers and Win32 DWORD values.

It also resolves #18946. Callers can now ask whether a native error matches a portable condition, including when a session should retry binding a port.

Fixes #19745.
Fixes #18946.

Approach

Portable errc values use the generic category. Boost’s errc::errc_t represents portable errno conditions. It previously converted to int, so systemError(errc::X, ...) interpreted it as a native code. The errc_t overloads preserve its generic category. When the TCP resolver reports success with no endpoints, the connector uses make_error_code(errc::io_error) so Boost supplies the category.

Portable conditions have an explicit predicate. Both equality overloads on core::Error compare the numeric code and category name. Zero codes represent success. Use error.matches(boost::system::errc::X) to ask whether a generic or native system error represents a portable condition. Boost supplies the platform mapping for native codes.

On Windows, ERROR_FILE_NOT_FOUND and ERROR_PATH_NOT_FOUND are distinct errors. Both match errc::no_such_file_or_directory. The file helpers still accept only those two native codes and the generic missing-file code. Socket and file-lock callers use the condition they intend to handle.

isDiskSpaceError() recognizes the portable no-space condition and POSIX EDQUOT. Atomic writes also recognize POSIX permission, read-only filesystem, busy mount point, and cross-device errors when deciding whether to try their fallback.

The listener retries a busy port. startHttpConnectionListenerWithTimeout() checks error.matches(boost::system::errc::address_in_use) after a bind failure. Desktop and standalone sessions can retry when a previous session is releasing the port. Initialization disposes of the listener that failed to bind before creating its replacement. The POSIX TCP listener logs its configuration warnings once across retries.

Error factories require a categorized code. The public systemError() and systemCallError() overloads reject bare integers. systemError() accepts a Boost error code or a registered Boost error-code enum in its own category, including Asio and JSON-RPC errors. Scoped standard error-code enums such as std::io_errc work through std::error_code. An unscoped enum registered only with the standard library needs an explicit std::error_code(value). systemCallError() takes a categorized code and prefixes its message with the call name. The unknown-VCS case in vcs_clone now reports json::errc::ParamInvalid in the JSON-RPC category.

Native calls and C runtime errors. Callers choose the category at the point where the origin of a number is known.

  • The 46 calls that passed an errno constant (systemError(EINVAL, ...)) now pass the matching errc. Most are in POSIX-only files, where they were correct but are now spelled portably. The ones that compile on Windows were wrong: Win32System.cpp (getChildProcesses) and SessionContentUrls.cpp.

  • The 3 POSIX-only test fixtures that need the native code (FileSerializerTests) build it explicitly with system_category(), as the new ErrorTests do.

  • The Win32 CRT callers and R's iconvstrImpl() save the runtime errno immediately after the failing call and use genericError(saved, ...). This preserves the code across cleanup, logging, and construction of the error location.

  • Some code built the same mistake by hand, as error_code(errc::X, system_category()). Windows' output capture (ioError()) and TcpIpAsyncConnector's empty-endpoint error reported errc::io_error as "Access is denied"; both now use the generic category, as do FilePath::completeChildPath()'s two "not within the parent" errors and the POSIX-only server proxy's permission_denied. AsyncServerTests built native POSIX codes that way; it now spells them as errno constants with system_category() (identical values).

  • LAST_SYSTEM_ERROR() is Windows-only and captures GetLastError() before constructing the source location. POSIX callers save errno and pass it to genericError() or to systemCallError() with generic_category() when a diagnostic includes the call name. Shared CRT callers, including the debug logger’s open() call, use the same errno convention on Windows. APIs such as pthread_atfork() that return an error number use that return value.

  • The R linter checks category-blind comparisons and errc values paired with system_category().

  • The local stream proxy rejects requests when the user lookup fails. It needs the resolved UID to verify socket ownership.

zlib and Mach return codes get their own categories. ZlibUtil.cpp and Response.cpp passed zlib return codes (e.g. Z_DATA_ERROR, -3), and MacResources.cpp passed kern_return_t values, to systemError(int). Their messages were strerror()'s (or Win32's) for an unrelated number. A new zlib::zlibError() (in ZlibUtil.hpp) and a file-local machError() report them as zlib / mach errors with zError() / mach_error_string() messages.

Visible changes besides the messages:

  • Portable errc errors and failures constructed with genericError(savedErrno, ...), including POSIX system calls, now log and serialize with category generic (the type field in JSON logs, category in RPC errors). The client checks only ServerErrorCause.isWindowsSharingViolation() by category, and that check is for a Win32 code.
  • On Windows the generic messages are the CRT's strerror() text.

Codes are compared as conditions, never by value against an errc (#18946). getCode() == errc::X and ec.value() == errc::X ignore the category, so on Windows they matched whichever Win32 code shared the errc's number. They're now error.matches(errc::X) or boost's ec == errc::X:

  • isResourceExhaustionError(): the accept backoff never ran on Windows, where asio reports WSAEMFILE (10024), not 24. boost maps WSAEMFILE and ERROR_NOT_ENOUGH_MEMORY/ERROR_OUTOFMEMORY to the two errcs; the system-category guard stays.
  • SessionChat.cpp's five "Permission denied" / "protocol not supported" checks: on Windows ERROR_ACCESS_DENIED is 5, not 13, so file permission errors fell through to the generic message.
  • SocketAcceptorService's destructor (WSAEBADF), and, for consistency, the POSIX-only LocalStreamAsyncServer/Client and SocketOwnership.cpp checks (same result on POSIX).
  • The Better BibTeX request handler now tests the original error for a timeout. The previous assignment overwrote unexpected transport errors before they could be logged.
  • The linter test also flags raw numeric comparisons with errc values.

handleStreamError() keeps the write's error code (#18946). StreamWriter turned the asio write error into an Error, and AsyncConnectionImpl::handleStreamError() rebuilt an error_code from it in the generic category, because an Error keeps only its category's name. StreamWriter now hands its error handler the error_code itself, which handleStreamError() passes on unchanged; the session's HttpConnectionImpl gets a small adapter that logs it as before.

The shared header exposes the same API to rstudio-pro. Downstream callers passing raw integers must identify their source when rebuilding. Portable condition checks use matches(), and serialized errc errors carry the generic category.

Automated Tests

  • src/cpp/shared_core/ErrorTests.cpp (new; rstudio-shared-core-tests, also run by rstudio-tests --scope core):
    • ErrorTest.ErrcErrorsUseTheGenericCategory: all four errc overloads build a generic-category error with the errc's generic message, keeping the description and cause.

    • ErrorTest.ErrcErrorsMatchTheSameErrcBuiltAnyWay: systemError(errc::X), Error(errc::X), systemError(std::make_error_code(std::errc::X)), and a generic error_code all compare equal.

    • ErrorTest.DistinctCodesCanMatchTheSameCondition checks exact equality against both Error and Boost error codes. On Windows it also checks that both native missing-file codes match the portable condition while remaining distinct.

    • ErrorTest.GenericErrorsUseTheGenericCategory checks the category, message and optional description for saved errno values.

    • ErrorTest.ErrcErrorsDoNotMatchUnrelatedErrors: a different errc, another category with the same number, and Success() don't match. On Windows, system 21 (ERROR_NOT_READY) doesn't match errc::is_a_directory.

    • ErrorTest.ErrorCodeEnumsUseTheirOwnCategory: an unscoped test error-code enum with its own category (unscoped like json::errc, so it would also convert to int) keeps that category, message, description, and cause through all four overloads.

    • Compile-time checks reject int and unsigned long across all four systemError forms and both named-call forms. CategorizedCodesKeepTheirCategory covers explicit codes, causes, descriptions and named-call messages. LastSystemErrorCapturesGetLastError checks Win32 capture and the call site. Non-Windows builds check that LAST_SYSTEM_ERROR is undefined.

  • FileSerializerTest.IsDiskSpaceErrorClassifies now also asserts that an errc no_space_on_device error is a disk-space error and an errc no_such_file_or_directory error is not.
  • ZlibTest.DecompressErrorsAreZlibErrors (new): a stream whose header names compression method 0 fails with a zlib-category Z_DATA_ERROR, zError()'s message, and the inflation description.
  • LoggingTest.CanJsonLogError pinned the old behavior (type system, and the Win32 text on Windows); it now expects generic and the generic message.
  • StreamWriter.ErrorHandlerGetsTheWritesErrorCode (new, core/http/StreamWriterTests.cpp): a stream whose writes fail with an asio.misc error hands the error handler that exact code, category included.
  • AsyncServerResourceExhaustion.ClassifiesResourceErrors now uses the codes asio reports (no_descriptors, no_memory, ...), which are native on each platform; on Windows it fails without the fix.
  • test-linter.R checks production comparisons against systemError(errc::…) and raw code values. Fixtures cover both operand orders, multiline calls and Windows-only branches.
  • No test forces host_statistics()/task_info() to fail, so MacResources.cpp's machError() is covered only by the build.

The Windows build runs the Windows-specific assertions in the shared-core tests. At commit 344f427171, the macOS runner passed all 2,014 C++ tests (890 core, 13 server-core, 26 shared-core, 951 rsession, 134 rserver). R testthat reported 4,850 passed, 14 skipped, zero failures and zero warnings.

The listener retry has no automated test, since it needs a whole session. Checked by hand with a desktop-mode rsession on a port another process held:

  • Before (main): one attempt, then exit 1 with system error 48 (Address already in use).
  • At commit 344f427171, holding the port produced 10 attempts over about a second and exit 1 with Operation timed out caused by Address already in use.
  • Releasing the port after the second attempt let the third bind succeed, and the session completed its startup R script.

The macOS follow-up at aaee1a040d passed 929 core, server-core, and shared-core C++ tests and 104 R linter expectations. A child-process callback check received Asio's original EOF category and message. Running the linter against the previous sources identified all four unsafe Win32 calls.

At 437be46c0f the full macOS rstudio-tests run passed 2,016 C++ tests and 4,847 R expectations. The R suite reported 14 skips and zero failures or warnings.

At a053d7a326 the macOS suite passed 2,015 C++ tests and 4,846 R expectations, with 14 R skips. The last-error runtime test now runs on Windows, and the macOS build checks that the macro is undefined.

QA Notes

On Windows:

  1. loadhistory(tempdir()) should report is a directory (as it does after report savehistory() / loadhistory() failures as errors on windows #19689).
  2. Error text in rsession logs for internal errors should read like errno messages (e.g. "Input/output error", "Invalid argument") rather than unrelated Win32 messages ("Access is denied", "The device does not recognize the command").

On any platform, Desktop: start RStudio while another process listens on the port the session is given. The session now retries for about a second before failing, instead of failing at once. This is hard to arrange through the Desktop app, so the hand check above is the practical test.

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 (n/a: no UI)
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

systemError(boost::system::errc::X) bound to the int overload and built a
system-category code, which holds Win32 codes on Windows, so the errno value
was read as a Win32 error and given that error's message. Add errc_t overloads
that build a generic-category code, and make Error's equality treat a generic
code as an error condition, so checks written as systemError(errc::X) still
match the errno or Win32 code the system reports.

That equivalence makes the address_in_use retry in
startHttpConnectionListenerWithTimeout() match for the first time, so free the
listener that failed to bind before allocating its replacement.

Addresses #19745.
@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 20, 2026
@kevinushey
kevinushey requested a review from gtritchie November 20, 2026 02:41
An enum argument converted to int and became a system-category code. Enums
that are boost error code enums now use their own category (asio, json-rpc,
windows_error, ...), and any other enum fails to compile. This moves the one
existing caller, SessionVCS's json::errc::ParamInvalid, into the json-rpc
category, so the client gets it as an invalid-parameter RPC error.

Addresses #19745.
systemError(EINVAL, ...) builds a system-category code, which Windows reads
as a Win32 error. Pass the matching errc instead, and give C runtime errno
values in the Win32-only files the generic category. A linter test fails on
either pattern.

Addresses #19745.
zlib return codes and kern_return_t values went to systemError(int), so their
messages were strerror()'s (or Win32's) for an unrelated number. Report them
with zlib's and mach's own messages instead.

Addresses #19745.
R_ERRNO (the C runtime errno, also on Windows) and errc values paired with
system_category() by hand made the same mistake; build those as generic codes
and add both to the linter test. Reject every unscoped enum without a boost
category in systemError(), and every enum in systemCallError(). Test zlib
errors against a deterministic Z_DATA_ERROR.

Addresses #19745.
The lint now finds systemCallError() with a non-literal name and covers every
file with Win32 in its name; captureCommand() reads errno before logging.

Addresses #19745.
ERROR_LOCATION may be evaluated first, and its allocations can change errno.

Addresses #19745.
Value comparisons against an errc ignore the code's category, so on Windows
a Win32 code matched whichever errc shared its number (and the accept backoff
never saw WSAEMFILE). Compare as conditions instead, and add the pattern to
the linter test. StreamWriter now hands its error handler the write's error
code, so handleStreamError() no longer rebuilds one in the generic category.

Addresses #18946.
Addresses #19745.
@kevinushey kevinushey changed the title build errc errors in the generic category fix errno values read as system error codes Nov 20, 2026

@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.

A few things below, plus one outside the diff:

src/cpp/r/session/RConsoleHistory.cpp:191: the #19689 comment says a bare errc value would go to systemError(int), which on Windows reads 21 as a Win32 code ("The device is not ready"). With the new errc_t overloads that's no longer true, so the comment now contradicts the code. The std::make_error_code(std::errc::...) calls at :181 and :196 build the same generic-category error as systemError(boost::system::errc::...), differing only in the Windows message text (MSVC's std table vs the CRT's strerror()). test-history.R:98 matches with ignore.case = TRUE, so either spelling passes. At least the comment should be updated or removed.

boost::system::system_category()),
error,
ERROR_LOCATION);
Error permissionError = systemError(boost::system::errc::permission_denied, error, ERROR_LOCATION);

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 bug predates this PR, but it's next to a line the PR changes. The check above (:913) lets a lookup failure through only when it's permission_denied, which the comment says means "no user was found". Since 670762b (2020), User::Impl::populateUser reports a missing user as ENOENT instead. This PR turns that into errc::no_such_file_or_directory in User.cpp, and the new equivalence doesn't make it match permission_denied. So a user who isn't in passwd yet (the PAM case the comment describes) always ends up here and is refused. Either the check should test for not-found (isNotFoundError(error)), or the comment should change to say the request is rejected.

// startHttpConnectionListenerWithTimeout() calls this again while the
// address is in use; replace the listener that failed to bind (it never
// started, so nothing else holds it)
delete s_pHttpConnectionListener;

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.

Now that the address_in_use retry actually runs, each attempt (about 10, from waitWithTimeout(fn, 0, 100, 1)) goes back through initTcpHttpConnectionListener() and logs its startup warnings again. A standalone session gets an empty shared secret, and verify-signatures defaults to false, so a session waiting on its reused port logs "The tcp http listener initialized without signature validation: --verify-signatures option missing" about 10 times instead of once. Running as root also repeats the line-75 warning. Could the warnings be logged once, or the retry rebind the same listener instead of rebuilding it?

Comment thread src/cpp/tests/testthat/test-linter.R Outdated

contents <- paste(readLines(cppFile, warn = FALSE), collapse = "\n")
patterns <- c(errnoConstant, rErrno, errcAsSystem, errcByValue)
if (grepl("Win32", basename(cppFile), fixed = 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.

The C runtime errno pattern only runs on files with Win32 in the name, so Windows-only #ifdef _WIN32 blocks in shared files (e.g. AdvisoryFileLock.cpp, FileSerializer.cpp) aren't checked. Also, errcByValue requires errc::, so error.getCode() == ENOENT in cross-platform code has the same category-blind problem but isn't flagged. I didn't find any current offenders, so this only matters for future code.

The std::make_error_code() spelling and its comment worked around
systemError(errc) reading the value as a Win32 code, which no longer happens.

Addresses #19745.
Builds a generic-category error from an int errno value, and rejects enums
at compile time (an errc goes to systemError()). Replaces the hand-built
std::error_code(..., std::generic_category()) at the C runtime errno sites.

Addresses #19745.
The check let a lookup failure through only when it was permission_denied,
but since 670762b a missing user is reported as not found, so the user
the comment describes (created later by PAM) was always refused. Check for
not found instead.

Addresses #18946.
The C runtime errno rule, and a new rule against comparing a code's value
with an errno constant, now cover #ifdef _WIN32 regions of shared files as
well as Win32 files.

Addresses #19745.
Letting a user who isn't in passwd through skips the uid check, and any local
user can create a socket in the world-writable streams directory, so an
impostor's socket could receive the request. Reject every lookup failure,
including the permission_denied one the old check let through, and fix the
comments.

Addresses #18946.
Recognize '#if _WIN32', conjunctions with _WIN32, and the #elif/#else
branches that follow a _WIN32 test; accept chained receivers such as
e.code().value(); don't flag EOF. Test genericError()'s description form
against enums too.

Addresses #19745.
@github-actions

Copy link
Copy Markdown

RStudio E2E - all platforms

1 test(s) failed

###################- 99% pass rate

Passed Failed Skipped Flaky
5808 1 254 0
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1453 0 49 0
❌ desktop-macos 1459 1 43 0
✅ desktop-windows 1448 0 60 0
✅ server-linux 1396 0 54 0
✅ setup 48 0 32 0

View report online


All platforms - commit b3f9edeade55cab50585f3d5d4191522acda1af2 - Run #2422

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Superseded by #19753, which fixes the same categories with a narrower change: systemError(int) stays errno on POSIX, Windows takes DWORD/LONG codes as Win32 and deletes the int overload, and condition checks use Error::matches(errc). The #18946 pieces (value comparisons, the busy-port retry) aren't included there.

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

Labels

None yet

Projects

None yet

2 participants