Skip to content

DLLs required by path find the DLLs they reference, loaded or alongside - #10

Closed
sholden wants to merge 8 commits into
feature/scoped-clr-extensionsfrom
fix/path-loaded-assembly-dependencies
Closed

sholden wants to merge 8 commits into
feature/scoped-clr-extensionsfrom
fix/path-loaded-assembly-dependencies

Conversation

@sholden

@sholden sholden commented Oct 29, 2026 •

Copy link
Copy Markdown
Owner

With CLR extension methods active, a DLL that references another DLL failed to load when both were required by absolute path.

require '/x/Demo.dll'
using_clr_extensions Demo        # or `using Demo` from #3
require '/x/Demo2.dll'           # Demo2 is built against Demo
# LoadError: Could not load file or assembly 'Demo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Requiring the same two DLLs through $LOAD_PATH worked. master has the bug too, through using_clr_extensions.

Extension methods only made it show up at the require. Once any are active, IronRuby reads each new assembly's extension methods as it loads, and reading Shout(this Widget) needs Widget. Without them the require succeeded, and the first call of a Demo2 method taking a Demo type raised Errno::ENOENT for the same missing assembly.

Cause

require loads a DLL by its path with Assembly.LoadFile, through the DLR's PlatformAdaptationLayer.LoadAssemblyFromPath. On .NET Core, LoadFile gives each file a load context of its own. A reference by name from that context finds the application's own assemblies and nothing else, so Demo2's reference to Demo failed .NET's probing and went to IronRuby's AppDomain.AssemblyResolve handler. That handler, Loader.ResolveAssembly, searched $LOAD_PATH and nothing else.

$LOAD_PATH had a second problem. If it held a different file of Demo from the one require had loaded, the handler loaded that file as a second Demo with its own Widget. A Widget made before that require then got NoMethodError for shout, and passing it to Demo::LaterExtensions.Shout raised TypeError.

What changed

Loader.ResolveAssembly now tries three places in turn.

  1. The assemblies this runtime has loaded. One answers if it has the simple name and culture asked for and at least the version asked for, which is the rule .NET's binder applies to an application's assemblies. A reference that names a public key token also needs the same token, so it can't bind to another publisher's assembly of the same name.
  2. $LOAD_PATH, unchanged. It keeps its old check, AssemblyName.ReferenceMatchesDefinition, which on .NET compares simple names only.
  3. The directory of the assembly that asked, if this runtime loaded that assembly from a file. That's roughly what .NET Framework's LoadFrom context did. The handler reads the candidate's identity with AssemblyName.GetAssemblyName and loads it only if it satisfies the reference. Like a $LOAD_PATH find, it's registered with the runtime, so its namespaces show up in Ruby.

The order keeps a dependency from being loaded twice. Every LoadFile of a different path makes a separate assembly with its own types. Because loaded assemblies come first, a copy on $LOAD_PATH or next to Demo2 is never loaded once Demo is.

Why both

I kept both approaches, because each fails on its own.

With only the loaded-assembly step, require '/x/Demo2.dll' still fails when Demo.dll sits next to it but was never required. $LOAD_PATH << '/x'; require 'Demo2.dll' already works in that case, and that's how a build's output folder is laid out.

With only the directory step, a Demo loaded from somewhere else gets a second copy. If Demo comes from /a and Demo2 from /b, which has its own Demo.dll, the probe loads /b/Demo.dll, and Demo2's Shout takes that copy's Widget, not the one Ruby made.

The directory step runs last, so it can't change what $LOAD_PATH resolves, and it only looks next to DLLs this runtime loaded from files. The handler .NET installs for Assembly.LoadFrom has the same limit. It only probes next to assemblies that LoadFrom loaded.

Several runtimes in one process

AssemblyResolve is a process-wide event that every runtime hooks, and the CLR asks the handlers in the order they were added. Before this PR, the first runtime whose $LOAD_PATH held a copy of a dependency answered for every runtime, with its own copy. The loaded-assembly step would have done the same with whatever copy the first runtime had loaded.

Each runtime now records the DLLs it loads from files, and a process-wide ConditionalWeakTable records those of every runtime. In all three steps, a runtime leaves a reference made by a DLL that another runtime loaded to that runtime. References from anything no runtime loaded from a file, such as IronRuby's own assemblies or a by-name load, are answered as before, so a program with one runtime sees no difference.

