|
| 1 | +# RTLD_GLOBAL Implementation for Scryer Prolog FFI |
| 2 | + |
| 3 | +## Summary |
| 4 | + |
| 5 | +Added RTLD_GLOBAL support to Scryer Prolog's FFI system to enable Python C extension compatibility (NumPy, SciPy, pandas, standard library modules like `math`, `socket`, etc.). |
| 6 | + |
| 7 | +**PR**: https://github.com/mthom/scryer-prolog/pull/3144 |
| 8 | +**Branch**: `rtld-global-support` |
| 9 | +**Status**: Submitted, awaiting review |
| 10 | + |
| 11 | +## Problem |
| 12 | + |
| 13 | +When embedding Python via Scryer Prolog's FFI, Python C extension modules fail to load with "undefined symbol" errors because: |
| 14 | + |
| 15 | +1. Scryer's FFI loads shared libraries with `RTLD_LOCAL` by default (via `libloading::Library::new()`) |
| 16 | +2. `RTLD_LOCAL` isolates library symbols - they're not visible to subsequently loaded libraries |
| 17 | +3. Python C extensions need to resolve symbols from libpython (e.g., `PyExc_ValueError`, `PyLong_Type`) |
| 18 | +4. With `RTLD_LOCAL`, these symbols are hidden, causing import failures |
| 19 | + |
| 20 | +### Example Error |
| 21 | +``` |
| 22 | +>>> import numpy as np |
| 23 | +ImportError: /path/to/numpy/_multiarray_umath.so: undefined symbol: PyExc_ValueError |
| 24 | +``` |
| 25 | + |
| 26 | +### Affected Packages |
| 27 | +- **Scientific**: NumPy, SciPy, pandas, matplotlib, polars |
| 28 | +- **Standard library**: `math`, `socket`, `_random`, `_datetime`, `_json` |
| 29 | +- **ML/AI**: PyTorch, TensorFlow |
| 30 | +- **Data**: pyarrow, polars |
| 31 | + |
| 32 | +## Solution |
| 33 | + |
| 34 | +Added a separate `use_foreign_module_global/2` predicate that loads libraries with `RTLD_GLOBAL | RTLD_LAZY` on Unix systems. The default `use_foreign_module/2` continues to use `RTLD_LOCAL` for safety and backwards compatibility. |
| 35 | + |
| 36 | +### Implementation Details |
| 37 | + |
| 38 | +#### 1. Modified `src/ffi.rs` (No Changes Needed) |
| 39 | + |
| 40 | +The `ForeignFunctionTable::load_library()` already has a `use_global: bool` parameter: |
| 41 | + |
| 42 | +```rust |
| 43 | +pub(crate) fn load_library( |
| 44 | + &mut self, |
| 45 | + library_name: &str, |
| 46 | + functions: &Vec<FunctionDefinition>, |
| 47 | + use_global: bool, // NEW PARAMETER |
| 48 | +) -> Result<(), Box<dyn Error>> { |
| 49 | + let mut ff_table: ForeignFunctionTable = Default::default(); |
| 50 | + |
| 51 | + // Load library with RTLD_GLOBAL if requested (needed for Python C extensions) |
| 52 | + let library = unsafe { |
| 53 | + #[cfg(unix)] |
| 54 | + { |
| 55 | + if use_global { |
| 56 | + use libloading::os::unix; |
| 57 | + // RTLD_LAZY | RTLD_GLOBAL - convert to generic Library type |
| 58 | + let unix_lib = unix::Library::open( |
| 59 | + Some(library_name), |
| 60 | + unix::RTLD_LAZY | unix::RTLD_GLOBAL |
| 61 | + )?; |
| 62 | + Library::from(unix_lib) |
| 63 | + } else { |
| 64 | + Library::new(library_name)? |
| 65 | + } |
| 66 | + } |
| 67 | + #[cfg(not(unix))] |
| 68 | + { |
| 69 | + // Windows doesn't have RTLD_GLOBAL concept |
| 70 | + Library::new(library_name)? |
| 71 | + } |
| 72 | + }; |
| 73 | + // ... rest of function |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +**Key points:** |
| 78 | +- Unix-specific: Uses `libloading::os::unix::Library::open()` with `RTLD_GLOBAL` flag |
| 79 | +- Cross-platform: Windows behavior unchanged (no RTLD_GLOBAL concept) |
| 80 | +- Type conversion: Converts `unix::Library` to generic `Library` type via `Library::from()` |
| 81 | + |
| 82 | +#### 2. Added New Builtin in `build/instructions_template.rs` |
| 83 | + |
| 84 | +Added `LoadForeignLibGlobal` enum variant alongside existing `LoadForeignLib`: |
| 85 | + |
| 86 | +```rust |
| 87 | +#[strum_discriminants(strum(props(Arity = "2", Name = "$load_foreign_lib")))] |
| 88 | +LoadForeignLib, |
| 89 | +#[strum_discriminants(strum(props(Arity = "2", Name = "$load_foreign_lib_global")))] |
| 90 | +LoadForeignLibGlobal, |
| 91 | +``` |
| 92 | + |
| 93 | +#### 3. Refactored `src/machine/system_calls.rs` |
| 94 | + |
| 95 | +Created two wrapper functions that call a shared implementation: |
| 96 | + |
| 97 | +```rust |
| 98 | +// Uses RTLD_LOCAL (default, safe) |
| 99 | +pub(crate) fn load_foreign_lib(&mut self) -> CallResult { |
| 100 | + self.load_foreign_lib_impl(false) |
| 101 | +} |
| 102 | + |
| 103 | +// Uses RTLD_GLOBAL (opt-in) |
| 104 | +pub(crate) fn load_foreign_lib_global(&mut self) -> CallResult { |
| 105 | + self.load_foreign_lib_impl(true) |
| 106 | +} |
| 107 | + |
| 108 | +// Shared implementation |
| 109 | +fn load_foreign_lib_impl(&mut self, use_global: bool) -> CallResult { |
| 110 | + // ... existing logic ... |
| 111 | + .load_library(&library_name.as_str(), &functions, use_global) |
| 112 | +} |
| 113 | +``` |
| 114 | + |
| 115 | +#### 4. Updated `src/lib/ffi.pl` |
| 116 | + |
| 117 | +Added new `use_foreign_module_global/2` predicate and updated documentation: |
| 118 | + |
| 119 | +```prolog |
| 120 | +% Default - uses RTLD_LOCAL (safe) |
| 121 | +use_foreign_module(LibName, Predicates) :- |
| 122 | + '$load_foreign_lib'(LibName, Predicates), |
| 123 | + maplist(assert_predicate, Predicates). |
| 124 | +
|
| 125 | +% Opt-in - uses RTLD_GLOBAL (for Python C extensions, plugin architectures) |
| 126 | +use_foreign_module_global(LibName, Predicates) :- |
| 127 | + '$load_foreign_lib_global'(LibName, Predicates), |
| 128 | + maplist(assert_predicate, Predicates). |
| 129 | +``` |
| 130 | + |
| 131 | +Documentation updated to clarify: |
| 132 | +- RTLD_LOCAL is the default and safe for most use cases |
| 133 | +- RTLD_GLOBAL is opt-in via `use_foreign_module_global/2` |
| 134 | +- Use cases for RTLD_GLOBAL (Python embedding, plugin architectures) |
| 135 | +- Warning about potential symbol conflicts |
| 136 | + |
| 137 | +## Testing |
| 138 | + |
| 139 | +### Test Environment |
| 140 | +- **OS**: Linux (Ubuntu-based) |
| 141 | +- **Python**: Conda Python 3.11 |
| 142 | +- **Packages**: NumPy 1.26.4, requests |
| 143 | + |
| 144 | +### Test Script |
| 145 | +Created `/tmp/test_numpy_conda.pl`: |
| 146 | + |
| 147 | +```prolog |
| 148 | +:- use_module(library(ffi)). |
| 149 | +:- use_module('src/lib/python'). |
| 150 | +:- initialization(main). |
| 151 | +
|
| 152 | +main :- |
| 153 | + % Use conda Python 3.11 with RTLD_GLOBAL |
| 154 | + py_initialize_global([ |
| 155 | + shared_library_path('/home/jay/miniconda3/envs/test/lib/libpython3.11.so') |
| 156 | + ]), |
| 157 | +
|
| 158 | + % Test NumPy (C extension) |
| 159 | + py_run_simple_string("import numpy as np"), |
| 160 | + py_run_simple_string("print(f'NumPy version: {np.__version__}')"), |
| 161 | + py_run_simple_string("arr = np.array([1, 2, 3, 4, 5])"), |
| 162 | + py_run_simple_string("print(f'Array sum: {arr.sum()}')"), |
| 163 | +
|
| 164 | + % Test standard library C extensions |
| 165 | + py_run_simple_string("import math"), |
| 166 | + py_run_simple_string("print(f'math.pi = {math.pi}')"), |
| 167 | +
|
| 168 | + py_run_simple_string("import socket"), |
| 169 | + py_run_simple_string("print(f'socket module loaded successfully')"), |
| 170 | +
|
| 171 | + py_finalize, |
| 172 | + halt. |
| 173 | +``` |
| 174 | + |
| 175 | +### Results |
| 176 | + |
| 177 | +**Before RTLD_GLOBAL**: ❌ Import failures |
| 178 | +``` |
| 179 | +ImportError: undefined symbol: PyExc_ValueError |
| 180 | +``` |
| 181 | + |
| 182 | +**After RTLD_GLOBAL**: ✅ Success |
| 183 | +``` |
| 184 | +NumPy version: 1.26.4 |
| 185 | +Array sum: 15 |
| 186 | +math.pi = 3.141592653589793 |
| 187 | +socket module loaded successfully |
| 188 | +``` |
| 189 | + |
| 190 | +### Docker Verification |
| 191 | + |
| 192 | +Updated `scryer-python` conda Docker example to use RTLD_GLOBAL branch: |
| 193 | + |
| 194 | +```dockerfile |
| 195 | +RUN git clone --branch rtld-global-support https://github.com/jjtolton/scryer-prolog.git && \ |
| 196 | + cd scryer-prolog && \ |
| 197 | + cargo build --release && \ |
| 198 | + mv target/release/scryer-prolog /usr/local/bin/ |
| 199 | +``` |
| 200 | + |
| 201 | +Docker test demonstrates: |
| 202 | +- Conda Python 3.11 + NumPy working |
| 203 | +- Array operations |
| 204 | +- HTTP requests via requests library |
| 205 | +- Complete scientific Python stack integration |
| 206 | + |
| 207 | +## Backwards Compatibility |
| 208 | + |
| 209 | +This change is fully backwards compatible: |
| 210 | + |
| 211 | +1. **Separate predicate**: New `use_foreign_module_global/2` doesn't affect existing code |
| 212 | +2. **Default behavior preserved**: `use_foreign_module/2` uses RTLD_LOCAL (safe default) |
| 213 | +3. **Platform-specific**: Only affects Unix; Windows behavior unchanged |
| 214 | +4. **Opt-in**: Users must explicitly choose RTLD_GLOBAL via the `_global` variant |
| 215 | +5. **No API breaking changes**: Existing arity and signatures unchanged |
| 216 | + |
| 217 | +## Prior Art |
| 218 | + |
| 219 | +Other language embedders use RTLD_GLOBAL for Python: |
| 220 | + |
| 221 | +- **JNA (Java Native Access)**: Uses `RTLD_GLOBAL` by default on Linux |
| 222 | +- **libpython-clj (Clojure)**: Leverages JNA's RTLD_GLOBAL behavior |
| 223 | +- **Python's import system**: Uses `RTLD_GLOBAL` for extension modules |
| 224 | + |
| 225 | +## Files Changed |
| 226 | + |
| 227 | +``` |
| 228 | +build/instructions_template.rs | +2 -0 (added LoadForeignLibGlobal builtin) |
| 229 | +src/machine/system_calls.rs | +13 -54 (refactored into two wrappers + shared impl) |
| 230 | +src/lib/ffi.pl | +50 -10 (added use_foreign_module_global/2 + docs) |
| 231 | +``` |
| 232 | + |
| 233 | +## Future Work |
| 234 | + |
| 235 | +Potential enhancements: |
| 236 | + |
| 237 | +1. **Symbol conflict detection**: Document and provide tools for detecting symbol conflicts |
| 238 | + |
| 239 | +2. **Testing**: Add automated tests for RTLD_GLOBAL functionality with Python C extensions |
| 240 | + |
| 241 | +3. **Per-library unloading**: Currently, loaded libraries persist; could add unload support |
| 242 | + |
| 243 | +## Development Process |
| 244 | + |
| 245 | +### Git Workflow |
| 246 | +1. Created worktree from `~/programs/scryer-prolog` against upstream master |
| 247 | +2. Applied patches to worktree |
| 248 | +3. Built and tested with debug build |
| 249 | +4. Committed changes with descriptive messages |
| 250 | +5. Pushed to fork: `jjtolton/scryer-prolog` branch `rtld-global-support` |
| 251 | +6. Created PR to `mthom/scryer-prolog` |
| 252 | + |
| 253 | +### Commits |
| 254 | +``` |
| 255 | +cb7eb081 Add RTLD_GLOBAL support for FFI library loading |
| 256 | +6453d318 Document RTLD_GLOBAL behavior in FFI module |
| 257 | +``` |
| 258 | + |
| 259 | +## Impact |
| 260 | + |
| 261 | +This change enables a **massive expansion** of Scryer Prolog's FFI capabilities: |
| 262 | + |
| 263 | +- ✅ Scientific computing with NumPy, SciPy, pandas |
| 264 | +- ✅ Machine learning with PyTorch, TensorFlow |
| 265 | +- ✅ Data processing with polars, pyarrow |
| 266 | +- ✅ Standard library modules (`math`, `socket`, `_random`, etc.) |
| 267 | +- ✅ Any Python package with C extensions |
| 268 | + |
| 269 | +**Bottom line**: Makes Python embedding via FFI actually practical for real-world use cases. |
| 270 | + |
| 271 | +## Related Work |
| 272 | + |
| 273 | +This change directly enables the `scryer-python` library: |
| 274 | +- **Repository**: https://github.com/jjtolton/scryer-prolog-python |
| 275 | +- **Purpose**: High-level Python integration for Scryer Prolog |
| 276 | +- **Demo**: Conda Docker example with NumPy working |
| 277 | + |
| 278 | +## References |
| 279 | + |
| 280 | +- **PR**: https://github.com/mthom/scryer-prolog/pull/3144 |
| 281 | +- **Branch**: https://github.com/jjtolton/scryer-prolog/tree/rtld-global-support |
| 282 | +- **libloading docs**: https://docs.rs/libloading/latest/libloading/ |
| 283 | +- **RTLD_GLOBAL man page**: `man 3 dlopen` |
0 commit comments