7.4 Dynamic Linking and Symbol Resolution
7.4.1 Motivation
When an R package containing compiled C code loads, the operating system must find the entry points. A package’s .so file (Linux) or .dll file (Windows) contains machine code that references other functions. These include R’s API functions, libc, third-party libraries, and internal functions.
The dynamic linker reads the binary and fills in these references. This process is symbol resolution. It happens once at load time. If it fails, the package cannot load. If it succeeds but resolves to the wrong function, the results are silent corruption.
7.4.2 Symbols, addresses, and the symbol table
A symbol is a name that refers to a function or global variable. In C:
int add(int a, int b) { return a + b; }
extern int external_var;
int call_add() { return add(1, 2) + external_var; }The function add is a symbol. When compiled to machine code, the code for call_add() contains a reference to the symbol add: something like “jump to the address of function add”. At compile time, the compiler does not know that address. It leaves a placeholder.
A symbol table maps symbol names to addresses. When the linker loads the .so file, it looks up each symbol it needs and fills in the actual addresses.
There is no single merged table. Each library carries its own symbol table in the binary, listing what it defines and exports and what it needs from elsewhere. On Linux, the dynamic linker searches those tables in order: first the global scope (the executable, the libraries it was linked with, and any library opened with RTLD_GLOBAL), then the scope of the library being loaded. A Windows DLL works differently: its import table names, for each symbol, the DLL that must supply it, such as R.dll.
When R calls dyn.load("mypackage.so"), the operating system’s dynamic linker reads the file, looks up each undefined symbol in those scopes, and fills in the addresses.
7.4.3 Load-time versus runtime resolution
Symbol resolution can happen at load time or at runtime. GNU R asks for load-time resolution.
dyn.load() defaults to now = TRUE, which on Unix-alikes passes RTLD_NOW to dlopen(): the linker resolves every undefined symbol before dlopen() returns, and if any is missing it reports an error and the library does not load. A Windows DLL’s ordinary imports are resolved at load as well.
This costs a little more at load time, and it makes the failure immediate. A missing symbol stops the load, with its name in the error, instead of crashing the first call that needs it.
Lazy binding (RTLD_LAZY) defers each function’s lookup until the first call. Programs start faster, because most functions in a large library are never called, but a missing function only shows up when the call is made, and the process dies there.
GNU R loads package libraries with dyn.load(local = TRUE, now = TRUE) by default, which becomes RTLD_LOCAL | RTLD_NOW on Unix-alikes. Every symbol in a compiled package must be resolvable when the package loads. If a symbol cannot be found, dyn.load() fails.
7.4.4 Symbol lookup and registration
When a compiled package loads, the linker needs to find several classes of symbols:
Libc functions:
malloc(),printf(),strlen(). These are defined in the C runtime library and are always available.C API functions:
Rf_allocVector(),Rf_protect(),Rf_eval(). These are entry points into the R runtime.Package-internal symbols: functions defined within the package that call each other.
Third-party libraries: if the package links to OpenSSL, BLAS, or other libraries.
The libc and C API symbols come from what the running R process has already loaded.
Where R’s own functions live depends on the platform and the build. On Windows they are in R.dll, and Rterm.exe and Rgui.exe are small front-ends that load it. On Unix-alikes, the default build compiles them into the R executable, which exports them for packages to find. A build configured with --enable-R-shlib puts them in a shared library, libR.so, and links packages against it; the macOS framework build implies that option.
Compiled packages link to these symbols at load time. The linker resolves Rf_allocVector to its address in R’s executable or library, and every later call to Rf_allocVector() from the package uses that same address.
7.4.5 Symbol registration and visibility
Not every function in a library is exported. Symbols can be marked public or private.
In C, the first control is the static keyword. A static function is local to its translation unit and is not exported. With the usual toolchain defaults, a function without static is exported, unless the library is built with -fvisibility=hidden (and the exceptions marked visible) or, on Windows, with a .def file that lists the exports. “Writing R Extensions” describes both, under “Controlling visibility”.
When a library is compiled, the linker marks exported symbols in the library’s symbol table. The dynamic linker uses this metadata. When loading a package, the linker only looks at exported symbols from libraries.
Symbol registration is R’s version of the same idea, one level up. The package author lists which C functions R code may call:
static const R_CallMethodDef callMethods[] = {
{"myFunc", (DL_FUNC) &myFunc, 2},
{NULL, NULL, 0}
};
void R_init_mypackage(DllInfo *dll) {
R_registerRoutines(dll, NULL, callMethods, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}Because of the R_useDynamicSymbols(dll, FALSE) call, only functions listed here are callable from R code; without it, R falls back to looking up any exported symbol by name. The routines are registered at load time. From then on, R can call them by name.
With registration in place, a package needs only one exported symbol, its R_init_<pkg> function. R’s own stats package is built that way.
7.4.6 Two libraries, one symbol name
Suppose two packages both export a function named helper(), and R loads both.
Under R’s defaults, each package keeps its own. dyn.load() opens a package library with RTLD_LOCAL, so its symbols are not added to the global scope, and a library loaded later never resolves a name against them.
Shadowing still happens in two cases. A library opened with dyn.load(local = FALSE) puts its symbols in the global scope, ahead of every later library’s own definitions. And a package that defines a function with the same name as one in the global scope, such as a function in R itself or in a library R loaded at startup, can find its own calls bound to that other definition, because on Linux the dynamic linker searches the global scope first. The linker gives no warning when this happens.
Symbol visibility helps here. A symbol marked hidden stays local to its library, and “Writing R Extensions” notes that hiding symbols reduces “the possibility of linking to other entry points of the same name”. But the package author has to opt in.
When a package library defines a symbol that also exists in the global scope, the dynamic linker can bind the package’s own references to the global definition. This shadowing is silent and can cause corruption if the two functions have different semantics.
R namespaces do not help with this: they separate R objects, not C symbols. What keeps the C symbols of two packages separate is the RTLD_LOCAL default, and on Windows the import table, which names the DLL each symbol must come from.
7.4.7 Finding R’s entry points across versions
R publishes a C API, and the two counts involved are not the same. R 4.6.1 on Windows exports 1,413 symbols from R.dll. “Writing R Extensions” documents a much smaller subset as the interface packages may use. The rest are exported because the Windows build exports every global symbol in R’s object files except those on a hide list, src/gnuwin32/Rdll.hide. Nothing promises them to anyone.
On Windows the package’s import table names R.dll as the source of each R symbol, and the loader looks there. On Linux the linker finds them in the global scope, where R’s executable or libR.so sits from the moment the process starts.
This works for load-time linking. But it creates a hard dependency on the names. The binary carries an unresolved reference for every R function it calls, and the loader has to find each one. What is burned in is the spelling, not the address. Where R happens to sit in memory is the loader’s problem, and relocation solves it.
The addresses also depend on which version of R is running. If R changes the implementation of Rf_allocVector() but keeps the name, the symbol resolves to the new address. This is usually fine. But if the new implementation behaves differently in a way the package depends on, the package can silently compute wrong results.
7.4.8 Relocation and position-independent code
Modern compiled binaries use position-independent code (PIC) or position-independent executables (PIE). This means the binary does not assume it is loaded at a specific address.
Position-independent code on Linux reaches every address it cannot know in advance through a table, the global offset table (GOT), instead of writing the address into its instructions. Relocation entries in the binary say which table slots need which symbol or offset, and at load time the dynamic linker fills them in.
This happens at load time, once per library. It is invisible to the package author. The code pages stay exactly as they are in the file, so the operating system can share them between processes; only the table and other data pages differ from the file on disk.
7.4.9 Dependency chains and circular references
A complex package can depend on several other packages. R handles that at the package level, before any linker is involved: loading package A’s namespace first loads the namespaces it imports, B and C, and their dependencies.
If B and C both depend on D, D is loaded once and shared. R keeps a registry of loaded namespaces, and the dynamic linker keeps a reference count for each library it has opened, so neither loads anything twice.
Circular package dependencies are refused. If A imports B and B imports A, loadNamespace() stops with “cyclic namespace dependency detected”. The dynamic linker itself copes with a cycle among shared libraries, because it loads each one once.
A multithreaded R with per-interpreter state may want different packages loaded in different interpreters. The dynamic linker loads each shared library once per process, so two interpreters that load the same package share its code and its C global variables, even when each has its own R namespace for it. This complicates dependency resolution.
7.4.10 The failure modes
Symbol resolution can fail in several ways:
Undefined symbol: the linker cannot find a symbol anywhere. The package does not load.
Symbol mismatch: the symbol exists but has the wrong type or calling convention. The linker often does not detect this at load time. Corruption happens at runtime.
Version mismatch: the symbol exists but is from a different version of the library with a different implementation. Behavior is undefined.
Circular dependency: two packages import each other. R refuses to load them.
Symbol shadowing: a package defines a symbol that also exists in the global scope. The linker silently binds to one of them, potentially the wrong one.
Errors 1 and 4 are caught and reported. Errors 2, 3, and 5 are silent. Debugging them requires reading the binary or using tools like nm or objdump to inspect symbols.
Further reading
- Writing R Extensions <https://cran.r-project.org/doc/manuals/r-release/R-exts.html>, chapter 5 (System and foreign language interfaces), and chapter 6 (The R API), in its section on controlling visibility <https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Controlling-visibility>.
- dlopen(3) <https://man7.org/linux/man-pages/man3/dlopen.3.html>, the Linux manual page for
RTLD_NOW,RTLD_LAZY,RTLD_LOCALandRTLD_GLOBAL. - System V AMD64 ABI <https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI>, sections on dynamic linking and relocation.
- The ELF specification <https://refspecs.linuxbase.org/elf/elf.pdf>, formal details of executable and shared object files.
Where this appears
- threaded-r Symbol resolution at load time is unchanged. R’s dyn.load() is patched so native code loads into the first interpreter only, unless the package declares itself safe for more than one.
- r-in-rust (rrs) Symbol resolution in the compatibility layer must replicate GNU R’s mechanism exactly.