IronRuby.Tests runs every test case in a new runtime of one process, so it hits this. I found it when Require_PathLoadedDependency6 failed. The runtime left over from test 5 still had that test's fixture directory on its $LOAD_PATH, and it answered test 6's reference.

Behaviour changes

  • A reference to an assembly that's already loaded now resolves to it, even when $LOAD_PATH holds another file of it. Before, that file was loaded as a second assembly. With one runtime, that's the only change to $LOAD_PATH resolution.
  • A by-name load of an assembly loaded by path returns that assembly. After require '/x/Demo.dll', load_assembly 'Demo' used to raise Assembly 'Demo' not found unless Demo was on $LOAD_PATH. Now it returns the loaded Demo, and so do require 'Demo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and System::Reflection::Assembly.load('Demo').
  • A dependency found next to a DLL is loaded, and its namespaces become Ruby's.
  • In a process with several runtimes, a runtime no longer answers references made by DLLs another runtime loaded, including from its $LOAD_PATH.

Tests

The tests write their fixture DLLs at test time with System.Reflection.Metadata's MetadataBuilder. PersistedAssemblyBuilder would have been shorter, but it needs .NET 9 and CI also runs IronRuby.Tests on net8.0. PathLoadedWidgets.dll has a class PathLoadedFixture.Widget. Each of the other DLLs is built against a given version of it and has an extension method Shout(this Widget).

The tests turn extension methods on with Context.ActivateExtensions, the call using_clr_extensions makes. using of a namespace doesn't exist on master, and using_clr_extensions prints #3's deprecation warning here but not on master, so either would have tied the commit to one branch.

  • Require_PathLoadedDependency1 is the reported case. Both DLLs are in one directory and required by path, with extension methods active.
  • Require_PathLoadedDependency2 requires only the extensions DLL. PathLoadedWidgets is found next to it and registered.
  • Require_PathLoadedDependency3 loads Widgets from a/ and makes a Widget, then requires the extensions from b/. b/ has its own copy of Widgets, and c/, on $LOAD_PATH, has a third. The Widget gets shout, and the process holds one PathLoadedWidgets from the test's directory.
  • Require_PathLoadedDependency4 loads Widgets 2.0. Extensions built against 1.0 load and work, and extensions built against 3.0 raise LoadError.
  • Require_PathLoadedDependency5 checks that $LOAD_PATH still resolves the reference, ahead of a copy next to the DLL.
  • Require_PathLoadedDependency6 runs a second runtime with its own copies. The test runtime first has a copy on its $LOAD_PATH, then one loaded.

To check that the tests catch what they're meant to, I ran them against master's Loader.cs and against six broken versions of the fix.

Loader.cs Failing tests
master's all six. Test 5 passes on its own and fails after test 3, whose runtime answers it from test 3's $LOAD_PATH.
no ownership check 2, 3, 4, 5, 6
name-only identity check 4
exact version match 4
no loaded-assembly step 3, 4
$LOAD_PATH before loaded assemblies 3
no directory step 2

Results below are from a Debug build on Linux with net10.0, unless noted.

  • IronRuby.Tests passes with 0 failures.
  • The net8.0 build compiles. This machine has no .NET 8 runtime, so I ran the net8.0 build's six new tests on .NET 10 with DOTNET_ROLL_FORWARD=Major, and they pass. CI ran net8.0 for real (below).
  • spec/language passes with 2935 examples and 0 failures.
  • The Kernel#require, require_relative, load and autoload specs give 213 examples, 0 failures and 2 errors. Both errors are "with an unreadable file raises a LoadError", which gets Errno::EACCES. They happen with master's Loader.cs too.
  • req.rb, req2.rb, req3.rb and req4.rb print :loaded. later.rb, and a copy of it that requires both DLLs by absolute path, print the same three lines.
    NoMethodError
    'LaterExtensions.Shout (extension)'
    NoMethodError
    
  • Checked by hand with the Demo DLLs: Demo loaded from a directory other than Demo2's, which has its own Demo.dll, leaves one Demo in the process. Demo2 required alone finds Demo next to it. A static Demo::LaterExtensions.Shout(widget) call after req.rb works. The by-name loads above return the path-loaded Demo. A Demo that's only on $LOAD_PATH resolves from there, and one that's nowhere still raises.
  • The commit applies cleanly to Largo's master at d3a7cf9. I cherry-picked it there in a scratch worktree and built it against a DLR with all of Build/dlr-patches, 0102 included. IronRuby.Tests passes with 0 failures, and req.rb, req2.rb and req4.rb print :loaded. I removed the worktree afterwards.

