Skip to content

Keep udunits objects in C++ instead of handing them to R - #443

Closed
billdenney wants to merge 1 commit into
r-quantities:mainfrom
billdenney:fix-finalizers-after-unload
Closed

billdenney wants to merge 1 commit into
r-quantities:mainfrom
billdenney:fix-finalizers-after-unload

Conversation

@billdenney

Copy link
Copy Markdown
Contributor

Fixes #442

I realize that this is a big change for an issue that is unlikely to affect users. If not of interest, please feel free to close and ignore.

Summary

ut_unit and cv_converter pointers were wrapped in Rcpp::XPtr with ut_free()/cv_free() C finalizers, and the internal R_ut_* helpers returned those handles to R. A handle that outlives the call that created it is finalized later, when that may no longer be safe:

  • After ud_exit() has freed its unit system (unloadNamespace(), detach(unload = TRUE), load_units_xml(), a pkgload reload): ut_free() reads unit->common.system->one from the freed ut_system (valgrind: 2 invalid reads per handle). For the dimensionless unit "1", which is the system's own singleton, R segfaults at the next gc() or at exit.
  • After the DLL has been unloaded (pkgload::unload(), library.dynam.unload()): the finalizer is a function pointer into the unmapped units.so, and R segfaults.

The exported API never kept a handle alive past the R_gc() in ud_exit(), so reproducing this takes a handle from an internal function:

library(units)
u <- units:::R_ut_parse("1")
unloadNamespace("units")
rm(u); gc()   # *** caught segfault *** (cause 'memory not mapped')
library(units)
lib <- find.package("units")
u <- units:::R_ut_parse("m")
unloadNamespace("units"); library.dynam.unload("units", lib)
rm(u); gc()   # *** caught segfault ***

Changes

  • Units and converters are owned by std::unique_ptr with ut_free()/cv_free() deleters. They are freed when the C++ call that created them returns or throws (keeping the free-on-error intent of 1148f59), and they never reach R. units.so no longer registers any finalizer.
  • The internal R_ut_* helpers take a unit string instead of a unit. install_unit() creates and maps its unit in one call, ud_map_unit(), replacing ud_map_symbols(), ud_map_names(), R_ut_new_base_unit() and R_ut_new_dimensionless_unit(). The unused wrappers that only passed pointers around (R_ut_get_dimensionless_unit_one(), R_ut_scale(), R_ut_offset(), R_ut_multiply(), R_ut_invert(), R_ut_divide(), R_ut_raise(), R_ut_root()) are removed. A GitHub code search finds no users of units:::R_ut_*.
  • ud_exit() drops its R_gc(), which only existed to run the finalizers before freeing the system (3e451b3).
  • Conversions no longer allocate R objects and finalizers. In a quick benchmark that is a few percent to ~12% faster, e.g. set_units() 0.675 s → 0.608 s and x + y 0.338 s → 0.298 s per 2000 calls.

Tests

A new test in test_udunits.R runs a child process. The child calls every native routine the DLL registers, taking the list from getDLLRegisteredRoutines() so that a new routine fails the test until it is covered. It holds all the results across a reload of the unit database and an unload of the namespace and the DLL, then runs gc() and exits. The parent checks that no result is an external pointer and that the child exits cleanly. With the old pointer API, the child segfaults and the test reports two failures instead of taking down the test runner.

  • R CMD check --no-manual: tests [ FAIL 0 | WARN 0 | SKIP 0 | PASS 590 ]; vignettes, "package/namespace can be unloaded cleanly" and "compiled code" are OK.
  • Scenario matrix, each scenario in its own process, run plain, with MALLOC_CHECK_=3 + MALLOC_PERTURB_, and under valgrind:
    • Before: every held handle gave 2 invalid reads, and a SIGSEGV (exit 139) for "1" or after the DLL was unloaded.
    • After: every scenario exits 0 with 0 valgrind errors.

🤖 Generated with Claude Code

Units and converters were wrapped in Rcpp::XPtr with ut_free()/cv_free()
C finalizers, and the R_ut_* helpers returned those handles to R. A handle
that outlives the call that created it is finalized later:

- after ud_exit() has freed its unit system (unloadNamespace(),
  detach(unload = TRUE), load_units_xml(), a pkgload reload): ut_free()
  reads unit->common.system->one from the freed system, and for the
  dimensionless unit "1", which is the system's own singleton, R segfaults;
- after the DLL has been unloaded (pkgload::unload(),
  library.dynam.unload()): the finalizer is a function pointer into the
  unmapped units.so, and R segfaults at the next gc() or at exit.

The exported API never kept a handle alive past the R_gc() in ud_exit(),
so reproducing this took a handle from an internal function, e.g.
units:::R_ut_parse("1"), but nothing stopped one from surviving.

Own units and converters with std::unique_ptr instead, so that they are
freed when the C++ call that created them returns or throws, and never
reach R. The R_ut_* helpers now take a unit string, install_unit() creates
and maps its unit in a single call (ud_map_unit), and the unused wrappers
that only passed pointers around are gone. ud_exit() no longer needs its
R_gc(), and units.so no longer registers any finalizer.

A new test holds the result of every registered native routine across a
reload of the unit database and an unload of the namespace and the DLL,
in a child process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Enchufa2

Copy link
Copy Markdown
Member

I'm not sure this is the approach I'd like to take, in case we plan to refactor the code, which is not on the table right now.

@Enchufa2 Enchufa2 closed this Sep 28, 2026
@billdenney
billdenney deleted the fix-finalizers-after-unload branch September 28, 2026 12:30
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.

Finalizers of udunits handles can run after ud_exit() or after units.so is unloaded

2 participants