diff --git a/.build/.gitignore b/.build/.gitignore new file mode 100644 index 0000000..7c9d611 --- /dev/null +++ b/.build/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!README.md diff --git a/.build/README.md b/.build/README.md new file mode 100644 index 0000000..e69de29 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 317e5cc..82d685d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -196,6 +196,16 @@ jobs: # muparser — Algorithmic API (gdal_global_reg_names fix) # pkgconf — pkg-config shim used by cmake find-modules # ntldd — walk PE import tree to find transitive DLL deps + # + # hdf5, netcdf — HDF5/NetCDF raster drivers (their DLL chains, + # incl. libopenblas/libgfortran, load cleanly in R; + # verified empirically 2026-07) + # + # NOTE: mingw-w64-ucrt-x86_64-gdal transitively installs podofo and + # poppler into /ucrt64 regardless of this list, so the PDF driver is + # disabled at cmake level (GDAL_ENABLE_DRIVER_PDF=OFF in build_gdal.sh): + # the MSYS2 libpodofo.dll fails DllMain (ERROR_DLL_INIT_FAILED 1114) in + # any process, which would make libgdal itself unloadable. - name: Setup MSYS2 UCRT64 id: msys2 uses: msys2/setup-msys2@v2 @@ -219,12 +229,11 @@ jobs: mingw-w64-ucrt-x86_64-curl mingw-w64-ucrt-x86_64-zlib mingw-w64-ucrt-x86_64-muparser - mingw-w64-ucrt-x86_64-arrow mingw-w64-ucrt-x86_64-hdf5 mingw-w64-ucrt-x86_64-netcdf + mingw-w64-ucrt-x86_64-arrow mingw-w64-ucrt-x86_64-geos mingw-w64-ucrt-x86_64-libspatialite - mingw-w64-ucrt-x86_64-poppler mingw-w64-ucrt-x86_64-openjpeg2 mingw-w64-ucrt-x86_64-libwebp mingw-w64-ucrt-x86_64-libjxl @@ -323,6 +332,37 @@ jobs: Select-Object Name, @{N='MB';E={[math]::Round($_.Length/1MB,2)}} | Sort-Object Name | Format-Table -AutoSize + # ── 7b. Smoke-test DLL loadability ──────────────────────────────────── + # LoadLibrary every bundled DLL in a plain Windows process. This catches + # DllMain initialization failures (ERROR_DLL_INIT_FAILED, 1114) before a + # broken bundle can be published — the exact failure mode that shipped + # in July 2026 when MSYS2's libpodofo.dll started failing DllMain and + # made libgdal-*.dll unloadable in every consumer process, including R. + # File-presence checks alone cannot detect this class of breakage. + - name: Smoke-test bundle DLL loadability + shell: pwsh + run: | + $bin = Join-Path $PWD "gdal-bundle\bin" + $env:PATH = "$bin;$env:PATH" + $sig = @' + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern IntPtr LoadLibraryW(string path); + '@ + $k32 = Add-Type -MemberDefinition $sig -Name Loader -Namespace Smoke -PassThru + $failures = @() + foreach ($dll in (Get-ChildItem "$bin\*.dll" | Sort-Object Name)) { + $h = $k32::LoadLibraryW($dll.FullName) + if ($h -eq [IntPtr]::Zero) { + $code = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + $failures += "$($dll.Name) (Win32 error $code)" + } + } + if ($failures.Count -gt 0) { + Write-Error ("FATAL: bundled DLLs failed to load:`n " + ($failures -join "`n ")) + exit 1 + } + Write-Host "✓ All $((Get-ChildItem "$bin\*.dll").Count) bundled DLLs load cleanly (no DllMain failures)" + # ── 8. Upload bundle as workflow artifact (always) ──────────────────── # compression-level: 0 — DLLs are already-compressed PE binaries. # Re-compressing wastes 30-60s and gains <5%. @@ -375,6 +415,8 @@ jobs: | `GDAL_HIDE_INTERNAL_SYMBOLS` | `ON` | Cleaner export table | | `--kill-at` | (linker) | Correct stdcall symbol decoration for MinGW DLLs | | Static GCC/stdc++/winpthread | (linker) | No Rtools or MSYS2 required at runtime | + | `GDAL_ENABLE_DRIVER_PDF` | `OFF` | MSYS2 libpodofo.dll fails DllMain (ERROR_DLL_INIT_FAILED 1114) in any process, making libgdal unloadable; poppler/podofo/pdfium backends all disabled | + | Loadability gate | (CI) | Every bundled DLL is LoadLibrary-tested in CI before publishing | ### Runtime bundle asset Download: diff --git a/.gitignore b/.gitignore index 7ab329b..216c16a 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,6 @@ .Renviron inst/doc .positai -.build/ inst/extdata/gdal-ucrt64-fallback.zip -docs +/docs/ **/.quarto/ diff --git a/DESCRIPTION b/DESCRIPTION index 5f53b41..4679aaa 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: gdalraster.windows Title: Windows GDAL Runtime and gdalraster Bootstrap Tools -Version: 0.3.0.9000 +Version: 0.3.1 Authors@R: person("Jimmy", "Briggs", , "jimmy.briggs@jimbrig.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0002-7489-8787")) diff --git a/NEWS.md b/NEWS.md index 0e8723f..5b10f0a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,4 +1,10 @@ -# gdalraster.windows (development version) +# gdalraster.windows 0.3.1 + +## GDAL runtime bundle + +- Fixed the bundle-wide `LoadLibrary failure: A dynamic link library (DLL) initialization routine failed` (Windows error 1114) that made published bundles unloadable on machines without Rtools' UCRT64 tree. Root cause: the MSYS2 `libpodofo.dll` (PDF driver backend) fails its `DllMain`-time OpenSSL initialization against the MSYS2 `libcrypto-3-x64.dll`. The PDF driver is now disabled outright (`GDAL_ENABLE_DRIVER_PDF=OFF` plus the poppler/podofo/pdfium backends). +- HDF5 and NetCDF drivers are enabled again; the earlier theory that their OpenBLAS/Fortran dependency chain conflicts with R's own DLLs was disproven empirically (every DLL in that chain loads cleanly inside R). +- Bundle verification now has three layers: dependency closure (`ntldd` walk plus a banned-DLL guard for PDF/NSS chains in `collect_dlls.sh`), loadability (every bundled DLL is `LoadLibrary`-tested in CI before an asset can publish), and functionality (the e2e workflow runs on every published bundle release). ## Fixes @@ -160,3 +166,5 @@ - Initial development version: GDAL runtime bundle install/activation helpers, `gdalraster` source-build integration, startup hooks, and the Windows CI build pipeline. + + diff --git a/README.md b/README.md index 5523b5f..274d778 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![R CMD CHECK](https://github.com/jimbrig/gdalraster.windows/actions/workflows/check.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/check.yml) [![Build GDAL (Windows)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/build.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/build.yml) +[![E2E Runtime Verification](https://github.com/jimbrig/gdalraster.windows/actions/workflows/e2e.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/e2e.yml) [![Build Package Website](https://github.com/jimbrig/gdalraster.windows/actions/workflows/pkgdown.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/pkgdown.yml) [![Automate Changelog](https://github.com/jimbrig/gdalraster.windows/actions/workflows/changelog.yml/badge.svg)](https://github.com/jimbrig/gdalraster.windows/actions/workflows/changelog.yml) diff --git a/dev/archive/.gitignore b/dev/archive/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/dev/archive/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/dev/docs/00-the-full-picture.md b/dev/docs/00-the-full-picture.md new file mode 100644 index 0000000..5707072 --- /dev/null +++ b/dev/docs/00-the-full-picture.md @@ -0,0 +1,85 @@ +# the full picture + +> [!NOTE] +> Start here. This is the narrative that connects everything: what problem +> this project solves, why every major design decision was forced rather +> than chosen, and what guarantees the system provides today. It assumes a +> senior engineer who does not need to know Windows C++ internals up front — +> concepts are introduced when the story needs them, and +> [`08-windows-dll-abi-deep-dive.md`](08-windows-dll-abi-deep-dive.md) has +> the full mechanics when you want them. + +## the one-paragraph version + +`gdalraster` needs a modern GDAL with the Algorithm API (muparser), which the R toolchain's own GDAL doesn't provide. Because `gdalraster` binds GDAL's **C++** API, and C++ has no cross-compiler binary standard, the GDAL it links must come from the same compiler family as R's Windows toolchain (MinGW/UCRT) — ruling out every convenient prebuilt GDAL (conda, OSGeo4W, vcpkg: all MSVC). So this project builds GDAL from source with MinGW in CI, ships it with its complete DLL closure as a versioned bundle, rebuilds `gdalraster` from source against that bundle on the user's machine, and manages the Windows loader at session startup so the right DLLs resolve. Each of those clauses exists because something broke without it. + +## act 1: the original problem (May 2026) + +`gdalraster::gdal_global_reg_names()` returned `character(0)` on Windows — the GDAL Algorithm API registry was empty. Two upstream causes: + +1. GDAL's algorithm registration uses C++ static constructors, which some static-linking toolchains dead-code-eliminated ([firelab/gdalraster#826](https://github.com/firelab/gdalraster/issues/826), fixed upstream in GDAL 3.12.2 via [OSGeo/gdal#13592](https://github.com/OSGeo/gdal/pull/13592)). +2. Rtools' bundled GDAL lacked muparser, which parts of the Algorithm API require. + +The fix that worked ([firelab/gdalraster#982](https://github.com/firelab/gdalraster/issues/982), reproduced in the original runbook kept locally under `dev/archive/`): build GDAL 3.13 from source in the Rtools45 UCRT64 shell with `GDAL_USE_MUPARSER=ON`, point `gdalraster` compilation at it via Makevars, and make the DLLs resolvable at runtime via PATH + preload in `.Rprofile`. + +That manual setup (`C:/gdal-ucrt64` + `C:/rtools45/ucrt64/bin` on PATH) is the ancestor of everything in this repo. Understanding *why it worked so reliably* took until July: all of its dependency DLLs came from one internally coherent, curated package set (Rtools45's ucrt64 tree). The productized bundle kept breaking precisely where it departed from that property. + +## act 2: why the design looks the way it does + +Each design element is a response to a constraint. In order: + +**Why build GDAL with MinGW at all, instead of using an existing GDAL?** R packages on Windows are compiled by Rtools, which is MinGW-GCC targeting UCRT. `gdalraster` binds GDAL's C++ classes (not a C shim), and C++ has no standard ABI: MSVC and GCC differ in name mangling, exception handling, class layout, and STL types. An MSVC GDAL (conda-forge/pixi, OSGeo4W, vcpkg) is not linkable from Rtools-compiled code — the symbols don't even have the same names. So the GDAL must be MinGW-built. (Deep dive §4.) + +**Why build in CI with MSYS2 rather than require users to build locally?** The manual runbook takes an hour and a toolchain install. CI builds once, publishes a versioned artifact, and every machine consumes the same bytes. The cost: MSYS2 is a rolling release, so the build environment's package set changes under us between builds — the root of two of the three production incidents (below). + +**Why ship a "bundle" (DLL closure) instead of just `libgdal-*.dll`?** The import table of `libgdal-39.dll` names ~78 direct dependency DLLs, with hundreds transitive. On the build machine they live in `/ucrt64/bin`; user machines don't have that. `tools/collect_dlls.sh` walks the import tree (`ntldd -R`) and copies everything non-Windows into `bundle/bin`, then fails the build if anything remains unresolved. (Deep dive §2, §8.) + +**Why rebuild `gdalraster` from source on the user's machine?** Same C++ ABI logic one level up: `gdalraster.dll` must be compiled against the bundle's GDAL headers and linked to its import library. The CRAN binary is linked (statically) against Rtools' own GDAL — different GDAL, no Algorithm API. `install_gdalraster()` does the source build with scoped Makevars (`withr::with_makevars`), so nothing persists in user config. + +**Why does the package manage `PATH`/preload at session start?** Compile-time linking and run-time loading are separate systems. At `library(gdalraster)`, the Windows loader must resolve `libgdal-39.dll` and its entire closure *at that moment*, by base name, through the DLL search order. `activate_gdal_runtime()` prepends the bundle's `bin/` to `PATH`, sets GDAL/PROJ data variables, and preloads `libgdal` into the process so every later request reuses it (first-loaded-wins rule). (Deep dive §2.) + +**Why is everything non-destructive/isolated by default?** The runtime installs under `tools::R_user_dir()` paths and `gdalraster` goes to an isolated library, because the target machines often *also* have the manual `C:/gdal-ucrt64` stack, CRAN sf/terra (which embed their own static GDAL), and unrelated GDALs (pixi/conda). Base-name collisions between GDAL stacks in one process are resolved by load order, so the package never wants to win by overwriting — only by activating first in sessions that opt in. + +## act 3: the three production incidents + +Every incident was a *distribution* failure, not a build failure — the DLL compiled and linked fine each time. This is the pattern to internalize: on Windows, the hard part is not producing a binary, it is controlling the environment the binary meets. + +| # | Incident | Mechanism | Countermeasure now in place | +|---|---|---|---| +| 1 | `msodbcsql17.dll` (June, #13) | GDAL's cmake auto-detected the SQL Server ODBC SDK on the GitHub runner and linked it; bundle verification blanket-trusted System32, where that DLL exists on runners but not user machines | `GDAL_USE_MSSQL_ODBC/NCLI=OFF`; verifier denies known vendor DLLs in System32 | +| 2 | Missing-module failures during early adoption | Transitive DLLs absent from `PATH` at load time in sessions without activation | loud preload failure in `activate_gdal_runtime()`; troubleshooting flow | +| 3 | `ERROR_DLL_INIT_FAILED` 1114 (July, e2e) | MSYS2's `libpodofo.dll` runs OpenSSL setup in its static initializers (DllMain, under loader lock) and fails against MSYS2's `libcrypto` — in every process; `libgdal` imported podofo because MSYS2's gdal package pulls it in and cmake auto-detected it | PDF driver disabled outright (`GDAL_ENABLE_DRIVER_PDF=OFF` + all backends); banned-DLL guard in `collect_dlls.sh`; LoadLibrary smoke gate in `build.yml` | + +Incident 3 deserves its own moral because it defeated the existing verification: the bundle was *complete* (every import resolved — `ntldd` proved it) but not *loadable* (one DLL failed initialization). Static inspection of any kind cannot catch that class; only actually loading the DLLs can. Hence the three-layer gate that now guards every release: + +1. **closure** — `ntldd` walk + banned-DLL regex (`collect_dlls.sh`) +2. **loadability** — `LoadLibrary` over every bundled DLL in a plain process (`build.yml` step 7b), before anything is published +3. **functionality** — the e2e workflow runs the full documented user flow on a clean Windows runner whenever a bundle release is published + +A secondary moral: incident 3 was initially misdiagnosed (blamed on an HDF5→OpenBLAS→Fortran conflict with R's own DLLs) and the wrong fix was merged before empirical bisection found podofo. Ten minutes of `LoadLibrary` sweeps beat hours of dependency-graph theory. When a DLL question arises, load things and observe. + +## act 4: what "working" means today + +The system is working when all of these hold: + +- `build.yml` produces a bundle that passes closure + loadability gates and publishes it as a `gdal-v*` release asset +- `install_gdal_runtime()` + `install_gdalraster()` + `verify_gdalraster_runtime()` succeed on a clean machine (proven weekly and per-release by `e2e.yml`) +- `gdalraster::gdal_global_reg_names()` returns a non-empty registry, and the embedded-python path (`gdal driver gpkg validate`) can import `osgeo_utils` + +The moving parts most likely to break it again, in likelihood order: + +1. **MSYS2 package churn** — a dependency's new build fails DllMain or changes behavior (incident 3's class). Caught by the loadability gate. +2. **GDAL cmake auto-detection drift** — a new optional dependency appears in the build env and gets linked (incident 1's class). Caught partially by the banned-DLL guard; watch the "disabled features" cmake summary on version bumps. +3. **GDAL soname bump** (`libgdal-40.dll` for 3.14) — everything discovers the DLL by glob, but rebuilt `gdalraster` is required per bundle. +4. **Rtools GCC major-version jumps** — GCC's C++ ABI is backward-compatible in practice, and the bundle statically embeds its own libstdc++, but a jump is the right time to rerun e2e before trusting local results. + +## reading map + +| You want | Read | +|---|---| +| Use the package | `vignettes/getting-started.qmd` → `runtime-guide.qmd` (canonical, on pkgdown) | +| Fix a broken session | `vignettes/troubleshooting.qmd`, then `05-troubleshooting.md` | +| Understand the design | this file, then `vignettes/architecture.qmd` | +| Understand Windows DLL/ABI mechanics | [`08-windows-dll-abi-deep-dive.md`](08-windows-dll-abi-deep-dive.md) | +| Change the build/CI | `03-ci-and-release.md`, comments in `tools/build_gdal.sh` and `.github/workflows/build.yml` (the comments are the authoritative rationale) | +| Historical archaeology | `07-*`, `dev/archive/` (session-specific; never treat as current) | \ No newline at end of file diff --git a/dev/docs/05-troubleshooting.md b/dev/docs/05-troubleshooting.md index 63e4c9d..63b83c3 100644 --- a/dev/docs/05-troubleshooting.md +++ b/dev/docs/05-troubleshooting.md @@ -36,7 +36,9 @@ First actions: ### `LoadLibrary` failure on package load -Most likely: +Two distinct classes — read the error text carefully: + +**"The specified module could not be found" (error 126)** - missing transitive DLLs in runtime `bin` - profile/path setup points to mixed toolchain DLLs @@ -52,6 +54,21 @@ Example: Rscript -e "gdalraster.windows::activate_gdal_runtime(); library(gdalraster); print(length(gdalraster::gdal_global_reg_names()))" ``` +**"A dynamic link library (DLL) initialization routine failed" (error 1114)** + +- a dependency DLL is present and resolvable but its `DllMain`/static + initializers fail; closure checks (`ntldd`) cannot catch this +- behavior can depend on which copy of a sub-dependency got loaded first + (e.g. libpodofo's OpenSSL init fails against MSYS2 libcrypto but succeeds + against Rtools45's — July 2026 incident) + +First actions: + +- sweep-load every bundle DLL individually (`dyn.load` loop or plain + `LoadLibrary`) to find the one that fails to initialize +- see `08-windows-dll-abi-deep-dive.md` sections 3 and 7 for mechanics and + the bisect method + ### embedded-python algorithm fails with `ModuleNotFoundError: No module named 'osgeo_utils'` Applies to GDAL algorithms implemented in Python, e.g. `driver gpkg validate`. diff --git a/dev/docs/06-toolchain-and-abi.md b/dev/docs/06-toolchain-and-abi.md index 079f675..85eadde 100644 --- a/dev/docs/06-toolchain-and-abi.md +++ b/dev/docs/06-toolchain-and-abi.md @@ -81,6 +81,16 @@ Current key flags and their intent: - `-DGDAL_HIDE_INTERNAL_SYMBOLS=ON` reduces exported symbol surface and avoids export-table pressure on Windows. +- `-DGDAL_ENABLE_DRIVER_PDF=OFF` (+ `GDAL_USE_POPPLER/PODOFO/PDFIUM=OFF`) + excludes the PDF driver and all its backends. MSYS2's `libpodofo.dll` + fails `DllMain` (error 1114) against the MSYS2 `libcrypto`, which made + the whole `libgdal-*.dll` unloadable in bundles published before July + 2026. See `08-windows-dll-abi-deep-dive.md` §3 for the full mechanics. + +- `-DGDAL_USE_MSSQL_ODBC=OFF`, `-DGDAL_USE_MSSQL_NCLI=OFF` + prevents linking the proprietary SQL Server ODBC driver present on CI + runner images but absent on end-user machines (issue #13). + - `-Wl,--kill-at` adjusts MinGW stdcall export decoration behavior for cleaner export names. diff --git a/dev/docs/08-windows-dll-abi-deep-dive.md b/dev/docs/08-windows-dll-abi-deep-dive.md new file mode 100644 index 0000000..f4cc94d --- /dev/null +++ b/dev/docs/08-windows-dll-abi-deep-dive.md @@ -0,0 +1,187 @@ +# windows dll loading and abi deep dive + +> [!NOTE] +> Learning-oriented deep dive written after the July 2026 e2e failure +> investigation. It uses this project's real failures as case studies to +> explain how compilation, linking, DLL loading, and ABI compatibility +> actually work on Windows — and why the MinGW/UCRT/CMake path is more +> nuanced than MSVC. Non-normative; see `vignettes/architecture.qmd` for the +> canonical user-facing material. + +## 1. the pipeline: compile → link → load + +Three distinct phases, each with its own failure modes. Most confusion comes from conflating them. + +### compile + +Source files become object files (`.o`). The compiler only needs *headers*. Nothing about DLLs matters yet. A successful compile proves the API (declarations) matched — nothing more. + +### link + +The linker (`ld` in MinGW, `link.exe` in MSVC) combines object files and resolves symbol references. For every symbol your code uses, the linker must find a definition in either: + +- another object file / static library (`.a`, `.lib`) — the code is copied into your binary, or +- an **import library** (`.dll.a` in MinGW, `.lib` in MSVC) — a thin stub that says "this symbol lives in `libgdal-39.dll`; emit an import table entry for it." + +The output DLL/EXE therefore contains an **import table**: a list of `(dll base name, symbol)` pairs. Inspect it with: + +```bash +objdump -p libgdal-39.dll | grep "DLL Name" +``` + +Key point: the import table records only the **base name** (`libpodofo.dll`), never a path. Where the file comes from at runtime is decided entirely by the loader (section 2). + +Windows-specific link concerns handled in `tools/build_gdal.sh`: + +- **exports and ordinals** — a PE DLL exposes symbols through an export table capped at 65,535 ordinals. GDAL's full C++ symbol set exceeds that, hence `-DGDAL_HIDE_INTERNAL_SYMBOLS=ON` (see [OSGeo/gdal#4706](https://github.com/OSGeo/gdal/issues/4706)). MSVC builds hit the same limit but the default there is already to export nothing unless annotated — MinGW's default (export everything) is what creates the pressure. +- **`-Wl,--kill-at`** — MinGW decorates `__stdcall` exports as `name@N`; this strips the decoration so lookups by plain name succeed. +- **static runtime embedding** — `-static-libgcc -static-libstdc++` plus whole-archive `winpthread` copies the GCC runtime *into* `libgdal`, so the DLL doesn't import `libgcc_s_seh-1.dll`/`libstdc++-6.dll` at all. (Compare: the manual `C:/gdal-ucrt64` build from [firelab/gdalraster#982](https://github.com/firelab/gdalraster/issues/982) did not use these flags and imports all three dynamically from `C:/rtools45/ucrt64/bin`.) + +### load + +At `LoadLibrary` time (which is what R's `dyn.load()` calls), the Windows loader: + +1. reads the import table of the requested DLL +2. recursively resolves every dependency (section 2) +3. maps them all into the process +4. runs each module's **`DllMain`** initialization (section 3) + +Steps 2 and 4 are where every failure in this project has lived. A build that compiles and links perfectly can still fail both. + +## 2. how the loader resolves dependencies + +For each base name in the import table: + +1. **already-loaded module list** — if a module with that base name is already in the process, it is reused. Full stop. This is the "first-loaded wins" rule: once *any* `libgdal-39.dll` is loaded, every later request for `libgdal-39.dll` gets that copy, regardless of PATH. This is why mixing the manual `C:/gdal-ucrt64` stack and the package-managed bundle in one R session is dangerous. +2. **API sets** — names like `api-ms-win-crt-heap-l1-1-0.dll` are virtual; the loader maps them to the real UCRT (`ucrtbase.dll`) via the API set schema. They always resolve on supported Windows; never bundle them. +3. **search order** — application directory, `System32`, the `PATH` entries, in order. R packages rely on `PATH` (or `AddDllDirectory`-style mechanisms), which is why `activate_gdal_runtime()` prepends `/bin` to `PATH` before anything touches GDAL. + +Failure at this stage → `LoadLibrary failure: The specified module could not be found.` (Win32 error 126). Note the misleading message: it names the DLL you *asked for*, not the missing transitive dependency five levels down. `ntldd -R` (or a manual BFS over `objdump -p` output) is how you find the real culprit. + +## 3. DllMain, static initializers, and error 1114 + +After mapping, each module gets a `DllMain(DLL_PROCESS_ATTACH)` call — made while the loader holds the global **loader lock**. For C++ DLLs, this is also when all namespace-scope constructors ("static initializers") run. + +If `DllMain` returns `FALSE` or an initializer throws, the *entire* `LoadLibrary` call fails with Win32 error 1114: + +``` +LoadLibrary failure: A dynamic link library (DLL) initialization routine failed. +``` + +Properties that make this failure class nasty: + +- **import scanning cannot detect it.** The dependency exists, resolves, and maps fine. `ntldd` reports a perfectly closed bundle. Only actually loading the DLL reveals it. This is exactly why `build.yml` now has a LoadLibrary smoke-test step over every bundled DLL, in addition to the `ntldd` closure check. +- **it can be environment- and dependency-version-dependent.** Whatever the initializer does (open files, initialize crypto, query fonts) depends on process state and on which copies of *its* dependencies got loaded. +- **one bad module poisons the root load.** `libgdal` imports `libpodofo` directly, so podofo's failed init makes `libgdal` itself unloadable, even though 174 of the bundle's 175 DLLs are fine. + +### case study: the podofo × libcrypto failure (July 2026) + +Observed: published bundle's `libgdal-39.dll` fails with 1114 everywhere — clean CI runners *and* the dev machine, R sessions *and* plain PowerShell. + +Isolation (sweep-`LoadLibrary` every bundled DLL individually): only `libpodofo.dll` fails. Its imports all load fine individually. The binary is **byte-identical** (same SHA-256) to `C:/rtools45/ucrt64/bin/libpodofo.dll`, which loads fine. + +The difference: which `libcrypto-3-x64.dll` is in the process. PoDoFo runs OpenSSL initialization inside its static initializers (under the loader lock). Against Rtools45's libcrypto it succeeds; against the MSYS2-bundle libcrypto builds shipped in the June and July bundles it fails. Preloading Rtools45's libcrypto before loading the bundle's podofo makes everything load — same podofo bytes, different outcome. + +Resolution: the PDF driver is disabled outright (`-DGDAL_ENABLE_DRIVER_PDF=OFF` plus `GDAL_USE_POPPLER/PODOFO/PDFIUM=OFF`). Disabling only poppler is insufficient because the PDF driver silently falls back to the podofo backend. + +Moral: *a DLL is not a pure function of its bytes.* Its load behavior depends on the dependency graph the process resolves for it. + +## 4. C ABI vs C++ ABI + +### C: a de facto stable ABI + +C has a small, conventional binary interface per platform: fixed calling conventions, no name mangling (or trivial decoration), struct layout rules everyone agrees on. This is why every FFI in existence (R's `.Call`, Python ctypes, etc.) targets C, and why GDAL's *C API* (`gdal.h`, `ogr_api.h`) is consumable from any compiler. If `gdalraster` used only GDAL's C API, an MSVC-built GDAL DLL would in principle be linkable from MinGW-built R code. + +### C++: no standard ABI at all + +The C++ standard deliberately does not define a binary interface. Each compiler family invents its own for: + +- **name mangling** — GCC/MinGW uses the Itanium C++ ABI scheme (`_ZN4gdal...`), MSVC uses its own (`?name@class@@...`). Symbols from one simply do not exist under the other's names, so cross-linking fails at link time — the *good* outcome. +- **class layout** — vtable structure, virtual base offsets, member ordering, empty-base optimization details. +- **exception handling** — MSVC uses SEH-based C++ exceptions; MinGW x86_64 uses SEH frames too but with GCC's own personality routines; an exception thrown by one runtime cannot be caught by the other. +- **standard library types** — `std::string`/`std::vector` from MSVC's STL and GCC's libstdc++ are different types with different layouts and different allocators. Passing them across a compiler boundary is undefined behavior even when everything links. +- **heap/CRT coupling** — memory allocated by one CRT must be freed by the same CRT. Cross-runtime `new`/`delete` corrupts heaps. + +`gdalraster` binds GDAL's **C++ API** (Algorithm API classes and more). Therefore GDAL and `gdalraster` must be built by the *same compiler family with compatible versions and the same CRT*. This single fact drives the whole architecture of this repo: MinGW UCRT64 GDAL + Rtools45 (also MinGW UCRT64) gdalraster, and never a prebuilt MSVC GDAL. + +GCC's own C++ ABI is stable-ish across versions (libstdc++ keeps backward compatibility), which is why an MSYS2 GCC 16 GDAL links from an Rtools45 GCC 14 gdalraster build — same mangling scheme, same libstdc++ family. The residual risk is forward-compat (old libstdc++ asked to satisfy new-GCC symbols), which static-linking libstdc++ into `libgdal` sidesteps. + +### the CRT dimension: msvcrt vs ucrt + +Windows historically had two C runtimes for MinGW targets: + +- `MSVCRT` — the ancient `msvcrt.dll`; MINGW64 environment targets it +- `UCRT` — the modern Universal C Runtime; UCRT64 environment and all of MSVC target it + +R ≥ 4.2 and Rtools42+ are UCRT. Everything in one process should share one CRT (per module; statically embedded copies are fine because their state is module-private). This repo pins UCRT64 everywhere. A MINGW64 (msvcrt) GDAL under a UCRT R would be a subtle-corruption machine. + +## 5. why mingw + cmake feels harder than msvc + +It isn't the compiler that's harder — it's the *distribution model*. + +| Concern | MSVC world (e.g. conda-forge/pixi) | MinGW/MSYS2 world (this repo) | +|---|---|---| +| Who assembles dependencies | Package manager with solver; a curated, mutually consistent set is installed per environment | `pacman` on a rolling release; whatever is in `/ucrt64` today is what cmake finds | +| Dependency detection | Same — cmake `find_package` — but the env contains only what you requested | cmake auto-detects *everything present*, including deps of unrelated packages (the MSYS2 `gdal` package's own dep tree: podofo, poppler, hdf4, …) | +| Runtime redistribution | Environment ships every DLL; activation sets PATH | You build the closure yourself (`collect_dlls.sh` + `ntldd`) | +| Version skew | Solver prevents mixing incompatible builds | CI MSYS2 vs local Rtools45 snapshot vs last month's CI can all differ (the libcrypto that broke podofo) | +| ABI for R packages | **Unusable** — R/Rtools is MinGW; MSVC C++ ABI is incompatible | Native fit — same toolchain family as Rtools | + +So the trade is forced: R's Windows toolchain is MinGW, `gdalraster` needs GDAL's C++ ABI, therefore GDAL must be MinGW-built — and with MinGW you inherit MSYS2's rolling-release packaging and DIY runtime closure. + +Concrete manifestations in this repo: + +- **auto-detection surprises**: CI runners had the MSSQL ODBC SDK installed → GDAL silently linked `msodbcsql17.dll` (issue #13). MSYS2's `gdal` package transitively installs podofo/poppler → the PDF driver got built against them even though we never asked. Countermeasures: explicit `GDAL_USE_*=OFF` / `GDAL_ENABLE_DRIVER_*=OFF` flags, plus the banned-DLL guard in `collect_dlls.sh`. +- **"present in the build env ≠ present on user machines"**: everything that resolves from `/ucrt64` at build time must be bundled or excluded. +- **"bundled ≠ loadable"**: closure verification (`ntldd`) is necessary but not sufficient; the smoke-load gate covers DllMain failures. + +## 6. the pixi/conda GDAL on this machine + +`where.exe gdal` → `C:\Users\jimmy\.pixi\bin\gdal.exe` is a conda-forge build: MSVC compiler, UCRT (all MSVC software is UCRT), dependencies managed by the conda solver inside the pixi environment. + +- It is a great *CLI* GDAL and completely healthy to keep. +- It can never back `gdalraster` (or `sf`/`terra` source builds): MSVC C++ ABI + MSVC import libraries (`gdal_i.lib`) are unusable from Rtools' MinGW toolchain (different mangling, different exception model, different STL). +- Coexistence is safe *between processes*. Within an R process, the only hazard is base-name collision (`gdal.exe`'s DLLs are named like `gdal.dll`, not `libgdal-39.dll`, so in practice they don't collide with the MinGW stack — but keep `.pixi/bin` *after* the GDAL runtime dirs in any PATH an R session uses). +- R packages from CRAN binaries (sf, terra, vapour) avoid all of this by statically linking their own GDAL *into* the package DLL — no shared `libgdal` at all, at the cost of no Algorithm API and duplicated code in memory. That's the design this repo's shared-runtime approach trades against, to get GDAL 3.13 + muparser + Arrow into `gdalraster`. + +## 7. failure-class cheat sheet + +| Symptom | Win32 error | Phase | Cause pattern | Diagnostic | +|---|---|---|---|---| +| `specified module could not be found` | 126 | dependency resolution | a *transitive* dep isn't on the search path (message names the root DLL, not the missing one) | `ntldd -R`, or `objdump -p` BFS; check PATH at the moment of load | +| `DLL initialization routine failed` | 1114 | DllMain | static initializer failed; often depends on *which copy* of a dependency got resolved | per-DLL `LoadLibrary` sweep; bisect by preloading alternate dependency copies | +| `%1 is not a valid Win32 application` | 193 | mapping | 32/64-bit mismatch or corrupt file | `objdump -f` (check `x86-64`) | +| entry point not found | 127 | symbol binding | version skew: DLL found, but lacks an export the importer expects | `objdump -p` exports vs imports diff | +| links fine, crashes at runtime | — | ABI | C++ ABI/CRT mismatch (wrong toolchain pairing) | check compiler provenance of every module in the process | + +## 8. verification toolbox + +What each tool proves — and what it cannot: + +- `objdump -p X.dll | grep "DLL Name"` — direct imports only. Fast, static. Cannot see transitive deps, delay-loads via `LoadLibrary` calls in code, or init failures. +- `ntldd -R X.dll` — recursive resolution using the *current environment's* PATH. Proves closure **for the machine and PATH you run it on** (this is why `ntldd-local.txt` from 2026-05-23 shows everything resolving to `C:\rtools45\ucrt64\bin` — that walk validated the dev machine, not a clean one). Cannot detect DllMain failures. +- `LoadLibrary` smoke test (now step 7b in `build.yml`) — proves every bundled DLL actually initializes in a plain process on a clean runner. Cannot prove R-session behavior or functional correctness. +- `dyn.load(dll, local = FALSE, now = TRUE)` in R — same as above but in the real consumer process, with R's own loaded-module state. +- e2e workflow — the only thing that proves the full documented user flow (`install_gdal_runtime()` → `install_gdalraster()` → `gdal_global_reg_names()` → `.Rprofile` hook) on a machine with no Rtools/MSYS2 leakage. + +Layered together these now gate every release: import closure (`ntldd` + banned-DLL regex) → loadability (smoke test) → functionality (e2e on release publish). + +## 9. project failure history in one table + +| Date | Failure | Class | Fix | +|---|---|---|---| +| 2026-05 (pre-repo, #982) | `character(0)` from `gdal_global_reg_names()` | build composition (no muparser in Rtools GDAL) | custom GDAL with `GDAL_USE_MUPARSER=ON` | +| 2026-05 | `module could not be found` at load | runtime search path | PATH activation + DLL preload (`activate_gdal_runtime()`) | +| 2026-06 (#13) | bundle worked in CI, failed on user machine | env-leak linkage: `msodbcsql17.dll` auto-detected on runner + verifier allowlisted System32 blanketly | `GDAL_USE_MSSQL_ODBC/NCLI=OFF`; `denied_system_regex` in verifier | +| 2026-07 (e2e, PR #22 era) | error 1114 on every clean machine | DllMain failure: podofo static init × MSYS2 libcrypto | `GDAL_ENABLE_DRIVER_PDF=OFF` (+ all PDF backends off); banned-DLL guard; LoadLibrary smoke gate in CI | + +Misdiagnosis note: PR #22 attributed the 1114 to an HDF5 → OpenBLAS → libgfortran/libgomp conflict with DLLs "already loaded by R". Empirical testing (loading all 175 bundle DLLs individually inside R 4.6.1) disproved this — the entire HDF5/OpenBLAS/Fortran chain loads cleanly, and R does not pin conflicting copies of those DLLs at startup. HDF5/NetCDF are therefore enabled in the build. The lesson generalizes: on Windows DLL questions, prefer a 10-minute empirical `LoadLibrary` bisect over dependency-graph theorizing; the loader has too many moving parts to reason about reliably from static inspection alone. + +## 10. further reading + +- Windows loader search order: Microsoft "Dynamic-link library search order" +- DllMain constraints: Microsoft "Dynamic-Link Library Best Practices" (why nontrivial work under the loader lock is dangerous — the exact trap podofo fell into) +- Itanium C++ ABI (the spec GCC/MinGW mangling follows) +- MSYS2 environments documentation (UCRT64 vs MINGW64 vs CLANG64) +- R Installation and Administration manual, "The Windows toolchain" (UCRT transition in R 4.2) +- GDAL building-from-source docs (driver/`GDAL_USE_*` option semantics) \ No newline at end of file diff --git a/dev/docs/README.md b/dev/docs/README.md index 6cca2fd..a7327ea 100644 --- a/dev/docs/README.md +++ b/dev/docs/README.md @@ -19,6 +19,8 @@ Canonical published docs: ## Recommended reading order (these notes) +0. [`00-the-full-picture.md`](00-the-full-picture.md) — start here: the + narrative connecting every design decision to the failure that forced it 1. [`01-overview.md`](01-overview.md) 2. [`06-toolchain-and-abi.md`](06-toolchain-and-abi.md) 3. [`02-runtime-model.md`](02-runtime-model.md) @@ -32,6 +34,13 @@ Canonical published docs: - Prefer references to code and upstream sources over narrative speculation. - Avoid session-specific conclusions in core maintainer docs. +## Deep dives + +- [`08-windows-dll-abi-deep-dive.md`](08-windows-dll-abi-deep-dive.md) — + learning-oriented reference on Windows DLL loading, C/C++ ABI, linkers, + MinGW-vs-MSVC distribution models, and this project's failure history + (written after the July 2026 e2e investigation) + ## Archive material Historical reconstruction notes (e.g. `07-*`) are retained for reference and diff --git a/dev/docs/reference/2026-05-26 - Perplexity - What is the relationship between shared library bi.md b/dev/docs/reference/2026-05-26 - Perplexity - What is the relationship between shared library bi.md deleted file mode 100644 index bccd14e..0000000 --- a/dev/docs/reference/2026-05-26 - Perplexity - What is the relationship between shared library bi.md +++ /dev/null @@ -1,1013 +0,0 @@ - - -# What is the relationship between shared library binaries and executable binaries or runtimes that use them? For example, when I compile, build, install etc some static binary such as GDAL, what is the best way to understand concepts such as bundling dependencies (ie external shared libraries) statically into the resulting build vs doing something that implies those external dependencies will be available at runtime instead etc.? I recently made https://github.com/jimbrig/gdalraster.windows which is a custom R package and GDAL build that specifically uses the same MinGW based RTools45/MSYS2/UCRT (I also do not know what these are really, all I know is mingw is the open/unix based alternative to MSVC for windows but I do not know how MSYS2 and UCRT are related to mingw or what they are other than Unix environments for windows with bash shells) to compile a GDAL library that provides C++ ABI compatibility for the algorithmic api bindings from gdalraster. However I in turn also must rebuild gdalraster linking to this new gdal build and also ensure the DLL is loaded before librarying gdalraster also…. - -This is a rich and deeply interconnected question — let me break it down layer by layer. - -*** - -## Binaries, Libraries, and Linking: The Foundation - -At the most fundamental level, a **binary** is just compiled machine code in a file. The key distinction is whether a binary is *self-sufficient* or *dependent*: - -- An **executable binary** (`.exe` on Windows, ELF with `main()` on Linux) has an entry point and can be launched by the OS directly. -- A **shared library** (`.dll` on Windows, `.so` on Linux) has no `main()`, exists purely to export functions/data, and is loaded into another process's address space either at startup or on demand.[^1_1] - -The critical technical detail is that shared libraries use **position-independent code (PIC)** — their machine code is compiled so it can be mapped to *any* virtual memory address in a process, rather than being fixed. This is what lets multiple processes share the same library simultaneously.[^1_2] - -*** - -## Static vs Dynamic Linking - -When you compile and link a program (or a shared library like `gdal.dll`), you must decide how each of its *own* dependencies gets bundled: - -**Static linking** copies the full object code of each dependency directly into your output binary at link time. The result is a single, self-contained artifact. No external `.dll` or `.so` needs to be present at runtime. The tradeoffs:[^1_3] - -- Larger binary size (every consumer carries its own copy of each library) -- Easier deployment — it "just works" with no external deps to resolve -- Bug fixes in a dependency require a full recompile and redistribution of your binary[^1_3] -- Slight performance edge because symbol resolution happens at link time, not runtime[^1_3] - -**Dynamic linking** records only a *reference* to a shared library in the binary's import table. The OS **loader** resolves and maps those dependencies at process startup (load-time dynamic linking) or when your code explicitly calls `LoadLibrary()` (runtime dynamic linking). The tradeoffs:[^1_4] - -- Smaller binaries, shared memory footprint -- Dependencies *must* be present on the target machine at the correct path and version -- You can patch a buggy dependency by just replacing the `.dll` without rebuilding consumers[^1_3] - -For your GDAL build, the key insight is: when you compile GDAL itself, it *dynamically links* many of its own dependencies (PROJ, GEOS, libcurl, SQLite, etc.) unless you explicitly tell the build system to link them statically with flags like `-static` or CMake options like `-DGDAL_USE_EXTERNAL_LIBS=...`. This means your `gdal.dll` will in turn require *those* DLLs at runtime. - -*** - -## The C++ ABI Problem — Why You Had to Rebuild Everything - -This is the crux of your `gdalraster.windows` project. **ABI** (Application Binary Interface) is the low-level contract between compiled binaries: how function names are mangled, how arguments are passed on the stack, how exceptions propagate, how vtables are laid out, etc.[^1_5] - -The problem is that **C++ has no standardized ABI across compilers** — MSVC and MinGW/GCC use fundamentally different C++ ABIs. This means:[^1_6] - -- If `gdal.dll` exposes C++ types (STL containers, virtual classes) and is compiled with MSVC, code compiled with MinGW GCC *cannot safely call those APIs*, even if the header files look identical[^1_7] -- The crash wouldn't necessarily be immediate — it could be a silent memory corruption, a misaligned vtable dispatch, or a thrown exception that crosses the ABI boundary and is never caught[^1_6] -- The *only* safe cross-compiler boundary for DLLs is **`extern "C"` linkage**, which disables name mangling and uses the C calling convention — but `gdalraster`'s bindings use the full C++ GDAL API, so that escape hatch doesn't apply here - -This is precisely why you had to build your own GDAL using the same toolchain (RTools45/MinGW/UCRT64) that R itself uses on Windows — so the C++ ABI on both sides of the boundary is identical. - -*** - -## The MSYS2 / MinGW / UCRT Ecosystem Demystified - -These are four distinct but layered concepts: - - -| Term | What it actually is | -| :-- | :-- | -| **MinGW-w64** | A project that ports GCC (the GNU Compiler Collection) to Windows, targeting the native Win32 API. It produces `.exe`/`.dll` files that run natively without any Unix emulation layer [^1_8] | -| **MSYS2** | A *distribution* and *package manager* (using `pacman`) for Windows that bundles MinGW-w64 toolchains, plus a POSIX shell layer (bash, coreutils, make). It's the *environment* you work in, not the compiler itself [^1_9] | -| **MSVCRT** | The old Microsoft Visual C++ Runtime — the C standard library that ships on all Windows versions. The `MINGW64` MSYS2 environment links against this. It has known non-C99 issues and doesn't support UTF-8 locale [^1_9] | -| **UCRT** | Universal C Runtime — the modern replacement that Microsoft also uses in Visual Studio by default since VS2015. The `UCRT64` MSYS2 environment links against this, giving much better MSVC compatibility [^1_9] | - -The critical rule: **you cannot safely mix binaries linked to MSVCRT with binaries linked to UCRT** at the object/static library level. For DLLs specifically, mixing is possible *as long as you don't share C runtime objects like `FILE*` or heap allocations across the boundary*. RTools45 specifically moved to UCRT64, which is why MSYS2's UCRT64 environment is the right toolchain to match.[^1_9] - -As of 2026-03-15, **MSYS2 has actually deprecated the MINGW64 environment** in favor of UCRT64, validating the choice your project made.[^1_9] - -*** - -## DLL Load Order and the `dyn.load()` Problem - -Your observation that you must `dyn.load()` the GDAL DLL *before* calling `library(gdalraster)` directly reflects how Windows resolves DLL dependencies at load time. When Windows loads `gdalraster.dll`, it immediately needs to resolve all of *its* import table entries — including `gdal.dll` — via the DLL search order:[^1_10] - -1. The directory of the loading executable (R's bin directory) -2. `System32` -3. The `PATH` environment variable entries, in order - -If your custom `gdal.dll` isn't in any of those places, the load fails before any R code even runs. By calling `dyn.load("path/to/gdal.dll")` first, you get Windows to map that DLL into the process, after which it's in the **loaded-module list** (step 4 in the search order). When `gdalraster.dll` then loads and asks for `gdal.dll`, Windows finds it already resident in memory and uses it.[^1_10] - -A more robust long-term approach is to use `Sys.setenv(PATH = ...)` to prepend your custom GDAL DLL's directory to `PATH` *before* the package loads, or to use `addDllDirectory()` (exposed via R's `.Machine$addDllDirectory`) on newer Windows/R builds. This way the system finds it automatically during the normal search rather than requiring manual pre-loading. - -*** - -## How This All Ties Together for Your Build - -Your `gdalraster.windows` workflow hits every one of these concepts in sequence: - -1. You compile `gdal.dll` with UCRT64 GCC, which statically bundles some dependencies (like PROJ internals) or dynamically links others — this determines which additional DLLs need to travel with `gdal.dll` -2. You compile `gdalraster.dll` linking against your `gdal.dll`'s import library (`.dll.a`), using the same UCRT64 GCC — C++ ABI is now consistent across both[^1_5] -3. At R runtime, you pre-load `gdal.dll` into the process before `library(gdalraster)`, so the Windows loader finds it in the already-loaded-module list rather than searching PATH[^1_10] - -The deeper architectural lesson is that **shared library systems are essentially a deferred promise** — when you build, you're writing an IOU ("I will need `gdal.dll` at runtime"), and the OS loader is the collections agency that either satisfies that IOU from what's available, or crashes your process if it can't. Static linking converts those IOUs into cash upfront at build time, eliminating the runtime collection problem entirely — at the cost of a larger, less updatable binary.[^1_3] -[^1_11][^1_12][^1_13][^1_14][^1_15][^1_16][^1_17][^1_18][^1_19][^1_20][^1_21][^1_22][^1_23][^1_24][^1_25][^1_26][^1_27][^1_28] - -
⁂
- -[^1_1]: https://en.wikipedia.org/wiki/Shared_library - -[^1_2]: https://stackoverflow.com/questions/62415074/difference-between-shared-library-so-a-linux-executable-file-without-extensio - -[^1_3]: https://www.sandordargo.com/blog/2024/10/02/dynamic-vs-static-linking - -[^1_4]: https://stackoverflow.com/questions/11224123/load-time-dynamic-linking-import-library-search-order - -[^1_5]: https://caiorss.github.io/C-Cpp-Notes/DLL-Binary-Components-SharedLibraries.html - -[^1_6]: https://github.com/llvm/llvm-project/issues/60847 - -[^1_7]: https://github.com/caiorss/C-Cpp-Notes/blob/master/DLL-Binary-Components-SharedLibraries.org - -[^1_8]: https://gitforwindows.org/the-difference-between-mingw-and-msys2.html - -[^1_9]: https://www.msys2.org/docs/environments/ - -[^1_10]: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order - -[^1_11]: https://www.reddit.com/r/linux4noobs/comments/pybvdv/difference_between_binaries_and_libraries/ - -[^1_12]: https://forums.raspberrypi.com/viewtopic.php?t=204543 - -[^1_13]: https://www.jsoftware.com/help/user/dll_so.htm - -[^1_14]: https://pypi.org/project/GDAL/ - -[^1_15]: https://news.ycombinator.com/item?id=32531224 - -[^1_16]: https://stackoverflow.com/questions/1993390/static-linking-vs-dynamic-linking - -[^1_17]: https://stackoverflow.com/questions/76552264/what-are-msys2-environments-how-do-i-pick-one - -[^1_18]: https://github.com/databrickslabs/mosaic/issues/524 - -[^1_19]: https://forum.dlang.org/thread/dobouzmhwabquswguunk@forum.dlang.org - -[^1_20]: https://devinsights.iblogger.org/msys2-environment-differences/ - -[^1_21]: https://www.reddit.com/r/C_Programming/comments/1lw83ye/how_to_install_64bit_msys2_really/ - -[^1_22]: https://github.com/msys2/MSYS2-packages/discussions/4706 - -[^1_23]: https://stackoverflow.com/questions/15082060/set-up-a-msvc-dll-to-be-abi-compatible-to-a-stdcall-mingw-dll - -[^1_24]: https://ziggit.dev/t/windows-gnu-mingw-and-msvc-binary-c-abi-compatibility-guarantees/6903 - -[^1_25]: https://forum.crystal-lang.org/t/how-to-detect-the-current-msys2-environment-ucrt64-mingw64-clang64-on-windows/8090 - -[^1_26]: https://github.com/dotnet/sdk/issues/33845 - -[^1_27]: https://github.com/microsoft/vscode-cpptools/issues/11063 - -[^1_28]: https://www.akshayjain.blog/post/understanding-the-windows-dll-search-order-a-deep-dive-into-internals-and-security-implications - - ---- - -# See https://github.com/firelab/gdalraster/issues/982 for my own explanation of what I did on my local machine and the response back. - -Then actually review the package source code and particularly the GitHub action workflow that builds the GDAL binary: https://github.com/jimbrig/gdalraster.windows - -And provide me with thorough insights back. - -Now I have a very complete picture of the code, the issue thread, the upstream maintainer's response, and the full build/runtime architecture. Let me write the analysis. - -*** - -## What You Built and Why It Works - -Your package and workflow represent a genuinely sophisticated solution to a deep, multi-layered Windows C++ toolchain problem. Let me walk through every layer of what your code does, where it's clever, and where there are rough edges worth addressing. - -*** - -## The Root Cause: Static Algorithm Registration in MXE Builds - -The upstream problem in [issue \#826](https://github.com/firelab/gdalraster/issues/826) is subtle and worth understanding precisely . GDAL's Algorithm API uses **static C++ constructors** to self-register algorithms into a global registry at DLL load time — essentially, each algorithm's `.cpp` file contains a file-scope object whose constructor calls `GDALAlgorithmRegistry::Register()`. This works fine when GDAL is built as a shared library in a normal GCC/UCRT64 environment . - -However, RTools45 uses a build system called **MXE** (M Cross Environment) which builds GDAL — and many of its deps — as **static archives (`.a` files)** that then get linked into a final shared `libgdal.dll` . The problem: when the linker pulls in object files from static archives, it uses **dead-code elimination** and only links objects that are explicitly referenced by something already in the link graph. Static initializers that *only* side-effect a global registry, and are never called by name from any other object, get silently discarded by the linker as unreachable dead code. The result is `gdal_global_reg_names()` returning `character(0)` — the registry is empty because the self-registration constructors never ran . - -The fix confirmed by `ctoney` is that this was patched upstream in GDAL 3.12.2 via [GDAL PR \#13592](https://github.com/OSGeo/gdal/pull/13592), and separately, **muparser** was missing from RTools' GDAL build (it was added in RTools release 6768) . You independently arrived at the same two root causes: wrong GDAL version + missing muparser . - -*** - -## The `build_gdal.sh` Script: What It Does and Why - -Your [`tools/build_gdal.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/build_gdal.sh) is the core artifact . The key CMake flags and the reasoning behind each: - - -| Flag | Why it's there | -| :-- | :-- | -| `-DGDAL_USE_MUPARSER=ON` | Enables the Algorithmic API — this is the primary fix | -| `-DGDAL_HIDE_INTERNAL_SYMBOLS=ON` | Reduces the DLL export table size; required because you hit `export ordinal too large 154394` errors — PE/COFF DLLs have a hard limit of 65535 export ordinals and GDAL's symbol count exceeds it without this | -| `-Wl,--kill-at` | MinGW adds an `@N` byte-count suffix to `__stdcall` symbol names (e.g. `Foo@8`). `--kill-at` strips these, producing clean symbol names that match MSVC-style import expectations — required for interop | -| `-static-libgcc -static-libstdc++ -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,-Bdynamic,--no-whole-archive` | **This is the single most important decision for distribution.** It embeds the GCC C++ and threading runtimes directly into the DLL rather than depending on `libgcc_s_seh-1.dll`, `libstdc++-6.dll`, `libwinpthread-1.dll` being present | -| `-DBUILD_TESTING=OFF -DBUILD_APPS=OFF` | ~30% build time reduction with no impact on the runtime DLL | - -The `--whole-archive` / `--no-whole-archive` sandwich around `-lwinpthread` is a non-obvious but critical linker trick. Normally `-Bstatic` prevents dead-code elimination, but `--whole-archive` forces *every* object in the archive to be included — necessary for pthreads because some initialization routines might otherwise be dropped . - -*** - -## `collect_dlls.sh`: The Real Complexity - -The [`tools/collect_dlls.sh`](https://github.com/jimbrig/gdalraster.windows/blob/main/tools/collect_dlls.sh) script is where the packaging actually becomes a hard problem . The approach uses `ntldd -R` — a recursive PE import tree walker for Windows — to walk every transitive dependency of `libgdal-39.dll` and collect any DLL that resolves to `/ucrt64/` (i.e., an MSYS2 package that won't exist on a plain Windows machine) . - -The final verification step is the most important part of this script: it re-runs `ntldd` after bundling and asserts that **no remaining deps resolve outside of `C:/Windows/`**, failing the CI build with a nonzero exit code if anything slips through . This is a strong correctness guarantee — you can't accidentally ship a bundle that requires Rtools or MSYS2 to be installed. - -One subtle issue in the safety-net: the script also explicitly copies `libgcc_s_seh-1.dll`, `libstdc++-6.dll`, `libwinpthread-1.dll` as a fallback even though `build_gdal.sh` statically links those runtimes . This is defensive and harmless — the DLL already has the runtime embedded, so the copies in `bin/` would only be used by *other* DLLs in the bundle that weren't built with static runtime flags. Good defensive practice. - -*** - -## The GitHub Actions Workflow Architecture - -The `build.yml` workflow has a notably well-thought-out structure : - -**Cache strategy**: The build cache is keyed on `gdal_version + runner.os + hash(build_gdal.sh, collect_dlls.sh)`. This means changing a version string or modifying either script invalidates the cache and forces a rebuild, but re-running the workflow to iterate on the R package side skips the 40-minute CMake build entirely . The cache key including the *script hash* (not just version) is sophisticated — most people only key on the version. - -**`path-type: minimal`** in the MSYS2 setup step is critical and often overlooked . Without it, the Windows `PATH` (including any installed Rtools) bleeds into the MSYS2 shell environment. This can silently cause cmake's `find_package()` to pick up the *wrong* version of PROJ, GEOS, or other deps — from Rtools rather than UCRT64 — producing a DLL that links against Rtools' libraries instead of MSYS2's, which then fails at runtime when those paths don't exist. The comment in your workflow explicitly documents this risk . - -**The two-job split** is also architecturally correct: Job 1 (`build-gdal`) runs entirely in MSYS2, produces a self-contained bundle, and passes it to Job 2 via `upload-artifact`. Job 2 (`verify-gdalraster-build`) uses `r-lib/actions/setup-r` which installs *Rtools45* (not MSYS2) — this correctly simulates an end-user R environment and proves the bundle works without MSYS2 present . - -The smoke test in step 8 of Job 2 is exactly right: - -```r -stopifnot(length(algs) > 0) -``` - -This directly tests the thing that was broken in issue \#826 — it won't pass with an empty registry . - -*** - -## The R Package Layer - -The R package (`gdalraster.windows`) serves as a bootstrap orchestrator. Its design is layered cleanly : - -- `install_gdal_runtime()` — downloads the prebuilt bundle from a GitHub Release asset and unpacks it to a user-managed directory (resolved via `tools::R_user_dir()` by default) -- `activate_gdal_runtime()` — prepends `bin/` to `PATH`, sets `GDAL_DATA` and `PROJ_LIB`/`PROJ_DATA`, and calls `dyn.load(dll_path, local = FALSE, now = TRUE)` -- `install_gdalraster()` — uses `withr::with_makevars()` to set `PKG_CPPFLAGS`/`PKG_LIBS` scoped to a single `install.packages()` call, installing gdalraster from source into a dedicated `lib` -- `load_gdalraster()` — prepends the custom `lib` to `.libPaths()` before calling `library(gdalraster)` - -The `zzz.R` `.onLoad` hook calls `startup_bootstrap()` automatically when `auto_bootstrap` option is TRUE , which means simply `library(gdalraster.windows)` will attempt the full setup sequence — a nice UX touch. The `startup_hook.R` utility `add_gdal_rprofile_hook()` writes a **managed marker block** (`# >>> gdalraster.windows hook >>>` / `# <<< gdalraster.windows hook <<<`) that can be idempotently re-written without duplicating the hook — better than most R packages that just blindly append to `.Rprofile`. - -The `install_gdalraster()` function uses `withr::with_makevars()` with `assignment = "="` rather than `"+="` . This is intentional: it *replaces* the `PKG_LIBS` variable rather than appending to any existing value. If a user already has a `~/.R/Makevars.win` pointing at a different GDAL, the `withr` scope overrides it for this install only without permanently modifying their file. - -*** - -## Areas Worth Improving - -**1. Hardcoded DLL version in `build_gdal.sh`** - -The final `ls -lh "${INSTALL_DIR}/bin/libgdal-39.dll"` hardcodes the SONAME version `39` . When GDAL bumps its SONAME (as it does with major releases), this will produce a misleading "file not found" error without failing the build itself. Better: use a glob `libgdal-*.dll` like the rest of your scripts do. - -**2. The `--allow-multiple-definition` linker flag in `install_gdalraster()`** - -In `gdal_runtime.R`, the `PKG_LIBS` passed to the source install includes `-Wl,--allow-multiple-definition` . This flag silences linker errors that occur when the same symbol appears in multiple translation units — a genuine red flag. It can mask real ABI violations or symbol conflicts between the custom GDAL and residual Rtools GDAL symbols. It's understandable as a pragmatic fix for intermittent link failures, but ideally you'd identify and eliminate the duplicate symbols rather than suppressing the diagnostic. - -**3. `GDAL_USE_ARROW=ON` without verifying Arrow IPC support** - -The build enables both Arrow and Parquet , which requires libarrow and libparquet to be either statically linked or bundled. The `collect_dlls.sh` *should* pick these up via `ntldd`, but Arrow's DLL dependency tree is particularly deep (it pulls in Thrift, Boost, etc.). The CI verification only checks that `gdal_global_reg_names()` returns non-empty — it doesn't test Arrow-specific drivers. A smoke test like `gdalraster::vsi_list("/vsiarrow/...")` or checking `gdal_formats()` for `Arrow` would give higher confidence. - -**4. No `inst/extdata/` fallback bundle** - -The `install_gdal_runtime()` function references a `packaged_fallback_zip()` that points to `inst/extdata/gdal-ucrt64-fallback.zip` . But looking at the package structure, no such zip is actually bundled in the repository — the `inst/` directory likely doesn't contain it due to its size. The fallback path is defensive, but documenting clearly in the package that the fallback is only available after a manual local build (not from CRAN/GitHub install) would prevent confusion. - -**5. The upstream fix makes your solution partly obsolete (but not fully)** - -`ctoney`'s response confirms that the static registration bug was fixed upstream in GDAL 3.12.2 and will be part of the next RTools update targeting GDAL 3.13.1 . Once that RTools release lands, the default `gdalraster` install from CRAN will "just work" for the Algorithm API. However, your package still provides genuine value beyond the bug fix: it pins a specific GDAL version, enables Arrow/Parquet/HDF5/NetCDF drivers that the lean MXE build may omit, and provides a reproducible CI pipeline for anyone who needs a custom GDAL feature set on Windows. - -*** - -## Summary of the Build Pipeline Flow - -``` -git tag gdal-v3.13.0 - │ - ▼ -Job 1 (MSYS2 UCRT64 shell) - ├── install UCRT64 toolchain + deps (muparser, arrow, hdf5, ...) - ├── cmake configure (--kill-at, -static-libgcc, MUPARSER=ON, HIDE_SYMBOLS=ON) - ├── cmake build → libgdal-39.dll - ├── collect_dlls.sh: ntldd -R → copy /ucrt64 deps → verify self-contained - └── upload artifact + GitHub Release zip - │ - ▼ -Job 2 (Rtools45 / standard Windows R env) - ├── download GDAL bundle from Job 1 - ├── write ~/.R/Makevars.win pointing at bundle - ├── download gdalraster source from CRAN - ├── R CMD INSTALL --build --no-test-load (links against bundled GDAL) - ├── smoke test: gdal_global_reg_names() returns length > 0 ✓ - └── upload gdalraster binary artifact -``` - -The end-to-end result is a fully self-contained `libgdal-39.dll` that carries its own runtime, a `gdalraster.dll` linked against it with matching C++ ABI, and an R package that orchestrates installation, PATH management, DLL preloading, and `.Rprofile` persistence — all without requiring the end user to have MSYS2, Rtools, or any compiler toolchain installed. - ---- - -# Another potential aspect of this I just thought about due to me having to deal with similar problems for my Linux WSL distro environment where I link and build against a pixi managed GDAL 3.13 when installing gdalraster to get the latest version and enable arrow / parquet driver support etc. is the ability to additionally have sf and terra package installations and result in alternative package builds against this new GDAL build - can you explore the feasibility of that for this windows implementation and any nuances involved? I know that sf does not use rtools45 binaries I don’t think and on linux it would install its own legacy (3.8) GDAL as a sysreq etc. which in worked around successfully from Linux but not sure about windows. - -I now have a very complete picture. Let me write the comprehensive analysis. - -*** - -## sf and terra Against a Custom GDAL on Windows: Feasibility and Nuances - -This is deeply feasible but requires navigating several interlocking problems that are quite different from the Linux/pixi case. Here's a thorough breakdown. - -*** - -## How sf and terra Actually Link on Windows - -The first critical thing to understand is what `Makevars.ucrt` does for both packages — and this is the key insight that changes everything. Both `sf` and `terra` have essentially **identical** `Makevars.ucrt` files : - -```makefile -ifeq (,$(shell pkg-config --version 2>/dev/null)) - PKG_LIBS = -lgdal -larmadillo -lopenblas ... [~50 static Rtools libs] ... -lproj -lsqlite3 ... -else - PKG_LIBS = $(shell pkg-config --libs gdal geos proj) -endif - -winlibs: - cp -r "$(R_TOOLS_SOFT)/share/gdal" ../inst/ - cp -r "$(R_TOOLS_SOFT)/share/proj" ../inst/ -``` - -The `ifeq` branch checks whether `pkg-config` is available. In a stock Rtools45 environment, **`pkg-config` is not on `PATH`** (or is present but not configured to find the UCRT64 packages) so the `ifeq` branch fires, hardcoding a massive explicit list of static libraries from `$(R_TOOLS_SOFT)` — the Rtools UCRT64 sysroot . The `winlibs:` target then **copies GDAL and PROJ data files from Rtools into `inst/`** inside the built package — this is why `sf` and `terra` are fully self-contained on Windows . - -The implication: **if `pkg-config` is available and configured** — as it would be in an MSYS2 shell pointing at your UCRT64 GDAL bundle — the second branch fires and `pkg-config --libs gdal geos proj` will emit your custom GDAL's paths. This is the clean mechanism both packages already provide for custom builds. - -*** - -## The DLL Conflict Problem: The Core Danger - -When you have a custom GDAL build (`libgdal-39.dll`) from `gdalraster.windows` and then also load `sf` or `terra` in the same R session — regardless of how they were compiled — you face the fundamental **Windows DLL deduplication rule**: `LoadLibrary` identifies DLLs by their *filename*, not their full path. The Windows loader keeps one canonical handle per DLL name per process. The second `LoadLibrary("libgdal-39.dll")` simply returns a reference to the already-loaded module — it does not load a second independent copy.[^4_1][^4_2] - -This means: **if `sf` or `terra` were compiled against Rtools' GDAL and your gdalraster was compiled against your custom GDAL bundle**, yet both DLLs happen to have the same filename `libgdal-39.dll` (same SONAME), only the first one loaded wins. The package loaded second will be calling functions in the wrong library. This is not a crash — it's a silent ABI mismatch that may appear to work for basic operations but will fail subtly or catastrophically on codepaths that use features compiled into one build but not the other (e.g., Arrow/muparser in your build vs. missing in Rtools' build).[^4_1] - -The safe outcome only happens when **all three packages link against the exact same `libgdal-39.dll` binary** — your custom one. - -*** - -## The Path to Actually Making This Work - -There are two distinct strategies, each with different complexity trade-offs. - -### Strategy 1: Recompile sf and terra Against Your Bundle (Full Solution) - -This mirrors exactly what `install_gdalraster()` does in your package, extended to `sf` and `terra`. The approach would be: - -**For sf:** - -```r -withr::with_makevars( - new = c( - PKG_CPPFLAGS = paste0('-I"', file.path(gdal_home, "include"), '"'), - PKG_LIBS = paste0('-L"', file.path(gdal_home, "lib"), '" -lgdal -lgeos_c -lproj'), - R_TOOLS_SOFT = gdal_home # override so winlibs copies YOUR gdal/proj data - ), - assignment = "=", - { - withr::with_envvar(c(PATH = ..., GDAL_DATA = ..., PROJ_LIB = ...), { - install.packages("sf", type = "source", lib = custom_lib, - INSTALL_opts = "--no-test-load") - }) - } -) -``` - -However, there is a **critical complication** in `sf`'s `Makevars.ucrt` . The `winlibs:` target does `cp -r "$(R_TOOLS_SOFT)/share/gdal" ../inst/`. If you override `R_TOOLS_SOFT` to point at your bundle, `sf` will copy your bundle's `share/gdal` and `share/proj` into its `inst/` — which is exactly what you want, since `sf` will then ship its own GDAL/PROJ data pointing at your build's data files. But this also means the `PKG_LIBS` hardcoded list (50+ static libs!) becomes irrelevant in the `ifeq` branch only if `pkg-config` is found. Your best bet is to **ensure `pkg-config` is available and configured** so the `else` branch fires. - -In your MSYS2 UCRT64 environment, this works automatically because `pkg-config --libs gdal` will correctly emit your build's flags. The problem is that the *source install* runs in the R process (not the MSYS2 shell), so `pkg-config` needs to be on `PATH` inside the `withr::with_envvar()` scope. - -**For terra**, the situation is structurally identical to `sf` — same `Makevars.ucrt` pattern . The only additional dependency to worry about is TBB (`libtbb12` in the `pkg-config` branch). Your custom GDAL build wouldn't ship TBB, so you'd need it from UCRT64 and bundled alongside. - -*** - -### Strategy 2: CRAN Binaries for sf/terra + Runtime PATH Ordering - -The path of least resistance — and what many people do without realizing the risk — is loading the CRAN binary `sf` and `terra` alongside your custom-GDAL `gdalraster`. Whether this is *safe* depends on the GDAL SONAME version: - -- **If Rtools' GDAL and your custom GDAL both produce `libgdal-39.dll`**: only one is loaded, determined by which package first calls `dyn.load()`. If you call `activate_gdal_runtime()` (which prepends your `bin/` to PATH and calls `dyn.load(dll_path, local=FALSE, now=TRUE)`) *before* `library(sf)`, your DLL wins and `sf` will use your custom GDAL at runtime. This is a legal but fragile arrangement — `sf` was compiled against Rtools' static libs list, but at runtime it resolves symbols from your DLL. As long as the ABI is compatible (same major GDAL, same calling conventions, MinGW toolchain on both sides), this usually works for the ~95% of operations that don't touch Arrow/muparser-specific codepaths. -- **If SONAME versions differ** (e.g., Rtools has `libgdal-38.dll`, you built `libgdal-39.dll`): both can coexist in memory because Windows treats them as different DLLs. `sf` binds to `libgdal-38.dll` from Rtools, `gdalraster` binds to your `libgdal-39.dll`. No conflict — they load fully independently. This is the cleanest accidental outcome, and worth checking on your specific Rtools vs. custom GDAL versions. - -*** - -## The Linux Parallel and Why Windows Is Harder - -On your WSL/pixi setup, you solved this by ensuring the pixi-managed `libgdal.so.X.Y.Z` was first on `LD_LIBRARY_PATH` before R started . Linux ELF shared libraries have versioned SONAME symbols and the dynamic linker uses `SONAME` + `rpath`/`runpath` embedded in each `.so` at build time, so two libraries with different SONAMEs load peacefully in the same process. On Linux, `sf` tries to install its own legacy GDAL (typically 3.8 from `libgdal-dev` on Ubuntu) as a sysreq — you worked around this by ensuring your pixi GDAL took precedence before configure ran . - -On Windows, the problem is structurally worse: there are no `rpath`/`runpath` mechanisms. Windows DLL resolution is pure PATH + KnownDLLs + side-by-side assembly lookup order, with no way to embed a preferred search path into a DLL at link time (the `DT_RPATH` equivalent simply doesn't exist in PE/COFF format). The only lever you have is controlling `PATH` order before the first `LoadLibrary` call.[^4_1] - -Additionally, `sf`'s `Makevars.ucrt` hardcodes static linkage against ~50 Rtools libraries without versions — if those libraries have ABI-level differences from your UCRT64 bundle's versions (e.g., different PROJ patch version, different GEOS), you'd need your bundle to provide every one of those `.a` files at matching versions too. This is why a full source rebuild against your bundle is the only truly correct approach. - -*** - -## Practical Recommendation for the Windows Package - -An `install_sf()` and `install_terra()` function in `gdalraster.windows` is feasible and would follow the same pattern as `install_gdalraster()` . The key differences to account for: - - -| Concern | `gdalraster` | `sf` / `terra` | -| :-- | :-- | :-- | -| `Makevars.ucrt` branch | No `ifeq` — simple flags | `ifeq pkg-config` — need pkg-config available OR override `R_TOOLS_SOFT` | -| `winlibs:` data copy | No `inst/` data copying | Copies `share/gdal` + `share/proj` into `inst/` — need `R_TOOLS_SOFT` override | -| Additional deps | Only GDAL | sf also needs GEOS, PROJ; terra needs TBB | -| `-Wl,--allow-multiple-definition` | Already present in your code | Likely needed here too due to same symbol duplication pattern | -| GEOS/PROJ bundling | Your GDAL DLL embeds these or they're in your `bin/` | Need to verify they're present in your bundle's `lib/` as `.a` files | - -The cleanest implementation would expose `pkg-config` from the bundle (MSYS2 UCRT64 provides `.pc` files in `lib/pkgconfig/`) and set `PKG_CONFIG_PATH` to point at them during the source install. This lets `sf`'s and `terra`'s `Makevars.ucrt` take the `pkg-config` branch naturally and emit correct link flags without you needing to maintain a hardcoded 50-library list . - -One additional build flag to add for `sf`: `-DHAVE_PROJ_H` is currently hardcoded in `sf`'s `Makevars.ucrt` but absent from the `else`/`pkg-config` branch, suggesting it's expected to be provided by `pkg-config`'s `--cflags`. Confirm your bundle's PROJ `.pc` file emits `-DHAVE_PROJ_H` in its `Cflags` output. - -*** - -## Summary of the Risk Profile - -- **Same GDAL SONAME, CRAN binaries, activation-first ordering** → *Probably works* for basic operations, fragile for Arrow/muparser features, depends on ABI compatibility. Low effort. -- **Same GDAL SONAME, all three compiled from source against your bundle** → *Correct and robust*, requires extending `gdalraster.windows` with `install_sf()` / `install_terra()` wrappers and bundling GEOS/PROJ static archives. Significant effort. -- **Different GDAL SONAMEs** → *Works accidentally and cleanly*, sf/terra use Rtools GDAL, gdalraster uses yours. No conflict, but no feature sharing across packages. - -The most principled path — and the one that would make `gdalraster.windows` genuinely valuable beyond just fixing the Algorithm registry issue — is the source-rebuild approach with `pkg-config` delegation. You already have the architecture for it; it's a matter of extending the pattern you built for `gdalraster` to cover `sf` and `terra` with the additional nuance of their `R_TOOLS_SOFT`-rooted `winlibs:` data copy step. -[^4_10][^4_11][^4_12][^4_13][^4_14][^4_15][^4_16][^4_17][^4_18][^4_19][^4_20][^4_21][^4_22][^4_23][^4_24][^4_25][^4_26][^4_27][^4_28][^4_29][^4_3][^4_30][^4_31][^4_32][^4_33][^4_34][^4_35][^4_36][^4_37][^4_38][^4_39][^4_4][^4_40][^4_41][^4_5][^4_6][^4_7][^4_8][^4_9] - -
⁂
- -[^4_1]: https://stackoverflow.com/questions/38698293/can-i-get-separate-dlls-to-resolve-their-imported-dlls-separately - -[^4_2]: https://stat.ethz.ch/R-manual/R-devel/library/base/help/dyn.load.html - -[^4_3]: https://github.com/r-spatial/sf - -[^4_4]: https://stackoverflow.com/questions/44973639/trouble-installing-sf-due-to-gdal - -[^4_5]: https://cran.r-project.org/package=sf - -[^4_6]: https://firelab.github.io/gdalraster/ - -[^4_7]: https://www.rdocumentation.org/packages/sf/versions/0.1-3 - -[^4_8]: https://github.com/rspatial/terra/issues/487 - -[^4_9]: https://www.hec.usace.army.mil/confluence/rasdocs/raski/latest/gdal-installation-issues - -[^4_10]: https://community.databricks.com/t5/data-engineering/install-r-package-quot-sf-quot/td-p/60090 - -[^4_11]: https://stackoverflow.com/questions/74575722/most-recent-terra-package-for-r-will-not-compile - -[^4_12]: https://stackoverflow.com/questions/6009506/unable-to-install-python-and-gdal-dll-load-failed - -[^4_13]: https://r-spatial.r-universe.dev/sf - -[^4_14]: https://github.com/rspatial/terra - -[^4_15]: https://github.com/pyinstaller/pyinstaller/issues/1376 - -[^4_16]: https://github.com/r-spatial/sf/discussions/2502 - -[^4_17]: https://www.rdocumentation.org/packages/terra/versions/0.9-12 - -[^4_18]: https://github.com/r-spatial/sf/issues/2159 - -[^4_19]: https://cran.r-project.org/doc/manuals/r-release/R-exts.html - -[^4_20]: https://github.com/r-spatial/sf/issues/408 - -[^4_21]: https://stackoverflow.com/questions/315285/can-i-use-two-incompatible-versions-of-the-same-dll-in-the-same-process - -[^4_22]: https://github.com/cran/rgdal/blob/master/inst/README.windows - -[^4_23]: https://www.reddit.com/r/gis/comments/1517den/trouble_with_installing_gdal/ - -[^4_24]: https://stackoverflow.com/questions/40634484/correct-installation-of-rtools-on-windows - -[^4_25]: https://gdal.org/en/stable/development/building_from_source.html - -[^4_26]: https://faims2-documentation.readthedocs.io/en/latest/Installing+GDAL+Tools+on+Windows/ - -[^4_27]: https://colinfay.me/writing-r-extensions/creating-r-packages-1.html - -[^4_28]: https://gamedev.net/forums/topic/677890-dll-access-mechanism-between-multiple-applications/ - -[^4_29]: https://stackoverflow.com/questions/72386315/is-it-possible-for-a-process-to-load-two-dll-with-same-name-but-different-versio - -[^4_30]: http://forum.vvvv.org/t/how-to-deal-with-different-versions-of-same-dll/14330 - -[^4_31]: https://learn.microsoft.com/en-us/answers/questions/5652481/how-to-use-multiple-dlls-with-the-same-name - -[^4_32]: https://michaelscodingspot.com/dotnet-dll-hell/ - -[^4_33]: https://dev.to/johnnymakestuff/how-to-use-two-versions-of-the-same-dll-in-the-same-project-31db - -[^4_34]: https://devnet.kentico.com/articles/referencing-multiple-versions-of-the-same-assembly-in-a-single-application - -[^4_35]: https://www.reddit.com/r/csharp/comments/1h4qzte/is_a_dll_when_loaded_considered_as_another_process/ - -[^4_36]: http://mynameiskali.blogspot.com/p/c-20-using-different-versions-of-same_24.html - -[^4_37]: https://rdrr.io/r/base/dynload.html - -[^4_38]: https://forums.ni.com/t5/LabVIEW/Execute-multiple-versions-of-the-same-NET-DLL/td-p/4192116 - -[^4_39]: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/dyn.load - -[^4_40]: https://www.reddit.com/r/csharp/comments/10gvqki/why_are_there_different_versions_for_the_same_dll/ - -[^4_41]: https://learn.microsoft.com/en-us/windows/win32/dlls/about-dynamic-link-libraries - - ---- - -# Note that neither sf nor terra include low level bindings to C++ APIs like the algorithmic API in a manner like gdalraster does with user facing functions etc. - in other words, this idea is primarily for providing a more ideal state that doesn’t require separate isolated GDALs or the fact that gdalraster can write and interact with libarrow drivers but sf cannot etc. which is still definitely a good practice or idea. From the prior response it may also be worth considering applying a similar pattern for the custom gdalraster build with the pkg-config and copied self container DLL in the packages installed folder along side its gdalraster.DLL which could help me avoid the pre library dyn load requirement right? - -Now I have a very complete picture of both the package architecture and the exact question being asked. The question is fundamentally about eliminating the pre-`library()` `dyn.load` requirement by shipping `libgdal-*.dll` **inside the `gdalraster` package's own directory** — the same pattern `sf` and `terra` already use — so the DLL is co-located with `gdalraster.dll` and gets found automatically at load time without any PATH manipulation. - -*** - -## The Core Insight: Co-located DLLs vs. Runtime PATH Manipulation - -Your current architecture requires a specific ordering: `activate_gdal_runtime()` (or the `.onLoad` auto-bootstrap) must run before `library(gdalraster)` so that `PATH` is prepended with the `bin/` directory and `libgdal-*.dll` is preloaded via `dyn.load()` before `gdalraster.dll` tries to find it . This is fragile — as the `.onAttach` warning in your own `zzz.R` explicitly acknowledges: *"gdalraster was already loaded before gdalraster.windows; restart session for full bootstrap control"* . - -The alternative you're proposing is sound and is exactly what `sf` and `terra` already do: the `winlibs:` target in their `Makevars.ucrt` copies `share/gdal` and `share/proj` into `inst/` at build time , and the built package ships those data files inside its installed directory. The analogous move for `gdalraster` is to **copy `libgdal-*.dll` and all its bundled dependency DLLs directly into `gdalraster/libs/x64/`** (the directory where `gdalraster.dll` itself lives), which changes the DLL resolution story completely. - -*** - -## Why This Works: Windows DLL Search Order - -When the Windows loader resolves imports for `gdalraster.dll`, the search order is:[^5_1] - -1. The directory containing the loading DLL itself (`gdalraster/libs/x64/`) -2. The process working directory -3. System directories (`C:\Windows\System32`, etc.) -4. Directories on `PATH` - -Step 1 is the key: if `libgdal-39.dll` is sitting in the same directory as `gdalraster.dll`, Windows finds it there **without `PATH` needing to be set at all**, before it even checks `PATH`. This is the canonical Windows pattern for self-contained application DLL bundling and is why `sf` and `terra`'s approach of copying into `inst/` works — their compiled `.dll` files end up adjacent to the bundled DLLs after `R CMD INSTALL`. - -For the `gdalraster` source install that `install_gdalraster()` performs, you already control the entire install pipeline via `withr::with_makevars()`. You can add a post-install step that copies the full set of DLLs from your `gdal_home/bin/` into the installed package's `libs/x64/` directory — precisely mirroring what `sf`'s `winlibs:` make target does at build time . - -*** - -## Concrete Implementation - -The change is a post-`install.packages()` copy step inside `install_gdalraster()`. After the source install completes, the installed `gdalraster` package directory will be at `file.path(lib, "gdalraster")`. Its DLL lives at `libs/x64/gdalraster.dll`. You need to copy all of `gdal_home/bin/*.dll` there: - -```r -# After the existing install.packages() call in install_gdalraster(): - -gdalraster_libs_dir <- file.path(lib, "gdalraster", "libs", "x64") -if (!dir.exists(gdalraster_libs_dir)) { - cli::cli_abort("gdalraster libs dir not found after install: {.path {gdalraster_libs_dir}}") -} - -gdal_dlls <- list.files(gdal_bin_dir(gdal_home), pattern = "\\.dll$", full.names = TRUE) -n_copied <- 0L -for (dll in gdal_dlls) { - dest <- file.path(gdalraster_libs_dir, basename(dll)) - if (!file.exists(dest)) { - file.copy(dll, dest) - n_copied <- n_copied + 1L - } -} -cli::cli_alert_success( - "copied {n_copied} GDAL runtime DLL{?s} into {.path {gdalraster_libs_dir}}" -) -``` - -With this in place, `library(gdalraster)` calls `dyn.load("gdalraster/libs/x64/gdalraster.dll")` and the Windows loader resolves `libgdal-39.dll` from the same directory — no `PATH` manipulation, no pre-load, no `.Rprofile` hook needed for the DLL resolution path. - -*** - -## What This Means for `activate_gdal_runtime()` and `.onLoad` - -Once the DLLs are co-located, the `activate_gdal_runtime()` call in `.onLoad` becomes responsible for only two things, not three: - - -| Responsibility | Co-located DLLs | Current approach | -| :-- | :-- | :-- | -| `libgdal-*.dll` is found at load time | ✅ Automatic via directory search | ❌ Requires pre-load / PATH prepend | -| `GDAL_DATA` env var set | Still needed | Still needed | -| `PROJ_LIB` / `PROJ_DATA` env vars set | Still needed | Still needed | -| `PATH` prepend for `gdal_translate` CLI tools | Still needed if user calls CLI | Still needed | - -The `preload = TRUE` default in `activate_gdal_runtime()` and the `dyn.load()` call in `load_gdal_dll()` become **optional** rather than mandatory . You'd still want to set `GDAL_DATA` and `PROJ_LIB` in `.onLoad` so gdalraster can find projection data, but this can happen *after* `gdalraster.dll` is loaded — it doesn't need to precede it. - -You could also copy `share/gdal` and `share/proj` into `gdalraster/inst/gdal` and `gdalraster/inst/proj` (analogous to `sf`'s `winlibs:` target) , then set the env vars from `system.file("gdal", package = "gdalraster")` in `.onLoad`. That makes the package fully self-contained — no dependency on `gdal_home` existing at runtime for data files, only for CLI tools. - -*** - -## The pkg-config Angle - -Your question also mentions making the build use `pkg-config` more naturally. This is complementary: shipping a `gdal.pc`, `geos.pc`, and `proj.pc` file inside `gdal_home/lib/pkgconfig/` (which your MSYS2 UCRT64 build already generates) and setting `PKG_CONFIG_PATH` in the `withr::with_envvar()` scope during `install_gdalraster()` means: - -- `sf`'s and `terra`'s `Makevars.ucrt` would take the `pkg-config` branch naturally -- `gdalraster`'s own source install doesn't need the hardcoded `PKG_CPPFLAGS`/`PKG_LIBS` construction since `configure` can discover them -- The `-Wl,--allow-multiple-definition` flag could potentially be removed if the `pkg-config` flags produce a cleaner link without the symbol duplication that flag is currently suppressing - -The clean `withr` scope for all three packages would become: - -```r -withr::with_envvar(c( - PATH = paste(c(gdal_bin_dir(gdal_home), Sys.getenv("PATH")), collapse = ";"), - PKG_CONFIG_PATH = file.path(gdal_home, "lib", "pkgconfig"), - GDAL_DATA = gdal_share_gdal_dir(gdal_home), - PROJ_LIB = gdal_share_proj_dir(gdal_home), - PROJ_DATA = gdal_share_proj_dir(gdal_home) -), { - # pkg-config branch fires automatically for sf and terra - install.packages("sf", type = "source", lib = lib, INSTALL_opts = "--no-test-load") - install.packages("terra", type = "source", lib = lib, INSTALL_opts = "--no-test-load") - # gdalraster can also use pkg-config, dropping the manual Makevars construction - install.packages(tarball, type = "source", lib = lib, INSTALL_opts = "--no-test-load") -}) -# Then copy DLLs into each package's libs/x64/ -for (pkg in c("gdalraster", "sf", "terra")) { - copy_gdal_dlls_to_pkg(gdal_home, lib, pkg) -} -``` - - -*** - -## One Nuance: DLL Count and Package Size - -Your `collect_dlls.sh` bundles every transitive UCRT64 dependency — Arrow, HDF5, NetCDF, PostgreSQL client, etc. . That DLL set is likely 80–120 files and probably 150–300 MB total. Copying all of them into each package's `libs/x64/` triples the disk footprint if you install all three packages. You have two options: - -- **Shared `libs/x64/` symlinks** — not reliable on Windows without admin rights (symlinks require a privilege) -- **One canonical copy, one consumer** — keep the DLLs in `gdalraster/libs/x64/` only, and rely on the fact that once `libgdal-39.dll` is loaded into the process by `gdalraster`, `sf` and `terra` will resolve to the already-loaded module when they call `LoadLibrary("libgdal-39.dll")` — the exact Windows DLL deduplication behavior that was a liability before now becomes an asset[^5_1] - -The load ordering requirement you were trying to eliminate is replaced by a package-load ordering that's much softer: `library(gdalraster)` must come before `library(sf)` and `library(terra)`, which is a natural dependency order any user would follow anyway. You can reinforce this with a simple check in `sf`'s/`terra`'s `.onLoad` path inside your bootstrap wrapper. - -
⁂
- -[^5_1]: https://stackoverflow.com/questions/38698293/can-i-get-separate-dlls-to-resolve-their-imported-dlls-separately - - ---- - -# Review everything from this session and thorough online research to ground your context and reasoning in the reality of this realm and not the specifics of this specific implementation and in turn provide guidance pertaining to this latest question and initial response back regarding making the current gdalraster work more streamlined as well as the idea to bring in sf and terra as possible extensions to integrate with - -Here's the report — it pulls everything together from the session context, the actual `Makevars.ucrt` source in `sf` and `terra`, the Windows DLL loader internals, and the upstream GDAL fix trajectory. - -The core takeaways at a glance: - -**On streamlining what you have:** - -- The `-Wl,--allow-multiple-definition` flag in `install_gdalraster()` is the most important thing to fix — it's masking a real symbol conflict that should be traced to its root (almost certainly Rtools GDAL `.a` files bleeding into the link). Use `-Wl,--warn-duplicate-common` to identify the culprits first. -- Add an early warning when `sf` or `terra` are already loaded before `activate_gdal_runtime()` runs — the ordering guarantee is the entire mechanism by which CRAN-binary `sf`/`terra` can be coerced to use your GDAL. -- The hardcoded `libgdal-39.dll` version check in `build_gdal.sh` will silently break on next SONAME bump. - -**On sf and terra extension:** - -- Both `sf` and `terra` already have a clean `pkg-config` branch in their `Makevars.ucrt` — the hook is there, you just need `pkg-config` on `PATH` or `R_TOOLS_SOFT` overridden to point at your bundle so the `winlibs:` target copies your GDAL data into `inst/` rather than Rtools'. -- `terra` needs `libtbb12` in the bundle for full TBB parallelism — it's in UCRT64, just needs bundling. -- The fundamental DLL identity rule means activation-first ordering is non-negotiable, and for source-rebuilt packages it's a non-issue entirely. - -**On the Linux comparison:** The reason pixi works cleanly on WSL is `RPATH`/`RUNPATH` — the Linux ELF loader can honor per-library preferred paths. PE/COFF has no equivalent, which is precisely why the `dyn.load(full_path, local=FALSE, now=TRUE)` before any `library(sf)` call is the only viable mechanism on Windows. -[^6_1][^6_10][^6_100][^6_101][^6_102][^6_103][^6_104][^6_105][^6_106][^6_107][^6_108][^6_109][^6_11][^6_110][^6_111][^6_112][^6_113][^6_114][^6_115][^6_116][^6_117][^6_118][^6_119][^6_12][^6_120][^6_121][^6_122][^6_123][^6_124][^6_125][^6_126][^6_127][^6_128][^6_129][^6_13][^6_130][^6_131][^6_132][^6_133][^6_134][^6_135][^6_136][^6_137][^6_138][^6_139][^6_14][^6_140][^6_141][^6_142][^6_143][^6_144][^6_145][^6_146][^6_147][^6_148][^6_149][^6_15][^6_150][^6_151][^6_152][^6_153][^6_154][^6_155][^6_156][^6_157][^6_158][^6_159][^6_16][^6_160][^6_161][^6_162][^6_163][^6_164][^6_165][^6_166][^6_167][^6_168][^6_169][^6_17][^6_170][^6_171][^6_172][^6_173][^6_174][^6_175][^6_176][^6_177][^6_18][^6_19][^6_2][^6_20][^6_21][^6_22][^6_23][^6_24][^6_25][^6_26][^6_27][^6_28][^6_29][^6_3][^6_30][^6_31][^6_32][^6_33][^6_34][^6_35][^6_36][^6_37][^6_38][^6_39][^6_4][^6_40][^6_41][^6_42][^6_43][^6_44][^6_45][^6_46][^6_47][^6_48][^6_49][^6_5][^6_50][^6_51][^6_52][^6_53][^6_54][^6_55][^6_56][^6_57][^6_58][^6_59][^6_6][^6_60][^6_61][^6_62][^6_63][^6_64][^6_65][^6_66][^6_67][^6_68][^6_69][^6_7][^6_70][^6_71][^6_72][^6_73][^6_74][^6_75][^6_76][^6_77][^6_78][^6_79][^6_8][^6_80][^6_81][^6_82][^6_83][^6_84][^6_85][^6_86][^6_87][^6_88][^6_89][^6_9][^6_90][^6_91][^6_92][^6_93][^6_94][^6_95][^6_96][^6_97][^6_98][^6_99] - -
⁂
- -[^6_1]: https://github.com/firelab/gdalraster/issues/858 - -[^6_2]: https://raw.githubusercontent.com/OSGeo/gdal/master/NEWS.md - -[^6_3]: https://blog.aaronballman.com/2011/08/what-happens-when-you-load-a-library/ - -[^6_4]: https://www.cnblogs.com/shangdawei/p/4056967.html - -[^6_5]: https://limbioliong.wordpress.com/2012/06/26/loading-2-dlls-of-the-same-name/ - -[^6_6]: https://stackoverflow.com/questions/38738899/multiple-loadlibrary-for-copies-of-the-same-dll - -[^6_7]: https://www.akshayjain.blog/post/understanding-the-windows-dll-search-order-a-deep-dive-into-internals-and-security-implications - -[^6_8]: https://r-spatial.github.io/sf/ - -[^6_9]: https://gdal.org/en/stable/download.html - -[^6_10]: https://anaconda.org/conda-forge/r-gdalraster - -[^6_11]: https://github.com/dlfcn-win32/dlfcn-win32/issues/104 - -[^6_12]: https://www.youtube.com/watch?v=-UQsUoMSlio - -[^6_13]: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order - -[^6_14]: https://stackoverflow.com/questions/74700637/determining-which-r-packages-and-dependencies-use-dll-files - -[^6_15]: https://forums.mydigitallife.net/threads/windows-internals-today-topic-ldrloaddll-loadlibraryexw.89432/ - -[^6_16]: https://cran.r-project.org/bin/windows/base/rw-FAQ.html - -[^6_17]: https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw - -[^6_18]: https://redcanary.com/threat-detection-report/techniques/dll-search-order-hijacking/ - -[^6_19]: https://stackoverflow.com/questions/42051228/workaround-bug-of-loadlibraryex-load-library-search-dll-load-dir-loading-w - -[^6_20]: https://www.reddit.com/r/programming/comments/d4xx1/windows_dllloading_security_flaw_puts_microsoft/ - -[^6_21]: https://bugs.python.org/issue36085 - -[^6_22]: https://colinfay.me/r-installation-administration/add-on-packages.html - -[^6_23]: https://community.alteryx.com/discussion/996509/r-package-error-unable-to-load-shared-object-vctrs-dll - -[^6_24]: https://github.com/Rdatatable/data.table/issues/3056 - -[^6_25]: https://rstudio.github.io/r-manuals/r-admin/Add-on-packages.html - -[^6_26]: https://rdrr.io/cran/pkgload/src/R/load-dll.R - -[^6_27]: https://svn.r-project.org/R/branches/djm-tcltk/src/library/base/R/dynload.R - -[^6_28]: https://www.reddit.com/r/learncpp/comments/unwwhs/how_do_programs_execute_with_dlls_in_separate/ - -[^6_29]: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/dyn.load - -[^6_30]: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-redirection - -[^6_31]: https://rdrr.io/r/base/library.dynam.html - -[^6_32]: https://stackoverflow.com/questions/30034542/unable-to-load-any-package-in-r-unable-to-load-shared-object - -[^6_33]: https://discourse.mc-stan.org/t/simple-stupid-problem-with-windows-rstan-suddenly-not-finding-dll-properly/24698 - -[^6_34]: https://stackoverflow.com/questions/38952571/how-to-load-custom-dll-in-r - -[^6_35]: https://forum.posit.co/t/every-libraries-failed-to-load-after-upgrading-r-to-3-6-0/29736 - -[^6_36]: https://stat.ethz.ch/R-manual/R-devel/library/base/help/library.dynam.html - -[^6_37]: https://github.com/RcppCore/Rcpp/issues/1095 - -[^6_38]: https://forum.posit.co/t/r-studio-package-installation-error-dyn-load-file-dllpath-dllpath/193962 - -[^6_39]: https://github.com/r-spatial/sf/discussions/2502 - -[^6_40]: https://wiki.tcl-lang.org/page/Extending+the+DLL+Search+Path+on+Windows - -[^6_41]: https://ploomber.io/blog/shiny-sf-fix/ - -[^6_42]: https://forums.ni.com/t5/LabWindows-CVI/Giving-the-path-to-a-DLL-in-the-EXE/td-p/4434761 - -[^6_43]: https://stackoverflow.com/questions/51210587/sf-on-r-3-5-cant-find-correct-version-of-gdal - -[^6_44]: https://www.rdocumentation.org/packages/terra/versions/0.2-8 - -[^6_45]: https://rspatial.github.io/terra/ - -[^6_46]: https://r-spatial.org/r/2020/03/17/wkt.html - -[^6_47]: https://stackoverflow.com/questions/21662728/cant-load-a-dll-file-in-r-using-dyn-load-windows-7-64bit - -[^6_48]: https://community.databricks.com/t5/data-engineering/unable-to-install-r-geospatial-libraries-raster-terra-sf-ncdf4/td-p/4723 - -[^6_49]: https://www.youtube.com/watch?v=2GNmhmoIiJs - -[^6_50]: https://stackoverflow.com/questions/62820628/on-windows-is-it-possible-to-get-dlls-to-look-for-dependencies-in-another-folde - -[^6_51]: https://andresrcs.rbind.io/2020/10/26/customizing_library_path/ - -[^6_52]: https://stat.ethz.ch/R-manual/R-patched/library/base/html/libPaths.html - -[^6_53]: https://rdrr.io/cran/librarian/man/lib_startup.html - -[^6_54]: https://docs.tibco.com/pub/enterprise-runtime-for-R/6.1.1/doc/html/Language_Reference/base/library.dynam.html - -[^6_55]: https://www.reddit.com/r/cpp_questions/comments/1bc7hdh/change_dll_path_for_a_compiled_program/ - -[^6_56]: https://discourse.mc-stan.org/t/error-when-configuring-rstan-c-toolchain/17915 - -[^6_57]: https://ibob.bg/blog/2018/12/16/windows-rpath/ - -[^6_58]: https://forum.posit.co/t/problems-with-r-4-0-0-windows-error-package-or-namespace-load-failed-for-stats-in-indl-x-as-logical-local-as-logical-now/62958 - -[^6_59]: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/library.dynam - -[^6_60]: https://github.com/r-spatial/discuss/issues/31 - -[^6_61]: https://www.reddit.com/r/gis/comments/1517den/trouble_with_installing_gdal/ - -[^6_62]: https://gdal.org/en/stable/development/building_from_source.html - -[^6_63]: https://github.com/astral-sh/uv/issues/11466 - -[^6_64]: https://geocompx.org/post/2023/rgdal-retirement/ - -[^6_65]: https://github.com/OSGeo/gdal/issues/5270 - -[^6_66]: https://cran.r-project.org/web/packages/gdalraster/readme/README.html - -[^6_67]: https://cran.r-project.org/web/packages/gdalraster/gdalraster.pdf - -[^6_68]: https://r-spatial.github.io/evolution/ogh23_bivand.html - -[^6_69]: https://www.hypertidy.org/posts/2017-09-01_gdal-in-r/ - -[^6_70]: https://www.nuget.org/packages/MaxRev.Gdal.WindowsRuntime.Minimal - -[^6_71]: https://stackoverflow.com/questions/34408699/having-trouble-installing-gdal-for-python-on-windows - -[^6_72]: https://wiki.bwhpc.de/e/BwUniCluster2.0/Software/R/terra - -[^6_73]: https://stackoverflow.com/questions/44973639/trouble-installing-sf-due-to-gdal - -[^6_74]: https://rdrr.io/cran/terra/man/gdal.html - -[^6_75]: https://www.reddit.com/r/rust/comments/1b2rlrs/quick_question_about_bundling_dll_files/ - -[^6_76]: http://hpc-community.unige.ch/t/problem-installing-sf-units-package-in-r-4-4-2/4143 - -[^6_77]: https://www.rdocumentation.org/packages/terra/versions/0.9-12 - -[^6_78]: https://github.com/rspatial/terra - -[^6_79]: https://thinkr.fr/Installation_spatial_EN.html - -[^6_80]: https://firelab.github.io/gdalraster/ - -[^6_81]: https://www.codeguru.com/windows/application-specific-paths-for-dll-loading/ - -[^6_82]: https://www.youtube.com/watch?v=4viTd3n9C9g - -[^6_83]: https://rasterio.readthedocs.io/en/latest/topics/switch.html - -[^6_84]: https://www.reddit.com/r/gis/comments/voafoy/how_do_i_successfully_install_gdal_on_windows/ - -[^6_85]: https://www.luisalucchese.com/post/solved-new-version-rasterio-gdal/ - -[^6_86]: https://www.hec.usace.army.mil/confluence/rasdocs/raski/latest/gdal-installation-issues - -[^6_87]: https://gdal.org/en/stable/programs/gdalwarp.html - -[^6_88]: https://stackoverflow.com/questions/63519334/how-can-i-link-r-packages-e-g-sf-or-mapview-to-the-latest-gdal-version - -[^6_89]: https://rspatial.r-universe.dev/terra/doc/readme.html - -[^6_90]: https://github.com/r-lib/withr - -[^6_91]: https://www.rdocumentation.org/packages/sf/versions/0.1-3 - -[^6_92]: https://kbroman.org/pkg_primer/pages/build.html - -[^6_93]: https://cran.r-project.org/package=sf - -[^6_94]: https://www.facebook.com/groups/ecologyinr/posts/1531673064362250/ - -[^6_95]: https://stackoverflow.com/questions/1474081/how-do-i-install-an-r-package-from-source - -[^6_96]: https://r-spatial.r-universe.dev/sf - -[^6_97]: https://datascienceplus.com/how-to-make-and-share-an-r-package-in-3-steps/ - -[^6_98]: https://www.100daysofredteam.com/p/what-is-dll-search-order-and-how - -[^6_99]: https://github.com/r-spatial/sf/issues/266 - -[^6_100]: https://github.com/rust-lang/rust/issues/56056 - -[^6_101]: https://www.reddit.com/r/gis/comments/1hojo4t/whats_the_point_of_pip_install_gdal_eli5/ - -[^6_102]: https://cran.r-project.org/package=gdalraster - -[^6_103]: http://stefanoborini.com/windows-dll-search-path/ - -[^6_104]: https://stackoverflow.com/questions/11224123/load-time-dynamic-linking-import-library-search-order - -[^6_105]: https://www.youtube.com/watch?v=tjNEoIYr_ag - -[^6_106]: https://rasterio.readthedocs.io/en/stable/topics/switch.html - -[^6_107]: https://github.com/OSGeo/gdal/issues/3368 - -[^6_108]: https://stackoverflow.com/questions/110249/building-and-deploying-dll-on-windows-sxs-manifests-and-all-that-jazz - -[^6_109]: https://stackoverflow.com/questions/51367237/sf-r-package-is-not-compatible-with-gdal-versions-below-2-0-0-after-installing - -[^6_110]: https://github.com/r-spatial/sf/issues/408 - -[^6_111]: https://discussions.unity.com/t/importing-gdal-from-nuget-package/757823 - -[^6_112]: https://pypi.org/project/GDAL/ - -[^6_113]: https://firelab.r-universe.dev/gdalraster - -[^6_114]: https://gdal.org/en/stable/programs/gdal_raster_blend.html - -[^6_115]: https://github.com/microsoft/vcpkg/discussions/36990 - -[^6_116]: https://cran.r-project.org/bin/windows/Rtools/rtools45/rtools.html - -[^6_117]: https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/INSTALL - -[^6_118]: https://stat.ethz.ch/R-manual/R-devel/library/utils/html/INSTALL.html - -[^6_119]: https://cran.r-project.org/package=terra - -[^6_120]: https://forums.opensuse.org/t/rstudio-dependencies-and-pkg-config/153749 - -[^6_121]: https://stackoverflow.com/questions/53279685/r-make-not-found-when-installing-a-r-package-from-local-tar-gz - -[^6_122]: https://cran.r-project.org/bin/windows/base/howto-R-4.2.html - -[^6_123]: https://stackoverflow.com/questions/75943925/how-to-fix-problem-with-installation-of-packages-raster-terra-rgdal-ra - -[^6_124]: https://github.com/cran/rgdal/blob/master/inst/README.windows - -[^6_125]: https://docs.alliancecan.ca/wiki/GDAL - -[^6_126]: https://discourse.mc-stan.org/t/trouble-installing-rstan-on-windows/14773 - -[^6_127]: https://www.reddit.com/r/linux4noobs/comments/pybvdv/difference_between_binaries_and_libraries/ - -[^6_128]: https://forums.raspberrypi.com/viewtopic.php?t=204543 - -[^6_129]: https://www.jsoftware.com/help/user/dll_so.htm - -[^6_130]: https://stackoverflow.com/questions/62415074/difference-between-shared-library-so-a-linux-executable-file-without-extensio - -[^6_131]: https://en.wikipedia.org/wiki/Shared_library - -[^6_132]: https://www.sandordargo.com/blog/2024/10/02/dynamic-vs-static-linking - -[^6_133]: https://www.msys2.org/docs/environments/ - -[^6_134]: https://caiorss.github.io/C-Cpp-Notes/DLL-Binary-Components-SharedLibraries.html - -[^6_135]: https://news.ycombinator.com/item?id=32531224 - -[^6_136]: https://stackoverflow.com/questions/1993390/static-linking-vs-dynamic-linking - -[^6_137]: https://stackoverflow.com/questions/76552264/what-are-msys2-environments-how-do-i-pick-one - -[^6_138]: https://github.com/databrickslabs/mosaic/issues/524 - -[^6_139]: https://github.com/caiorss/C-Cpp-Notes/blob/master/DLL-Binary-Components-SharedLibraries.org - -[^6_140]: https://forum.dlang.org/thread/dobouzmhwabquswguunk@forum.dlang.org - -[^6_141]: https://devinsights.iblogger.org/msys2-environment-differences/ - -[^6_142]: https://www.reddit.com/r/C_Programming/comments/1lw83ye/how_to_install_64bit_msys2_really/ - -[^6_143]: https://github.com/msys2/MSYS2-packages/discussions/4706 - -[^6_144]: https://stackoverflow.com/questions/15082060/set-up-a-msvc-dll-to-be-abi-compatible-to-a-stdcall-mingw-dll - -[^6_145]: https://gitforwindows.org/the-difference-between-mingw-and-msys2.html - -[^6_146]: https://ziggit.dev/t/windows-gnu-mingw-and-msvc-binary-c-abi-compatibility-guarantees/6903 - -[^6_147]: https://forum.crystal-lang.org/t/how-to-detect-the-current-msys2-environment-ucrt64-mingw64-clang64-on-windows/8090 - -[^6_148]: https://github.com/dotnet/sdk/issues/33845 - -[^6_149]: https://github.com/llvm/llvm-project/issues/60847 - -[^6_150]: https://github.com/microsoft/vscode-cpptools/issues/11063 - -[^6_151]: https://github.com/r-spatial/sf - -[^6_152]: https://github.com/rspatial/terra/issues/487 - -[^6_153]: https://community.databricks.com/t5/data-engineering/install-r-package-quot-sf-quot/td-p/60090 - -[^6_154]: https://stackoverflow.com/questions/74575722/most-recent-terra-package-for-r-will-not-compile - -[^6_155]: https://stackoverflow.com/questions/6009506/unable-to-install-python-and-gdal-dll-load-failed - -[^6_156]: https://github.com/pyinstaller/pyinstaller/issues/1376 - -[^6_157]: https://github.com/r-spatial/sf/issues/2159 - -[^6_158]: https://cran.r-project.org/doc/manuals/r-release/R-exts.html - -[^6_159]: https://stackoverflow.com/questions/315285/can-i-use-two-incompatible-versions-of-the-same-dll-in-the-same-process - -[^6_160]: https://stackoverflow.com/questions/40634484/correct-installation-of-rtools-on-windows - -[^6_161]: https://faims2-documentation.readthedocs.io/en/latest/Installing+GDAL+Tools+on+Windows/ - -[^6_162]: https://colinfay.me/writing-r-extensions/creating-r-packages-1.html - -[^6_163]: https://gamedev.net/forums/topic/677890-dll-access-mechanism-between-multiple-applications/ - -[^6_164]: https://stackoverflow.com/questions/72386315/is-it-possible-for-a-process-to-load-two-dll-with-same-name-but-different-versio - -[^6_165]: http://forum.vvvv.org/t/how-to-deal-with-different-versions-of-same-dll/14330 - -[^6_166]: https://learn.microsoft.com/en-us/answers/questions/5652481/how-to-use-multiple-dlls-with-the-same-name - -[^6_167]: https://michaelscodingspot.com/dotnet-dll-hell/ - -[^6_168]: https://dev.to/johnnymakestuff/how-to-use-two-versions-of-the-same-dll-in-the-same-project-31db - -[^6_169]: https://stackoverflow.com/questions/38698293/can-i-get-separate-dlls-to-resolve-their-imported-dlls-separately - -[^6_170]: https://devnet.kentico.com/articles/referencing-multiple-versions-of-the-same-assembly-in-a-single-application - -[^6_171]: https://www.reddit.com/r/csharp/comments/1h4qzte/is_a_dll_when_loaded_considered_as_another_process/ - -[^6_172]: http://mynameiskali.blogspot.com/p/c-20-using-different-versions-of-same_24.html - -[^6_173]: https://rdrr.io/r/base/dynload.html - -[^6_174]: https://forums.ni.com/t5/LabVIEW/Execute-multiple-versions-of-the-same-NET-DLL/td-p/4192116 - -[^6_175]: https://www.reddit.com/r/csharp/comments/10gvqki/why_are_there_different_versions_for_the_same_dll/ - -[^6_176]: https://stat.ethz.ch/R-manual/R-devel/library/base/help/dyn.load.html - -[^6_177]: https://learn.microsoft.com/en-us/windows/win32/dlls/about-dynamic-link-libraries - diff --git a/dev/docs/reference/Custom GDAL Runtime on Windows Streamlining gdalraster.windows and Extending to sf and terra.md b/dev/docs/reference/Custom GDAL Runtime on Windows Streamlining gdalraster.windows and Extending to sf and terra.md deleted file mode 100644 index 0f99baa..0000000 --- a/dev/docs/reference/Custom GDAL Runtime on Windows Streamlining gdalraster.windows and Extending to sf and terra.md +++ /dev/null @@ -1,267 +0,0 @@ -# Custom GDAL Runtime on Windows: Streamlining `gdalraster.windows` and Extending to `sf` and `terra` - -## Executive Summary - -The `gdalraster.windows` package solves a genuine, deep problem: the Rtools45 MXE build of GDAL historically omitted `muparser` and shipped with the static-registration bug that left the Algorithm API registry empty. The current implementation is already architecturally sound, but several design decisions leave friction for users and create integration complexity when adding `sf` and `terra`. This report synthesizes grounded reality — the actual `Makevars.ucrt` files in both packages, the Windows DLL loader semantics, and the upstream GDAL fix trajectory — to provide actionable guidance on streamlining the existing solution and extending it correctly.[^1][^2][^3][^4] - -*** - -## Part 1: The Present State of the Ecosystem - -### Upstream GDAL Fix and Its Implications - -The bug that motivated `gdalraster.windows` — static algorithm self-registration being dead-stripped by the MXE static-archive linker — was patched upstream in GDAL 3.12.2 via a PR that explicitly links registration objects. The next Rtools UCRT64 revision targeting GDAL 3.13.x is expected to carry both this fix and `muparser`. This matters for scoping: once that Rtools release lands, the CRAN binary of `gdalraster` will work correctly for the Algorithm API *without* the custom bundle. However, `gdalraster.windows` retains ongoing value beyond the bug fix:[^2][^1] - -- It pins a user-controlled GDAL version independently of Rtools release cadence -- It enables drivers (Arrow, Parquet, HDF5, NetCDF) that the lean MXE build may not compile in -- It provides a reproducible pipeline for any downstream custom GDAL feature requirement -- It can serve as the single shared GDAL runtime for `sf` and `terra` in the same session - -The package should therefore be repositioned in its README and documentation from "workaround for issue #826" to "custom GDAL feature-set manager for Windows R spatial workflows." - -### What the CRAN Binaries for sf and terra Actually Bundle - -Both `sf` (CRAN) and `terra` (CRAN) on Windows ship as pre-compiled binaries that statically link against the Rtools UCRT64 sysroot at CRAN build time. The `Makevars.ucrt` for both packages is identical in structure: - -```makefile -ifeq (,$(shell pkg-config --version 2>/dev/null)) - PKG_LIBS = -fopenmp -lgdal ... [~50 static Rtools libs] ... -lproj -lsqlite3 ... -else - PKG_LIBS = $(shell pkg-config --libs gdal geos proj) -endif - -all: clean winlibs - -winlibs: - cp -r "$(R_TOOLS_SOFT)/share/gdal" ../inst/ - cp -r "$(R_TOOLS_SOFT)/share/proj" ../inst/ -``` - - - -The `ifeq` block checks whether `pkg-config` is available. At CRAN build time on the Windows builder, `pkg-config` is not on the PATH in the standard Rtools environment, so the `ifeq` branch fires and the packages link against Rtools' 50-library static list. The `winlibs:` target copies GDAL and PROJ data files from the Rtools sysroot (`R_TOOLS_SOFT`) directly into each package's `inst/` directory, making the CRAN binaries fully self-contained — they do not require any system GDAL to be present at runtime. This is why `sf` "just works" on a stock Windows R install with no external libraries. - -The key insight is that `terra` adds one extra element in the `pkg-config` branch that the `ifeq` branch lacks: - -```makefile -else - PKG_LIBS = $(shell pkg-config --libs gdal geos proj) - PKG_LIBS += -ltbb12 - PKG_CXXFLAGS += -DHAVE_TBB -endif -``` - -This means a source-rebuild of `terra` against a custom GDAL using the `pkg-config` path will try to link against `libtbb12`. This library must either be in the bundle or provided separately — Intel TBB is available in UCRT64 (`ucrt64/lib/libtbb12.dll.a`) and would need to be included in `collect_dlls.sh`'s sweep. - -*** - -## Part 2: The Windows DLL Conflict Problem in Precise Terms - -### How Windows Resolves DLL Identity - -Windows' `LdrpLoadLibrary` identifies a DLL by its module name (filename only, case-insensitive), not its full path. The first call to `LoadLibrary("libgdal-39.dll")` maps the file into the process's virtual address space and creates an entry in the loaded module list keyed by `"libgdal-39.dll"`. Any subsequent `LoadLibrary("libgdal-39.dll")` — regardless of whether the DLL is in a different directory — simply increments the reference count on the already-loaded module and returns the same handle. There is no process-level equivalent of Linux `RTLD_LOCAL` that would create an independent copy.[^3][^4] - -This creates a strict constraint: **in any R session that loads both `gdalraster` (from the custom bundle) and `sf`/`terra` (CRAN binaries), there can only be one active `libgdal-39.dll` in memory.** The one that wins is whichever package gets `dyn.load`-ed first. - -There is one partial escape hatch: loading a DLL by its *full absolute path* via `LoadLibrary` can force a separate mapping if the filenames differ. Two DLLs with the same filename but in different directories cannot coexist unless copied and renamed. This is not a practical approach for R package integration.[^5][^6] - -### The Safe DLL Search Order - -When `dyn.load(dll_path, local=FALSE, now=TRUE)` is called with a full absolute path (as `activate_gdal_runtime()` does), Windows maps that specific file. The subsequent implicit loads triggered by `library(sf)` will call `LoadLibrary("libgdal-39.dll")` *without* a full path; the loader will then check the already-loaded module list first. If the custom bundle's `libgdal-39.dll` was already loaded by the explicit path call, the loader returns the already-mapped module — and `sf` runs against the custom GDAL.[^4] - -This means the activation-first ordering in `activate_gdal_runtime()` is not merely a best practice — it is the *only* mechanism by which CRAN binary `sf`/`terra` can be coerced to use the custom GDAL at runtime. - -### Dependency DLL Resolution After Load - -A subtlety documented in MSDN and confirmed by Windows loader research: when the loader resolves a DLL's *import dependencies* (the DLLs listed in its import address table), it uses the DLL search order based on the *calling process's* current search path at the time the parent DLL is loaded, not the path of the parent DLL itself. This means that even if `libgdal-39.dll` is loaded from `C:\Users\Jimmy\AppData\Local\gdalraster.windows\bin\`, its own dependencies (e.g., `libproj-*.dll`, `libgeos_c-*.dll`) will be searched via the standard DLL search order: application directory → system directories → `PATH`.[^7][^4] - -This is why `activate_gdal_runtime()` prepending `bin/` to `PATH` *before* the `dyn.load()` call is architecturally correct: at the moment the loader resolves `libgdal-39.dll`'s transitive dependencies, the bundle's `bin/` directory is already first on `PATH`. - -*** - -## Part 3: Streamlining the Current gdalraster.windows Implementation - -### The `--allow-multiple-definition` Flag - -The current `install_gdalraster()` passes `-Wl,--allow-multiple-definition` in `PKG_LIBS`. This is a linker flag that suppresses duplicate symbol errors — a red flag that indicates two or more object files or archives in the link define the same symbol. This almost certainly arises from symbol overlap between the custom bundle's `libgdal.dll.a` import library and residual static archives from Rtools that get pulled in by gdalraster's own transitive dependencies. - -The correct fix is to ensure the import library provided to the linker comes *only* from the custom bundle, with no Rtools static archives for GDAL or GDAL-linked libraries mixed in. This can be achieved by explicitly controlling the library search path order: `-L"$(GDAL_HOME)/lib" -lgdal` with no `-L$(R_TOOLS_SOFT)/lib` before it. If Rtools' GDAL `.a` files are still being found, adding `-L` for the bundle path *and* using `-Wl,--no-undefined` would make the linker error visibly on what symbol is truly duplicated, so it can be resolved rather than suppressed. - -### The DLL Version Hardcode in `build_gdal.sh` - -The verification step `ls -lh "${INSTALL_DIR}/bin/libgdal-39.dll"` hardcodes the SONAME version `39`. When GDAL bumps its SONAME (which happens on major API version changes), this will produce a silent false negative — the script will exit with an error about a missing file even though the build succeeded and produced `libgdal-40.dll`. The fix is straightforward: use `libgdal-*.dll` as the glob pattern, consistent with how the rest of the codebase already matches DLL names. - -### Session Startup Sequencing - -The current `.onLoad` / `startup_bootstrap()` approach in `zzz.R` runs `activate_gdal_runtime()` followed by `load_gdalraster()` automatically when `auto_bootstrap` is enabled. This is correct but has a subtle ordering problem: if `sf` or `terra` is already loaded *before* `library(gdalraster.windows)` is called (common in scripts that do `library(sf); library(gdalraster.windows)`), the custom GDAL's DLL loses the race — `sf`'s import of `libgdal-N.dll` from Rtools' embedded copy has already won. - -The recommended fix is to document prominently (and enforce with a warning) that `library(gdalraster.windows)` must be the *first* spatial package loaded in the session. This could be implemented as a check in `activate_gdal_runtime()`: - -```r -already_loaded <- any(c("sf", "terra") %in% loadedNamespaces()) -if (already_loaded) { - cli::cli_warn(c( - "!" = "sf or terra was loaded before gdalraster.windows.", - "i" = "The custom GDAL runtime may not be active for those packages.", - "i" = "Restart R and load gdalraster.windows first." - )) -} -``` - -### The `.Rprofile` Hook Approach - -The managed marker block in `startup_hook.R` (`add_gdal_rprofile_hook()`) is the right way to handle persistent session setup. However, there is a race condition if the user's `.Rprofile` also loads `sf` (via `library(sf)` or through another package's `.Rprofile` hook) before the `gdalraster.windows` hook runs. R processes `.Rprofile` line by line, so hook ordering matters. The hook should be written to execute as early as possible in `.Rprofile`, and documentation should advise users to place the `gdalraster.windows` hook before any other spatial package calls. - -*** - -## Part 4: Extending to sf and terra — The Full Landscape - -### Three Integration Models - -There are three distinct ways `sf` and `terra` can coexist with the custom GDAL bundle, each with different correctness guarantees: - -| Model | How it works | DLL conflict risk | Effort | Recommended for | -|-------|-------------|------------------|--------|-----------------| -| **Runtime-only coexistence** | CRAN binaries + activation-first ordering | Low (if ordering held) | None | Casual use, read-only operations | -| **Source rebuild against bundle** | `install_sf()` / `install_terra()` wrappers in `gdalraster.windows` | None | High | Production workflows needing Arrow/Parquet drivers in sf/terra | -| **Pixi/conda-forge unified environment** | All packages built by conda-forge against the same GDAL | None (separate namespace) | Medium | Cross-platform reproducibility | - -### Model 1: Runtime-Only Coexistence - -For users who load CRAN binary `sf`/`terra` alongside the custom `gdalraster`, the only requirement is the ordering guarantee: `activate_gdal_runtime()` and `dyn.load(dll_path)` must complete before any `library(sf)` or `library(terra)` call. Under this model, `sf` and `terra` will use the custom GDAL at runtime for all file I/O and geometry operations, but the binary was compiled against Rtools' GDAL, meaning: - -- Arrow/Parquet read capabilities in `sf::st_read()` will not be available (the binary wasn't compiled with those drivers) -- The GDAL version seen at runtime (`sf::sf_extSoftVersions()`) may report the custom version, but driver availability is determined at compile time -- This is functionally safe for everything except driver-specific features not in the Rtools build - -This is the lowest-friction path and appropriate for most use cases once the upstream Rtools GDAL version catches up. - -### Model 2: Source Rebuild — Architecture and Key Differences - -An `install_sf()` function in `gdalraster.windows` would follow the same `withr::with_makevars` / `withr::with_envvar` pattern as `install_gdalraster()`. However, both `sf` and `terra`'s `Makevars.ucrt` introduce complications that do not exist for `gdalraster`: - -**The `pkg-config` branch gating.** Both packages' `Makevars.ucrt` only use the clean `pkg-config --libs gdal geos proj` flag generation if `pkg-config` is available on `PATH`. In the standard Rtools45 environment, `pkg-config` is absent. The MSYS2 UCRT64 package `mingw-w64-ucrt-x86_64-pkg-config` provides it and it is present in MSYS2 shells, but when the source install runs inside an R process via `withr::with_envvar`, `pkg-config` will only be visible if the MSYS2 `bin/` path is in `PATH` at that moment. - -The correct approach is to either: -1. Add the MSYS2 `bin/` to `PATH` in the `withr::with_envvar` scope, or -2. Explicitly set `R_TOOLS_SOFT` in the scoped environment to point at the custom bundle root, so the `ifeq` branch fires but `winlibs:` copies data from the bundle rather than Rtools - -Option 2 is architecturally cleaner because it avoids the `pkg-config` dependency and means the `~50 static lib` list in the `ifeq` branch is used — but those 50 libraries must actually exist in the bundle's `lib/` directory as `.a` files for the link to succeed. This makes it essential that `build_gdal.sh` produces matching static archives for every library in that list. - -**The `winlibs:` data copy.** Both `sf` and `terra` have an unconditional `winlibs:` target that does `cp -r "$(R_TOOLS_SOFT)/share/gdal" ../inst/` and `cp -r "$(R_TOOLS_SOFT)/share/proj" ../inst/`. This is the mechanism by which `sf` and `terra` bundle GDAL and PROJ data files inside the package installation, making them self-contained. If `R_TOOLS_SOFT` is overridden to the bundle's root, this will copy the bundle's `share/gdal/` and `share/proj/` into each package's `inst/`, which is the correct desired behavior — each package carries its own copy of the data from the same source. - -The `install_sf()` wrapper therefore needs to set `R_TOOLS_SOFT` in `Makevars` so the `winlibs:` target resolves correctly: - -```r -makevars <- c( - R_TOOLS_SOFT = gdal_home, # → winlibs: copies share/gdal, share/proj from bundle - PKG_CPPFLAGS = paste0('-DHAVE_PROJ_H -I"', file.path(gdal_home, "include"), '"'), - PKG_LIBS = paste0('-L"', file.path(gdal_home, "lib"), '" -lgdal -lgeos_c -lproj ...') -) -``` - -**TBB requirement for terra.** The `pkg-config` branch in `terra`'s `Makevars.ucrt` adds `-ltbb12` and `-DHAVE_TBB`. The `ifeq` branch does not include TBB (there is a commented-out `-ltbb_static` line), meaning a source rebuild using the `ifeq` path will compile without TBB parallelism. This is a functionally acceptable trade-off: `terra` works without TBB, just without multithreaded raster operations. Alternatively, `libtbb12` from UCRT64 can be bundled alongside the GDAL bundle and added to `PKG_LIBS`. - -**GEOS dependency.** Both `sf` and `terra` link against `libgeos_c` and `libgeos`, which must be provided by the bundle. GDAL itself depends on GEOS and includes it in its own link graph, but the `.a` file must also be available at `gdal_home/lib/libgeos_c.a` and `libgeos.a` for `sf`'s and `terra`'s compiler invocations to succeed. - -### The `HAVE_PROJ_H` Flag for sf - -`sf`'s `Makevars.ucrt` hardcodes `-DHAVE_PROJ_H` in `PKG_CPPFLAGS` regardless of the `ifeq`/`else` branch. This flag signals that PROJ's C API header (`proj.h`, the modern API, as opposed to the deprecated `projects.h`) is present. When performing a source rebuild, this flag must remain in the `PKG_CPPFLAGS` passed via `withr::with_makevars`. If the bundle's PROJ include directory provides `proj.h` (it will if PROJ >= 6 was used, which is the case for any modern GDAL build), this flag will be correct. - -### The s2 Geometry Dependency - -`sf` uses the `s2` R package for geodetic geometry operations on long/lat coordinates by default (since sf 1.0). `s2` has its own compiled C++ code that bundles Google's S2 geometry library directly and does *not* link against GDAL at all. This means `s2` is immune to the DLL conflict problem — it can be installed from CRAN as a binary without any interaction with the custom GDAL bundle.[^8] - -### Model 3: Pixi/conda-forge Unified Environment - -The cleanest theoretical solution — and the one that already works for your Linux WSL setup — is using `pixi` or `conda-forge` to manage a unified environment where GDAL, `r-sf`, `r-terra`, and `r-gdalraster` are all built by conda-forge against the same `libgdal` package. On Windows, this means running R through the pixi/conda environment rather than standalone Rtools R.[^9] - -The `conda-forge` channel provides `r-gdalraster` binaries and builds `r-sf` and `r-terra` via `r-spatial` feedstocks — all against the same conda-forge GDAL. There is no DLL conflict because all packages are compiled against the same shared library; `libgdal-arrow-parquet` can be installed as a plugin.[^10][^9] - -The trade-off is that running R through a conda/pixi environment on Windows requires either the conda command-line environment or a conda-aware IDE configuration, which diverges from the standard "open RStudio, install from CRAN" workflow. For a consulting engineering context, this may or may not be acceptable depending on whether end-users need to reproduce the environment. - -*** - -## Part 5: Recommended Implementation Roadmap - -### Immediate: Streamlining What Exists - -1. **Remove `--allow-multiple-definition`** from `install_gdalraster()`. Add a diagnostic that identifies the duplicate symbols (`-Wl,--warn-duplicate-common`) and fix the root cause by ensuring no Rtools GDAL archives contaminate the link. - -2. **Fix the hardcoded DLL version check** in `build_gdal.sh` from `libgdal-39.dll` to `libgdal-*.dll`. - -3. **Add an early warning in `activate_gdal_runtime()`** if `sf` or `terra` namespaces are already loaded, directing users to restart R and load the custom runtime first. - -4. **Expose a `gdal_runtime_info()` function** (similar to `sf::sf_extSoftVersions()`) that returns the active GDAL version, build drivers, muparser availability, and Arrow/Parquet status as a named list. This gives users immediate diagnostic information. - -5. **Add the `.Rprofile` hook ordering note** to documentation: the `gdalraster.windows` hook must appear before any other spatial package calls in `.Rprofile`. - -### Near-Term: sf and terra Integration - -6. **Implement `install_sf()` and `install_terra()` wrapper functions** using the `withr::with_makevars` + `withr::with_envvar` pattern, setting `R_TOOLS_SOFT` to the bundle root so the `winlibs:` target copies data correctly. Target the `ifeq` branch path for initial simplicity. - -7. **Extend `collect_dlls.sh`** to explicitly check for `libgeos_c-*.dll` and verify it is bundled — currently the `ntldd -R` sweep should pick it up, but an explicit assertion would make failure modes visible in CI. - -8. **Bundle `libtbb12.dll`** from UCRT64 in the bundle's `bin/` for `terra` TBB support, and add it to the `collect_dlls.sh` allow-list. - -9. **Implement `verify_sf_runtime()` and `verify_terra_runtime()`** smoke tests that check `sf::gdal_version()` and `terra::gdal()` report the expected version number, confirming the source-rebuilt packages are actually using the custom GDAL. - -### Longer-Term: CI Integration - -10. **Add a Job 3** to the GitHub Actions workflow that performs the `install_sf()` + `install_terra()` source rebuilds using the bundle produced by Job 1, then loads all three packages in the same R session and verifies: - - `sf::gdal_version()` matches the custom version - - `terra::gdal()` matches the custom version - - `gdalraster::gdal_version()` matches - - `sf::st_drivers()` includes `Arrow` and `Parquet` - - `gdalraster::gdal_global_reg_names()` returns non-empty - - All three packages report consistent GDAL, GEOS, and PROJ versions - -This CI job provides the correctness guarantee that is currently impossible to achieve with CRAN binaries. - -*** - -## Part 6: The Linux Parallel and Key Divergence - -The pixi-managed GDAL 3.13 approach that works cleanly on WSL differs from the Windows situation in three fundamental ways that explain why the solution is easier on Linux:[^9] - -| Property | Linux (ELF) | Windows (PE/COFF) | -|----------|-------------|-------------------| -| Runtime library identity | SONAME embedded in `.so` at link time | Filename only, determined at load time | -| Multiple same-name libs in process | Prevented by SONAME versioning; different SONAMEs coexist | Same filename → one canonical loaded instance regardless of path | -| Preferred search path in binary | `RPATH`/`RUNPATH` embedded at link time | Not supported; PATH-only at runtime | -| sf/terra "own GDAL" installation | installs `libgdal-dev` headers as sysreq, runtime controlled by `LD_LIBRARY_PATH` | Bundles complete static link into package `.dll`, no runtime system dependency | - -On Linux, `LD_PRELOAD` or `LD_LIBRARY_PATH` being set before R starts is sufficient to ensure all packages resolve to the pixi GDAL because the ELF dynamic linker evaluates `RPATH`/`RUNPATH` per-library. On Windows, there is no per-library equivalent — the only mechanism is the process-wide `PATH` order at the time each DLL is first `LoadLibrary`-called. The `activate_gdal_runtime()` design correctly handles this by calling `dyn.load(dll_path)` with a full absolute path before any package that would otherwise trigger an implicit `LoadLibrary` for `libgdal-N.dll`.[^9] - -*** - -## Conclusion - -The `gdalraster.windows` package is the right approach for the right problem. The core architecture — build a self-contained GDAL bundle in MSYS2 UCRT64, verify it is truly self-contained via `ntldd`, install `gdalraster` from source against it using scoped `Makevars` — is technically correct and robust. The refinements needed are largely about removing the `--allow-multiple-definition` workaround, hardening the activation-ordering guarantee, and extending the pattern to `sf` and `terra`. - -The sf/terra extension is feasible via source rebuild with `R_TOOLS_SOFT` override, but requires that the GDAL bundle provides compatible static archives for every library in `sf`/`terra`'s `Makevars.ucrt` link list. For users willing to run R through a pixi/conda-forge environment, Model 3 provides the cleanest multi-package coexistence because conda-forge builds all spatial R packages against its own internally consistent GDAL. The source-rebuild model within `gdalraster.windows` is the right approach for users who need to stay within the standard Rtools R environment while accessing a feature-complete GDAL.[^10][^9] - ---- - -## References - -1. [Enable muparser in the RTools build of GDAL (so that ... - GitHub](https://github.com/firelab/gdalraster/issues/858) - Start with a working RTools 4.5, revision 6691, that successfully builds R packages including gdalra... - -2. [https://raw.githubusercontent.com/OSGeo/gdal/maste...](https://raw.githubusercontent.com/OSGeo/gdal/master/NEWS.md) - GDAL 3.12.2 is a bugfix release. ## Build * Arrow/Parquet: fix build issue with libarrow 23.0 with p... - -3. [What Happens When You Load a Library - Aaron Ballman](https://blog.aaronballman.com/2011/08/what-happens-when-you-load-a-library/) - This explains why loading one library can suddenly pull in several others — they're necessary! After... - -4. [DLL Dynamic-Link Library Search Order - IAmAProgrammer - 博客园](https://www.cnblogs.com/shangdawei/p/4056967.html) - An application can also use LOAD_LIBRARY_SEARCH flags with the SetDefaultDllDirectories function to ... - -5. [Loading 2 DLLs of the Same Name. - limbioliong - WordPress.com](https://limbioliong.wordpress.com/2012/06/26/loading-2-dlls-of-the-same-name/) - You can use 2 different HMODULEs to obtain 2 function address from 2 different DLLs using the same f... - -6. [Multiple LoadLibrary for copies of the same DLL - Stack Overflow](https://stackoverflow.com/questions/38738899/multiple-loadlibrary-for-copies-of-the-same-dll) - I have a DLL which is not thread-safe and must be used by multiple threads. I am not sure how Window... - -7. [Understanding the Windows DLL Search Order: A Deep Dive into ...](https://www.akshayjain.blog/post/understanding-the-windows-dll-search-order-a-deep-dive-into-internals-and-security-implications) - Learn the technical workings of Windows DLL search order, its role in system behavior, and how attac... - -8. [Simple Features for R • sf - r-spatial](https://r-spatial.github.io/sf/) - Support for simple feature access, a standardized way to encode and analyze spatial vector data. Bin... - -9. [Download — GDAL documentation](https://gdal.org/en/stable/download.html) - The GDAL project distributes GDAL as source code and Containers only. Binaries produced by others ar... - -10. [r-gdalraster - conda-forge - Anaconda.org](https://anaconda.org/conda-forge/r-gdalraster) - Install r-gdalraster with Anaconda.org. API bindings to the Geospatial Data Abstraction Library ('GD... - diff --git a/tools/build_gdal.sh b/tools/build_gdal.sh index 0dd6fbe..eab2c92 100644 --- a/tools/build_gdal.sh +++ b/tools/build_gdal.sh @@ -24,6 +24,26 @@ # OS-provided DLL and breaks LoadLibrary on end-user machines that don't # have that driver installed. The MSSQLSpatial driver falls back to the # generic ODBC32-based path (same as the MSYS2 gdal package). +# - GDAL_ENABLE_DRIVER_PDF=OFF (plus GDAL_USE_POPPLER/PODOFO/PDFIUM=OFF) — +# libpodofo.dll fails its DllMain with ERROR_DLL_INIT_FAILED (1114) in +# ANY process (verified with plain LoadLibrary outside R) when it +# resolves the MSYS2-bundle libcrypto-3-x64.dll. PoDoFo performs OpenSSL +# initialization inside its static initializers (DllMain, under loader +# lock) and that init fails against the libcrypto builds shipped in the +# 2026-06/2026-07 bundles; preloading Rtools45's libcrypto (OpenSSL +# 3.6.2, C:\rtools45\ucrt64\bin) makes the identical libpodofo.dll load +# fine. Because libgdal imports libpodofo directly when the PDF driver +# is built, that single fragile dependency makes libgdal-*.dll itself +# unloadable. Turning off only GDAL_USE_POPPLER is NOT enough: the PDF +# driver then falls back to podofo. The driver must be disabled +# outright. PDF support is rarely needed in R spatial workflows, so this +# is a safe trade-off. +# Empirical note (2026-07): every other bundled DLL — including +# libopenblas/libgfortran-5/libgomp-1 (HDF5 chain) and nss3/libpoppler — +# loads cleanly via dyn.load() inside an R 4.6 (Rtools45-era) session. +# An earlier theory that the HDF5→OpenBLAS→Fortran chain conflicts with +# Rtools DLLs already loaded by R was disproven by that test, so HDF5 and +# NetCDF stay enabled. # ============================================================================= set -euo pipefail @@ -75,12 +95,16 @@ cmake -B build -G Ninja \ -DGDAL_USE_MUPARSER=ON \ -DGDAL_USE_ARROW=ON \ -DGDAL_USE_PARQUET=ON \ - -DGDAL_USE_HDF5=ON \ - -DGDAL_USE_NETCDF=ON \ -DGDAL_USE_GEOS=ON \ -DGDAL_USE_SPATIALITE=ON \ + -DGDAL_USE_HDF5=ON \ + -DGDAL_USE_NETCDF=ON \ -DGDAL_HIDE_INTERNAL_SYMBOLS=ON \ \ + -DGDAL_ENABLE_DRIVER_PDF=OFF \ + -DGDAL_USE_POPPLER=OFF \ + -DGDAL_USE_PODOFO=OFF \ + -DGDAL_USE_PDFIUM=OFF \ -DGDAL_USE_MSSQL_ODBC=OFF \ -DGDAL_USE_MSSQL_NCLI=OFF \ \ diff --git a/tools/collect_dlls.sh b/tools/collect_dlls.sh index bddcc40..a9ecf3f 100644 --- a/tools/collect_dlls.sh +++ b/tools/collect_dlls.sh @@ -94,6 +94,28 @@ if [[ -z "${GDAL_DLL}" ]]; then exit 1 fi +# Guard: the PDF driver must stay disabled (GDAL_ENABLE_DRIVER_PDF=OFF in +# build_gdal.sh). The MSYS2 libpodofo.dll fails DllMain with +# ERROR_DLL_INIT_FAILED (1114) in any process, which makes a libgdal that +# imports it unloadable. Poppler's NSS/NSPR chain is banned alongside it so a +# config regression re-enabling the driver via either backend fails the build +# here instead of shipping a broken bundle. +banned_dep_regex='^(libpodofo[^ ]*\.dll|libpoppler[^ ]*\.dll|nss3\.dll|nssutil3\.dll|smime3\.dll|libnspr4\.dll|nspr4\.dll|libplc4\.dll|libplds4\.dll)$' +banned_found="$( + ntldd -R "${GDAL_DLL}" \ + | awk '{ if ($2 != "=>") next; print tolower($1) }' \ + | sort -u \ + | grep -E "${banned_dep_regex}" || true +)" +if [[ -n "${banned_found}" ]]; then + echo "" + echo "FATAL: libgdal links banned dependency DLLs (broken/unnecessary at runtime):" + printf ' %s\n' ${banned_found} + echo "" + echo "Re-check the PDF driver flags in tools/build_gdal.sh and rebuild." + exit 1 +fi + # Note: with "set -euo pipefail", grep returns 1 when there are no matches. # That is valid here, so we parse defensively and never fail on "no deps found". deps_to_copy="$( diff --git a/vignettes/architecture.qmd b/vignettes/architecture.qmd index d88125d..41a0400 100644 --- a/vignettes/architecture.qmd +++ b/vignettes/architecture.qmd @@ -65,6 +65,7 @@ From [`tools/build_gdal.sh`](https://github.com/jimbrig/gdalraster.windows/blob/ |------|---------| | `-DGDAL_USE_MUPARSER=ON` | Algorithm API support (expression evaluation) | | `-DGDAL_USE_ARROW/PARQUET/HDF5/NETCDF/GEOS/SPATIALITE=ON` | Extended driver profile beyond the lean Rtools build | +| `-DGDAL_ENABLE_DRIVER_PDF=OFF` (+ poppler/podofo/pdfium `OFF`) | The MSYS2 `libpodofo.dll` fails its DLL initialization routine (Windows error 1114) in any process; a `libgdal` that imports it cannot be loaded at all, so the PDF driver is excluded from the bundle | | `-DGDAL_HIDE_INTERNAL_SYMBOLS=ON` | Restricts the export table to the public API (PE/COFF DLLs cap export ordinals at 65,535 and GDAL's full symbol set exceeds it — see [OSGeo/gdal#4706](https://github.com/OSGeo/gdal/issues/4706)) | | `-Wl,--kill-at` | Strips `@N` stdcall decoration from exports so symbol names match what loaders expect | | `-static-libgcc -static-libstdc++` + whole-archive `winpthread` | Embeds the GCC runtime into the DLLs — end users need neither Rtools nor MSYS2 at runtime | diff --git a/vignettes/troubleshooting.qmd b/vignettes/troubleshooting.qmd index 5e0fe68..515b4d6 100644 --- a/vignettes/troubleshooting.qmd +++ b/vignettes/troubleshooting.qmd @@ -61,6 +61,30 @@ Rscript -e "gdalraster.windows::activate_gdal_runtime(); library(gdalraster); pr A DLL can be "missing" even when CI verified the bundle: GitHub runner images ship products that install DLLs into `System32` (e.g. the Microsoft ODBC Driver for SQL Server, `msodbcsql17.dll`), so a dependency on them resolves in CI but not on end-user machines. The build disables such linkage (`GDAL_USE_MSSQL_ODBC=OFF`) and bundle verification rejects known non-OS `System32` DLLs, but any import in the `objdump` output that is neither in the bundle's `bin/` nor a Windows system DLL is the culprit. +## `LoadLibrary failure: A dynamic link library (DLL) initialization routine failed` + +This is a different failure class from "module could not be found" (Windows error 1114 vs 126). Every dependency was *found* and mapped into the process, but one of them failed its own initialization (`DllMain` / C++ static constructors), which makes the whole `libgdal-*.dll` load fail. Two properties make it confusing: + +- **Dependency-closure checks cannot detect it.** The bundle can be verified complete (`ntldd` reports every import resolved) and still fail this way — the broken DLL is present, it just cannot initialize. This is why bundle builds are also *load-tested* in CI (every DLL is passed through `LoadLibrary` in a plain process before an asset is published). +- **The same DLL bytes can load in one process and fail in another**, because its initializer's behavior depends on which copies of *its* dependencies the loader resolved (first-loaded-wins by base name). + +To isolate the culprit, sweep-load the bundle's DLLs individually in a fresh session — the failing one is rarely `libgdal` itself: + +```{r} +#| eval: false +bin <- file.path(gdalraster.windows::gdal_home(), "bin") +withr::local_envvar(PATH = paste(bin, Sys.getenv("PATH"), sep = ";")) +for (dll in list.files(bin, pattern = "\\.dll$", full.names = TRUE)) { + ok <- tryCatch( + { dyn.load(dll, local = FALSE, now = TRUE); TRUE }, + error = function(e) FALSE + ) + if (!ok) cat("FAILS TO INITIALIZE:", basename(dll), "\n") +} +``` + +Historical instance: bundles published before July 2026 shipped `libpodofo.dll` (a PDF-driver backend), whose static initializers run OpenSSL setup during `DllMain` and fail against the MSYS2-built `libcrypto-3-x64.dll` — in any process, R or not. Current bundles exclude the PDF driver entirely (`GDAL_ENABLE_DRIVER_PDF=OFF`) and CI refuses to publish a bundle containing any DLL that fails to load. If you see this error with a current bundle, reinstall the runtime first (`install_gdal_runtime(overwrite = TRUE)`), then run the sweep above and report the failing DLL in an issue. + ## `install_gdal_runtime(overwrite = TRUE)` cannot delete the old runtime Deleting `gdal_home` fails when its DLLs are mapped into a running process. The installer releases the current session's own preloaded runtime DLLs automatically, and refuses to run at all while `gdalraster` is loaded (its DLL pins the runtime — restart R first). If deletion still fails, another process holds locks: other R sessions using the runtime, or File Explorer windows/preview panes open on the runtime directory. Close them ([PowerToys File Locksmith](https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith) or Resource Monitor identify the locker) and rerun.