CI ran on this PR and passed all seven checks. IronRuby.Tests reported 0 failure lines on ubuntu and windows with both net8.0 and net10.0, and spec/language passed with 2935 examples and 0 failures on net8.0 and net10.0. An earlier version of this description said CI doesn't run on the fork's PRs. It does.

Not changed

The DLR's LoadAssemblyFromPath still calls Assembly.LoadFile. Loading each runtime's DLLs into one shared load context would let .NET resolve these references itself. But that changes how every DLL loads, the DLR is shared code, and a host can install its own platform layer, so a fix there wouldn't reach every host. The resolve handler is IronRuby's and works with any platform layer.

Found, not fixed

  • A require that fails while IronRuby reads the DLL's extension methods leaves the DLL registered with the runtime but out of $LOADED_FEATURES. Requiring it again returns true but never reads its extension methods, because the DLR's ScriptDomainManager.LoadAssembly raises AssemblyLoaded once per assembly. After a failed require '/x/Demo2.dll', a require of Demo and a retry, w.shout is still a NoMethodError while Demo::LaterExtensions.Shout(w) works. With this PR the first require fails only when nothing satisfies the reference. master behaves the same. A DLL whose extension methods couldn't be read can be required again #11 fixes this, along with a worse variant: an unreadable DLL that was only queued made the next using raise and lost the extension methods of everything queued after it.
  • require of a second file with the same identity still loads a second copy, as in require '/a/Demo.dll' followed by require '/b/Demo.dll'. The resolver no longer makes copies on its own, but require loads the file it's given.

Stack

  1. CLR extension methods reach a method group used before using_clr_extensions Largo/ironruby#43, merged, fixes stale CLR overloads after using_clr_extensions
  2. Refinements: only refined calls pay, and the JIT and OSR keep working Largo/ironruby#49 makes refinements cost nothing where they can't change a call
  3. using System::Linq: CLR extension methods scoped like C#'s using directive #3 scopes CLR extension methods with using
  4. This PR, stacked on using System::Linq: CLR extension methods scoped like C#'s using directive #3. It's the DLL loading fix that using System::Linq: CLR extension methods scoped like C#'s using directive #3's description mentions. The commit doesn't depend on Refinements: only refined calls pay, and the JIT and OSR keep working Largo/ironruby#49 or using System::Linq: CLR extension methods scoped like C#'s using directive #3 and also applies to master on its own.
  5. A DLL whose extension methods couldn't be read can be required again #11, stacked on this PR, makes a DLL whose extension methods couldn't be read retryable.

🤖 Generated with Claude Code

sholden and others added 7 commits October 29, 2026 08:57
…ective

using_clr_extensions activates a namespace's extension methods for every call
in the runtime: a gem calling it changes what `list.select' means in every
other file. C# scopes them to the files that say `using System.Linq;', and
Ruby has the same notion for refinements, so `using' now accepts a CLR
namespace and brings its extension methods into the rest of the file, class
body or eval string, exactly where a refinement would be active:

  using System::Linq
  list.where { it > 1 }.order_by { -it }.to_a

`using System::Linq::Enumerable' brings in one static class's extension
methods, as C#'s `using static' does.

Extension methods come last, as in C#, rather than at the extended type's
place in the ancestors: a call that finds a Ruby method calls it
(list.select is Enumerable#select), one that finds a CLR method group gets them
as more overloads (list.count(pred) next to List#Count; an exact tie still goes
to the instance method), and one that finds nothing gets them alone
(list.where). The CLR-cased name (list.Select) still reaches them.

Built on the refinement machinery: a CLR namespace in a scope's `using' list is
part of its RefinementActivation, so methods defined there record it, call
sites guard on it, and send/public_send/method/respond_to? and irb see it. The
namespace's extension methods are filed with the types they extend (including
those of assemblies loaded later) under their CLR and Ruby names, and those
names join the per-(module, name) index stage one introduced - only calls of
those names on those types take the lexical guard. The group a call sees is
cached per class version, name and activation.

