Repository navigation
Ruby C API: load C extensions on Linux and Windows; build gems' extensions (sqlite3) - #226
Merged
Merged
Conversation
IronRuby had no C API: Src/StdLib/include/ruby.h was a single #error, and a require of a compiled extension raised LoadError. This adds a first one, so a C extension built by mkmf against IronRuby's headers can be required (Linux x64). - Src/StdLib/include: CRuby 4.0's headers (Ruby's licence, BSD-2-Clause), imported by Util/capi/import-headers.rb, which turns the inline functions that read object memory (RSTRING_PTR, RARRAY_LEN, RBASIC flags, RB_BUILTIN_TYPE, the encoding index) into calls. - libironruby-capi.so (Src/Ruby/CApi/native, Util/build-capi.sh): exports the rb_* functions. Most forward through a function-pointer table to [UnmanagedCallersOnly] methods generated from functions.txt; variadic functions, rb_protect/rb_rescue2/rb_ensure and printf with PRIsVALUE are C; every other declared function is a NotImplementedError stub. Ruby exceptions cross C frames by setjmp/longjmp between trampolines, as in CRuby, since CLR exceptions cannot unwind native frames on Unix. - Src/Ruby/CApi: CRuby's VALUE encoding for immediates, a handle table for everything else, methods defined from C, blocks and rb_yield, native mirrors for RSTRING_PTR/RARRAY_PTR, ~300 functions for objects, classes, constants, exceptions, numbers, strings, encodings, arrays and hashes. - Loader: an ELF/Mach-O .so is dlopened and Init_<name> called, if it carries the rb_ir_abi_version marker IronRuby's headers emit; a CRuby-built one gets a LoadError. - RbConfig: a gcc toolchain and rubyarchhdrdir on Linux, so mkmf builds. Measured with ruby/spec's capi specs (mspec ci): boolean 4/4, constants 77/77, integer 29/29, array 79/79, string 234/234. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… regions Measured over the whole of ruby/spec's optional/capi (one mspec ci run): 1359 of 1627 examples pass, up from 738 of 1539; no file crashes or hangs the run. - Handles are 32-byte native slots laid out as RBasic (flags, klass) plus the table index, so an extension that reads RBASIC(obj) itself - ruby/spec's rbasic specs do - gets a plausible answer instead of a segfault that would end the whole process. - rb_thread_call_without_gvl and friends mark the thread "sleep" and run the extension's unblocking function when Thread#wakeup, #raise, #kill or a signal for the main thread reach it (RubyUtils.NativeUnblockHook); RUBY_UBF_IO interrupts the blocking call with SIGVTALRM. Without this the thread specs blocked in read(2) until mspec's timeout killed the run. - The non-inline rb_scan_args, rb_struct_define/new, rb_exec_recursive, CRuby's rb_gvar_* getters and setters, ruby_strdup/strtod and the Onigmo character functions an rb_encoding's macros call are C. - Conversions, Struct, Range, Regexp, IO, Mutex, Thread, Fiber, Set, Proc, Time (struct timeval/timespec by value), class variables, global variables backed by C, encodings. - Every function CRuby exports gets a NotImplementedError stub, not only the ones the headers declare: an extension that declares one itself (hash_spec.c's rb_ident_hash_new) otherwise failed to dlopen. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s them Co-Authored-By: Claude Opus 5.5 <[email protected]>
rb_define_alloc_func gives a class an allocator that Class#allocate and Class#new go through (RubyClass.CAllocator, inherited by subclasses; the JIT's plain-allocation fast path steps aside for such a class). Data_Wrap_Struct and TypedData_Wrap_Struct make a DataObject whose handle slot, now 48 bytes, is laid out as RData/RTypedData, so DATA_PTR, RTYPEDDATA_TYPE and TypedData_Get_Struct work as plain memory reads as they do on CRuby. dup and clone of such an object allocate through the allocator. rb_get_alloc_func answers a working allocator for every class. ruby_xmalloc & co are C. typed_data_spec 12/14 (was not loading), object_spec 125/132. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o the real gem With the C API (libironruby-capi next to the executable and a compiler in RbConfig), RubyGems and Bundler now build a gem's C extension as on CRuby. One that fails to build leaves the gem as before - Ruby files only - with a warning, instead of failing the install. Libraries IronRuby implements itself (sqlite3, nokogiri, json...) keep their built-in version unless IRONRUBY_NATIVE_GEMS names them (or is "*"): then the name is no longer pinned, its extension is built, and the installed gem is activated ahead of the built-in. Extensions now link against libironruby-capi (LIBRUBYARG), as CRuby's link against libruby: mkmf's have_func links a test program, which failed without it, so sqlite3's extconf took the code path for CRuby's bignum internals. rb_apply, rb_utf8_str_new and rb_utf8_str_new_cstr, the three functions the sqlite3 gem used that were stubs. Checked: IRONRUBY_NATIVE_GEMS=sqlite3 igem install sqlite3 --platform ruby -- --enable-system-libraries builds sqlite3-2.10.2's extension, and require "sqlite3" then runs queries, binds, prepared statements, transactions, exceptions and Ruby-defined SQL functions on it. Without the variable require "sqlite3" is the built-in 2.9.6 as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- C's long is 32-bit on Windows: the native entry points take and return CLong/CULong (generate.rb), C long ranges and FIXNUM_MAX (LONG_MAX / 2) are the platform's, struct timeval is two C longs. - The shim builds as libironruby-capi.dll with MinGW gcc, exporting every function and global VALUE, plus the import library extensions link against (build-capi.sh, Ruby.csproj). Unwinding uses GCC's __builtin_setjmp, as CRuby's MinGW build does, instead of the CRT's SEH-unwinding longjmp. RUBY_UBF_IO cancels the blocked thread's synchronous I/O. - The loader recognises a native PE DLL (no CLR metadata) and loads it with LoadLibrary; it refuses one that does not import libironruby-capi.dll (a CRuby-built extension) instead of relying on a weak symbol. - RbConfig describes RubyInstaller's MinGW toolchain on Windows; host_os and RUBY_PLATFORM still say mswin64, so Src/StdLib/ironruby/mkmf.rb clears mkmf's MSVC mode and RubyGems is pointed at make rather than nmake. - The headers gain ruby/win32.h and x64-mingw-ucrt/ruby/config.h from RubyInstaller's CRuby 4.0.5 (import-headers.rb --also). Linux unchanged (capi specs and the sqlite3 gem checked again). Co-Authored-By: Claude Opus 5.5 <[email protected]>
… on Windows
Fixes found running it in the Windows VM (MSYS2 UCRT64 gcc 16, .NET 10):
- the arity dispatch casts to each arity's own function type: in C23, GCC
16's default, VALUE (*)() takes no arguments;
- rb_out_of_int is declared with SIGNED_VALUE (long long on Windows);
- the shim's name and the C long and Fixnum ranges asked IsWindows before it
was initialised (static fields of a partial class across files): it is a
property now;
- RbConfig on Windows: the import library's directory written out (mkmf
takes the drive letter off a $(bindir) reference), and gcc's OBJEXT/LIBEXT
(mkmf's try_compile looked for conftest.obj, so every have_header failed);
- rb_locale_str_new & co use Encoding.find("locale"), a code page on Windows.
And a fix for Windows IronRuby in general: Gem.load_path_insert_index
compared $LOAD_PATH entries as written, but ir.cmd puts the standard
library on it with backslashes and a forward-slash copy comes later, so a
newer installed version of a default gem stayed behind the built-in one.
Windows results: ruby/spec optional/capi 1186 of 1457 examples (whole
directory, no crash or hang); the five first files pass except bignum's
setup, which disagrees with IronRuby's 64-bit RbConfig::LIMITS FIXNUM_MAX.
IRONRUBY_NATIVE_GEMS=sqlite3 igem install sqlite3 --platform ruby --
--enable-system-libraries builds sqlite3 2.10.2, and require "sqlite3" runs
it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Important Review skippedToo many files! This PR contains 235 files, which is 85 over the limit of 150. To get a review, reduce the PR to 150 files or fewer by splitting it into smaller PRs or changing its base branch. Upgrade to Team to raise the limit.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
IronRuby gets a Ruby C API: a C extension compiled against
ruby.hcan berequired, on Linux x64 and Windows x64 (MinGW gcc, as RubyInstaller uses), andgem installbuilds gems' C extensions. WithIRONRUBY_NATIVE_GEMS=sqlite3, the real sqlite3 gem (2.10.2) installs, builds its extension and runs on both platforms instead of IronRuby's built-in C# port.Design and limits:
Src/Ruby/CApi/README.md.What's in it
Src/StdLib/include): CRuby 4.0's own (Ruby's licence, BSD-2-Clause), imported byUtil/capi/import-headers.rb, which turns the macros that read object memory (RSTRING_PTR,RARRAY_LEN,RBASICflags,RB_BUILTIN_TYPE...) into calls.config.hforx86_64-linuxandx64-mingw-ucrt.libironruby-capi.so/.dll+ import library (Util/build-capi.sh). It exports therb_*functions; most forward through a function-pointer table to[UnmanagedCallersOnly]methods generated fromSrc/Ruby/CApi/functions.txt(~520), the variadic and exception-catching ones are C, and every other function CRuby declares or exports is a stub raisingNotImplementedError, so an extension loads even if it uses something not implemented yet.DATA_PTR,RTYPEDDATA_TYPEand directRBASICreads work.rb_define_alloc_func(RubyClass.CAllocator, used byClass#allocate/#new).rb_thread_call_without_gvlmarks the thread asleep and runs the extension's unblocking function onThread#wakeup/#kill/#raiseor a signal..soor a PE DLL without CLR metadata is dlopened/LoadLibrary'd; one built for CRuby is refused with aLoadError.Src/StdLib/ironruby/mkmf.rbturns mkmf's MSVC mode off, sinceRUBY_PLATFORMstaysx64-mswin64.IRONRUBY_NATIVE_GEMSnames them.Gem.load_path_insert_indexcompared$LOAD_PATHentries as written;ir.cmdputs the stdlib there with backslashes, so a newer installed version of a default gem never won on Windows.Results
ruby/spec
optional/capi, whole directory in onemspec cirun, no crash or hang (before: 0 of 1670):boolean, constants, integer, array and string pass completely on both. Most Windows-only failures are bignum_spec, whose setup disagrees with IronRuby's 64-bit
RbConfig::LIMITS["FIXNUM_MAX"](31-bit Fixnums in the Windows C ABI).Checks: IronRuby.Tests passes on Linux and on Windows (VM);
spec/languagehas only its known failure;command_line,core/thread,core/signal,library/rbconfigandkernel/requirespecs pass.Not in this PR
Util/build-capi.sh; Windows: the same from an MSYS2 shell), so CI runs without the C API.T_DATAobject'sdfreenever runs: objects handed to C are kept alive for the process.rb_io_tand the IO wait functions,rb_lastline_*/rb_backref_set, st tables, macOS, MSVC-built extensions.🤖 Generated with Claude Code