native-filenames: find out where native methods are defined in ruby
I’ve just released the first version of the native-filenames
Ruby gem.
This gem can be used to probe where a native extension was defined. Here’s a quick example of how to use it:
[1] pry(main)> require 'native-filenames'
# Modern versions of bigdecimal use a native extension:
[2] pry(main)> require 'bigdecimal'
[3] pry(main)> NativeFilenames.filename_for(BigDecimal.singleton_class, :save_rounding_mode)
=> "/rvm/gems/ruby-3.4.4/gems/bigdecimal-3.2.2/lib/bigdecimal.so"
# Can also enquire about the standard library:
[4] pry(main)> NativeFilenames.filename_for(Array, :each)
=> "/rvm/rubies/ruby-3.4.4/bin/../lib/libruby.so.3.4"
# If something is written in Ruby, then you get an error:
[5] pry(main)> NativeFilenames.filename_for(Pry.singleton_class, :start)
RuntimeError: direct_bind_get_cfunc failed: method_entry is not a cfunc (RuntimeError)
I’ve just proposed to the Ruby core team that this behavior be incorporated in backtraces by default. (P.s.: This is now the behavior of the Datadog Ruby Profiler, starting with release 2.18.0.)
That is, given this example:
require 'bigdecimal'
BigDecimal.singleton_class.prepend(
Module.new do
def save_rounding_mode
super
end
end
)
[:example].each do
BigDecimal.save_rounding_mode do
puts caller
sleep 1
end
end
you’d see this with Ruby 3.4:
native-filenames-example.rb:6:in 'BigDecimal.save_rounding_mode'
native-filenames-example.rb:6:in 'save_rounding_mode'
native-filenames-example.rb:12:in 'block in <main>'
native-filenames-example.rb:11:in 'Array#each'
native-filenames-example.rb:11:in '<main>'
but I’m hoping that in Ruby 3.5 it’ll become:
/rvm/gems/ruby-3.4.4/gems/bigdecimal-3.2.2/lib/bigdecimal.so:0:in 'BigDecimal.save_rounding_mode'
native-filenames-example.rb:6:in 'save_rounding_mode'
native-filenames-example.rb:12:in 'block in <main>'
/rvm/rubies/ruby-3.4.4/lib/libruby.so.3.4:0:in 'Array#each'
native-filenames-example.rb:11:in '<main>'
If you’re interested in the discussion, it’s up on https://bugs.ruby-lang.org/issues/21501. Feedback very welcome!