A program that `using's System::Linq pays nothing where it makes no LINQ call;
a hot LINQ call costs ~12% more than through using_clr_extensions, for the
guard. using_clr_extensions keeps working as before and now warns, once per
process, that it is deprecated.

ClrScopedExtensions1-4 cover the lexical scope, extension methods coming last
(Ruby method, merged CLR group, extension alone; Widget/Square/Box fixtures),
`using static', and a call bound before the first `using' of the namespace.
The tests of using_clr_extensions expect its one warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… only lexically

The scoped form put extension methods last, behind every Ruby method, so
`using System::Linq' turned list.select from LINQ's Select (what
using_clr_extensions gives) into Enumerable#select, and code moving from one
form to the other had to rename its calls to their CLR names. The scoped form is
meant to be using_clr_extensions confined to a file, class body or eval string,
so it now resolves the same way.

An extension method sits where a refinement of the type it extends would, and a
class's place also has those of the interfaces it implements, as
using_clr_extensions puts both in the class's own CLR method group:

  using System::Linq
  list.select { it * 2 }.to_a   # LINQ's Select, ahead of Enumerable#select
  dictionary.select { ... }     # LINQ's too, ahead of the IDictionary one
  [3, 1].select { it > 1 }      # Array#select: Array's ancestors have no IEnumerable[T]
  [3, 1].Select { ... }         # NoMethodError, as before

A CLR method group anywhere still gets them as more overloads, the instance member
winning an exact tie (list.count(pred), list.reverse). A Ruby method defined
ahead of them wins, and a site bound to them re-binds when one is defined or
removed. A singleton class sees them, as respond_to? and method did under
using_clr_extensions.

Across 13 receivers (List, Integer[], HashSet, Dictionary, an OfType iterator,
a List with a singleton class, Array, Hash, Range, String, Object, ...) and 30
calls, the two forms now print the same, except that a Ruby class including
IEnumerable[Object] gets LINQ through `using' and doesn't through
using_clr_extensions. 101samples.rb prints the same under both with only its
using line changed.

ClrScopedExtensions2 expects LINQ's select; ClrScopedExtensions5 covers Array,
Dictionary, a singleton, Enumerable#where behind LINQ's on a List and ahead of
nothing on an Array, and a Ruby select defined and removed on List[Integer].

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sions has them

using_clr_extensions adds extension methods to the CLR method groups of classes
backed by a CLR type, its own and those of its interfaces, and nowhere else. The
scoped form also looked at interface modules themselves, so a Ruby class that
includes IEnumerable[Object] got LINQ through `using' and nothing through
using_clr_extensions. Now only a CLR class's place counts, when deciding whether
extensions shadow a Ruby method and when gathering them into a group.

Against master (14d53a5), over 20 receivers - CLR collections, a List with a
singleton class, Ruby subclasses of List with and without their own select,
class objects, Array, Hash, Range, String, Struct, Set, Enumerator - and 30
calls each: `using System::Linq' prints what master's using_clr_extensions
does, and a program that `using's it in one module prints, outside that
module, what master prints with no activation. using_clr_extensions and no
activation print what they print on master.

ClrScopedExtensions5 also checks the Ruby class including IEnumerable[Object].

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Src/Samples/Linq/101samples.rb stopped parsing when Ruby stopped accepting a
trailing comma in a nested block parameter, |(c,), p|, and nothing ran it
after that. Past the parse error it raised a NameError at FirstOrDefault,
which names Fixnum, gone since Ruby 3.2.

- |(c,), p| is |(c, _), p|.
- Fixnum is Integer, which is System::Int32 in IronRuby.
- Min: Projection called sum, copied from Sum: Projection, and printed the
  total length of the words instead of the shortest. It calls min now,
  through method(:min).of(Object, Integer) as Min: Grouped does. A
  Func<Object, int> fits both Min(Func<TSource, int>) and
  Min<TSource, TResult>(Func<TSource, TResult>), and IronRuby can't choose
  between them where C# picks the first.
- Repeat printed its 7s without a newline, so the next heading ran on.
- OfType was commented out as an IronRuby bug. It works now.

The file still calls using_clr_extensions. Its output is the reference for
moving it to `using'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The samples were the last code outside the tests that called
using_clr_extensions, so they printed its deprecation warning. They say
`using System::Linq' now. Inside the scope calls resolve as they did under
using_clr_extensions, so every call keeps its name, and the output is the
same apart from the warning.

to_seq, which turns the samples' arrays into the IEnumerable<T> LINQ
extends, was a method added to Object for the whole program. It is a
refinement of Object now, active below the `using' like the LINQ methods.
Nothing in the file calls it before that point.

A probe at each of the 119 call sites with a LINQ method's name saw all of
them run: 112 reach a System.Linq.Enumerable method, and the other 7 are
Array#join on what to_a returned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Nothing ran Src/Samples/Linq/101samples.rb, so nobody noticed when it stopped
parsing. build-and-test now runs it on each OS and target framework, after the
socket check, and diffs its stdout and stderr against
Src/Samples/Linq/101samples.expected, which holds this branch's output on
Linux and net10.0.

A wrong answer, an exception or a warning fails the step. Tried locally by
putting using_clr_extensions back, which adds its deprecation warning; by
changing count(pred) to where(pred); by raising in the middle; and by
dropping `using LinqSampleHelpers', which makes to_seq undefined. The sample
takes about 1.6 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The samples passed every LINQ delegate as lambda { ... }. A block goes to a
method's trailing delegate parameter, so a call whose last argument was a
lambda now takes a block:
numbers.where { |n| n < 5 }, group_by(->(p) { p.category }) { |c, g| ... },
aggregate(start_balance) { |balance, next_withdrawal| ... }. A lambda that
isn't the last argument, such as a key selector before a result selector,
and the make_pair and identity helpers are -> lambdas now.

Two indexed samples keep a lambda. On .NET 9 and later OfType returns one
of LINQ's private iterator classes, whose own public Where(Func<T, bool>)
and Select(Func<T, R>) IronRuby binds to. A block with two parameters fits
those too, because a proc takes any number of arguments, so
digits.where { |digit, index| ... } got nil for index and
numbers.select { |num, index| ... } was ambiguous. A lambda's arity rules
them out. The indexed select_many, take_while and skip_while have no such
methods to compete with and take blocks. Each of the two has a comment.

The output is unchanged, so 101samples.expected is too. A probe at each of
the 119 call sites with a LINQ method's name still sees all of them reach
the same methods as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sholden
sholden force-pushed the feature/scoped-clr-extensions branch from 0901891 to 1f7acf0 Compare October 29, 2026 16:08
require loads a DLL by its path with Assembly.LoadFile, which on .NET Core
gives each file a load context of its own, where a reference by name finds
the application's assemblies and no other. A reference from one such DLL to
another fell to IronRuby's AssemblyResolve handler, which only searched
$LOAD_PATH. So two DLLs required by their paths, the second built against
the first, broke as soon as anything read the second's signatures:

  require '/x/Demo.dll'
  using_clr_extensions Demo
  require '/x/Demo2.dll'   # LoadError: Could not load file or assembly
                           # 'Demo, Version=1.0.0.0, ...'

Active extension methods are read as each assembly loads, so there the
require raised. Without them, the first call of a Demo2 method taking a Demo
type raised Errno::ENOENT instead. And when $LOAD_PATH held another file of
Demo, the handler loaded it as a second Demo, whose Widget isn't the one
Ruby made: Demo2's methods wouldn't take Ruby's Widgets.

The handler now tries three places in turn:

- The assemblies the runtime has loaded. One answers if it has the simple
  name and culture asked for, at least the version asked for (the rule .NET's
  binder applies to an application's assemblies), and the public key token if
  the reference names one.
- $LOAD_PATH, as before, with its name-only check.
- The directory of the DLL that asked, if the runtime loaded it from a file,
  roughly what .NET Framework's LoadFrom context did. A file there is loaded
  only if its identity will do, and becomes the runtime's as a $LOAD_PATH
  find does.

AssemblyResolve is the process's event, and every runtime in a process is
asked, in the order they hooked it. A runtime now leaves a reference made by
a DLL that another runtime loaded from a file to that runtime. Before, the
first runtime whose $LOAD_PATH held a copy of the dependency answered for
all of them, with its copy. IronRuby.Tests, which runs each test in a new
runtime of one process, is such a process: without this, the new tests
answer each other's references.

Require_PathLoadedDependency1-6 cover the reported case, the directory,
copies on $LOAD_PATH and next to the DLL that must not be loaded again,
versions, $LOAD_PATH before the directory, and a second runtime with copies
of its own. The fixture DLLs are written at test time with
System.Reflection.Metadata; PersistedAssemblyBuilder would need .NET 9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant