From 6e48998b7c837b273d14d72b61263af7e647a865 Mon Sep 17 00:00:00 2001 From: Jose Narvaez Date: Wed, 31 Jan 2024 17:45:10 +0000 Subject: [PATCH 01/28] Add C API rb_enc_interned_str_cstr function Co-authored-by: Thomas Marshall --- CHANGELOG.md | 1 + lib/cext/ABI_check.txt | 2 +- spec/ruby/optional/capi/ext/string_spec.c | 6 ++++++ spec/ruby/optional/capi/string_spec.rb | 25 +++++++++++++++++++++++ src/main/c/cext/string.c | 5 +++++ 5 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 74fe2c50306f..aff41c93ad12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ Compatibility: * Do not autosplat a proc that accepts a single positional argument and keywords (#3039, @andrykonchin). * Support passing anonymous * and ** parameters as method call arguments (#3039, @andrykonchin). * Handle either positional or keywords arguments by default in `Struct.new` (#3039, @rwstauner). +* Add `rb_enc_interned_str_cstr` function (#3408, @goyox86, @thomasmarshall). Performance: diff --git a/lib/cext/ABI_check.txt b/lib/cext/ABI_check.txt index f599e28b8ab0..b4de39476753 100644 --- a/lib/cext/ABI_check.txt +++ b/lib/cext/ABI_check.txt @@ -1 +1 @@ -10 +11 diff --git a/spec/ruby/optional/capi/ext/string_spec.c b/spec/ruby/optional/capi/ext/string_spec.c index 702620b9dacb..390c5a8ab2be 100644 --- a/spec/ruby/optional/capi/ext/string_spec.c +++ b/spec/ruby/optional/capi/ext/string_spec.c @@ -584,6 +584,11 @@ static VALUE string_spec_rb_str_unlocktmp(VALUE self, VALUE str) { return rb_str_unlocktmp(str); } +static VALUE string_spec_rb_enc_interned_str_cstr(VALUE self, VALUE str, VALUE enc) { + rb_encoding *e = rb_to_encoding(enc); + return rb_enc_interned_str_cstr(RSTRING_PTR(str), e); +} + void Init_string_spec(void) { VALUE cls = rb_define_class("CApiStringSpecs", rb_cObject); rb_define_method(cls, "rb_cstr2inum", string_spec_rb_cstr2inum, 2); @@ -685,6 +690,7 @@ void Init_string_spec(void) { rb_define_method(cls, "rb_str_catf", string_spec_rb_str_catf, 1); rb_define_method(cls, "rb_str_locktmp", string_spec_rb_str_locktmp, 1); rb_define_method(cls, "rb_str_unlocktmp", string_spec_rb_str_unlocktmp, 1); + rb_define_method(cls, "rb_enc_interned_str_cstr", string_spec_rb_enc_interned_str_cstr, 2); } #ifdef __cplusplus diff --git a/spec/ruby/optional/capi/string_spec.rb b/spec/ruby/optional/capi/string_spec.rb index 3a47fa9762fd..eef170e78bf9 100644 --- a/spec/ruby/optional/capi/string_spec.rb +++ b/spec/ruby/optional/capi/string_spec.rb @@ -1227,4 +1227,29 @@ def inspect -> { @s.rb_str_unlocktmp("test") }.should raise_error(RuntimeError, 'temporal unlocking already unlocked string') end end + + describe "rb_enc_interned_str_cstr" do + it "returns a frozen string" do + str = "hello" + val = @s.rb_enc_interned_str_cstr(str, Encoding::US_ASCII) + + val.should.is_a?(String) + val.encoding.should == Encoding::US_ASCII + val.should.frozen? + end + + it "returns the same frozen string" do + str = "hello" + result1 = @s.rb_enc_interned_str_cstr(str, Encoding::US_ASCII) + result2 = @s.rb_enc_interned_str_cstr(str, Encoding::US_ASCII) + result1.should.equal?(result2) + end + + it "returns different frozen strings for different encodings" do + str = "hello" + result1 = @s.rb_enc_interned_str_cstr(str, Encoding::US_ASCII) + result2 = @s.rb_enc_interned_str_cstr(str, Encoding::UTF_8) + result1.should_not.equal?(result2) + end + end end diff --git a/src/main/c/cext/string.c b/src/main/c/cext/string.c index be58ad1bc573..4c7e0be48b46 100644 --- a/src/main/c/cext/string.c +++ b/src/main/c/cext/string.c @@ -437,3 +437,8 @@ long rb_str_coderange_scan_restartable(const char *s, const char *e, rb_encoding *cr = ENC_CODERANGE_VALID; return e - s; } + +VALUE rb_enc_interned_str_cstr(const char *ptr, rb_encoding *enc) { + VALUE str = rb_enc_str_new_cstr(ptr, enc); + return rb_fstring(str); +} From 40c6850640a327140d91747e9645c4f78bc76c8a Mon Sep 17 00:00:00 2001 From: Thomas Marshall Date: Thu, 1 Feb 2024 18:38:58 +0000 Subject: [PATCH 02/28] Add C API rb_str_to_interned_str function --- CHANGELOG.md | 1 + lib/cext/ABI_check.txt | 2 +- spec/ruby/optional/capi/ext/string_spec.c | 5 +++++ spec/ruby/optional/capi/string_spec.rb | 16 ++++++++++++++++ src/main/c/cext/string.c | 4 ++++ 5 files changed, 27 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aff41c93ad12..86e7fb10d3e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ Compatibility: * Support passing anonymous * and ** parameters as method call arguments (#3039, @andrykonchin). * Handle either positional or keywords arguments by default in `Struct.new` (#3039, @rwstauner). * Add `rb_enc_interned_str_cstr` function (#3408, @goyox86, @thomasmarshall). +* Add `rb_str_to_interned_str` function (#3408, @thomasmarshall). Performance: diff --git a/lib/cext/ABI_check.txt b/lib/cext/ABI_check.txt index b4de39476753..48082f72f087 100644 --- a/lib/cext/ABI_check.txt +++ b/lib/cext/ABI_check.txt @@ -1 +1 @@ -11 +12 diff --git a/spec/ruby/optional/capi/ext/string_spec.c b/spec/ruby/optional/capi/ext/string_spec.c index 390c5a8ab2be..9c13d805c5ca 100644 --- a/spec/ruby/optional/capi/ext/string_spec.c +++ b/spec/ruby/optional/capi/ext/string_spec.c @@ -589,6 +589,10 @@ static VALUE string_spec_rb_enc_interned_str_cstr(VALUE self, VALUE str, VALUE e return rb_enc_interned_str_cstr(RSTRING_PTR(str), e); } +static VALUE string_spec_rb_str_to_interned_str(VALUE self, VALUE str) { + return rb_str_to_interned_str(str); +} + void Init_string_spec(void) { VALUE cls = rb_define_class("CApiStringSpecs", rb_cObject); rb_define_method(cls, "rb_cstr2inum", string_spec_rb_cstr2inum, 2); @@ -691,6 +695,7 @@ void Init_string_spec(void) { rb_define_method(cls, "rb_str_locktmp", string_spec_rb_str_locktmp, 1); rb_define_method(cls, "rb_str_unlocktmp", string_spec_rb_str_unlocktmp, 1); rb_define_method(cls, "rb_enc_interned_str_cstr", string_spec_rb_enc_interned_str_cstr, 2); + rb_define_method(cls, "rb_str_to_interned_str", string_spec_rb_str_to_interned_str, 1); } #ifdef __cplusplus diff --git a/spec/ruby/optional/capi/string_spec.rb b/spec/ruby/optional/capi/string_spec.rb index eef170e78bf9..48a06bfdcd38 100644 --- a/spec/ruby/optional/capi/string_spec.rb +++ b/spec/ruby/optional/capi/string_spec.rb @@ -1252,4 +1252,20 @@ def inspect result1.should_not.equal?(result2) end end + + describe "rb_str_to_interned_str" do + it "returns a frozen string" do + str = "hello" + result = @s.rb_str_to_interned_str(str) + result.should.is_a?(String) + result.should.frozen? + end + + it "returns the same frozen string" do + str = "hello" + result1 = @s.rb_str_to_interned_str(str) + result2 = @s.rb_str_to_interned_str(str) + result1.should.equal?(result2) + end + end end diff --git a/src/main/c/cext/string.c b/src/main/c/cext/string.c index 4c7e0be48b46..211af65bb87a 100644 --- a/src/main/c/cext/string.c +++ b/src/main/c/cext/string.c @@ -442,3 +442,7 @@ VALUE rb_enc_interned_str_cstr(const char *ptr, rb_encoding *enc) { VALUE str = rb_enc_str_new_cstr(ptr, enc); return rb_fstring(str); } + +VALUE rb_str_to_interned_str(VALUE str) { + return rb_fstring(str); +} From bb9d829cc43021f6815f288ae1e3ba6485510823 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Mon, 5 Feb 2024 18:47:39 +0100 Subject: [PATCH 03/28] Improve C API specs --- spec/ruby/optional/capi/string_spec.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/spec/ruby/optional/capi/string_spec.rb b/spec/ruby/optional/capi/string_spec.rb index 48a06bfdcd38..aceb84e8307b 100644 --- a/spec/ruby/optional/capi/string_spec.rb +++ b/spec/ruby/optional/capi/string_spec.rb @@ -1251,6 +1251,10 @@ def inspect result2 = @s.rb_enc_interned_str_cstr(str, Encoding::UTF_8) result1.should_not.equal?(result2) end + + it "returns the same string as String#-@" do + @s.rb_enc_interned_str_cstr("hello", Encoding::UTF_8).should.equal?(-"hello") + end end describe "rb_str_to_interned_str" do @@ -1267,5 +1271,15 @@ def inspect result2 = @s.rb_str_to_interned_str(str) result1.should.equal?(result2) end + + it "returns different frozen strings for different encodings" do + result1 = @s.rb_str_to_interned_str("hello".force_encoding(Encoding::US_ASCII)) + result2 = @s.rb_str_to_interned_str("hello".force_encoding(Encoding::UTF_8)) + result1.should_not.equal?(result2) + end + + it "returns the same string as String#-@" do + @s.rb_str_to_interned_str("hello").should.equal?(-"hello") + end end end From 55634b795fc41238d226de3792de480615b0bdde Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Mon, 5 Feb 2024 18:50:40 +0100 Subject: [PATCH 04/28] Implement in terms of public C API methods --- lib/cext/ABI_check.txt | 2 +- src/main/c/cext/string.c | 6 +++--- src/main/java/org/truffleruby/cext/CExtNodes.java | 2 ++ 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/cext/ABI_check.txt b/lib/cext/ABI_check.txt index 48082f72f087..b1bd38b62a08 100644 --- a/lib/cext/ABI_check.txt +++ b/lib/cext/ABI_check.txt @@ -1 +1 @@ -12 +13 diff --git a/src/main/c/cext/string.c b/src/main/c/cext/string.c index 211af65bb87a..ed1f212bc4d7 100644 --- a/src/main/c/cext/string.c +++ b/src/main/c/cext/string.c @@ -160,7 +160,7 @@ VALUE rb_str_to_str(VALUE string) { } VALUE rb_fstring(VALUE str) { - return RUBY_INVOKE(str, "-@"); + return rb_str_to_interned_str(str); } VALUE rb_str_buf_new(long capacity) { @@ -440,9 +440,9 @@ long rb_str_coderange_scan_restartable(const char *s, const char *e, rb_encoding VALUE rb_enc_interned_str_cstr(const char *ptr, rb_encoding *enc) { VALUE str = rb_enc_str_new_cstr(ptr, enc); - return rb_fstring(str); + return rb_str_to_interned_str(str); } VALUE rb_str_to_interned_str(VALUE str) { - return rb_fstring(str); + return RUBY_INVOKE(str, "-@"); } diff --git a/src/main/java/org/truffleruby/cext/CExtNodes.java b/src/main/java/org/truffleruby/cext/CExtNodes.java index c7854c81717e..3407d5d76e3d 100644 --- a/src/main/java/org/truffleruby/cext/CExtNodes.java +++ b/src/main/java/org/truffleruby/cext/CExtNodes.java @@ -796,6 +796,8 @@ RubyString rbStrNewNul(int byteLength, } + /** Alternative to rb_str_new*() which does not copy the bytes from native memory, to use when the copy is + * unnecessary. */ @CoreMethod(names = "rb_tr_temporary_native_string", onSingleton = true, required = 3, lowerFixnum = 2) public abstract static class TemporaryNativeStringNode extends CoreMethodArrayArgumentsNode { From eff94ef71b92c310d6a0dadbfadbe96628cae87d Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Mon, 5 Feb 2024 18:52:21 +0100 Subject: [PATCH 05/28] Remove specs for rb_fstring() * It is a private function and the specs are redundant with specs for rb_str_to_interned_str(). --- spec/ruby/optional/capi/ext/string_spec.c | 7 ------- spec/ruby/optional/capi/string_spec.rb | 19 ------------------- 2 files changed, 26 deletions(-) diff --git a/spec/ruby/optional/capi/ext/string_spec.c b/spec/ruby/optional/capi/ext/string_spec.c index 9c13d805c5ca..44f2e2b7dcf2 100644 --- a/spec/ruby/optional/capi/ext/string_spec.c +++ b/spec/ruby/optional/capi/ext/string_spec.c @@ -51,12 +51,6 @@ VALUE string_spec_rb_str_set_len_RSTRING_LEN(VALUE self, VALUE str, VALUE len) { return INT2FIX(RSTRING_LEN(str)); } -VALUE rb_fstring(VALUE str); /* internal.h, used in ripper */ - -VALUE string_spec_rb_str_fstring(VALUE self, VALUE str) { - return rb_fstring(str); -} - VALUE string_spec_rb_str_buf_new(VALUE self, VALUE len, VALUE str) { VALUE buf; @@ -597,7 +591,6 @@ void Init_string_spec(void) { VALUE cls = rb_define_class("CApiStringSpecs", rb_cObject); rb_define_method(cls, "rb_cstr2inum", string_spec_rb_cstr2inum, 2); rb_define_method(cls, "rb_cstr_to_inum", string_spec_rb_cstr_to_inum, 3); - rb_define_method(cls, "rb_fstring", string_spec_rb_str_fstring, 1); rb_define_method(cls, "rb_str2inum", string_spec_rb_str2inum, 2); rb_define_method(cls, "rb_str_append", string_spec_rb_str_append, 2); rb_define_method(cls, "rb_str_buf_new", string_spec_rb_str_buf_new, 2); diff --git a/spec/ruby/optional/capi/string_spec.rb b/spec/ruby/optional/capi/string_spec.rb index aceb84e8307b..d9c20cf1760f 100644 --- a/spec/ruby/optional/capi/string_spec.rb +++ b/spec/ruby/optional/capi/string_spec.rb @@ -498,25 +498,6 @@ def inspect end end - describe "rb_fstring" do - it 'returns self if the String is frozen' do - input = 'foo'.freeze - output = @s.rb_fstring(input) - - output.should equal(input) - output.should.frozen? - end - - it 'returns a frozen copy if the String is not frozen' do - input = 'foo' - output = @s.rb_fstring(input) - - output.should.frozen? - output.should_not equal(input) - output.should == 'foo' - end - end - describe "rb_str_subseq" do it "returns a byte-indexed substring" do str = "\x00\x01\x02\x03\x04".force_encoding("binary") From 2e34b37075a3d47f601afe5a0a0e4698e36a44a6 Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Wed, 24 Jan 2024 16:52:29 +0200 Subject: [PATCH 06/28] Remove Fixnum and Bignum constants --- CHANGELOG.md | 1 + bench/asciidoctor/asciidoctor/lib/asciidoctor/document.rb | 2 +- spec/ffi/fixtures/compile.rb | 2 +- spec/tags/core/integer/constants_tags.txt | 2 -- src/main/ruby/truffleruby/core/integer.rb | 3 --- 5 files changed, 3 insertions(+), 7 deletions(-) delete mode 100644 spec/tags/core/integer/constants_tags.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 97aba9d79020..669e88f16171 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ Compatibility: * Limit maximum encoding set size by 256 (#3039, @thomasmarshall, @goyox86). * Remove deprecated methods `Dir.exists?`, `File.exists?`, and `Kernel#=~` (#3039, @patricklinpl, @nirvdrum). * Remove deprecated `FileTest.exists?` method (#3039, @andrykonchin). +* Remove deprecated `Fixnum` and `Bignum` constants (#3039, @andrykonchin). Performance: diff --git a/bench/asciidoctor/asciidoctor/lib/asciidoctor/document.rb b/bench/asciidoctor/asciidoctor/lib/asciidoctor/document.rb index 094661d71830..042f8a4a8c01 100644 --- a/bench/asciidoctor/asciidoctor/lib/asciidoctor/document.rb +++ b/bench/asciidoctor/asciidoctor/lib/asciidoctor/document.rb @@ -225,7 +225,7 @@ def initialize data = nil, options = {} # safely resolve the safe mode from const, int or string if !(safe_mode = options[:safe]) @safe = SafeMode::SECURE - elsif ::Fixnum === safe_mode + elsif ::Integer === safe_mode # this is fixed in upstream in v1.5.5 (https://github.com/asciidoctor/asciidoctor/blob/main/CHANGELOG.adoc#155-2016-10-05---mojavelinux) # be permissive in case API user wants to define new levels @safe = safe_mode else diff --git a/spec/ffi/fixtures/compile.rb b/spec/ffi/fixtures/compile.rb index f2e831a631bf..3399631e2a9d 100644 --- a/spec/ffi/fixtures/compile.rb +++ b/spec/ffi/fixtures/compile.rb @@ -11,7 +11,7 @@ module TestLibrary CPU = case RbConfig::CONFIG['host_cpu'].downcase when /i[3456]86/ # Darwin always reports i686, even when running in 64bit mode - if RbConfig::CONFIG['host_os'] =~ /darwin/ && 0xfee1deadbeef.is_a?(Fixnum) + if RbConfig::CONFIG['host_os'] =~ /darwin/ && [1].pack("J").bytesize == 8 "x86_64" else "i386" diff --git a/spec/tags/core/integer/constants_tags.txt b/spec/tags/core/integer/constants_tags.txt deleted file mode 100644 index 3e90c60b54c4..000000000000 --- a/spec/tags/core/integer/constants_tags.txt +++ /dev/null @@ -1,2 +0,0 @@ -fails:Fixnum is no longer defined -fails:Bignum is no longer defined diff --git a/src/main/ruby/truffleruby/core/integer.rb b/src/main/ruby/truffleruby/core/integer.rb index 9054763c021b..695234dc2929 100644 --- a/src/main/ruby/truffleruby/core/integer.rb +++ b/src/main/ruby/truffleruby/core/integer.rb @@ -34,9 +34,6 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -Fixnum = Bignum = Integer -Object.deprecate_constant :Fixnum, :Bignum - class Integer < Numeric # Have a copy in Integer of the Numeric version, as MRI does From ae69a9552ec6bd4397df96536ac9901e989eaa55 Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Wed, 15 Nov 2023 19:08:35 +0200 Subject: [PATCH 07/28] Fix {Proc,Method,UnboundMethod}#parameters to return proper parameter names --- CHANGELOG.md | 1 + spec/ruby/core/method/parameters_spec.rb | 16 +++++++++++ spec/ruby/core/proc/parameters_spec.rb | 4 +++ spec/tags/core/method/parameters_tags.txt | 3 -- spec/tags/core/proc/parameters_tags.txt | 3 -- .../arguments/ArgumentDescriptorUtils.java | 28 +++++++++++++------ .../org/truffleruby/parser/ArgumentType.java | 1 + .../parser/TranslatorEnvironment.java | 6 ++-- 8 files changed, 44 insertions(+), 18 deletions(-) delete mode 100644 spec/tags/core/method/parameters_tags.txt delete mode 100644 spec/tags/core/proc/parameters_tags.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 97aba9d79020..879bc333db46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ Compatibility: * Limit maximum encoding set size by 256 (#3039, @thomasmarshall, @goyox86). * Remove deprecated methods `Dir.exists?`, `File.exists?`, and `Kernel#=~` (#3039, @patricklinpl, @nirvdrum). * Remove deprecated `FileTest.exists?` method (#3039, @andrykonchin). +* Fix {Method,Proc}#parameters and return `*`, `**` and `&` names for anonymous parameters (@andrykonchin). Performance: diff --git a/spec/ruby/core/method/parameters_spec.rb b/spec/ruby/core/method/parameters_spec.rb index 7d2b37fac751..8495aef4d2d3 100644 --- a/spec/ruby/core/method/parameters_spec.rb +++ b/spec/ruby/core/method/parameters_spec.rb @@ -22,6 +22,8 @@ def one_splat_one_block(*args, &block) local_is_not_parameter = {} end + def forward_parameters(...) end + def underscore_parameters(_, _, _ = 1, *_, _:, _: 2, **_, &_); end define_method(:one_optional_defined_method) {|x = 1|} @@ -267,6 +269,20 @@ def object.foo(&) end end + ruby_version_is ""..."3.1" do + it "returns [:rest, :*], [:block, :&] for forward parameters operator" do + m = MethodSpecs::Methods.new + m.method(:forward_parameters).parameters.should == [[:rest, :*], [:block, :&]] + end + end + + ruby_version_is "3.1" do + it "returns [:rest, :*], [:keyrest, :**], [:block, :&] for forward parameters operator" do + m = MethodSpecs::Methods.new + m.method(:forward_parameters).parameters.should == [[:rest, :*], [:keyrest, :**], [:block, :&]] + end + end + it "returns the args and block for a splat and block argument" do m = MethodSpecs::Methods.new m.method(:one_splat_one_block).parameters.should == [[:rest, :args], [:block, :block]] diff --git a/spec/ruby/core/proc/parameters_spec.rb b/spec/ruby/core/proc/parameters_spec.rb index b8b91cdf83a6..972596d2ea88 100644 --- a/spec/ruby/core/proc/parameters_spec.rb +++ b/spec/ruby/core/proc/parameters_spec.rb @@ -170,4 +170,8 @@ [:block, :_] ] end + + it "returns :nokey for **nil parameter" do + proc { |**nil| }.parameters.should == [[:nokey]] + end end diff --git a/spec/tags/core/method/parameters_tags.txt b/spec/tags/core/method/parameters_tags.txt deleted file mode 100644 index 6734404a04ee..000000000000 --- a/spec/tags/core/method/parameters_tags.txt +++ /dev/null @@ -1,3 +0,0 @@ -fails:Method#parameters adds rest arg with name * for "star" argument -fails:Method#parameters adds keyrest arg with ** as a name for "double star" argument -fails:Method#parameters adds block arg with name & for anonymous block argument diff --git a/spec/tags/core/proc/parameters_tags.txt b/spec/tags/core/proc/parameters_tags.txt deleted file mode 100644 index 07834e1c3c9d..000000000000 --- a/spec/tags/core/proc/parameters_tags.txt +++ /dev/null @@ -1,3 +0,0 @@ -fails:Proc#parameters adds rest arg with name * for "star" argument -fails:Proc#parameters adds keyrest arg with ** as a name for "double star" argument -fails:Proc#parameters adds block arg with name & for anonymous block argument diff --git a/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java b/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java index 71b29b04e4c2..5be1c86f8b47 100644 --- a/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java +++ b/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java @@ -15,11 +15,15 @@ import org.truffleruby.RubyLanguage; import org.truffleruby.core.array.ArrayHelpers; import org.truffleruby.core.array.RubyArray; +import org.truffleruby.core.symbol.RubySymbol; import org.truffleruby.parser.ArgumentDescriptor; import org.truffleruby.parser.ArgumentType; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; -import org.truffleruby.parser.TranslatorEnvironment; + +import static org.truffleruby.parser.TranslatorEnvironment.FORWARDED_BLOCK_NAME; +import static org.truffleruby.parser.TranslatorEnvironment.FORWARDED_KEYWORD_REST_NAME; +import static org.truffleruby.parser.TranslatorEnvironment.FORWARDED_REST_NAME; public final class ArgumentDescriptorUtils { @@ -44,16 +48,22 @@ private static RubyArray toArray(RubyLanguage language, RubyContext context, Arg private static RubyArray toArray(RubyLanguage language, RubyContext context, ArgumentType argType, String name) { final Object[] store; + final RubySymbol typeSymbol = language.getSymbol(argType.symbolicName); - if (argType.anonymous || name == null) { - store = new Object[]{ language.getSymbol(argType.symbolicName) }; + if (argType == ArgumentType.anonrest) { + store = new Object[]{ typeSymbol, language.getSymbol("*") }; + } else if (argType == ArgumentType.anonkeyrest) { + store = new Object[]{ typeSymbol, language.getSymbol("**") }; + } else if (argType == ArgumentType.rest && name.equals(FORWARDED_REST_NAME)) { + store = new Object[]{ typeSymbol, language.getSymbol("*") }; + } else if (argType == ArgumentType.keyrest && name.equals(FORWARDED_KEYWORD_REST_NAME)) { + store = new Object[]{ typeSymbol, language.getSymbol("**") }; + } else if (argType == ArgumentType.block && name.equals(FORWARDED_BLOCK_NAME)) { + store = new Object[]{ typeSymbol, language.getSymbol("&") }; + } else if (argType.anonymous || name == null) { + store = new Object[]{ typeSymbol }; } else { - // make sure to normalize parameter names to "_" if they start with "_$" - if (name.startsWith(TranslatorEnvironment.UNDERSCORE_PREFIX)) { - name = "_"; - } - - store = new Object[]{ language.getSymbol(argType.symbolicName), language.getSymbol(name) }; + store = new Object[]{ typeSymbol, language.getSymbol(name) }; } return ArrayHelpers.createArray(context, language, store); diff --git a/src/main/java/org/truffleruby/parser/ArgumentType.java b/src/main/java/org/truffleruby/parser/ArgumentType.java index 47596228b1c7..5bd18da6e5a9 100644 --- a/src/main/java/org/truffleruby/parser/ArgumentType.java +++ b/src/main/java/org/truffleruby/parser/ArgumentType.java @@ -39,6 +39,7 @@ public enum ArgumentType { anonopt("opt", true), anonrest("rest", true), anonkeyrest("keyrest", true), + anonblock("block", true), nokey("nokey", true); // **nil ArgumentType(String symbolicName, boolean anonymous) { diff --git a/src/main/java/org/truffleruby/parser/TranslatorEnvironment.java b/src/main/java/org/truffleruby/parser/TranslatorEnvironment.java index 7c2da7ba0f25..83f31ba40922 100644 --- a/src/main/java/org/truffleruby/parser/TranslatorEnvironment.java +++ b/src/main/java/org/truffleruby/parser/TranslatorEnvironment.java @@ -57,11 +57,11 @@ public final class TranslatorEnvironment { static final String DEFAULT_KEYWORD_REST_NAME = Layouts.TEMP_PREFIX + "kwrest"; /** local variable name for * parameter caused by desugaring ... parameter (forward-everything) */ - static final String FORWARDED_REST_NAME = Layouts.TEMP_PREFIX + "forward_rest"; + public static final String FORWARDED_REST_NAME = Layouts.TEMP_PREFIX + "forward_rest"; /** local variable name for ** parameter caused by desugaring ... parameter (forward-everything) */ - static final String FORWARDED_KEYWORD_REST_NAME = Layouts.TEMP_PREFIX + "forward_kwrest"; + public static final String FORWARDED_KEYWORD_REST_NAME = Layouts.TEMP_PREFIX + "forward_kwrest"; /** local variable name for & parameter caused by desugaring ... parameter (forward-everything) */ - static final String FORWARDED_BLOCK_NAME = Layouts.TEMP_PREFIX + "forward_block"; + public static final String FORWARDED_BLOCK_NAME = Layouts.TEMP_PREFIX + "forward_block"; /** A prefix for duplicated '_' local variables to build unique names */ public static final String UNDERSCORE_PREFIX = "_$"; From b049fe07769bcae1ab7ca711a323201dc2be7e76 Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Tue, 6 Feb 2024 19:53:55 +0200 Subject: [PATCH 08/28] Repair Method#parameters and return [:rest] without name for methods implemented with #method_missing --- .../java/org/truffleruby/language/methods/SharedMethodInfo.java | 2 +- src/main/java/org/truffleruby/parser/ArgumentDescriptor.java | 2 +- src/main/java/org/truffleruby/parser/ArgumentType.java | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java b/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java index c9c00a66cae0..0e2af90b9a95 100644 --- a/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java +++ b/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java @@ -91,7 +91,7 @@ public SharedMethodInfo convertMethodMissingToMethod(RubyModule declaringModule, blockDepth, moduleAndMethodName(declaringModule, methodName), notes, - ArgumentDescriptor.ANY); + ArgumentDescriptor.ANY_UNNAMED); } public SourceSection getSourceSection() { diff --git a/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java b/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java index bb562488390f..9d82030959b3 100644 --- a/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java +++ b/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java @@ -36,7 +36,7 @@ public final class ArgumentDescriptor { /** The name of the argument */ public final String name; - public static final ArgumentDescriptor[] ANY = { new ArgumentDescriptor(ArgumentType.anonrest) }; + public static final ArgumentDescriptor[] ANY_UNNAMED = { new ArgumentDescriptor(ArgumentType.unnamedrest) }; public static final ArgumentDescriptor[] AT_LEAST_ONE = { new ArgumentDescriptor(ArgumentType.anonreq), new ArgumentDescriptor(ArgumentType.anonrest) }; diff --git a/src/main/java/org/truffleruby/parser/ArgumentType.java b/src/main/java/org/truffleruby/parser/ArgumentType.java index 5bd18da6e5a9..5e0f5dce00a6 100644 --- a/src/main/java/org/truffleruby/parser/ArgumentType.java +++ b/src/main/java/org/truffleruby/parser/ArgumentType.java @@ -40,6 +40,7 @@ public enum ArgumentType { anonrest("rest", true), anonkeyrest("keyrest", true), anonblock("block", true), + unnamedrest("rest", true), nokey("nokey", true); // **nil ArgumentType(String symbolicName, boolean anonymous) { From 0964c6afc5678b5eb18bd9151b40a9939387409b Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Wed, 7 Feb 2024 12:32:08 +0200 Subject: [PATCH 09/28] Repair Method#parameters and return no names for core methods not implemented in Ruby --- .../java/org/truffleruby/core/proc/RubyProc.java | 2 +- .../java/org/truffleruby/language/methods/Arity.java | 12 ++++++------ .../language/methods/SharedMethodInfo.java | 2 +- .../java/org/truffleruby/parser/ArgumentType.java | 8 +++++--- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/truffleruby/core/proc/RubyProc.java b/src/main/java/org/truffleruby/core/proc/RubyProc.java index 7feae8893abb..93a99cee2d6d 100644 --- a/src/main/java/org/truffleruby/core/proc/RubyProc.java +++ b/src/main/java/org/truffleruby/core/proc/RubyProc.java @@ -123,7 +123,7 @@ public int getArityNumber() { } public ArgumentDescriptor[] getArgumentDescriptors() { - return argumentDescriptors == null ? arity.toAnonymousArgumentDescriptors() : argumentDescriptors; + return argumentDescriptors == null ? arity.toUnnamedArgumentDescriptors() : argumentDescriptors; } // region SourceLocation diff --git a/src/main/java/org/truffleruby/language/methods/Arity.java b/src/main/java/org/truffleruby/language/methods/Arity.java index 5bbf8a58ead9..2bc910b00921 100644 --- a/src/main/java/org/truffleruby/language/methods/Arity.java +++ b/src/main/java/org/truffleruby/language/methods/Arity.java @@ -164,23 +164,23 @@ public String[] getRequiredKeywordArguments() { return requiredKeywords; } - public ArgumentDescriptor[] toAnonymousArgumentDescriptors() { + public ArgumentDescriptor[] toUnnamedArgumentDescriptors() { List descs = new ArrayList<>(); for (int i = 0; i < preRequired; i++) { - descs.add(new ArgumentDescriptor(ArgumentType.anonreq)); + descs.add(new ArgumentDescriptor(ArgumentType.unnamedreq)); } for (int i = 0; i < optional; i++) { - descs.add(new ArgumentDescriptor(ArgumentType.anonopt)); + descs.add(new ArgumentDescriptor(ArgumentType.unnamedopt)); } if (hasRest) { - descs.add(new ArgumentDescriptor(ArgumentType.anonrest)); + descs.add(new ArgumentDescriptor(ArgumentType.unnamedrest)); } for (int i = 0; i < postRequired; i++) { - descs.add(new ArgumentDescriptor(ArgumentType.anonreq)); + descs.add(new ArgumentDescriptor(ArgumentType.unnamedreq)); } for (String keyword : keywordArguments) { @@ -188,7 +188,7 @@ public ArgumentDescriptor[] toAnonymousArgumentDescriptors() { } if (hasKeywordsRest) { - descs.add(new ArgumentDescriptor(ArgumentType.anonkeyrest)); + descs.add(new ArgumentDescriptor(ArgumentType.unnamedkeyrest)); } return descs.toArray(ArgumentDescriptor.EMPTY_ARRAY); diff --git a/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java b/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java index 0e2af90b9a95..74a184167a4a 100644 --- a/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java +++ b/src/main/java/org/truffleruby/language/methods/SharedMethodInfo.java @@ -116,7 +116,7 @@ public ArgumentDescriptor[] getRawArgumentDescriptors() { } public ArgumentDescriptor[] getArgumentDescriptors() { - return argumentDescriptors == null ? arity.toAnonymousArgumentDescriptors() : argumentDescriptors; + return argumentDescriptors == null ? arity.toUnnamedArgumentDescriptors() : argumentDescriptors; } public boolean isBlock() { diff --git a/src/main/java/org/truffleruby/parser/ArgumentType.java b/src/main/java/org/truffleruby/parser/ArgumentType.java index 5e0f5dce00a6..63a53a9dfb56 100644 --- a/src/main/java/org/truffleruby/parser/ArgumentType.java +++ b/src/main/java/org/truffleruby/parser/ArgumentType.java @@ -36,12 +36,14 @@ public enum ArgumentType { rest("rest", false), req("req", false), anonreq("req", true), - anonopt("opt", true), anonrest("rest", true), anonkeyrest("keyrest", true), - anonblock("block", true), + unnamedreq("req", true), + unnamedopt("opt", true), unnamedrest("rest", true), - nokey("nokey", true); // **nil + unnamedkeyrest("keyrest", true), + + nokey("nokey", true); ArgumentType(String symbolicName, boolean anonymous) { this.symbolicName = symbolicName; From 497aca307858c1e7e40f5012ce9b1c493874f4ec Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Wed, 7 Feb 2024 13:45:53 +0200 Subject: [PATCH 10/28] Repair Proc#parameters to return no names for proc created with Symbol#to_proc --- src/main/java/org/truffleruby/core/proc/RubyProc.java | 1 + src/main/java/org/truffleruby/core/symbol/SymbolNodes.java | 2 +- .../java/org/truffleruby/parser/ArgumentDescriptor.java | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/truffleruby/core/proc/RubyProc.java b/src/main/java/org/truffleruby/core/proc/RubyProc.java index 93a99cee2d6d..f2c949ef20d5 100644 --- a/src/main/java/org/truffleruby/core/proc/RubyProc.java +++ b/src/main/java/org/truffleruby/core/proc/RubyProc.java @@ -123,6 +123,7 @@ public int getArityNumber() { } public ArgumentDescriptor[] getArgumentDescriptors() { + // parameters can be unnamed in a Proc created using Symbol#to_proc return argumentDescriptors == null ? arity.toUnnamedArgumentDescriptors() : argumentDescriptors; } diff --git a/src/main/java/org/truffleruby/core/symbol/SymbolNodes.java b/src/main/java/org/truffleruby/core/symbol/SymbolNodes.java index 253d561fc17b..5d9f6666a94b 100644 --- a/src/main/java/org/truffleruby/core/symbol/SymbolNodes.java +++ b/src/main/java/org/truffleruby/core/symbol/SymbolNodes.java @@ -226,7 +226,7 @@ public static RootCallTarget createCallTarget(RubyLanguage language, RubySymbol 0, "&:" + symbol.getString(), "Symbol#to_proc", - ArgumentDescriptor.AT_LEAST_ONE); + ArgumentDescriptor.AT_LEAST_ONE_UNNAMED); // ModuleNodes.DefineMethodNode relies on the lambda CallTarget to always use a RubyLambdaRootNode, // and we want to use a single CallTarget for both proc and lambda. diff --git a/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java b/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java index 9d82030959b3..07e26e592ddc 100644 --- a/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java +++ b/src/main/java/org/truffleruby/parser/ArgumentDescriptor.java @@ -37,9 +37,9 @@ public final class ArgumentDescriptor { public final String name; public static final ArgumentDescriptor[] ANY_UNNAMED = { new ArgumentDescriptor(ArgumentType.unnamedrest) }; - public static final ArgumentDescriptor[] AT_LEAST_ONE = { - new ArgumentDescriptor(ArgumentType.anonreq), - new ArgumentDescriptor(ArgumentType.anonrest) }; + public static final ArgumentDescriptor[] AT_LEAST_ONE_UNNAMED = { + new ArgumentDescriptor(ArgumentType.unnamedreq), + new ArgumentDescriptor(ArgumentType.unnamedrest) }; public static final ArgumentDescriptor[] EMPTY_ARRAY = new ArgumentDescriptor[0]; public ArgumentDescriptor(ArgumentType type, String name) { From 857a0eae0e3b2ea8d67cf263126bf91c329c39d4 Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Wed, 7 Feb 2024 12:32:44 +0200 Subject: [PATCH 11/28] Add comments to document ArgumentType enum --- .../truffleruby/language/methods/Arity.java | 2 ++ .../org/truffleruby/parser/ArgumentType.java | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/main/java/org/truffleruby/language/methods/Arity.java b/src/main/java/org/truffleruby/language/methods/Arity.java index 2bc910b00921..9d307c6fa67b 100644 --- a/src/main/java/org/truffleruby/language/methods/Arity.java +++ b/src/main/java/org/truffleruby/language/methods/Arity.java @@ -164,6 +164,8 @@ public String[] getRequiredKeywordArguments() { return requiredKeywords; } + /** Generate argument descriptors for a method/proc that doesn't provide parameter names, e.g a core method + * implemented in Java. */ public ArgumentDescriptor[] toUnnamedArgumentDescriptors() { List descs = new ArrayList<>(); diff --git a/src/main/java/org/truffleruby/parser/ArgumentType.java b/src/main/java/org/truffleruby/parser/ArgumentType.java index 63a53a9dfb56..201d1dfc8bdd 100644 --- a/src/main/java/org/truffleruby/parser/ArgumentType.java +++ b/src/main/java/org/truffleruby/parser/ArgumentType.java @@ -26,23 +26,43 @@ ***** END LICENSE BLOCK *****/ package org.truffleruby.parser; +/** Reflects semantic of different method/proc declared parameters types. + * + * Symbolic names match type names returned by the {Method, Proc}#parameters methods. */ public enum ArgumentType { + /** optional keyword argument */ key("key", false), + /** required keyword argument */ keyreq("keyreq", false), + /** keyword rest parameter */ keyrest("keyrest", false), + /** block parameter */ block("block", false), + /** optional positional parameter */ opt("opt", false), + /** rest parameter */ rest("rest", false), + /** required positional parameter */ req("req", false), + + /* Parameters declared in a method/proc explicitly without name, e.g. anonymous *, ** , and &. Required parameter + * can be anonymous only in case of parameters nesting (e.g. `def foo(a, (b, c)) end`) */ anonreq("req", true), anonrest("rest", true), anonkeyrest("keyrest", true), + + /* Parameters in a method that doesn't provide parameter names, e.g. implemented using #method_missing or a core + * method implemented in Java. + * + * A tiny difference between unnamed and anonymous parameters is that anonymous are reported by the #parameters + * method with names (*, ** or &). But unnamed are reported without names. */ unnamedreq("req", true), unnamedopt("opt", true), unnamedrest("rest", true), unnamedkeyrest("keyrest", true), + /** no-keyword-arguments parameter (**nil) */ nokey("nokey", true); ArgumentType(String symbolicName, boolean anonymous) { From 7ce7d687a22175ee7addea8ee3c4f04bf1c1ef88 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 13:40:30 +0100 Subject: [PATCH 12/28] Tag transient spec * It frequently fails in CI: 1) TCPSocket#initialize raises IO::TimeoutError with :connect_timeout when no server is listening on the given address ERROR IO::TimeoutError: execution expired spec/ruby/library/socket/tcpsocket/shared/new.rb:30:in `block (3 levels) in ' spec/ruby/library/socket/tcpsocket/initialize_spec.rb:5:in `' --- spec/tags/library/socket/tcpsocket/initialize_tags.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/spec/tags/library/socket/tcpsocket/initialize_tags.txt b/spec/tags/library/socket/tcpsocket/initialize_tags.txt index a8e951605c85..81ebbab92c06 100644 --- a/spec/tags/library/socket/tcpsocket/initialize_tags.txt +++ b/spec/tags/library/socket/tcpsocket/initialize_tags.txt @@ -5,3 +5,4 @@ fails:TCPSocket#initialize using IPv6 when a server is listening on the given ad fails:TCPSocket#initialize using IPv6 when a server is listening on the given address creates a socket which is set to close on exec slow:TCPSocket#initialize raises IO::TimeoutError with :connect_timeout when no server is listening on the given address slow:TCPSocket#initialize with a running server connects to a server when passed connect_timeout argument +fails(transient):TCPSocket#initialize raises IO::TimeoutError with :connect_timeout when no server is listening on the given address From c98a2362d42c84fba015012c42e197bc72ac1504 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 13:44:29 +0100 Subject: [PATCH 13/28] Use CoreSymbols to avoid extra lookups --- .../language/arguments/ArgumentDescriptorUtils.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java b/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java index 5be1c86f8b47..aa8d6166c295 100644 --- a/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java +++ b/src/main/java/org/truffleruby/language/arguments/ArgumentDescriptorUtils.java @@ -51,15 +51,15 @@ private static RubyArray toArray(RubyLanguage language, RubyContext context, Arg final RubySymbol typeSymbol = language.getSymbol(argType.symbolicName); if (argType == ArgumentType.anonrest) { - store = new Object[]{ typeSymbol, language.getSymbol("*") }; + store = new Object[]{ typeSymbol, language.coreSymbols.MULTIPLY }; } else if (argType == ArgumentType.anonkeyrest) { - store = new Object[]{ typeSymbol, language.getSymbol("**") }; + store = new Object[]{ typeSymbol, language.coreSymbols.POW }; } else if (argType == ArgumentType.rest && name.equals(FORWARDED_REST_NAME)) { - store = new Object[]{ typeSymbol, language.getSymbol("*") }; + store = new Object[]{ typeSymbol, language.coreSymbols.MULTIPLY }; } else if (argType == ArgumentType.keyrest && name.equals(FORWARDED_KEYWORD_REST_NAME)) { - store = new Object[]{ typeSymbol, language.getSymbol("**") }; + store = new Object[]{ typeSymbol, language.coreSymbols.POW }; } else if (argType == ArgumentType.block && name.equals(FORWARDED_BLOCK_NAME)) { - store = new Object[]{ typeSymbol, language.getSymbol("&") }; + store = new Object[]{ typeSymbol, language.coreSymbols.AMPERSAND }; } else if (argType.anonymous || name == null) { store = new Object[]{ typeSymbol }; } else { From 4e39224104a341b8bdc8670d1a97f6eecea45f75 Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Fri, 9 Feb 2024 14:57:31 +0200 Subject: [PATCH 14/28] Update JRuby to v9.4.4.0 --- 3rd_party_licenses.txt | 419 ++------------ doc/legal/jruby-copying.txt | 1072 +---------------------------------- doc/legal/legal.md | 2 +- 3 files changed, 59 insertions(+), 1434 deletions(-) diff --git a/3rd_party_licenses.txt b/3rd_party_licenses.txt index 03ade260170e..086ddbd7f22d 100644 --- a/3rd_party_licenses.txt +++ b/3rd_party_licenses.txt @@ -1384,7 +1384,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== -JRuby 9.2.19.0 +JRuby 9.4.4.0 JRuby is Copyright (c) 2007-2018 The JRuby project, and is released under a tri EPL/GPL/LGPL license. You can use it, redistribute it @@ -1396,18 +1396,15 @@ and/or modify it under the terms of the: OR GNU Lesser General Public License version 2.1 -bytelist (http://github.com/jruby/bytelist), jnr-posix (https://github.com/jnr/jnr-posix), jruby-openssl (https://github.com/jruby/jruby-openssl), jruby-readline (https://github.com/jruby/jruby-readline), -psych (https://github.com/ruby/psych), yydebug (https://github.com/jruby/jay-yydebug/) are released under the same copyright/license. Some additional libraries distributed with JRuby are not covered by -JRuby's licence. Most of these libraries and their licenses are listed +JRuby's licence. Most of these libraries and their licenses are listed below. Also see LICENSE.RUBY for most files found in lib/ruby/stdlib. -Not all of these additional libraries are used in TruffleRuby. asm (http://asm.objectweb.org) is distributed under the BSD license and is @@ -1442,6 +1439,10 @@ Not all of these additional libraries are used in TruffleRuby. Copyright (C) 2010 Wayne Meissner Copyright (c) 2008-2009, Petr Kobalicek + psych (https://github.com/ruby/psych) is distributed under the MIT license: + + Copyright (c) 2009 Aaron Patterson, et al. + The following libraries are redistributed under the Apache Software License v2.0, available below. invokebinder (https://github.com/headius/invokebinder) @@ -1454,7 +1455,6 @@ Not all of these additional libraries are used in TruffleRuby. jnr-unixsocket (https://github.com/jnr/jnr-unixsocket) joda-time (http://joda-time.sourceforge.net) maven (http://maven.apache.org/) - nailgun (http://martiansoftware.com/nailgun) options (https://github.com/headius/options) snakeyaml (https://github.com/asomov/snakeyaml) unsafe-fences (https://github.com/headius/unsafe-fences) @@ -1807,7 +1807,7 @@ The complete text of the GNU General Public License v2 is as follows: The precise terms and conditions for copying, distribution and modification follow. - + GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @@ -1862,7 +1862,7 @@ The complete text of the GNU General Public License v2 is as follows: License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) - + These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in @@ -1920,7 +1920,7 @@ The complete text of the GNU General Public License v2 is as follows: access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. - + 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is @@ -1977,7 +1977,7 @@ The complete text of the GNU General Public License v2 is as follows: This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - + 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License @@ -2090,7 +2090,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - + Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a @@ -2146,7 +2146,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - + GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @@ -2193,7 +2193,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - + 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 @@ -2251,7 +2251,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - + Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. @@ -2302,7 +2302,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - + 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work @@ -2364,7 +2364,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - + 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined @@ -2405,7 +2405,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - + 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or @@ -2457,7 +2457,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - + 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is @@ -2491,7 +2491,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: DAMAGES. END OF TERMS AND CONDITIONS - + How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest @@ -2797,377 +2797,28 @@ The complete text of the MIT license is as follows: FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -The complete text of the GPL v2, and classpath exception: - -The GNU General Public License (GPL) - -Version 2, June 1991 - -Copyright (C) 1989, 1991 Free Software Foundation, Inc. -59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -Preamble - -The licenses for most software are designed to take away your freedom to share -and change it. By contrast, the GNU General Public License is intended to -guarantee your freedom to share and change free software--to make sure the -software is free for all its users. This General Public License applies to -most of the Free Software Foundation's software and to any other program whose -authors commit to using it. (Some other Free Software Foundation software is -covered by the GNU Library General Public License instead.) You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom to -distribute copies of free software (and charge for this service if you wish), -that you receive source code or can get it if you want it, that you can change -the software or use pieces of it in new free programs; and that you know you -can do these things. - -To protect your rights, we need to make restrictions that forbid anyone to deny -you these rights or to ask you to surrender the rights. These restrictions -translate to certain responsibilities for you if you distribute copies of the -software, or if you modify it. - -For example, if you distribute copies of such a program, whether gratis or for -a fee, you must give the recipients all the rights that you have. You must -make sure that they, too, receive or can get the source code. And you must -show them these terms so they know their rights. - -We protect your rights with two steps: (1) copyright the software, and (2) -offer you this license which gives you legal permission to copy, distribute -and/or modify the software. - -Also, for each author's protection and ours, we want to make certain that -everyone understands that there is no warranty for this free software. If the -software is modified by someone else and passed on, we want its recipients to -know that what they have is not the original, so that any problems introduced -by others will not reflect on the original authors' reputations. - -Finally, any free program is threatened constantly by software patents. We -wish to avoid the danger that redistributors of a free program will -individually obtain patent licenses, in effect making the program proprietary. -To prevent this, we have made it clear that any patent must be licensed for -everyone's free use or not licensed at all. - -The precise terms and conditions for copying, distribution and modification -follow. - -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License applies to any program or other work which contains a notice -placed by the copyright holder saying it may be distributed under the terms of -this General Public License. The "Program", below, refers to any such program -or work, and a "work based on the Program" means either the Program or any -derivative work under copyright law: that is to say, a work containing the -Program or a portion of it, either verbatim or with modifications and/or -translated into another language. (Hereinafter, translation is included -without limitation in the term "modification".) Each licensee is addressed as -"you". - -Activities other than copying, distribution and modification are not covered by -this License; they are outside its scope. The act of running the Program is -not restricted, and the output from the Program is covered only if its contents -constitute a work based on the Program (independent of having been made by -running the Program). Whether that is true depends on what the Program does. - -1. You may copy and distribute verbatim copies of the Program's source code as -you receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice and -disclaimer of warranty; keep intact all the notices that refer to this License -and to the absence of any warranty; and give any other recipients of the -Program a copy of this License along with the Program. - -You may charge a fee for the physical act of transferring a copy, and you may -at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Program or any portion of it, thus -forming a work based on the Program, and copy and distribute such modifications -or work under the terms of Section 1 above, provided that you also meet all of -these conditions: - - a) You must cause the modified files to carry prominent notices stating - that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in whole or - in part contains or is derived from the Program or any part thereof, to be - licensed as a whole at no charge to all third parties under the terms of - this License. - - c) If the modified program normally reads commands interactively when run, - you must cause it, when started running for such interactive use in the - most ordinary way, to print or display an announcement including an - appropriate copyright notice and a notice that there is no warranty (or - else, saying that you provide a warranty) and that users may redistribute - the program under these conditions, and telling the user how to view a copy - of this License. (Exception: if the Program itself is interactive but does - not normally print such an announcement, your work based on the Program is - not required to print an announcement.) - -These requirements apply to the modified work as a whole. If identifiable -sections of that work are not derived from the Program, and can be reasonably -considered independent and separate works in themselves, then this License, and -its terms, do not apply to those sections when you distribute them as separate -works. But when you distribute the same sections as part of a whole which is a -work based on the Program, the distribution of the whole must be on the terms -of this License, whose permissions for other licensees extend to the entire -whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your -rights to work written entirely by you; rather, the intent is to exercise the -right to control the distribution of derivative or collective works based on -the Program. - -In addition, mere aggregation of another work not based on the Program with the -Program (or with a work based on the Program) on a volume of a storage or -distribution medium does not bring the other work under the scope of this -License. - -3. You may copy and distribute the Program (or a work based on it, under -Section 2) in object code or executable form under the terms of Sections 1 and -2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable source - code, which must be distributed under the terms of Sections 1 and 2 above - on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three years, to - give any third party, for a charge no more than your cost of physically - performing source distribution, a complete machine-readable copy of the - corresponding source code, to be distributed under the terms of Sections 1 - and 2 above on a medium customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer to - distribute corresponding source code. (This alternative is allowed only - for noncommercial distribution and only if you received the program in - object code or executable form with such an offer, in accord with - Subsection b above.) - -The source code for a work means the preferred form of the work for making -modifications to it. For an executable work, complete source code means all -the source code for all modules it contains, plus any associated interface -definition files, plus the scripts used to control compilation and installation -of the executable. However, as a special exception, the source code -distributed need not include anything that is normally distributed (in either -source or binary form) with the major components (compiler, kernel, and so on) -of the operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the source -code from the same place counts as distribution of the source code, even though -third parties are not compelled to copy the source along with the object code. - -4. You may not copy, modify, sublicense, or distribute the Program except as -expressly provided under this License. Any attempt otherwise to copy, modify, -sublicense or distribute the Program is void, and will automatically terminate -your rights under this License. However, parties who have received copies, or -rights, from you under this License will not have their licenses terminated so -long as such parties remain in full compliance. - -5. You are not required to accept this License, since you have not signed it. -However, nothing else grants you permission to modify or distribute the Program -or its derivative works. These actions are prohibited by law if you do not -accept this License. Therefore, by modifying or distributing the Program (or -any work based on the Program), you indicate your acceptance of this License to -do so, and all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - -6. Each time you redistribute the Program (or any work based on the Program), -the recipient automatically receives a license from the original licensor to -copy, distribute or modify the Program subject to these terms and conditions. -You may not impose any further restrictions on the recipients' exercise of the -rights granted herein. You are not responsible for enforcing compliance by -third parties to this License. - -7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), conditions -are imposed on you (whether by court order, agreement or otherwise) that -contradict the conditions of this License, they do not excuse you from the -conditions of this License. If you cannot distribute so as to satisfy -simultaneously your obligations under this License and any other pertinent -obligations, then as a consequence you may not distribute the Program at all. -For example, if a patent license would not permit royalty-free redistribution -of the Program by all those who receive copies directly or indirectly through -you, then the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply and -the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or -other property right claims or to contest validity of any such claims; this -section has the sole purpose of protecting the integrity of the free software -distribution system, which is implemented by public license practices. Many -people have made generous contributions to the wide range of software -distributed through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing to -distribute software through any other system and a licensee cannot impose that -choice. - -This section is intended to make thoroughly clear what is believed to be a -consequence of the rest of this License. - -8. If the distribution and/or use of the Program is restricted in certain -countries either by patents or by copyrighted interfaces, the original -copyright holder who places the Program under this License may add an explicit -geographical distribution limitation excluding those countries, so that -distribution is permitted only in or among countries not thus excluded. In -such case, this License incorporates the limitation as if written in the body -of this License. - -9. The Free Software Foundation may publish revised and/or new versions of the -General Public License from time to time. Such new versions will be similar in -spirit to the present version, but may differ in detail to address new problems -or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any later -version", you have the option of following the terms and conditions either of -that version or of any later version published by the Free Software Foundation. -If the Program does not specify a version number of this License, you may -choose any version ever published by the Free Software Foundation. - -10. If you wish to incorporate parts of the Program into other free programs -whose distribution conditions are different, write to the author to ask for -permission. For software which is copyrighted by the Free Software Foundation, -write to the Free Software Foundation; we sometimes make exceptions for this. -Our decision will be guided by the two goals of preserving the free status of -all derivatives of our free software and of promoting the sharing and reuse of -software generally. - -NO WARRANTY - -11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR -THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE -STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE -PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND -PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, -YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL -ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE -PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR -INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA -BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER -OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively convey the exclusion -of warranty; and each file should have at least the "copyright" line and a -pointer to where the full notice is found. - - One line to give the program's name and a brief idea of what it does. - - Copyright (C) - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., 59 - Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this when it -starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author Gnomovision comes - with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free - software, and you are welcome to redistribute it under certain conditions; - type 'show c' for details. - -The hypothetical commands 'show w' and 'show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may be -called something other than 'show w' and 'show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your school, -if any, to sign a "copyright disclaimer" for the program, if necessary. Here -is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - 'Gnomovision' (which makes passes at compilers) written by James Hacker. - - signature of Ty Coon, 1 April 1989 - - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General Public -License instead of this License. - -"CLASSPATH" EXCEPTION TO THE GPL - -Certain source files distributed by Oracle America and/or its affiliates are -subject to the following clarification and special exception to the GPL, but -only where Oracle has expressly included in the particular source file's header -the words "Oracle designates this particular file as subject to the "Classpath" -exception as provided by Oracle in the LICENSE file that accompanied this code." - - Linking this library statically or dynamically with other modules is making - a combined work based on this library. Thus, the terms and conditions of - the GNU General Public License cover the whole combination. - - As a special exception, the copyright holders of this library give you - permission to link this library with independent modules to produce an - executable, regardless of the license terms of these independent modules, - and to copy and distribute the resulting executable under terms of your - choice, provided that you also meet, for each linked independent module, - the terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. If - you modify this library, you may extend this exception to your version of - the library, but you are not obligated to do so. If you do not wish to do - so, delete this exception statement from your version. - The full text of the zlib licence: -Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: -1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. -Jean-loup Gailly Mark Adler -jloup@gzip.org madler@alumni.caltech.edu + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu =============================================================================== diff --git a/doc/legal/jruby-copying.txt b/doc/legal/jruby-copying.txt index 7c2957b5871c..af372fd73f24 100644 --- a/doc/legal/jruby-copying.txt +++ b/doc/legal/jruby-copying.txt @@ -11,16 +11,14 @@ and/or modify it under the terms of the: OR GNU Lesser General Public License version 2.1 -bytelist (http://github.com/jruby/bytelist), jnr-posix (https://github.com/jnr/jnr-posix), jruby-openssl (https://github.com/jruby/jruby-openssl), jruby-readline (https://github.com/jruby/jruby-readline), -psych (https://github.com/ruby/psych), yydebug (https://github.com/jruby/jay-yydebug/) are released under the same copyright/license. Some additional libraries distributed with JRuby are not covered by -JRuby's licence. Most of these libraries and their licenses are listed +JRuby's licence. Most of these libraries and their licenses are listed below. Also see LICENSE.RUBY for most files found in lib/ruby/stdlib. asm (http://asm.objectweb.org) is distributed under the BSD license and is @@ -39,7 +37,7 @@ below. Also see LICENSE.RUBY for most files found in lib/ruby/stdlib. The "rake" library (https://github.com/ruby/rake) is distributed under the MIT license, and has the following copyright: - + Copyright (c) 2003, 2004 Jim Weirich jcodings (http://github.com/jruby/jcodings) and @@ -56,6 +54,10 @@ below. Also see LICENSE.RUBY for most files found in lib/ruby/stdlib. Copyright (C) 2010 Wayne Meissner Copyright (c) 2008-2009, Petr Kobalicek + psych (https://github.com/ruby/psych) is distributed under the MIT license: + + Copyright (c) 2009 Aaron Patterson, et al. + The following libraries are redistributed under the Apache Software License v2.0, available below. invokebinder (https://github.com/headius/invokebinder) @@ -68,7 +70,6 @@ below. Also see LICENSE.RUBY for most files found in lib/ruby/stdlib. jnr-unixsocket (https://github.com/jnr/jnr-unixsocket) joda-time (http://joda-time.sourceforge.net) maven (http://maven.apache.org/) - nailgun (http://martiansoftware.com/nailgun) options (https://github.com/headius/options) snakeyaml (https://github.com/asomov/snakeyaml) unsafe-fences (https://github.com/headius/unsafe-fences) @@ -795,7 +796,7 @@ The complete text of the GNU Lesser General Public License 2.1 is as follows: on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - + 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an @@ -1154,688 +1155,10 @@ The following licenses cover code other than JRuby which is included with JRuby. Licenses listed below include: -* GNU General Public License version 3 * Apache 2.0 License * BSD License * MIT License -The complete text of the GNU General Public License version 3 is as follows: - - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for - software and other kinds of works. - - The licenses for most software and other practical works are designed - to take away your freedom to share and change the works. By contrast, - the GNU General Public License is intended to guarantee your freedom to - share and change all versions of a program--to make sure it remains free - software for all its users. We, the Free Software Foundation, use the - GNU General Public License for most of our software; it applies also to - any other work released this way by its authors. You can apply it to - your programs, too. - - When we speak of free software, we are referring to freedom, not - price. Our General Public Licenses are designed to make sure that you - have the freedom to distribute copies of free software (and charge for - them if you wish), that you receive source code or can get it if you - want it, that you can change the software or use pieces of it in new - free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you - these rights or asking you to surrender the rights. Therefore, you have - certain responsibilities if you distribute copies of the software, or if - you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether - gratis or for a fee, you must pass on to the recipients the same - freedoms that you received. You must make sure that they, too, receive - or can get the source code. And you must show them these terms so they - know their rights. - - Developers that use the GNU GPL protect your rights with two steps: - (1) assert copyright on the software, and (2) offer you this License - giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains - that there is no warranty for this free software. For both users' and - authors' sake, the GPL requires that modified versions be marked as - changed, so that their problems will not be attributed erroneously to - authors of previous versions. - - Some devices are designed to deny users access to install or run - modified versions of the software inside them, although the manufacturer - can do so. This is fundamentally incompatible with the aim of - protecting users' freedom to change the software. The systematic - pattern of such abuse occurs in the area of products for individuals to - use, which is precisely where it is most unacceptable. Therefore, we - have designed this version of the GPL to prohibit the practice for those - products. If such problems arise substantially in other domains, we - stand ready to extend this provision to those domains in future versions - of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. - States should not allow patents to restrict development and use of - software on general-purpose computers, but in those that do, we wish to - avoid the special danger that patents applied to a free program could - make it effectively proprietary. To prevent this, the GPL assures that - patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and - modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of - works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this - License. Each licensee is addressed as "you". "Licensees" and - "recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work - in a fashion requiring copyright permission, other than the making of an - exact copy. The resulting work is called a "modified version" of the - earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based - on the Program. - - To "propagate" a work means to do anything with it that, without - permission, would make you directly or secondarily liable for - infringement under applicable copyright law, except executing it on a - computer or modifying a private copy. Propagation includes copying, - distribution (with or without modification), making available to the - public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other - parties to make or receive copies. Mere interaction with a user through - a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" - to the extent that it includes a convenient and prominently visible - feature that (1) displays an appropriate copyright notice, and (2) - tells the user that there is no warranty for the work (except to the - extent that warranties are provided), that licensees may convey the - work under this License, and how to view a copy of this License. If - the interface presents a list of user commands or options, such as a - menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work - for making modifications to it. "Object code" means any non-source - form of a work. - - A "Standard Interface" means an interface that either is an official - standard defined by a recognized standards body, or, in the case of - interfaces specified for a particular programming language, one that - is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other - than the work as a whole, that (a) is included in the normal form of - packaging a Major Component, but which is not part of that Major - Component, and (b) serves only to enable use of the work with that - Major Component, or to implement a Standard Interface for which an - implementation is available to the public in source code form. A - "Major Component", in this context, means a major essential component - (kernel, window system, and so on) of the specific operating system - (if any) on which the executable work runs, or a compiler used to - produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all - the source code needed to generate, install, and (for an executable - work) run the object code and to modify the work, including scripts to - control those activities. However, it does not include the work's - System Libraries, or general-purpose tools or generally available free - programs which are used unmodified in performing those activities but - which are not part of the work. For example, Corresponding Source - includes interface definition files associated with source files for - the work, and the source code for shared libraries and dynamically - linked subprograms that the work is specifically designed to require, - such as by intimate data communication or control flow between those - subprograms and other parts of the work. - - The Corresponding Source need not include anything that users - can regenerate automatically from other parts of the Corresponding - Source. - - The Corresponding Source for a work in source code form is that - same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of - copyright on the Program, and are irrevocable provided the stated - conditions are met. This License explicitly affirms your unlimited - permission to run the unmodified Program. The output from running a - covered work is covered by this License only if the output, given its - content, constitutes a covered work. This License acknowledges your - rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not - convey, without conditions so long as your license otherwise remains - in force. You may convey covered works to others for the sole purpose - of having them make modifications exclusively for you, or provide you - with facilities for running those works, provided that you comply with - the terms of this License in conveying all material for which you do - not control copyright. Those thus making or running the covered works - for you must do so exclusively on your behalf, under your direction - and control, on terms that prohibit them from making any copies of - your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under - the conditions stated below. Sublicensing is not allowed; section 10 - makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological - measure under any applicable law fulfilling obligations under article - 11 of the WIPO copyright treaty adopted on 20 December 1996, or - similar laws prohibiting or restricting circumvention of such - measures. - - When you convey a covered work, you waive any legal power to forbid - circumvention of technological measures to the extent such circumvention - is effected by exercising rights under this License with respect to - the covered work, and you disclaim any intention to limit operation or - modification of the work as a means of enforcing, against the work's - users, your or third parties' legal rights to forbid circumvention of - technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you - receive it, in any medium, provided that you conspicuously and - appropriately publish on each copy an appropriate copyright notice; - keep intact all notices stating that this License and any - non-permissive terms added in accord with section 7 apply to the code; - keep intact all notices of the absence of any warranty; and give all - recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, - and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to - produce it from the Program, in the form of source code under the - terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent - works, which are not by their nature extensions of the covered work, - and which are not combined with it such as to form a larger program, - in or on a volume of a storage or distribution medium, is called an - "aggregate" if the compilation and its resulting copyright are not - used to limit the access or legal rights of the compilation's users - beyond what the individual works permit. Inclusion of a covered work - in an aggregate does not cause this License to apply to the other - parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms - of sections 4 and 5, provided that you also convey the - machine-readable Corresponding Source under the terms of this License, - in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded - from the Corresponding Source as a System Library, need not be - included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any - tangible personal property which is normally used for personal, family, - or household purposes, or (2) anything designed or sold for incorporation - into a dwelling. In determining whether a product is a consumer product, - doubtful cases shall be resolved in favor of coverage. For a particular - product received by a particular user, "normally used" refers to a - typical or common use of that class of product, regardless of the status - of the particular user or of the way in which the particular user - actually uses, or expects or is expected to use, the product. A product - is a consumer product regardless of whether the product has substantial - commercial, industrial or non-consumer uses, unless such uses represent - the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, - procedures, authorization keys, or other information required to install - and execute modified versions of a covered work in that User Product from - a modified version of its Corresponding Source. The information must - suffice to ensure that the continued functioning of the modified object - code is in no case prevented or interfered with solely because - modification has been made. - - If you convey an object code work under this section in, or with, or - specifically for use in, a User Product, and the conveying occurs as - part of a transaction in which the right of possession and use of the - User Product is transferred to the recipient in perpetuity or for a - fixed term (regardless of how the transaction is characterized), the - Corresponding Source conveyed under this section must be accompanied - by the Installation Information. But this requirement does not apply - if neither you nor any third party retains the ability to install - modified object code on the User Product (for example, the work has - been installed in ROM). - - The requirement to provide Installation Information does not include a - requirement to continue to provide support service, warranty, or updates - for a work that has been modified or installed by the recipient, or for - the User Product in which it has been modified or installed. Access to a - network may be denied when the modification itself materially and - adversely affects the operation of the network or violates the rules and - protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, - in accord with this section must be in a format that is publicly - documented (and with an implementation available to the public in - source code form), and must require no special password or key for - unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this - License by making exceptions from one or more of its conditions. - Additional permissions that are applicable to the entire Program shall - be treated as though they were included in this License, to the extent - that they are valid under applicable law. If additional permissions - apply only to part of the Program, that part may be used separately - under those permissions, but the entire Program remains governed by - this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option - remove any additional permissions from that copy, or from any part of - it. (Additional permissions may be written to require their own - removal in certain cases when you modify the work.) You may place - additional permissions on material, added by you to a covered work, - for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you - add to a covered work, you may (if authorized by the copyright holders of - that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further - restrictions" within the meaning of section 10. If the Program as you - received it, or any part of it, contains a notice stating that it is - governed by this License along with a term that is a further - restriction, you may remove that term. If a license document contains - a further restriction but permits relicensing or conveying under this - License, you may add to a covered work material governed by the terms - of that license document, provided that the further restriction does - not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you - must place, in the relevant source files, a statement of the - additional terms that apply to those files, or a notice indicating - where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the - form of a separately written license, or stated as exceptions; - the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly - provided under this License. Any attempt otherwise to propagate or - modify it is void, and will automatically terminate your rights under - this License (including any patent licenses granted under the third - paragraph of section 11). - - However, if you cease all violation of this License, then your - license from a particular copyright holder is reinstated (a) - provisionally, unless and until the copyright holder explicitly and - finally terminates your license, and (b) permanently, if the copyright - holder fails to notify you of the violation by some reasonable means - prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is - reinstated permanently if the copyright holder notifies you of the - violation by some reasonable means, this is the first time you have - received notice of violation of this License (for any work) from that - copyright holder, and you cure the violation prior to 30 days after - your receipt of the notice. - - Termination of your rights under this section does not terminate the - licenses of parties who have received copies or rights from you under - this License. If your rights have been terminated and not permanently - reinstated, you do not qualify to receive new licenses for the same - material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or - run a copy of the Program. Ancillary propagation of a covered work - occurring solely as a consequence of using peer-to-peer transmission - to receive a copy likewise does not require acceptance. However, - nothing other than this License grants you permission to propagate or - modify any covered work. These actions infringe copyright if you do - not accept this License. Therefore, by modifying or propagating a - covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically - receives a license from the original licensors, to run, modify and - propagate that work, subject to this License. You are not responsible - for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an - organization, or substantially all assets of one, or subdividing an - organization, or merging organizations. If propagation of a covered - work results from an entity transaction, each party to that - transaction who receives a copy of the work also receives whatever - licenses to the work the party's predecessor in interest had or could - give under the previous paragraph, plus a right to possession of the - Corresponding Source of the work from the predecessor in interest, if - the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the - rights granted or affirmed under this License. For example, you may - not impose a license fee, royalty, or other charge for exercise of - rights granted under this License, and you may not initiate litigation - (including a cross-claim or counterclaim in a lawsuit) alleging that - any patent claim is infringed by making, using, selling, offering for - sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this - License of the Program or a work on which the Program is based. The - work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims - owned or controlled by the contributor, whether already acquired or - hereafter acquired, that would be infringed by some manner, permitted - by this License, of making, using, or selling its contributor version, - but do not include claims that would be infringed only as a - consequence of further modification of the contributor version. For - purposes of this definition, "control" includes the right to grant - patent sublicenses in a manner consistent with the requirements of - this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free - patent license under the contributor's essential patent claims, to - make, use, sell, offer for sale, import and otherwise run, modify and - propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express - agreement or commitment, however denominated, not to enforce a patent - (such as an express permission to practice a patent or covenant not to - sue for patent infringement). To "grant" such a patent license to a - party means to make such an agreement or commitment not to enforce a - patent against the party. - - If you convey a covered work, knowingly relying on a patent license, - and the Corresponding Source of the work is not available for anyone - to copy, free of charge and under the terms of this License, through a - publicly available network server or other readily accessible means, - then you must either (1) cause the Corresponding Source to be so - available, or (2) arrange to deprive yourself of the benefit of the - patent license for this particular work, or (3) arrange, in a manner - consistent with the requirements of this License, to extend the patent - license to downstream recipients. "Knowingly relying" means you have - actual knowledge that, but for the patent license, your conveying the - covered work in a country, or your recipient's use of the covered work - in a country, would infringe one or more identifiable patents in that - country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or - arrangement, you convey, or propagate by procuring conveyance of, a - covered work, and grant a patent license to some of the parties - receiving the covered work authorizing them to use, propagate, modify - or convey a specific copy of the covered work, then the patent license - you grant is automatically extended to all recipients of the covered - work and works based on it. - - A patent license is "discriminatory" if it does not include within - the scope of its coverage, prohibits the exercise of, or is - conditioned on the non-exercise of one or more of the rights that are - specifically granted under this License. You may not convey a covered - work if you are a party to an arrangement with a third party that is - in the business of distributing software, under which you make payment - to the third party based on the extent of your activity of conveying - the work, and under which the third party grants, to any of the - parties who would receive the covered work from you, a discriminatory - patent license (a) in connection with copies of the covered work - conveyed by you (or copies made from those copies), or (b) primarily - for and in connection with specific products or compilations that - contain the covered work, unless you entered into that arrangement, - or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting - any implied license or other defenses to infringement that may - otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or - otherwise) that contradict the conditions of this License, they do not - excuse you from the conditions of this License. If you cannot convey a - covered work so as to satisfy simultaneously your obligations under this - License and any other pertinent obligations, then as a consequence you may - not convey it at all. For example, if you agree to terms that obligate you - to collect a royalty for further conveying from those to whom you convey - the Program, the only way you could satisfy both those terms and this - License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have - permission to link or combine any covered work with a work licensed - under version 3 of the GNU Affero General Public License into a single - combined work, and to convey the resulting work. The terms of this - License will continue to apply to the part which is the covered work, - but the special requirements of the GNU Affero General Public License, - section 13, concerning interaction through a network will apply to the - combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of - the GNU General Public License from time to time. Such new versions will - be similar in spirit to the present version, but may differ in detail to - address new problems or concerns. - - Each version is given a distinguishing version number. If the - Program specifies that a certain numbered version of the GNU General - Public License "or any later version" applies to it, you have the - option of following the terms and conditions either of that numbered - version or of any later version published by the Free Software - Foundation. If the Program does not specify a version number of the - GNU General Public License, you may choose any version ever published - by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future - versions of the GNU General Public License can be used, that proxy's - public statement of acceptance of a version permanently authorizes you - to choose that version for the Program. - - Later license versions may give you additional or different - permissions. However, no additional obligations are imposed on any - author or copyright holder as a result of your choosing to follow a - later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY - APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT - HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY - OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, - THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM - IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF - ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING - WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS - THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY - GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE - USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF - DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD - PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), - EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF - SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided - above cannot be given local legal effect according to their terms, - reviewing courts shall apply local law that most closely approximates - an absolute waiver of all civil liability in connection with the - Program, unless a warranty or assumption of liability accompanies a - copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest - possible use to the public, the best way to achieve this is to make it - free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest - to attach them to the start of each source file to most effectively - state the exclusion of warranty; and each file should have at least - the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - - Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short - notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - - The hypothetical commands `show w' and `show c' should show the appropriate - parts of the General Public License. Of course, your program's commands - might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, - if any, to sign a "copyright disclaimer" for the program, if necessary. - For more information on this, and how to apply and follow the GNU GPL, see - . - - The GNU General Public License does not permit incorporating your program - into proprietary programs. If your program is a subroutine library, you - may consider it more useful to permit linking proprietary applications with - the library. If this is what you want to do, use the GNU Lesser General - Public License instead of this License. But first, please read - . - The complete text of the Apache 2.0 License is as follows: Apache License @@ -2089,374 +1412,25 @@ The complete text of the MIT license is as follows: FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -The complete text of the GPL v2, and classpath exception: - -The GNU General Public License (GPL) - -Version 2, June 1991 - -Copyright (C) 1989, 1991 Free Software Foundation, Inc. -59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -Preamble - -The licenses for most software are designed to take away your freedom to share -and change it. By contrast, the GNU General Public License is intended to -guarantee your freedom to share and change free software--to make sure the -software is free for all its users. This General Public License applies to -most of the Free Software Foundation's software and to any other program whose -authors commit to using it. (Some other Free Software Foundation software is -covered by the GNU Library General Public License instead.) You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom to -distribute copies of free software (and charge for this service if you wish), -that you receive source code or can get it if you want it, that you can change -the software or use pieces of it in new free programs; and that you know you -can do these things. - -To protect your rights, we need to make restrictions that forbid anyone to deny -you these rights or to ask you to surrender the rights. These restrictions -translate to certain responsibilities for you if you distribute copies of the -software, or if you modify it. - -For example, if you distribute copies of such a program, whether gratis or for -a fee, you must give the recipients all the rights that you have. You must -make sure that they, too, receive or can get the source code. And you must -show them these terms so they know their rights. - -We protect your rights with two steps: (1) copyright the software, and (2) -offer you this license which gives you legal permission to copy, distribute -and/or modify the software. - -Also, for each author's protection and ours, we want to make certain that -everyone understands that there is no warranty for this free software. If the -software is modified by someone else and passed on, we want its recipients to -know that what they have is not the original, so that any problems introduced -by others will not reflect on the original authors' reputations. - -Finally, any free program is threatened constantly by software patents. We -wish to avoid the danger that redistributors of a free program will -individually obtain patent licenses, in effect making the program proprietary. -To prevent this, we have made it clear that any patent must be licensed for -everyone's free use or not licensed at all. - -The precise terms and conditions for copying, distribution and modification -follow. - -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License applies to any program or other work which contains a notice -placed by the copyright holder saying it may be distributed under the terms of -this General Public License. The "Program", below, refers to any such program -or work, and a "work based on the Program" means either the Program or any -derivative work under copyright law: that is to say, a work containing the -Program or a portion of it, either verbatim or with modifications and/or -translated into another language. (Hereinafter, translation is included -without limitation in the term "modification".) Each licensee is addressed as -"you". - -Activities other than copying, distribution and modification are not covered by -this License; they are outside its scope. The act of running the Program is -not restricted, and the output from the Program is covered only if its contents -constitute a work based on the Program (independent of having been made by -running the Program). Whether that is true depends on what the Program does. - -1. You may copy and distribute verbatim copies of the Program's source code as -you receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice and -disclaimer of warranty; keep intact all the notices that refer to this License -and to the absence of any warranty; and give any other recipients of the -Program a copy of this License along with the Program. - -You may charge a fee for the physical act of transferring a copy, and you may -at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Program or any portion of it, thus -forming a work based on the Program, and copy and distribute such modifications -or work under the terms of Section 1 above, provided that you also meet all of -these conditions: - - a) You must cause the modified files to carry prominent notices stating - that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in whole or - in part contains or is derived from the Program or any part thereof, to be - licensed as a whole at no charge to all third parties under the terms of - this License. - - c) If the modified program normally reads commands interactively when run, - you must cause it, when started running for such interactive use in the - most ordinary way, to print or display an announcement including an - appropriate copyright notice and a notice that there is no warranty (or - else, saying that you provide a warranty) and that users may redistribute - the program under these conditions, and telling the user how to view a copy - of this License. (Exception: if the Program itself is interactive but does - not normally print such an announcement, your work based on the Program is - not required to print an announcement.) - -These requirements apply to the modified work as a whole. If identifiable -sections of that work are not derived from the Program, and can be reasonably -considered independent and separate works in themselves, then this License, and -its terms, do not apply to those sections when you distribute them as separate -works. But when you distribute the same sections as part of a whole which is a -work based on the Program, the distribution of the whole must be on the terms -of this License, whose permissions for other licensees extend to the entire -whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your -rights to work written entirely by you; rather, the intent is to exercise the -right to control the distribution of derivative or collective works based on -the Program. - -In addition, mere aggregation of another work not based on the Program with the -Program (or with a work based on the Program) on a volume of a storage or -distribution medium does not bring the other work under the scope of this -License. - -3. You may copy and distribute the Program (or a work based on it, under -Section 2) in object code or executable form under the terms of Sections 1 and -2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable source - code, which must be distributed under the terms of Sections 1 and 2 above - on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three years, to - give any third party, for a charge no more than your cost of physically - performing source distribution, a complete machine-readable copy of the - corresponding source code, to be distributed under the terms of Sections 1 - and 2 above on a medium customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer to - distribute corresponding source code. (This alternative is allowed only - for noncommercial distribution and only if you received the program in - object code or executable form with such an offer, in accord with - Subsection b above.) - -The source code for a work means the preferred form of the work for making -modifications to it. For an executable work, complete source code means all -the source code for all modules it contains, plus any associated interface -definition files, plus the scripts used to control compilation and installation -of the executable. However, as a special exception, the source code -distributed need not include anything that is normally distributed (in either -source or binary form) with the major components (compiler, kernel, and so on) -of the operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the source -code from the same place counts as distribution of the source code, even though -third parties are not compelled to copy the source along with the object code. - -4. You may not copy, modify, sublicense, or distribute the Program except as -expressly provided under this License. Any attempt otherwise to copy, modify, -sublicense or distribute the Program is void, and will automatically terminate -your rights under this License. However, parties who have received copies, or -rights, from you under this License will not have their licenses terminated so -long as such parties remain in full compliance. - -5. You are not required to accept this License, since you have not signed it. -However, nothing else grants you permission to modify or distribute the Program -or its derivative works. These actions are prohibited by law if you do not -accept this License. Therefore, by modifying or distributing the Program (or -any work based on the Program), you indicate your acceptance of this License to -do so, and all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - -6. Each time you redistribute the Program (or any work based on the Program), -the recipient automatically receives a license from the original licensor to -copy, distribute or modify the Program subject to these terms and conditions. -You may not impose any further restrictions on the recipients' exercise of the -rights granted herein. You are not responsible for enforcing compliance by -third parties to this License. - -7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), conditions -are imposed on you (whether by court order, agreement or otherwise) that -contradict the conditions of this License, they do not excuse you from the -conditions of this License. If you cannot distribute so as to satisfy -simultaneously your obligations under this License and any other pertinent -obligations, then as a consequence you may not distribute the Program at all. -For example, if a patent license would not permit royalty-free redistribution -of the Program by all those who receive copies directly or indirectly through -you, then the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply and -the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or -other property right claims or to contest validity of any such claims; this -section has the sole purpose of protecting the integrity of the free software -distribution system, which is implemented by public license practices. Many -people have made generous contributions to the wide range of software -distributed through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing to -distribute software through any other system and a licensee cannot impose that -choice. - -This section is intended to make thoroughly clear what is believed to be a -consequence of the rest of this License. - -8. If the distribution and/or use of the Program is restricted in certain -countries either by patents or by copyrighted interfaces, the original -copyright holder who places the Program under this License may add an explicit -geographical distribution limitation excluding those countries, so that -distribution is permitted only in or among countries not thus excluded. In -such case, this License incorporates the limitation as if written in the body -of this License. - -9. The Free Software Foundation may publish revised and/or new versions of the -General Public License from time to time. Such new versions will be similar in -spirit to the present version, but may differ in detail to address new problems -or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any later -version", you have the option of following the terms and conditions either of -that version or of any later version published by the Free Software Foundation. -If the Program does not specify a version number of this License, you may -choose any version ever published by the Free Software Foundation. - -10. If you wish to incorporate parts of the Program into other free programs -whose distribution conditions are different, write to the author to ask for -permission. For software which is copyrighted by the Free Software Foundation, -write to the Free Software Foundation; we sometimes make exceptions for this. -Our decision will be guided by the two goals of preserving the free status of -all derivatives of our free software and of promoting the sharing and reuse of -software generally. - -NO WARRANTY - -11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR -THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE -STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE -PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND -PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, -YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL -ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE -PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR -INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA -BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER -OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively convey the exclusion -of warranty; and each file should have at least the "copyright" line and a -pointer to where the full notice is found. - - One line to give the program's name and a brief idea of what it does. - - Copyright (C) - - This program is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., 59 - Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this when it -starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author Gnomovision comes - with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free - software, and you are welcome to redistribute it under certain conditions; - type 'show c' for details. - -The hypothetical commands 'show w' and 'show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may be -called something other than 'show w' and 'show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your school, -if any, to sign a "copyright disclaimer" for the program, if necessary. Here -is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - 'Gnomovision' (which makes passes at compilers) written by James Hacker. - - signature of Ty Coon, 1 April 1989 - - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General Public -License instead of this License. - -"CLASSPATH" EXCEPTION TO THE GPL - -Certain source files distributed by Oracle America and/or its affiliates are -subject to the following clarification and special exception to the GPL, but -only where Oracle has expressly included in the particular source file's header -the words "Oracle designates this particular file as subject to the "Classpath" -exception as provided by Oracle in the LICENSE file that accompanied this code." - - Linking this library statically or dynamically with other modules is making - a combined work based on this library. Thus, the terms and conditions of - the GNU General Public License cover the whole combination. - - As a special exception, the copyright holders of this library give you - permission to link this library with independent modules to produce an - executable, regardless of the license terms of these independent modules, - and to copy and distribute the resulting executable under terms of your - choice, provided that you also meet, for each linked independent module, - the terms and conditions of the license of that module. An independent - module is a module which is not derived from or based on this library. If - you modify this library, you may extend this exception to your version of - the library, but you are not obligated to do so. If you do not wish to do - so, delete this exception statement from your version. - The full text of the zlib licence: -Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: -1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. -Jean-loup Gailly Mark Adler -jloup@gzip.org madler@alumni.caltech.edu + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu \ No newline at end of file diff --git a/doc/legal/legal.md b/doc/legal/legal.md index 398528de2375..82e809b53cc4 100644 --- a/doc/legal/legal.md +++ b/doc/legal/legal.md @@ -58,7 +58,7 @@ MIT licence, see `mit.txt`. ## JRuby -TruffleRuby contains code from JRuby 9.2.19.0, including Java implementation +TruffleRuby contains code from JRuby 9.4.4.0, including Java implementation code, build system, shell script launchers, standard library modified from MRI, and so on. From 973fe9ee6a6869e727a56aabc54fe2d1d21bac9f Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Fri, 9 Feb 2024 15:06:27 +0200 Subject: [PATCH 15/28] Import FFI gem v1.16.3 --- lib/truffle/ffi/autopointer.rb | 29 ++---- lib/truffle/ffi/compat.rb | 43 ++++++++ lib/truffle/ffi/data_converter.rb | 4 +- lib/truffle/ffi/dynamic_library.rb | 89 ++++++++++++++++ lib/truffle/ffi/enum.rb | 29 ++++-- lib/truffle/ffi/ffi.rb | 3 + lib/truffle/ffi/function.rb | 71 +++++++++++++ lib/truffle/ffi/library.rb | 126 ++++++++++------------- lib/truffle/ffi/library_path.rb | 109 ++++++++++++++++++++ lib/truffle/ffi/managedstruct.rb | 2 +- lib/truffle/ffi/platform.rb | 28 ++--- lib/truffle/ffi/struct.rb | 3 +- lib/truffle/ffi/struct_layout.rb | 2 +- lib/truffle/ffi/struct_layout_builder.rb | 2 +- lib/truffle/ffi/types.rb | 38 +++++-- lib/truffle/ffi/variadic.rb | 27 +++-- lib/truffle/ffi/version.rb | 2 +- spec/ffi/async_callback_spec.rb | 23 +++++ spec/ffi/bitmask_spec.rb | 71 +++++++++++++ spec/ffi/buffer_spec.rb | 10 ++ spec/ffi/dynamic_library_spec.rb | 60 +++++++++++ spec/ffi/enum_spec.rb | 38 +++++-- spec/ffi/errno_spec.rb | 8 ++ spec/ffi/ffi_spec.rb | 23 +++++ spec/ffi/fixtures/BitmaskTest.c | 20 ++++ spec/ffi/fixtures/ClosureTest.c | 12 +-- spec/ffi/fixtures/PipeHelperWindows.c | 4 +- spec/ffi/fixtures/PointerTest.c | 2 + spec/ffi/fixtures/compile.rb | 4 +- spec/ffi/fork_spec.rb | 9 ++ spec/ffi/function_spec.rb | 42 ++++++++ spec/ffi/function_type_spec.rb | 27 +++++ spec/ffi/gc_compact_spec.rb | 66 ++++++++++++ spec/ffi/library_spec.rb | 95 +++++++++++++++-- spec/ffi/managed_struct_spec.rb | 15 +-- spec/ffi/memorypointer_spec.rb | 34 ++++++ spec/ffi/platform_spec.rb | 13 +++ spec/ffi/pointer_spec.rb | 53 +++++++++- spec/ffi/rbx/memory_pointer_spec.rb | 20 ++++ spec/ffi/spec_helper.rb | 4 +- spec/ffi/struct_by_ref_spec.rb | 9 ++ spec/ffi/struct_initialize_spec.rb | 2 +- spec/ffi/struct_spec.rb | 122 +++++++++++++++++++++- spec/ffi/type_spec.rb | 76 ++++++++++++++ spec/ffi/variadic_spec.rb | 32 ++++++ 45 files changed, 1322 insertions(+), 179 deletions(-) create mode 100644 lib/truffle/ffi/compat.rb create mode 100644 lib/truffle/ffi/dynamic_library.rb create mode 100644 lib/truffle/ffi/function.rb create mode 100644 lib/truffle/ffi/library_path.rb create mode 100644 spec/ffi/dynamic_library_spec.rb create mode 100644 spec/ffi/function_type_spec.rb create mode 100644 spec/ffi/gc_compact_spec.rb create mode 100644 spec/ffi/type_spec.rb diff --git a/lib/truffle/ffi/autopointer.rb b/lib/truffle/ffi/autopointer.rb index 679d7e691df3..bbcb6db7597f 100644 --- a/lib/truffle/ffi/autopointer.rb +++ b/lib/truffle/ffi/autopointer.rb @@ -76,21 +76,21 @@ class AutoPointer < Pointer # going to be useful if you subclass {AutoPointer}, and override # #release, which by default does nothing. def initialize(ptr, proc=nil, &block) + raise TypeError, "Invalid pointer" if ptr.nil? || !ptr.kind_of?(Pointer) || + ptr.kind_of?(MemoryPointer) || ptr.kind_of?(AutoPointer) super(ptr.type_size, ptr) - raise TypeError, "Invalid pointer" if ptr.nil? || !ptr.kind_of?(Pointer) \ - || ptr.kind_of?(MemoryPointer) || ptr.kind_of?(AutoPointer) @releaser = if proc if not proc.respond_to?(:call) raise RuntimeError.new("proc must be callable") end - CallableReleaser.new(ptr, proc) + Releaser.new(ptr, proc) else - if not self.class.respond_to?(:release) + if not self.class.respond_to?(:release, true) raise RuntimeError.new("no release method defined") end - DefaultReleaser.new(ptr, self.class) + Releaser.new(ptr, self.class.method(:release)) end ObjectSpace.define_finalizer(self, @releaser) @@ -107,6 +107,7 @@ def free # @return [Boolean] +autorelease+ # Set +autorelease+ property. See {Pointer Autorelease section at Pointer}. def autorelease=(autorelease) + raise FrozenError.new("can't modify frozen #{self.class}") if frozen? @releaser.autorelease=(autorelease) end @@ -149,23 +150,7 @@ def free def call(*args) release(@ptr) if @autorelease && @ptr end - end - - # DefaultReleaser is a {Releaser} used when an {AutoPointer} is defined - # without Proc or Method. In this case, the pointer to release must be of - # a class derived from AutoPointer with a {release} class method. - class DefaultReleaser < Releaser - # @param [Pointer] ptr - # @return [nil] - # Release +ptr+ using the {release} class method of its class. - def release(ptr) - @proc.release(ptr) - end - end - # CallableReleaser is a {Releaser} used when an {AutoPointer} is defined with a - # Proc or a Method. - class CallableReleaser < Releaser # Release +ptr+ by using Proc or Method defined at +ptr+ # {AutoPointer#initialize initialization}. # @@ -182,7 +167,7 @@ def release(ptr) # @return [Type::POINTER] # @raise {RuntimeError} if class does not implement a +#release+ method def self.native_type - if not self.respond_to?(:release) + if not self.respond_to?(:release, true) raise RuntimeError.new("no release method defined for #{self.inspect}") end Type::POINTER diff --git a/lib/truffle/ffi/compat.rb b/lib/truffle/ffi/compat.rb new file mode 100644 index 000000000000..756901343877 --- /dev/null +++ b/lib/truffle/ffi/compat.rb @@ -0,0 +1,43 @@ +# +# Copyright (C) 2023-2023 Lars Kanis +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +module FFI + if defined?(Ractor.make_shareable) + # This is for FFI internal use only. + def self.make_shareable(obj) + Ractor.make_shareable(obj) + end + else + def self.make_shareable(obj) + obj.freeze + end + end +end diff --git a/lib/truffle/ffi/data_converter.rb b/lib/truffle/ffi/data_converter.rb index 1527588b7584..7852e7ee5fd9 100644 --- a/lib/truffle/ffi/data_converter.rb +++ b/lib/truffle/ffi/data_converter.rb @@ -31,7 +31,7 @@ module FFI # This module is used to extend somes classes and give then a common API. # - # Most of methods defined here must be overriden. + # Most of methods defined here must be overridden. module DataConverter # Get native type. # @@ -41,7 +41,7 @@ module DataConverter # Get native type from +type+. # # @overload native_type - # @raise {NotImplementedError} This method must be overriden. + # @raise {NotImplementedError} This method must be overridden. def native_type(type = nil) if type @native_type = FFI.find_type(type) diff --git a/lib/truffle/ffi/dynamic_library.rb b/lib/truffle/ffi/dynamic_library.rb new file mode 100644 index 000000000000..b415033f1aaa --- /dev/null +++ b/lib/truffle/ffi/dynamic_library.rb @@ -0,0 +1,89 @@ +# +# Copyright (C) 2008-2010 Wayne Meissner +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + class DynamicLibrary + SEARCH_PATH = %w[/usr/lib /usr/local/lib /opt/local/lib] + if FFI::Platform::ARCH == 'aarch64' && FFI::Platform.mac? + SEARCH_PATH << '/opt/homebrew/lib' + end + + SEARCH_PATH_MESSAGE = "Searched in , #{SEARCH_PATH.join(', ')}".freeze + + def self.load_library(name, flags) + if name == FFI::CURRENT_PROCESS + FFI::DynamicLibrary.open(nil, RTLD_LAZY | RTLD_LOCAL) + else + flags ||= RTLD_LAZY | RTLD_LOCAL + + libnames = (name.is_a?(::Array) ? name : [name]) + libnames = libnames.map(&:to_s).map { |n| [n, FFI.map_library_name(n)].uniq }.flatten.compact + errors = [] + + libnames.each do |libname| + lib = try_load(libname, flags, errors) + return lib if lib + + unless libname.start_with?("/") || FFI::Platform.windows? + SEARCH_PATH.each do |prefix| + path = "#{prefix}/#{libname}" + if File.exist?(path) + lib = try_load(path, flags, errors) + return lib if lib + end + end + end + end + + raise LoadError, [*errors, SEARCH_PATH_MESSAGE].join(".\n") + end + end + private_class_method :load_library + + def self.try_load(libname, flags, errors) + begin + lib = FFI::DynamicLibrary.open(libname, flags) + return lib if lib + + # LoadError for C ext & JRuby, RuntimeError for TruffleRuby + rescue LoadError, RuntimeError => ex + if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short|invalid file format)/ + if File.binread($1) =~ /(?:GROUP|INPUT) *\( *([^ \)]+)/ + return try_load($1, flags, errors) + end + end + + errors << ex + nil + end + end + private_class_method :try_load + end +end diff --git a/lib/truffle/ffi/enum.rb b/lib/truffle/ffi/enum.rb index 8fcb49859530..aaef29a610c9 100644 --- a/lib/truffle/ffi/enum.rb +++ b/lib/truffle/ffi/enum.rb @@ -192,6 +192,7 @@ class Bitmask < Enum # @param [nil, Symbol] tag name of new Bitmask def initialize(*args) @native_type = args.first.kind_of?(FFI::Type) ? args.shift : Type::INT + @signed = [Type::INT8, Type::INT16, Type::INT32, Type::INT64].include?(@native_type) info, @tag = *args @kv_map = Hash.new unless info.nil? @@ -220,7 +221,7 @@ def initialize(*args) # @param [Symbol] query # @return [Integer] # @overload [](query) - # Get bitmaks value from symbol array + # Get bitmask value from symbol array # @param [Array] query # @return [Integer] # @overload [](*query) @@ -240,7 +241,7 @@ def [](*query) when Symbol flat_query.inject(0) do |val, o| v = @kv_map[o] - if v then val |= v else val end + if v then val | v else val end end when Integer, ->(o) { o.respond_to?(:to_int) } val = flat_query.inject(0) { |mask, o| mask |= o.to_int } @@ -260,35 +261,41 @@ def [](*query) def to_native(query, ctx) return 0 if query.nil? flat_query = [query].flatten - flat_query.inject(0) do |val, o| + res = flat_query.inject(0) do |val, o| case o when Symbol v = @kv_map[o] raise ArgumentError, "invalid bitmask value, #{o.inspect}" unless v - val |= v + val | v when Integer - val |= o + val | o when ->(obj) { obj.respond_to?(:to_int) } - val |= o.to_int + val | o.to_int else raise ArgumentError, "invalid bitmask value, #{o.inspect}" end end + # Take two's complement of positive values bigger than the max value + # for the type when native type is signed. + if @signed && res >= (1 << (@native_type.size * 8 - 1)) + res = -(-res & ((1 << (@native_type.size * 8)) - 1)) + end + res end # @param [Integer] val # @param ctx unused # @return [Array] list of symbol names corresponding to val, plus an optional remainder if some bits don't match any constant def from_native(val, ctx) - list = @kv_map.select { |_, v| v & val != 0 }.keys + flags = @kv_map.select { |_, v| v & val != 0 } + list = flags.keys + # force an unsigned value of the correct size + val &= (1 << (@native_type.size * 8)) - 1 if @signed # If there are unmatch flags, # return them in an integer, # else information can be lost. # Similar to Enum behavior. - remainder = val ^ list.inject(0) do |tmp, o| - v = @kv_map[o] - if v then tmp |= v else tmp end - end + remainder = val ^ flags.values.reduce(0, :|) list.push remainder unless remainder == 0 return list end diff --git a/lib/truffle/ffi/ffi.rb b/lib/truffle/ffi/ffi.rb index dfffa8ca0142..2c5ea20c29dc 100644 --- a/lib/truffle/ffi/ffi.rb +++ b/lib/truffle/ffi/ffi.rb @@ -28,9 +28,11 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +require 'ffi/compat' require 'ffi/platform' require 'ffi/data_converter' require 'ffi/types' +require 'ffi/library_path' require 'ffi/library' require 'ffi/errno' require 'ffi/abstract_memory' @@ -45,3 +47,4 @@ require 'ffi/variadic' require 'ffi/enum' require 'ffi/version' +require 'ffi/function' diff --git a/lib/truffle/ffi/function.rb b/lib/truffle/ffi/function.rb new file mode 100644 index 000000000000..ac4daf03ecaf --- /dev/null +++ b/lib/truffle/ffi/function.rb @@ -0,0 +1,71 @@ +# +# Copyright (C) 2008-2010 JRuby project +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +module FFI + class Function + # Only MRI allows function type queries + if private_method_defined?(:type) + # Retrieve the return type of the function + # + # This method returns FFI type returned by the function. + # + # @return [FFI::Type] + def return_type + type.return_type + end + + # Retrieve Array of parameter types + # + # This method returns an Array of FFI types accepted as function parameters. + # + # @return [Array] + def param_types + type.param_types + end + end + + # Stash the Function in a module variable so it can be inspected by attached_functions. + # On CRuby it also ensures that it does not get garbage collected. + module RegisterAttach + def attach(mod, name) + funcs = mod.instance_variable_get("@ffi_functions") + unless funcs + funcs = {} + mod.instance_variable_set("@ffi_functions", funcs) + end + funcs[name.to_sym] = self + # Jump to the native attach method of CRuby, JRuby or Tuffleruby + super + end + end + private_constant :RegisterAttach + prepend RegisterAttach + end +end diff --git a/lib/truffle/ffi/library.rb b/lib/truffle/ffi/library.rb index 43b2bfe1599d..d6008ae1026d 100644 --- a/lib/truffle/ffi/library.rb +++ b/lib/truffle/ffi/library.rb @@ -28,10 +28,12 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# +require 'ffi/dynamic_library' + module FFI - CURRENT_PROCESS = USE_THIS_PROCESS_AS_LIBRARY = Object.new + CURRENT_PROCESS = USE_THIS_PROCESS_AS_LIBRARY = FFI.make_shareable(Object.new) - # @param [#to_s] lib library name + # @param [String, FFI::LibraryPath] lib library name or LibraryPath object # @return [String] library name formatted for current platform # Transform a generic library name to a platform library name # @example @@ -43,15 +45,7 @@ module FFI # FFI.map_library_name 'jpeg' # -> "jpeg.dll" def self.map_library_name(lib) # Mangle the library name to reflect the native library naming conventions - lib = Library::LIBC if lib == 'c' - - if lib && File.basename(lib) == lib - lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/ - r = Platform::IS_WINDOWS || Platform::IS_MAC ? "\\.#{Platform::LIBSUFFIX}$" : "\\.so($|\\.[1234567890]+)" - lib += ".#{Platform::LIBSUFFIX}" unless lib =~ /#{r}/ - end - - lib + LibraryPath.wrap(lib).to_s end # Exception raised when a function is not found in libraries @@ -95,62 +89,11 @@ def self.extended(mod) def ffi_lib(*names) raise LoadError.new("library names list must not be empty") if names.empty? - lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL - ffi_libs = names.map do |name| + lib_flags = defined?(@ffi_lib_flags) && @ffi_lib_flags - if name == FFI::CURRENT_PROCESS - FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL) - - else - libnames = (name.is_a?(::Array) ? name : [ name ]).map(&:to_s).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact - lib = nil - errors = {} - - libnames.each do |libname| - begin - orig = libname - lib = FFI::DynamicLibrary.open(libname, lib_flags) - break if lib - - rescue Exception => ex - ldscript = false - if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*(invalid ELF header|file too short|invalid file format)/ - if File.binread($1) =~ /(?:GROUP|INPUT) *\( *([^ \)]+)/ - libname = $1 - ldscript = true - end - end - - if ldscript - retry - else - # TODO better library lookup logic - unless libname.start_with?("/") || FFI::Platform.windows? - path = ['/usr/lib/','/usr/local/lib/','/opt/local/lib/', '/opt/homebrew/lib/'].find do |pth| - File.exist?(pth + libname) - end - if path - libname = path + libname - retry - end - end - - libr = (orig == libname ? orig : "#{orig} #{libname}") - errors[libr] = ex - end - end - end - - if lib.nil? - raise LoadError.new(errors.values.join(".\n")) - end - - # return the found lib - lib - end + @ffi_libs = names.map do |name| + FFI::DynamicLibrary.send(:load_library, name, lib_flags) end - - @ffi_libs = ffi_libs end # Set the calling convention for {#attach_function} and {#callback} @@ -258,7 +201,7 @@ def attach_function(name, func, args, returns = nil, options = nil) end raise LoadError unless function - invokers << if arg_types.length > 0 && arg_types[arg_types.length - 1] == FFI::NativeType::VARARGS + invokers << if arg_types[-1] == FFI::NativeType::VARARGS VariadicInvoker.new(function, arg_types, find_type(ret_type), options) else @@ -330,6 +273,7 @@ def function_names(name, arg_types) # Attach C variable +cname+ to this module. def attach_variable(mname, a1, a2 = nil) cname, type = a2 ? [ a1, a2 ] : [ mname.to_s, a1 ] + mname = mname.to_sym address = nil ffi_libraries.each do |lib| begin @@ -344,9 +288,10 @@ def attach_variable(mname, a1, a2 = nil) # If it is a global struct, just attach directly to the pointer s = s = type.new(address) # Assigning twice to suppress unused variable warning self.module_eval <<-code, __FILE__, __LINE__ - @@ffi_gvar_#{mname} = s + @ffi_gsvars = {} unless defined?(@ffi_gsvars) + @ffi_gsvars[#{mname.inspect}] = s def self.#{mname} - @@ffi_gvar_#{mname} + @ffi_gsvars[#{mname.inspect}] end code @@ -358,12 +303,13 @@ def self.#{mname} # Attach to this module as mname/mname= # self.module_eval <<-code, __FILE__, __LINE__ - @@ffi_gvar_#{mname} = s + @ffi_gvars = {} unless defined?(@ffi_gvars) + @ffi_gvars[#{mname.inspect}] = s def self.#{mname} - @@ffi_gvar_#{mname}[:gvar] + @ffi_gvars[#{mname.inspect}][:gvar] end def self.#{mname}=(value) - @@ffi_gvar_#{mname}[:gvar] = value + @ffi_gvars[#{mname.inspect}][:gvar] = value end code @@ -588,5 +534,43 @@ def find_type(t) end || FFI.find_type(t) end + + # Retrieve all attached functions and their function signature + # + # This method returns a Hash of method names of attached functions connected by #attach_function and the corresponding function type. + # The function type responds to #return_type and #param_types which return the FFI types of the function signature. + # + # @return [Hash< Symbol => [FFI::Function, FFI::VariadicInvoker] >] + def attached_functions + @ffi_functions || {} + end + + # Retrieve all attached variables and their type + # + # This method returns a Hash of variable names and the corresponding type or variables connected by #attach_variable . + # + # @return [Hash< Symbol => ffi_type >] + def attached_variables + ( + (@ffi_gsvars || {}).map do |name, gvar| + [name, gvar.class] + end + + (@ffi_gvars || {}).map do |name, gvar| + [name, gvar.layout[:gvar].type] + end + ).to_h + end + + # Freeze all definitions of the module + # + # This freezes the module's definitions, so that it can be used in a Ractor. + # No further methods or variables can be attached and no further enums or typedefs can be created in this module afterwards. + def freeze + instance_variables.each do |name| + var = instance_variable_get(name) + FFI.make_shareable(var) + end + nil + end end end diff --git a/lib/truffle/ffi/library_path.rb b/lib/truffle/ffi/library_path.rb new file mode 100644 index 000000000000..5575a5f18da4 --- /dev/null +++ b/lib/truffle/ffi/library_path.rb @@ -0,0 +1,109 @@ +# +# Copyright (C) 2023 Lars Kanis +# +# This file is part of ruby-ffi. +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the Ruby FFI project nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# + +module FFI + # Transform a generic library name and ABI number to a platform library name + # + # Example: + # module LibVips + # extend FFI::Library + # ffi_lib LibraryPath.new("vips", abi_number: 42) + # end + # + # This translates to the following library file names: + # libvips-42.dll on Windows + # libvips.so.42 on Linux + # libvips.42.dylib on Macos + # + # See https://packaging.ubuntu.com/html/libraries.html for more information about library naming. + class LibraryPath + attr_reader :name + attr_reader :abi_number + attr_reader :root + + # Build a new library path + # + # * name : The name of the library without file prefix or suffix. + # * abi_number : The ABI number of the library. + # * root : An optional base path prepended to the library name. + def initialize(name, abi_number: nil, root: nil) + @name = name + @abi_number = abi_number + @root = root + end + + def self.wrap(value) + # We allow instances of LibraryPath to pass through transparently: + return value if value.is_a?(self) + + # We special case a library named 'c' to be the standard C library: + return Library::LIBC if value == 'c' + + # If provided a relative file name we convert it into a library path: + if value && File.basename(value) == value + return self.new(value) + end + + # Otherwise, we assume it's a full path to a library: + return value + end + + def full_name + # If the abi_number is given, we format it specifically according to platform rules: + if abi_number + if Platform.windows? + "#{Platform::LIBPREFIX}#{name}-#{abi_number}.#{Platform::LIBSUFFIX}" + elsif Platform.mac? + "#{Platform::LIBPREFIX}#{name}.#{abi_number}.#{Platform::LIBSUFFIX}" + else # Linux? BSD? etc. + "#{Platform::LIBPREFIX}#{name}.#{Platform::LIBSUFFIX}.#{abi_number}" + end + else + # Otherwise we just add prefix and suffix: + lib = name + # Add library prefix if missing + lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/ + # Add library extension if missing + r = Platform.windows? || Platform.mac? ? "\\.#{Platform::LIBSUFFIX}$" : "\\.so($|\\.[1234567890]+)" + lib += ".#{Platform::LIBSUFFIX}" unless lib =~ /#{r}/ + lib + end + end + + def to_s + if root + # If the root path is given, we generate the full path: + File.join(root, full_name) + else + full_name + end + end + end +end diff --git a/lib/truffle/ffi/managedstruct.rb b/lib/truffle/ffi/managedstruct.rb index b5ec8a379769..5d243e5b5bc8 100644 --- a/lib/truffle/ffi/managedstruct.rb +++ b/lib/truffle/ffi/managedstruct.rb @@ -75,7 +75,7 @@ class ManagedStruct < FFI::Struct # @overload initialize # A new instance of FFI::ManagedStruct. def initialize(pointer=nil) - raise NoMethodError, "release() not implemented for class #{self}" unless self.class.respond_to? :release + raise NoMethodError, "release() not implemented for class #{self}" unless self.class.respond_to?(:release, true) raise ArgumentError, "Must supply a pointer to memory for the Struct" unless pointer super AutoPointer.new(pointer, self.class.method(:release)) end diff --git a/lib/truffle/ffi/platform.rb b/lib/truffle/ffi/platform.rb index bf01a27ad31b..5ac4dd70ea75 100644 --- a/lib/truffle/ffi/platform.rb +++ b/lib/truffle/ffi/platform.rb @@ -29,13 +29,15 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.# require 'rbconfig' +require_relative 'compat' + module FFI class PlatformError < LoadError; end # This module defines different constants and class methods to play with # various platforms. module Platform - OS = case RbConfig::CONFIG['host_os'].downcase + OS = FFI.make_shareable(case RbConfig::CONFIG['host_os'].downcase when /linux/ "linux" when /darwin/ @@ -54,13 +56,13 @@ module Platform "windows" else RbConfig::CONFIG['host_os'].downcase - end + end) OSVERSION = RbConfig::CONFIG['host_os'].gsub(/[^\d]/, '').to_i - CPU = RbConfig::CONFIG['host_cpu'] + CPU = FFI.make_shareable(RbConfig::CONFIG['host_cpu']) - ARCH = case CPU.downcase + ARCH = FFI.make_shareable(case CPU.downcase when /amd64|x86_64|x64/ "x86_64" when /i\d86|x86|i86pc/ @@ -81,7 +83,7 @@ module Platform end else RbConfig::CONFIG['host_cpu'] - end + end) private # @param [String) os @@ -105,21 +107,21 @@ def self.is_os(os) # Add the version for known ABI breaks name_version = "12" if IS_FREEBSD && OSVERSION >= 12 # 64-bit inodes - NAME = "#{ARCH}-#{OS}#{name_version}" - CONF_DIR = File.join(File.dirname(__FILE__), 'platform', NAME) + NAME = FFI.make_shareable("#{ARCH}-#{OS}#{name_version}") + CONF_DIR = FFI.make_shareable(File.join(File.dirname(__FILE__), 'platform', NAME)) public - LIBPREFIX = case OS + LIBPREFIX = FFI.make_shareable(case OS when /windows|msys/ '' when /cygwin/ 'cyg' else 'lib' - end + end) - LIBSUFFIX = case OS + LIBSUFFIX = FFI.make_shareable(case OS when /darwin/ 'dylib' when /linux|bsd|solaris/ @@ -129,9 +131,9 @@ def self.is_os(os) else # Punt and just assume a sane unix (i.e. anything but AIX) 'so' - end + end) - LIBC = if IS_WINDOWS + LIBC = FFI.make_shareable(if IS_WINDOWS crtname = RbConfig::CONFIG["RUBY_SO_NAME"][/msvc\w+/] || 'ucrtbase' "#{crtname}.dll" elsif IS_GNU @@ -143,7 +145,7 @@ def self.is_os(os) "msys-2.0.dll" else "#{LIBPREFIX}c.#{LIBSUFFIX}" - end + end) LITTLE_ENDIAN = 1234 unless defined?(LITTLE_ENDIAN) BIG_ENDIAN = 4321 unless defined?(BIG_ENDIAN) diff --git a/lib/truffle/ffi/struct.rb b/lib/truffle/ffi/struct.rb index 70282580b04c..725b9cb7647a 100644 --- a/lib/truffle/ffi/struct.rb +++ b/lib/truffle/ffi/struct.rb @@ -203,9 +203,10 @@ class << self # :field3, :string # end def layout(*spec) - warn "[DEPRECATION] Struct layout is already defined for class #{self.inspect}. Redefinition as in #{caller[0]} will be disallowed in ffi-2.0." if defined?(@layout) return @layout if spec.size == 0 + warn "[DEPRECATION] Struct layout is already defined for class #{self.inspect}. Redefinition as in #{caller[0]} will be disallowed in ffi-2.0." if defined?(@layout) + builder = StructLayoutBuilder.new builder.union = self < Union builder.packed = @packed if defined?(@packed) diff --git a/lib/truffle/ffi/struct_layout.rb b/lib/truffle/ffi/struct_layout.rb index d5a78a7a7d76..3fd68cb40e31 100644 --- a/lib/truffle/ffi/struct_layout.rb +++ b/lib/truffle/ffi/struct_layout.rb @@ -80,8 +80,8 @@ def put(ptr, value) class Mapped < Field def initialize(name, offset, type, orig_field) - super(name, offset, type) @orig_field = orig_field + super(name, offset, type) end def get(ptr) diff --git a/lib/truffle/ffi/struct_layout_builder.rb b/lib/truffle/ffi/struct_layout_builder.rb index 4d6a464103a1..d7d26a23e5af 100644 --- a/lib/truffle/ffi/struct_layout_builder.rb +++ b/lib/truffle/ffi/struct_layout_builder.rb @@ -112,7 +112,7 @@ def packed=(packed) Type::FLOAT64, Type::LONGDOUBLE, Type::BOOL, - ] + ].freeze # @param [String, Symbol] name name of the field # @param [Array, DataConverter, Struct, StructLayout::Field, Symbol, Type] type type of the field diff --git a/lib/truffle/ffi/types.rb b/lib/truffle/ffi/types.rb index 90f50c1b542a..c0bea0534748 100644 --- a/lib/truffle/ffi/types.rb +++ b/lib/truffle/ffi/types.rb @@ -33,12 +33,24 @@ # see {file:README} module FFI + unless defined?(self.custom_typedefs) + # Truffleruby and JRuby don't support Ractor so far. + # So they don't need separation between builtin and custom types. + def self.custom_typedefs + TypeDefs + end + writable_typemap = true + end + # @param [Type, DataConverter, Symbol] old type definition used by {FFI.find_type} # @param [Symbol] add new type definition's name to add # @return [Type] # Add a definition type to type definitions. + # + # The type definition is local per Ractor. def self.typedef(old, add) - TypeDefs[add] = self.find_type(old) + tm = custom_typedefs + tm[add] = self.find_type(old) end # (see FFI.typedef) @@ -46,6 +58,14 @@ def self.add_typedef(old, add) typedef old, add end + class << self + private def __typedef(old, add) + TypeDefs[add] = self.find_type(old) + end + + private :custom_typedefs + end + # @param [Type, DataConverter, Symbol] name # @param [Hash] type_map if nil, {FFI::TypeDefs} is used @@ -57,14 +77,18 @@ def self.find_type(name, type_map = nil) if name.is_a?(Type) name - elsif type_map && type_map.has_key?(name) + elsif type_map&.has_key?(name) type_map[name] + elsif (tm=custom_typedefs).has_key?(name) + tm[name] + elsif TypeDefs.has_key?(name) TypeDefs[name] elsif name.is_a?(DataConverter) - (type_map || TypeDefs)[name] = Type::Mapped.new(name) + tm = (type_map || custom_typedefs) + tm[name] = Type::Mapped.new(name) else raise TypeError, "unable to resolve type '#{name}'" end @@ -168,7 +192,7 @@ def self.from_native(val, ctx) end end - typedef(StrPtrConverter, :strptr) + __typedef(StrPtrConverter, :strptr) # @param type +type+ is an instance of class accepted by {FFI.find_type} # @return [Numeric] @@ -184,11 +208,13 @@ def self.type_size(type) f.each_line { |line| if line.index(prefix) == 0 new_type, orig_type = line.chomp.slice(prefix.length..-1).split(/\s*=\s*/) - typedef(orig_type.to_sym, new_type.to_sym) + __typedef(orig_type.to_sym, new_type.to_sym) end } end - typedef :pointer, :caddr_t + __typedef :pointer, :caddr_t rescue Errno::ENOENT end + + FFI.make_shareable(TypeDefs) unless writable_typemap end diff --git a/lib/truffle/ffi/variadic.rb b/lib/truffle/ffi/variadic.rb index 743ce7f0f34c..ee33409105bf 100644 --- a/lib/truffle/ffi/variadic.rb +++ b/lib/truffle/ffi/variadic.rb @@ -54,16 +54,27 @@ def attach(mod, mname) invoker = self params = "*args" call = "call" - mod.module_eval <<-code - @@#{mname} = invoker - def self.#{mname}(#{params}) - @@#{mname}.#{call}(#{params}) - end - def #{mname}(#{params}) - @@#{mname}.#{call}(#{params}) - end + mname = mname.to_sym + mod.module_eval <<-code, __FILE__, __LINE__ + @ffi_functions = {} unless defined?(@ffi_functions) + @ffi_functions[#{mname.inspect}] = invoker + + def self.#{mname}(#{params}) + @ffi_functions[#{mname.inspect}].#{call}(#{params}) + end + + define_method(#{mname.inspect}, &method(#{mname.inspect})) code invoker end + + # Retrieve Array of parameter types + # + # This method returns an Array of FFI types accepted as function parameters. + # + # @return [Array] + def param_types + [*@fixed, Type::Builtin::VARARGS] + end end end diff --git a/lib/truffle/ffi/version.rb b/lib/truffle/ffi/version.rb index 3027569288f8..fef4c1cb699a 100644 --- a/lib/truffle/ffi/version.rb +++ b/lib/truffle/ffi/version.rb @@ -1,3 +1,3 @@ module FFI - VERSION = '1.15.5' + VERSION = '1.16.3' end diff --git a/spec/ffi/async_callback_spec.rb b/spec/ffi/async_callback_spec.rb index 51a4886435e8..7bb9f70c7c4d 100644 --- a/spec/ffi/async_callback_spec.rb +++ b/spec/ffi/async_callback_spec.rb @@ -50,4 +50,27 @@ module LibTest expect(callback_runner_thread.name).to eq("FFI Callback Runner") end + + it "works in Ractor", :ractor do + skip "not yet supported on TruffleRuby" if RUBY_ENGINE == "truffleruby" + + res = Ractor.new do + v = 0xdeadbeef + correct_ractor = false + correct_thread = false + thread = Thread.current + rac = Ractor.current + cb = Proc.new do |i| + v = i + correct_ractor = rac == Ractor.current + correct_thread = thread != Thread.current + end + LibTest.testAsyncCallback(cb, 0x7fffffff) + + [v, correct_ractor, correct_thread] + end.take + + expect(res).to eq([0x7fffffff, true, true]) + end + end diff --git a/spec/ffi/bitmask_spec.rb b/spec/ffi/bitmask_spec.rb index 4a404b0b39ee..b85214d6649c 100644 --- a/spec/ffi/bitmask_spec.rb +++ b/spec/ffi/bitmask_spec.rb @@ -58,6 +58,40 @@ module TestBitmask4 attach_function :test_tagged_nonint_bitmask6, :test_tagged_nonint_bitmask3, [:bitmask_type6], :bitmask_type6 end +module TestBitmask5 + extend FFI::Library + ffi_lib TestLibrary::PATH + + bitmask FFI::Type::INT8, :bitmask_type1, [:c1, :c2, :c3, 7] + bitmask FFI::Type::INT16, :bitmask_type2, [:c4, :c5, :c6, 15] + bitmask FFI::Type::INT32, :bitmask_type3, [:c7, :c8, :c9, 31] + bitmask FFI::Type::INT64, :bitmask_type4, [:c10, :c11, :c12, 63] + bitmask FFI::Type::INT, :bitmask_type5, [:c13, :c14, :c15, FFI::Type::INT.size * 8 - 1] + + attach_function :test_tagged_nonint_signed_bitmask1, [:bitmask_type1], :bitmask_type1 + attach_function :test_tagged_nonint_signed_bitmask2, [:bitmask_type2], :bitmask_type2 + attach_function :test_tagged_nonint_signed_bitmask3, [:bitmask_type3], :bitmask_type3 + attach_function :test_tagged_nonint_signed_bitmask4, [:bitmask_type4], :bitmask_type4 + attach_function :test_tagged_nonint_signed_bitmask5, :test_untagged_bitmask, [:bitmask_type5], :bitmask_type5 +end + +module TestBitmask6 + extend FFI::Library + ffi_lib TestLibrary::PATH + + bitmask FFI::Type::UINT8, :bitmask_type1, [:c1, :c2, :c3, 7] + bitmask FFI::Type::UINT16, :bitmask_type2, [:c4, :c5, :c6, 15] + bitmask FFI::Type::UINT32, :bitmask_type3, [:c7, :c8, :c9, 31] + bitmask FFI::Type::UINT64, :bitmask_type4, [:c10, :c11, :c12, 63] + bitmask FFI::Type::UINT, :bitmask_type5, [:c13, :c14, :c15, FFI::Type::UINT.size * 8 - 1] + + attach_function :test_tagged_nonint_unsigned_bitmask1, :test_untagged_nonint_bitmask, [:bitmask_type1], :bitmask_type1 + attach_function :test_tagged_nonint_unsigned_bitmask2, :test_tagged_nonint_bitmask1, [:bitmask_type2], :bitmask_type2 + attach_function :test_tagged_nonint_unsigned_bitmask3, :test_tagged_nonint_bitmask2, [:bitmask_type3], :bitmask_type3 + attach_function :test_tagged_nonint_unsigned_bitmask4, :test_tagged_nonint_bitmask3, [:bitmask_type4], :bitmask_type4 + attach_function :test_tagged_nonint_unsigned_bitmask5, :test_tagged_uint_bitmask, [:bitmask_type5], :bitmask_type5 +end + describe "A library with no bitmask or enum defined" do it "returns nil when asked for an enum" do expect(TestBitmask0.enum_type(:foo)).to be_nil @@ -248,6 +282,23 @@ module TestBitmask4 expect(TestBitmask4.test_tagged_nonint_bitmask6([1<<14,1<<42,1<<43])).to eq([:c26,:c28,1<<43]) end + it "only remainder is given if only undefined mask are returned" do + expect(TestBitmask3.test_tagged_typedef_bitmask1(1<<4)).to eq([1<<4]) + expect(TestBitmask3.test_tagged_typedef_bitmask1([1<<4])).to eq([1<<4]) + expect(TestBitmask3.test_tagged_typedef_bitmask2(1<<6)).to eq([1<<6]) + expect(TestBitmask3.test_tagged_typedef_bitmask2([1<<6])).to eq([1<<6]) + expect(TestBitmask3.test_tagged_typedef_bitmask3(1<<7)).to eq([1<<7]) + expect(TestBitmask3.test_tagged_typedef_bitmask3([1<<7])).to eq([1<<7]) + expect(TestBitmask3.test_tagged_typedef_bitmask4(1<<9)).to eq([1<<9]) + expect(TestBitmask3.test_tagged_typedef_bitmask4([1<<9])).to eq([1<<9]) + expect(TestBitmask4.test_tagged_nonint_bitmask4(1<<10)).to eq([1<<10]) + expect(TestBitmask4.test_tagged_nonint_bitmask4([1<<10])).to eq([1<<10]) + expect(TestBitmask4.test_tagged_nonint_bitmask5(1<<16)).to eq([1<<16]) + expect(TestBitmask4.test_tagged_nonint_bitmask5([1<<16])).to eq([1<<16]) + expect(TestBitmask4.test_tagged_nonint_bitmask6(1<<43)).to eq([1<<43]) + expect(TestBitmask4.test_tagged_nonint_bitmask6([1<<43])).to eq([1<<43]) + end + it "wrong constants rejected" do expect { TestBitmask3.test_tagged_typedef_bitmask1([:c2,:c4,:c5]) }.to raise_error(ArgumentError) expect { TestBitmask3.test_tagged_typedef_bitmask2([:c6,:c8,:c9]) }.to raise_error(ArgumentError) @@ -583,3 +634,23 @@ module TestBitmask4 end.to raise_error(ArgumentError, /duplicate/) end end + +describe "Signed bitmasks" do + it "do not return a remainder when used with their most significant bit set" do + expect(TestBitmask5.test_tagged_nonint_signed_bitmask1([:c1, :c2, :c3])).to eq([:c1, :c2, :c3]) + expect(TestBitmask5.test_tagged_nonint_signed_bitmask2([:c4, :c5, :c6])).to eq([:c4, :c5, :c6]) + expect(TestBitmask5.test_tagged_nonint_signed_bitmask3([:c7, :c8, :c9])).to eq([:c7, :c8, :c9]) + expect(TestBitmask5.test_tagged_nonint_signed_bitmask4([:c10, :c11, :c12])).to eq([:c10, :c11, :c12]) + expect(TestBitmask5.test_tagged_nonint_signed_bitmask5([:c13, :c14, :c15])).to eq([:c13, :c14, :c15]) + end +end + +describe "Unsigned bitmasks" do + it "do not return a remainder when used with their most significant bit set" do + expect(TestBitmask6.test_tagged_nonint_unsigned_bitmask1([:c1, :c2, :c3])).to eq([:c1, :c2, :c3]) + expect(TestBitmask6.test_tagged_nonint_unsigned_bitmask2([:c4, :c5, :c6])).to eq([:c4, :c5, :c6]) + expect(TestBitmask6.test_tagged_nonint_unsigned_bitmask3([:c7, :c8, :c9])).to eq([:c7, :c8, :c9]) + expect(TestBitmask6.test_tagged_nonint_unsigned_bitmask4([:c10, :c11, :c12])).to eq([:c10, :c11, :c12]) unless RUBY_ENGINE == 'truffleruby' + expect(TestBitmask6.test_tagged_nonint_unsigned_bitmask5([:c13, :c14, :c15])).to eq([:c13, :c14, :c15]) + end +end diff --git a/spec/ffi/buffer_spec.rb b/spec/ffi/buffer_spec.rb index 619cb6bb5a30..e031f7cfcc2d 100644 --- a/spec/ffi/buffer_spec.rb +++ b/spec/ffi/buffer_spec.rb @@ -285,3 +285,13 @@ expect(block_executed).to be true end end + +describe "Buffer#memsize_of" do + it "has a memsize function", skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + buf = FFI::Buffer.new 14 + size = ObjectSpace.memsize_of(buf) + expect(size).to be > base_size + end +end diff --git a/spec/ffi/dynamic_library_spec.rb b/spec/ffi/dynamic_library_spec.rb new file mode 100644 index 000000000000..088a8226b60a --- /dev/null +++ b/spec/ffi/dynamic_library_spec.rb @@ -0,0 +1,60 @@ +# +# This file is part of ruby-ffi. +# For licensing, see LICENSE.SPECS +# + +require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) + +describe FFI::DynamicLibrary do + it "should be shareable for Ractor", :ractor do + libtest = FFI::DynamicLibrary.open(TestLibrary::PATH, + FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_GLOBAL) + + res = Ractor.new(libtest) do |libtest2| + libtest2.find_symbol("testClosureVrV").address + end.take + + expect( res ).to be > 0 + end + + it "load a library in a Ractor", :ractor do + res = Ractor.new do + libtest = FFI::DynamicLibrary.open(TestLibrary::PATH, + FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_GLOBAL) + libtest.find_symbol("testClosureVrV") + end.take + + expect(res.address).to be > 0 + end + + it "has a memsize function", skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + libtest = FFI::DynamicLibrary.open(TestLibrary::PATH, + FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_GLOBAL) + size = ObjectSpace.memsize_of(libtest) + expect(size).to be > base_size + end + + describe Symbol do + before do + @libtest = FFI::DynamicLibrary.open( + TestLibrary::PATH, + FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_GLOBAL, + ) + end + + it "has a memsize function", skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + symbol = @libtest.find_symbol("gvar_gstruct_set") + size = ObjectSpace.memsize_of(symbol) + expect(size).to be > base_size + end + + it "should be shareable for Ractor", :ractor do + symbol = @libtest.find_symbol("gvar_gstruct_set") + expect(Ractor.shareable?(symbol)).to be true + end + end +end diff --git a/spec/ffi/enum_spec.rb b/spec/ffi/enum_spec.rb index b8c5b573d473..7a55b07083d2 100644 --- a/spec/ffi/enum_spec.rb +++ b/spec/ffi/enum_spec.rb @@ -26,14 +26,18 @@ module TestEnum3 ffi_lib TestLibrary::PATH enum :enum_type1, [:c1, :c2, :c3, :c4] - enum :enum_type2, [:c5, 42, :c6, :c7, :c8] - enum :enum_type3, [:c9, 42, :c10, :c11, 4242, :c12] - enum :enum_type4, [:c13, 42, :c14, 4242, :c15, 424242, :c16, 42424242] - attach_function :test_tagged_typedef_enum1, [:enum_type1], :enum_type1 + + enum :enum_type2, [:c5, 42, :c6, :c7, :c8] attach_function :test_tagged_typedef_enum2, [:enum_type2], :enum_type2 + + enum :enum_type3, [:c9, 42, :c10, :c11, 4242, :c12] attach_function :test_tagged_typedef_enum3, [:enum_type3], :enum_type3 + + enum :enum_type4, [:c13, 42, :c14, 4242, :c15, 424242, :c16, 42424242] attach_function :test_tagged_typedef_enum4, [:enum_type4], :enum_type4 + + freeze end module TestEnum4 @@ -44,18 +48,22 @@ module TestEnum4 enum :enum_type1, [:c5, 0x42, :c6, :c7, :c8] enum :enum_type2, [:c9, 0x42, :c10, :c11, 0x4242, :c12] enum :enum_type3, [:c13, 0x42, :c14, 0x4242, :c15, 0x42424242, :c16, 0x4242424242424242] - enum FFI::Type::UINT16, :enum_type4, [:c17, 0x42, :c18, :c19, :c20] - enum FFI::Type::UINT32, :enum_type5, [:c21, 0x42, :c22, :c23, 0x4242, :c24] - enum FFI::Type::UINT64, :enum_type6, [:c25, 0x42, :c26, 0x4242, :c27, 0x42424242, :c28, 0x4242424242424242] - enum FFI::Type::UINT64, [:c29, 0x4242424242424242, :c30, :c31, :c32] attach_function :test_untagged_nonint_enum, [:uint8], :uint8 attach_function :test_tagged_nonint_enum1, [:uint16], :uint16 attach_function :test_tagged_nonint_enum2, [:uint32], :uint32 attach_function :test_tagged_nonint_enum3, [:uint64], :uint64 + + enum FFI::Type::UINT16, :enum_type4, [:c17, 0x42, :c18, :c19, :c20] + enum FFI::Type::UINT32, :enum_type5, [:c21, 0x42, :c22, :c23, 0x4242, :c24] + enum FFI::Type::UINT64, :enum_type6, [:c25, 0x42, :c26, 0x4242, :c27, 0x42424242, :c28, 0x4242424242424242] + enum FFI::Type::UINT64, [:c29, 0x4242424242424242, :c30, :c31, :c32] + attach_function :test_tagged_nonint_enum4, :test_tagged_nonint_enum1, [:enum_type4], :enum_type4 attach_function :test_tagged_nonint_enum5, :test_tagged_nonint_enum2, [:enum_type5], :enum_type5 attach_function :test_tagged_nonint_enum6, :test_tagged_nonint_enum3, [:enum_type6], :enum_type6 + + freeze end describe "A library with no enum defined" do @@ -430,4 +438,18 @@ module TestEnum4 end end.to raise_error(ArgumentError, /duplicate/) end + + it "should be usable in Ractor", :ractor do + res = Ractor.new do + [ + TestEnum1.test_untagged_enum(:c1), + TestEnum3.test_tagged_typedef_enum1(:c1), + TestEnum4.test_tagged_nonint_enum4(0x45), + TestEnum3.enum_type(:enum_type1)[0], + TestEnum4.enum_type(:enum_type6)[0x4242424242424242], + TestEnum4.enum_value(:c3) + ] + end.take + expect( res ).to eq( [0, :c1, :c20, :c1, :c28, 2] ) + end end diff --git a/spec/ffi/errno_spec.rb b/spec/ffi/errno_spec.rb index 4170f92ba899..c0207b8b62d4 100644 --- a/spec/ffi/errno_spec.rb +++ b/spec/ffi/errno_spec.rb @@ -34,4 +34,12 @@ module LibTest expect(FFI.errno).to eq(0x12345678) end end + + it "works in Ractor", :ractor do + res = Ractor.new do + LibTest.setLastError(0x12345678) + FFI.errno + end.take + expect(res).to eq(0x12345678) + end end diff --git a/spec/ffi/ffi_spec.rb b/spec/ffi/ffi_spec.rb index 4de53104e0ac..bf4b8353d8d6 100644 --- a/spec/ffi/ffi_spec.rb +++ b/spec/ffi/ffi_spec.rb @@ -12,10 +12,24 @@ let(:prefix) { FFI::Platform::LIBPREFIX } let(:suffix) { FFI::Platform::LIBSUFFIX } + it "should add platform library preffix if not present" do + expect(FFI.map_library_name("dummy")).to eq("#{prefix}dummy.#{suffix}") + end + it "should add platform library extension if not present" do expect(FFI.map_library_name("#{prefix}dummy")).to eq("#{prefix}dummy.#{suffix}") end + it "should'n add platform library extension if already present" do + if FFI::Platform.windows? + expect(FFI.map_library_name("#{prefix}dummy-5.dll")).to eq("#{prefix}dummy-5.dll") + elsif FFI::Platform.mac? + expect(FFI.map_library_name("#{prefix}dummy.5.dylib")).to eq("#{prefix}dummy.5.dylib") + else # Linux? BSD? etc. + expect(FFI.map_library_name("#{prefix}dummy.so.5")).to eq("#{prefix}dummy.so.5") + end + end + it "should add platform library extension even if lib suffix is present in name" do expect(FFI.map_library_name("#{prefix}dummy_with_#{suffix}")).to eq("#{prefix}dummy_with_#{suffix}.#{suffix}") end @@ -24,6 +38,15 @@ expect(FFI.map_library_name('c')).to eq(FFI::Library::LIBC) end + it "should return library path with abi version" do + expect(FFI.map_library_name(FFI::LibraryPath.new('vips', abi_number: 42))).to be =~ /#{prefix}vips.*42/ + end + + it "should return library path with root" do + root = "/non/existant/root" + + expect(FFI.map_library_name(FFI::LibraryPath.new('vips', abi_number: 42, root: root))).to be =~ /#{root}/#{prefix}vips.*42/ + end end describe "VERSION" do diff --git a/spec/ffi/fixtures/BitmaskTest.c b/spec/ffi/fixtures/BitmaskTest.c index 17ad0aa2cd1a..045387632bd6 100644 --- a/spec/ffi/fixtures/BitmaskTest.c +++ b/spec/ffi/fixtures/BitmaskTest.c @@ -29,6 +29,26 @@ uint64_t test_tagged_nonint_bitmask3(uint64_t val) { return val; } +unsigned int test_tagged_uint_bitmask(unsigned int val) { + return val; +} + +int8_t test_tagged_nonint_signed_bitmask1(int8_t val) { + return val; +} + +int16_t test_tagged_nonint_signed_bitmask2(int16_t val) { + return val; +} + +int32_t test_tagged_nonint_signed_bitmask3(int32_t val) { + return val; +} + +int64_t test_tagged_nonint_signed_bitmask4(int64_t val) { + return val; +} + typedef enum {c1 = (1<<0), c2 = (1<<1), c3 = (1<<2), c4 = (1<<3)} bitmask_type1; int test_tagged_typedef_bitmask1(int val) { return val; diff --git a/spec/ffi/fixtures/ClosureTest.c b/spec/ffi/fixtures/ClosureTest.c index 16f72c4074de..47273e8485be 100644 --- a/spec/ffi/fixtures/ClosureTest.c +++ b/spec/ffi/fixtures/ClosureTest.c @@ -16,10 +16,10 @@ double testClosureVrDva(double d, ...) { va_list args; - double (*closure)(void); + typedef double (*closure_fun)(void); va_start(args, d); - closure = va_arg(args, double (*)(void)); + closure_fun closure = va_arg(args, closure_fun); va_end(args); return d + closure(); @@ -27,12 +27,12 @@ double testClosureVrDva(double d, ...) { long testClosureVrILva(int i, long l, ...) { va_list args; - int (*cl1)(int); - long (*cl2)(long); + typedef int (*cl1_fun)(int); + typedef long (*cl2_fun)(long); va_start(args, l); - cl1 = va_arg(args, int (*)(int)); - cl2 = va_arg(args, long (*)(long)); + cl1_fun cl1 = va_arg(args, cl1_fun); + cl2_fun cl2 = va_arg(args, cl2_fun); va_end(args); return cl1(i) + cl2(l); diff --git a/spec/ffi/fixtures/PipeHelperWindows.c b/spec/ffi/fixtures/PipeHelperWindows.c index 0bdbd2ec8c42..31b4a2a5b75c 100644 --- a/spec/ffi/fixtures/PipeHelperWindows.c +++ b/spec/ffi/fixtures/PipeHelperWindows.c @@ -16,7 +16,7 @@ int pipeHelperCreatePipe(FD_TYPE pipefd[2]) sprintf( name, "\\\\.\\Pipe\\pipeHelper-%u-%i", (unsigned int)GetCurrentProcessId(), pipe_idx++ ); - pipefd[0] = CreateNamedPipe( name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, + pipefd[0] = CreateNamedPipeA( name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_WAIT, 1, // Number of pipes 5, // Out buffer size @@ -26,7 +26,7 @@ int pipeHelperCreatePipe(FD_TYPE pipefd[2]) if(pipefd[0] == INVALID_HANDLE_VALUE) return -1; - pipefd[1] = CreateFile( name, GENERIC_WRITE, 0, NULL, + pipefd[1] = CreateFileA( name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); diff --git a/spec/ffi/fixtures/PointerTest.c b/spec/ffi/fixtures/PointerTest.c index a7f392a1a32b..02dbc2704470 100644 --- a/spec/ffi/fixtures/PointerTest.c +++ b/spec/ffi/fixtures/PointerTest.c @@ -5,7 +5,9 @@ */ #include +#ifndef _MSC_VER #include +#endif #include #include #include diff --git a/spec/ffi/fixtures/compile.rb b/spec/ffi/fixtures/compile.rb index f2e831a631bf..2be97cb86895 100644 --- a/spec/ffi/fixtures/compile.rb +++ b/spec/ffi/fixtures/compile.rb @@ -22,6 +22,8 @@ module TestLibrary "powerpc64" when /ppc|powerpc/ "powerpc" + when /sparcv9|sparc64/ + "sparcv9" when /^arm/ if RbConfig::CONFIG['host_os'] =~ /darwin/ "aarch64" @@ -67,5 +69,5 @@ def self.compile_library(path, lib) lib end - PATH = compile_library(".", "libtest.#{FFI::Platform::LIBSUFFIX}") + PATH = FFI.make_shareable(compile_library(".", "libtest.#{FFI::Platform::LIBSUFFIX}")) end diff --git a/spec/ffi/fork_spec.rb b/spec/ffi/fork_spec.rb index 2c663ee2ae68..421982df2036 100644 --- a/spec/ffi/fork_spec.rb +++ b/spec/ffi/fork_spec.rb @@ -62,5 +62,14 @@ def run_async_callback(libtest) expect(Process.wait2[1].exitstatus).to eq(44) end + + it "GC doesn't crash when the dispatcher thread was stopped. #1050" do + FFI::Function.new(:int, [], proc{}) + fork do + GC.start + Process.exit 45 + end + expect(Process.wait2[1].exitstatus).to eq(45) + end end end diff --git a/spec/ffi/function_spec.rb b/spec/ffi/function_spec.rb index 5bc2421ec1c8..77d09d887d45 100644 --- a/spec/ffi/function_spec.rb +++ b/spec/ffi/function_spec.rb @@ -48,6 +48,30 @@ module LibTest expect(LibTest.testFunctionAdd(10, 10, function_add)).to eq(20) end + def adder(a, b) + a + b + end + + it "can be made shareable for Ractor", :ractor do + add = FFI::Function.new(:int, [:int, :int], &method(:adder)) + Ractor.make_shareable(add) + + res = Ractor.new(add) do |add2| + LibTest.testFunctionAdd(10, 10, add2) + end.take + + expect( res ).to eq(20) + end + + it "should be usable with Ractor", :ractor do + res = Ractor.new do + function_add = FFI::Function.new(:int, [:int, :int]) { |a, b| a + b } + LibTest.testFunctionAdd(10, 10, function_add) + end.take + + expect( res ).to eq(20) + end + it 'can be used to wrap an existing function pointer' do expect(FFI::Function.new(:int, [:int, :int], @libtest.find_function('testAdd')).call(10, 10)).to eq(20) end @@ -59,6 +83,16 @@ module Foo; end expect(Foo.add(10, 10)).to eq(20) end + it 'can be attached to two modules' do + module Foo1; end + module Foo2; end + fp = FFI::Function.new(:int, [:int, :int], @libtest.find_function('testAdd')) + fp.attach(Foo1, 'add') + fp.attach(Foo2, 'add') + expect(Foo1.add(11, 11)).to eq(22) + expect(Foo2.add(12, 12)).to eq(24) + end + it 'can be used to extend an object' do fp = FFI::Function.new(:int, [:int, :int], @libtest.find_function('testAdd')) foo = Object.new @@ -103,4 +137,12 @@ class << self; self; end fp = FFI::Function.new(:int, [:int, :int], @libtest.find_function('testAdd')) expect { fp.free }.to raise_error RuntimeError end + + it 'has a memsize function', skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + function = FFI::Function.new(:int, [:int, :int], @libtest.find_function('testAdd')) + size = ObjectSpace.memsize_of(function) + expect(size).to be > base_size + end end diff --git a/spec/ffi/function_type_spec.rb b/spec/ffi/function_type_spec.rb new file mode 100644 index 000000000000..2f171d88a144 --- /dev/null +++ b/spec/ffi/function_type_spec.rb @@ -0,0 +1,27 @@ +# +# This file is part of ruby-ffi. +# For licensing, see LICENSE.SPECS +# + +require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) + +describe "FFI::FunctionType", skip: RUBY_ENGINE != "ruby" do + it 'is initialized with return type and a list of parameter types' do + function_type = FFI::FunctionType.new(:int, [ :char, :ulong ]) + expect(function_type.return_type).to be == FFI::Type::Builtin::INT + expect(function_type.param_types).to be == [ FFI::Type::Builtin::CHAR, FFI::Type::Builtin::ULONG ] + end + + it 'has a memsize function' do + base_size = ObjectSpace.memsize_of(Object.new) + + function_type = FFI::FunctionType.new(:int, []) + size = ObjectSpace.memsize_of(function_type) + expect(size).to be > base_size + + base_size = size + function_type = FFI::FunctionType.new(:int, [:char]) + size = ObjectSpace.memsize_of(function_type) + expect(size).to be > base_size + end +end diff --git a/spec/ffi/gc_compact_spec.rb b/spec/ffi/gc_compact_spec.rb new file mode 100644 index 000000000000..974d7f859f46 --- /dev/null +++ b/spec/ffi/gc_compact_spec.rb @@ -0,0 +1,66 @@ +# -*- rspec -*- +# encoding: utf-8 +# +# Tests to verify correct implementation of compaction callbacks in rb_data_type_t definitions. +# +# Compaction callbacks update moved VALUEs. +# In ruby-2.7 they are invoked only while GC.compact or GC.verify_compaction_references. +# Ruby constants are usually moved, but local variables are not. +# +# Effectiveness of the tests below should be verified by commenting the compact callback out like so: +# +# const rb_data_type_t rbffi_struct_layout_data_type = { +# .wrap_struct_name = "FFI::StructLayout", +# .function = { +# .dmark = struct_layout_mark, +# .dfree = struct_layout_free, +# .dsize = struct_layout_memsize, +# # ffi_compact_callback( struct_layout_compact ) +# }, +# .parent = &rbffi_type_data_type, +# .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED +# }; +# +# This should result in a segmentation fault aborting the whole process. +# Therefore the effectiveness of only one test can be verified per rspec run. + +require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) + +describe "GC.compact", if: GC.respond_to?(:compact) do + before :all do + + class St1 < FFI::Struct + layout :i, :int + end + ST1 = St1.new + + class St2 < FFI::Struct + layout :i, :int + end + ST2 = St2.new + ST2[:i] = 6789 + + begin + # Use GC.verify_compaction_references instead of GC.compact . + # This has the advantage that all movable objects are actually moved. + # The downside is that it doubles the heap space of the Ruby process. + # Therefore we call it only once and do several tests afterwards. + GC.verify_compaction_references(toward: :empty, double_heap: true) + rescue NotImplementedError, NoMethodError => err + skip("GC.compact skipped: #{err}") + end + end + + it "should compact FFI::StructLayout without field cache" do + expect( ST1[:i] ).to eq( 0 ) + end + + it "should compact FFI::StructLayout with field cache" do + expect( ST2[:i] ).to eq( 6789 ) + end + + it "should compact FFI::StructLayout::Field" do + l = St1.layout + expect( l.fields.first.type ).to eq( FFI::Type::Builtin::INT32 ) + end +end diff --git a/spec/ffi/library_spec.rb b/spec/ffi/library_spec.rb index ca28974c9d5e..8691b17c0435 100644 --- a/spec/ffi/library_spec.rb +++ b/spec/ffi/library_spec.rb @@ -5,6 +5,12 @@ require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) +module TestEnumValueRactor + extend FFI::Library + enum :something, [:one, :two] + freeze +end + describe "Library" do describe ".enum_value" do m = Module.new do @@ -20,6 +26,14 @@ it "should return nil for an invalid key" do expect(m.enum_value(:three)).to be nil end + + it "should be queryable in Ractor", :ractor do + res = Ractor.new do + TestEnumValueRactor.enum_value(:one) + end.take + + expect( res ).to eq(0) + end end describe "#ffi_convention" do @@ -88,7 +102,7 @@ class StructUCDP < FFI::Struct }.to raise_error(LoadError) end - it "interprets INPUT() in loader scripts", unless: FFI::Platform.windows? do + it "interprets INPUT() in linker scripts", unless: FFI::Platform.windows? || FFI::Platform.mac? do path = File.dirname(TestLibrary::PATH) file = File.basename(TestLibrary::PATH) script = File.join(path, "ldscript.so") @@ -184,15 +198,49 @@ class StructUCDP < FFI::Struct end.getpid).to eq(Process.pid) }.to raise_error(LoadError) end + end - it "attach_function :bool_return_true from [ File.expand_path(#{TestLibrary::PATH.inspect}) ]" do - mod = Module.new do |m| - m.extend FFI::Library - ffi_lib File.expand_path(TestLibrary::PATH) - attach_function :bool_return_true, [ ], :bool - end - expect(mod.bool_return_true).to be true + it "attach_function :bool_return_true from [ File.expand_path(#{TestLibrary::PATH.inspect}) ]" do + mod = Module.new do |m| + m.extend FFI::Library + ffi_lib File.expand_path(TestLibrary::PATH) + attach_function :bool_return_true, [ ], :bool end + expect(mod.bool_return_true).to be true + end + + it "can define a foo! function" do + mod = Module.new do |m| + m.extend FFI::Library + ffi_lib File.expand_path(TestLibrary::PATH) + attach_function :foo!, :bool_return_true, [], :bool + end + expect(mod.foo!).to be true + end + + it "can define a foo? function" do + mod = Module.new do |m| + m.extend FFI::Library + ffi_lib File.expand_path(TestLibrary::PATH) + attach_function :foo?, :bool_return_true, [], :bool + end + expect(mod.foo?).to be true + end + + it "can reveal the function type" do + skip 'this is not yet implemented on JRuby' if RUBY_ENGINE == 'jruby' + skip 'this is not yet implemented on Truffleruby' if RUBY_ENGINE == 'truffleruby' + + mod = Module.new do |m| + m.extend FFI::Library + ffi_lib File.expand_path(TestLibrary::PATH) + attach_function :bool_return_true, [ :string ], :bool + end + + fun = mod.attached_functions + expect(fun.keys).to eq([:bool_return_true]) + expect(fun[:bool_return_true].param_types).to eq([FFI::Type::STRING]) + expect(fun[:bool_return_true].return_type).to eq(FFI::Type::BOOL) end def gvar_lib(name, type) @@ -322,4 +370,35 @@ class GlobalStruct < FFI::Struct expect(val[:data]).to eq(i) end end + + it "can reveal its attached global struct based variables" do + lib = Module.new do |m| + m.extend FFI::Library + ffi_lib TestLibrary::PATH + attach_variable :gvari, "gvar_gstruct", GlobalStruct + end + expect(lib.attached_variables).to eq({ gvari: GlobalStruct }) + end + + it "can reveal its attached global variables" do + lib = Module.new do |m| + m.extend FFI::Library + ffi_lib TestLibrary::PATH + attach_variable "gvaro", "gvar_u32", :uint32 + end + expect(lib.attached_variables).to eq({ gvaro: FFI::Type::UINT32 }) + end + + it "should have shareable constants for Ractor", :ractor do + res = Ractor.new do + [ + FFI::Library::LIBC, + FFI::Library::CURRENT_PROCESS, + FFI::CURRENT_PROCESS, + FFI::USE_THIS_PROCESS_AS_LIBRARY, + ] + end.take + + expect( res.size ).to be > 0 + end end diff --git a/spec/ffi/managed_struct_spec.rb b/spec/ffi/managed_struct_spec.rb index 9b02c344bc77..6299bdcc2ce5 100644 --- a/spec/ffi/managed_struct_spec.rb +++ b/spec/ffi/managed_struct_spec.rb @@ -21,7 +21,7 @@ class NoRelease < FFI::ManagedStruct ; layout :i, :int; end it "should be the right class" do class WhatClassAmI < FFI::ManagedStruct layout :i, :int - def self.release + def self.release(_ptr) end end @@ -31,7 +31,7 @@ def self.release it "should build with self reference" do class ClassWithSelfRef < FFI::ManagedStruct layout :data, self.ptr - def self.release + def self.release(_ptr) end end @@ -39,13 +39,15 @@ def self.release end # see #427 - it "should release memory properly", :broken => true do + it "should release memory properly" do class PleaseReleaseMe < FFI::ManagedStruct layout :i, :int @@count = 0 - def self.release + def self.release(_ptr) @@count += 1 end + private_class_method :release + def self.wait_gc(count) loop = 5 while loop > 0 && @@count < count @@ -53,16 +55,17 @@ def self.wait_gc(count) TestLibrary.force_gc sleep 0.05 if @@count < count end + @@count end end loop_count = 30 wiggle_room = 5 - expect(PleaseReleaseMe).to receive(:release).at_least(loop_count-wiggle_room).times loop_count.times do PleaseReleaseMe.new(ManagedStructTestLib.ptr_from_address(0x12345678)) end - PleaseReleaseMe.wait_gc loop_count + calls = PleaseReleaseMe.wait_gc(loop_count) + expect(calls).to be >= loop_count-wiggle_room end end diff --git a/spec/ffi/memorypointer_spec.rb b/spec/ffi/memorypointer_spec.rb index c8d1b429d829..f29e2cb972e6 100644 --- a/spec/ffi/memorypointer_spec.rb +++ b/spec/ffi/memorypointer_spec.rb @@ -28,6 +28,21 @@ expect(MemoryPointer.new(1024).total).to eq 1024 end end +describe "MemoryPointer#clear" do + it "should clear the memory" do + ptr = MemoryPointer.new(:long) + ptr.write_long 1234 + expect(ptr.read_long).to eq(1234) + ptr.clear + expect(ptr.read_long).to eq(0) + end + it "should deny changes when frozen" do + skip "not yet supported on TruffleRuby" if RUBY_ENGINE == "truffleruby" + skip "not yet supported on JRuby" if RUBY_ENGINE == "jruby" + ptr = MemoryPointer.new(:long).freeze + expect{ ptr.clear }.to raise_error(RuntimeError, /memory write/) + end +end describe "MemoryPointer#read_array_of_long" do it "foo" do ptr = MemoryPointer.new(:long, 1024) @@ -76,3 +91,22 @@ module Stdio expect(Stdio.fclose(fp)).to eq 0 unless fp.nil? or fp.null? end end +describe "#autorelease" do + it "should be true by default" do + expect(MemoryPointer.new(8).autorelease?).to be true + end + + it "should return false when autorelease=(false)" do + ptr = MemoryPointer.new(8) + ptr.autorelease = false + expect(ptr.autorelease?).to be false + ptr.free + end + + it "should deny changes when frozen" do + skip "not yet supported on TruffleRuby" if RUBY_ENGINE == "truffleruby" + skip "not yet supported on JRuby" if RUBY_ENGINE == "jruby" + ptr = MemoryPointer.new(8).freeze + expect{ ptr.autorelease = false }.to raise_error(FrozenError) + end +end diff --git a/spec/ffi/platform_spec.rb b/spec/ffi/platform_spec.rb index ad236217acd0..8890b072afa4 100644 --- a/spec/ffi/platform_spec.rb +++ b/spec/ffi/platform_spec.rb @@ -134,4 +134,17 @@ expect(FFI::Platform::BYTE_ORDER).to eq(order) end end + + it "should have shareable constants for Ractor", :ractor do + res = Ractor.new do + [ + FFI::Platform::OS, + FFI::Platform::CPU, + FFI::Platform::ARCH, + FFI::Platform::OS, + ] + end.take + + expect( res.size ).to be > 0 + end end diff --git a/spec/ffi/pointer_spec.rb b/spec/ffi/pointer_spec.rb index b216a161df0d..0494ac339b9e 100644 --- a/spec/ffi/pointer_spec.rb +++ b/spec/ffi/pointer_spec.rb @@ -90,6 +90,13 @@ def to_ptr expect(PointerTestLib.ptr_ret_pointer(memory, 0).address).to eq(0xdeadbeef) end + it "#write_pointer frozen object" do + skip "not yet supported on TruffleRuby" if RUBY_ENGINE == "truffleruby" + skip "not yet supported on JRuby" if RUBY_ENGINE == "jruby" + memory = FFI::MemoryPointer.new(:pointer).freeze + expect{ memory.write_pointer(PointerTestLib.ptr_from_address(0xdeadbeef)) }.to raise_error(RuntimeError, /memory write/) + end + it "#read_array_of_pointer" do values = [0x12345678, 0xfeedf00d, 0xdeadbeef] memory = FFI::MemoryPointer.new :pointer, values.size @@ -237,6 +244,28 @@ def to_ptr expect(FFI::Pointer.new(0).slice(0, 10).size_limit?).to be true end end + + describe "#initialize" do + it 'can use addresses with high bit set' do + max_address = 2**FFI::Platform::ADDRESS_SIZE - 1 + pointer = FFI::Pointer.new(:uint8, max_address) + expect(pointer.address).to eq(max_address) + end + end if (RUBY_ENGINE != "truffleruby" && RUBY_ENGINE != "jruby") + + describe "#inspect" do + it "should include the address" do + FFI::Pointer.new(1234).inspect.should =~ /address=0x0*4d2/ + end + + it "should not include the size if the pointer is unsized" do + FFI::Pointer.new(1234).inspect.should_not =~ /size=/ + end + + it "should include the size if there is one" do + FFI::MemoryPointer.new(:char, 16).inspect.should =~ /size=16/ + end + end end describe "AutoPointer" do @@ -249,6 +278,7 @@ class AutoPointerTestHelper def self.release @@count += 1 if @@count > 0 end + private_class_method(:release) def self.reset @@count = 0 end @@ -267,10 +297,11 @@ def self.finalizer end class AutoPointerSubclass < FFI::AutoPointer def self.release(ptr); end + private_class_method(:release) end # see #427 - it "cleanup via default release method", :broken => true do + it "cleanup via default release method", gc_dependent: true do expect(AutoPointerSubclass).to receive(:release).at_least(loop_count-wiggle_room).times AutoPointerTestHelper.reset loop_count.times do @@ -283,7 +314,7 @@ def self.release(ptr); end end # see #427 - it "cleanup when passed a proc", :broken => true do + it "cleanup when passed a proc", gc_dependent: true do # NOTE: passing a proc is touchy, because it's so easy to create a memory leak. # # specifically, if we made an inline call to @@ -302,7 +333,7 @@ def self.release(ptr); end end # see #427 - it "cleanup when passed a method", :broken => true do + it "cleanup when passed a method", gc_dependent: true do expect(AutoPointerTestHelper).to receive(:release).at_least(loop_count-wiggle_room).times AutoPointerTestHelper.reset loop_count.times do @@ -319,6 +350,7 @@ def self.release(ptr); end ffi_lib TestLibrary::PATH class CustomAutoPointer < FFI::AutoPointer def self.release(ptr); end + private_class_method(:release) end attach_function :ptr_from_address, [ FFI::Platform::ADDRESS_SIZE == 32 ? :uint : :ulong_long ], CustomAutoPointer end @@ -341,6 +373,7 @@ def self.release(ptr); end describe "#autorelease?" do ptr_class = Class.new(FFI::AutoPointer) do def self.release(ptr); end + private_class_method(:release) end it "should be true by default" do @@ -352,11 +385,17 @@ def self.release(ptr); end ptr.autorelease = false expect(ptr.autorelease?).to be false end + + it "should deny changes when frozen" do + ptr = ptr_class.new(FFI::Pointer.new(0xdeadbeef)).freeze + expect{ ptr.autorelease = false }.to raise_error(FrozenError) + end end describe "#type_size" do ptr_class = Class.new(FFI::AutoPointer) do def self.release(ptr); end + private_class_method(:release) end it "type_size of AutoPointer should match wrapped Pointer" do @@ -373,5 +412,13 @@ def self.release(ptr); end expect(mptr[1].read_uint).to eq(0xcafebabe) end end + + it "has a memsize function", skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + pointer = FFI::Pointer.new(:int, 0xdeadbeef) + size = ObjectSpace.memsize_of(pointer) + expect(size).to be > base_size + end end diff --git a/spec/ffi/rbx/memory_pointer_spec.rb b/spec/ffi/rbx/memory_pointer_spec.rb index 387897355da3..1270c9b358eb 100644 --- a/spec/ffi/rbx/memory_pointer_spec.rb +++ b/spec/ffi/rbx/memory_pointer_spec.rb @@ -104,6 +104,18 @@ expect(m.read FFI::Type::BOOL).to eq(false) end + it "allows definition of a custom typedef" do + FFI.typedef :uint32, :fubar_t + expect(FFI.find_type(:fubar_t)).to eq(FFI::Type::Builtin::UINT32) + end + + it "allows overwriting of a default typedef" do + FFI.typedef :uint32, :char + expect(FFI.find_type(:char)).to eq(FFI::Type::Builtin::UINT32) + ensure + FFI.typedef FFI::Type::Builtin::CHAR, :char + end + it "allows writing a custom typedef" do FFI.typedef :uint, :fubar_t FFI.typedef :size_t, :fubar2_t @@ -189,4 +201,12 @@ end expect(block_executed).to be true end + + it "has a memsize function", skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + pointer = FFI::MemoryPointer.from_string("FFI is Awesome") + size = ObjectSpace.memsize_of(pointer) + expect(size).to be > base_size + end end diff --git a/spec/ffi/spec_helper.rb b/spec/ffi/spec_helper.rb index bb12050de429..22d1c47d1039 100644 --- a/spec/ffi/spec_helper.rb +++ b/spec/ffi/spec_helper.rb @@ -5,9 +5,11 @@ require_relative 'fixtures/compile' require 'timeout' +require 'objspace' RSpec.configure do |c| - c.filter_run_excluding :broken => true + c.filter_run_excluding gc_dependent: true unless ENV['FFI_TEST_GC'] == 'true' + c.filter_run_excluding( :ractor ) unless defined?(Ractor) && RUBY_VERSION >= "3.1" end module TestLibrary diff --git a/spec/ffi/struct_by_ref_spec.rb b/spec/ffi/struct_by_ref_spec.rb index 0858423a4558..a775f92fd6d0 100644 --- a/spec/ffi/struct_by_ref_spec.rb +++ b/spec/ffi/struct_by_ref_spec.rb @@ -39,5 +39,14 @@ expect { @api.struct_test(other_class.new) }.to raise_error(TypeError) end + + it "can reveal the mapped type converter" do + skip 'this is not yet implemented on JRuby' if RUBY_ENGINE == 'jruby' + skip 'this is not yet implemented on Truffleruby' if RUBY_ENGINE == 'truffleruby' + + param_type = @api.attached_functions[:struct_test].param_types[0] + expect(param_type).to be_a(FFI::Type::Mapped) + expect(param_type.converter).to be_a(FFI::StructByReference) + end end diff --git a/spec/ffi/struct_initialize_spec.rb b/spec/ffi/struct_initialize_spec.rb index beb2477ec1d6..a53ab8e309f9 100644 --- a/spec/ffi/struct_initialize_spec.rb +++ b/spec/ffi/struct_initialize_spec.rb @@ -28,7 +28,7 @@ def initialize super FFI::MemoryPointer.new(:pointer).put_int(0, 0x1234).get_pointer(0) self.magic = 42 end - def self.release;end + def self.release(_ptr);end end expect(ManagedStructWithInitialize.new.magic).to eq(42) end diff --git a/spec/ffi/struct_spec.rb b/spec/ffi/struct_spec.rb index fb574d292d1a..6afe47537950 100644 --- a/spec/ffi/struct_spec.rb +++ b/spec/ffi/struct_spec.rb @@ -215,6 +215,19 @@ def initialize(a, b) expect(s[:b]).to eq(0xdeadcafebabe) end + it "Can use DataConverter in an embedded array" do + class Blub #< FFI::Struct + extend FFI::DataConverter + native_type FFI::Type::INT + end + + class Zork < FFI::Struct + layout :c, [Blub, 2], 2 + end + z = Zork.new + expect(z[:c].to_a).to eq [0, 0] + end + it "Can use Struct subclass as parameter type" do expect(module StructParam extend FFI::Library @@ -410,6 +423,7 @@ def self.int_field_test(type, values) s.pointer.put_double(0, 1.0) expect(s.pointer.get_double(0)).to eq(1.0) end + module EnumFields extend FFI::Library TestEnum = enum :test_enum, [:c1, 10, :c2, 20, :c3, 30, :c4, 40] @@ -456,13 +470,24 @@ class TestStruct < FFI::Struct end it "Can have CallbackInfo struct field" do + s = CallbackMember::TestStruct.new + add_proc = lambda { |a, b| a + b } + sub_proc = lambda { |a, b| a - b } + s[:add] = add_proc + s[:sub] = sub_proc + expect(CallbackMember.struct_call_add_cb(s, 40, 2)).to eq(42) + expect(CallbackMember.struct_call_sub_cb(s, 44, 2)).to eq(42) + end + + it "Can use CallbackInfo struct field in Ractor", :ractor do + res = Ractor.new do s = CallbackMember::TestStruct.new - add_proc = lambda { |a, b| a+b } - sub_proc = lambda { |a, b| a-b } + add_proc = lambda { |a, b| a + b } s[:add] = add_proc - s[:sub] = sub_proc - expect(CallbackMember.struct_call_add_cb(s, 40, 2)).to eq(42) - expect(CallbackMember.struct_call_sub_cb(s, 44, 2)).to eq(42) + CallbackMember.struct_call_add_cb(s, 40, 2) + end.take + + expect( res ).to eq(42) end it "Can return its members as a list" do @@ -532,6 +557,34 @@ class TestStruct < FFI::Struct expect(a.members).to eq([:a]) expect(b.members).to eq([:a, :b]) end + + it "can be made shareable for Ractor", :ractor do + a = Class.new(FFI::Struct) do + layout :a, :char + end.new + a[:a] = -34 + Ractor.make_shareable(a) + + res = Ractor.new(a) do |a2| + a2[:a] + end.take + + expect( res ).to eq(-34) + end + + it "should be usable with Ractor", :ractor do + class TestStructRactor < FFI::Struct + layout :i, :int + end + + res = Ractor.new do + s = TestStructRactor.new + s[:i] = 0x14 + LibTest.ptr_ret_int32_t(s, 0) + end.take + + expect( res ).to eq(0x14) + end end end @@ -1027,6 +1080,65 @@ class BuggedStruct < FFI::Struct end end +describe "Struct memsize functions", skip: RUBY_ENGINE != "ruby" do + it "has a memsize function" do + base_size = ObjectSpace.memsize_of(Object.new) + + c = Class.new(FFI::Struct) do + layout :b, :bool + end + struct = c.new + size = ObjectSpace.memsize_of(struct) + expect(size).to be > base_size + end + + class SmallCustomStruct < FFI::Struct + layout :pointer, :pointer + end + + class LargerCustomStruct < FFI::Struct + layout :pointer, :pointer, + :c, :char, + :i, :int + end + + it "StructLayout has a memsize function" do + base_size = ObjectSpace.memsize_of(Object.new) + + layout = SmallCustomStruct.layout + size = ObjectSpace.memsize_of(layout) + expect(size).to be > base_size + base_size = size + + layout = LargerCustomStruct.layout + size = ObjectSpace.memsize_of(layout) + expect(size).to be > base_size + end + + it "StructField has a memsize function" do + base_size = ObjectSpace.memsize_of(Object.new) + + layout = SmallCustomStruct.layout + size = ObjectSpace.memsize_of(layout[:pointer]) + expect(size).to be > base_size + end + + it "StructLayout should be shareable with Ractor", :ractor do + kl = Class.new(FFI::Struct) do + layout :ptr, :pointer + end + expect(Ractor.shareable?(kl.layout)).to eq(true) + end + + it "StructField should be shareable with Ractor", :ractor do + kl = Class.new(FFI::Struct) do + layout :ptr, :pointer + end + expect(Ractor.shareable?(kl.layout[:ptr])).to eq(true) + end +end + + describe "Struct order" do before :all do @struct = Class.new(FFI::Struct) do diff --git a/spec/ffi/type_spec.rb b/spec/ffi/type_spec.rb new file mode 100644 index 000000000000..e880c8326158 --- /dev/null +++ b/spec/ffi/type_spec.rb @@ -0,0 +1,76 @@ +# +# This file is part of ruby-ffi. +# For licensing, see LICENSE.SPECS +# + +require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper")) + +describe FFI::Type do + it 'has a memsize function', skip: RUBY_ENGINE != "ruby" do + base_size = ObjectSpace.memsize_of(Object.new) + + size = ObjectSpace.memsize_of(FFI::Type.new(42)) + expect(size).to be > base_size + base_size = size + + converter = Module.new do + extend FFI::DataConverter + + def self.native_type + @native_type_called = true + FFI::Type::INT32 + end + + def self.to_native(val, ctx) + @to_native_called = true + ToNativeMap[val] + end + + def self.from_native(val, ctx) + @from_native_called = true + FromNativeMap[val] + end + end + + size = ObjectSpace.memsize_of(FFI::Type::Mapped.new(converter)) + expect(size).to be > base_size + base_size = size + + # Builtin types are larger as they also have a name and own ffi_type + size = ObjectSpace.memsize_of(FFI::Type::Builtin::CHAR) + expect(size).to be > base_size + end + + it "should be shareable with Ractor", :ractor do + expect(Ractor.shareable?(FFI::Type.new(5))).to eq(true) + end + + describe :Builtin do + it "should be shareable with Ractor", :ractor do + expect(Ractor.shareable?(FFI::Type::INT32)).to eq(true) + end + end + + describe :Mapped do + it "should be shareable with Ractor", :ractor do + converter = Module.new do + extend FFI::DataConverter + + def self.native_type + FFI::Type::INT32 + end + + def self.to_native(val, ctx) + ToNativeMap[val] + end + + def self.from_native(val, ctx) + FromNativeMap[val] + end + end + expect(Ractor.shareable?(converter)).to eq(true) + type = FFI::Type::Mapped.new(converter) + expect(Ractor.shareable?(type)).to eq(true) + end + end +end diff --git a/spec/ffi/variadic_spec.rb b/spec/ffi/variadic_spec.rb index f379ed41dbd8..b528c0919c2b 100644 --- a/spec/ffi/variadic_spec.rb +++ b/spec/ffi/variadic_spec.rb @@ -23,6 +23,8 @@ module LibTest attach_function :testBlockingClose, [ :pointer ], :void attach_function :testCallbackVrDva, :testClosureVrDva, [ :double, :varargs ], :double attach_function :testCallbackVrILva, :testClosureVrILva, [ :int, :long, :varargs ], :long + + freeze end it "takes enum arguments" do @@ -37,6 +39,15 @@ module LibTest expect(LibTest.pack_varargs2(buf, :c1, "ii", :int, :c3, :int, :c4)).to eq(:c2) end + it "can reveal its return and parameters" do + skip 'this is not yet implemented on JRuby' if RUBY_ENGINE == 'jruby' + skip 'this is not yet implemented on Truffleruby' if RUBY_ENGINE == 'truffleruby' + + fun = LibTest.attached_functions[:testBlockingWRva] + expect(fun.param_types).to eq([FFI::Type::POINTER, FFI::Type::CHAR, FFI::Type::VARARGS]) + expect(fun.return_type).to eq(FFI::Type::INT8) + end + it 'can wrap a blocking function with varargs' do handle = LibTest.testBlockingOpen expect(handle).not_to be_null @@ -87,12 +98,33 @@ module LibTest expect(LibTest.testCallbackVrDva(3.0, :cbVrD, pr)).to be_within(0.0000001).of(45.0) end + it "can be called as instance method" do + kl = Class.new do + include LibTest + def call + pr = proc { 42.0 } + testCallbackVrDva(3.0, :cbVrD, pr) + end + end + expect(kl.new.call).to be_within(0.0000001).of(45.0) + end + it "call variadic with several callback arguments" do pr1 = proc { |i| i + 1 } pr2 = proc { |l| l + 2 } expect(LibTest.testCallbackVrILva(5, 6, :cbVrI, pr1, :cbVrL, pr2)).to eq(14) end + it "should be usable with Ractor", :ractor do + res = Ractor.new do + pr = proc { 42.0 } + LibTest.testCallbackVrDva(3.0, :cbVrD, pr) + end.take + + expect(res).to be_within(0.0000001).of(45.0) + end + + module Varargs PACK_VALUES = { 'c' => [ 0x12 ], From ff79149386e464814423442bfbdd3cce1f0032fe Mon Sep 17 00:00:00 2001 From: Andrew Konchin Date: Tue, 13 Feb 2024 15:20:04 +0200 Subject: [PATCH 16/28] Update RSpec version used for FFI specs to v3.12 to support Ruby 3.2 --- spec/ffi/Gemfile.lock | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/spec/ffi/Gemfile.lock b/spec/ffi/Gemfile.lock index e636abe72fe0..f6992c1551a6 100644 --- a/spec/ffi/Gemfile.lock +++ b/spec/ffi/Gemfile.lock @@ -1,20 +1,20 @@ GEM remote: https://rubygems.org/ specs: - diff-lcs (1.3) - rspec (3.8.0) - rspec-core (~> 3.8.0) - rspec-expectations (~> 3.8.0) - rspec-mocks (~> 3.8.0) - rspec-core (3.8.0) - rspec-support (~> 3.8.0) - rspec-expectations (3.8.2) + diff-lcs (1.5.0) + rspec (3.12.0) + rspec-core (~> 3.12.0) + rspec-expectations (~> 3.12.0) + rspec-mocks (~> 3.12.0) + rspec-core (3.12.2) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.3) diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-mocks (3.8.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.6) diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-support (3.8.0) + rspec-support (~> 3.12.0) + rspec-support (3.12.1) PLATFORMS ruby From 1a7f2b36cfed0b73fe4bf31deb0e69e88229ef4e Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 15:19:14 +0100 Subject: [PATCH 17/28] Avoid using org.jcodings.Encoding#getIndex() * That index is not deterministic and depends on classloading, so use it as little as possible. --- .../core/encoding/EncodingManager.java | 21 +++---- .../truffleruby/core/encoding/Encodings.java | 61 +++++++++++-------- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/truffleruby/core/encoding/EncodingManager.java b/src/main/java/org/truffleruby/core/encoding/EncodingManager.java index 2066f88d73b3..72e31a3e548c 100644 --- a/src/main/java/org/truffleruby/core/encoding/EncodingManager.java +++ b/src/main/java/org/truffleruby/core/encoding/EncodingManager.java @@ -67,15 +67,11 @@ public void defineEncodings() { } private void initializeEncodings(RubyClass encodingClass) { - var iterator = EncodingDB.getEncodings().entryIterator(); - while (iterator.hasNext()) { - var entry = iterator.next(); - if (entry.value.getEncoding() == Encodings.DUMMY_ENCODING_BASE) { - continue; - } - final RubyEncoding rubyEncoding = defineBuiltInEncoding(entry.value); - for (String constName : EncodingUtils.encodingNames(entry.bytes, entry.p, entry.end)) { - encodingClass.fields.setConstant(context, null, constName, rubyEncoding); + for (RubyEncoding encoding : Encodings.BUILT_IN_ENCODINGS) { + defineBuiltInEncoding(encoding); + byte[] name = encoding.jcoding.getName(); + for (String constName : EncodingUtils.encodingNames(name, 0, name.length)) { + encodingClass.fields.setConstant(context, null, constName, encoding); } } } @@ -238,16 +234,13 @@ RubyEncoding getRubyEncoding(int encodingIndex) { } @TruffleBoundary - public synchronized RubyEncoding defineBuiltInEncoding(EncodingDB.Entry encodingEntry) { - final int encodingIndex = encodingEntry.getEncoding().getIndex(); - final RubyEncoding rubyEncoding = Encodings.getBuiltInEncoding(encodingEntry.getEncoding()); + public void defineBuiltInEncoding(RubyEncoding rubyEncoding) { + final int encodingIndex = rubyEncoding.index; assert ENCODING_LIST_BY_ENCODING_INDEX[encodingIndex] == null; ENCODING_LIST_BY_ENCODING_INDEX[encodingIndex] = rubyEncoding; addToLookup(rubyEncoding.toString(), rubyEncoding); - return rubyEncoding; - } @TruffleBoundary diff --git a/src/main/java/org/truffleruby/core/encoding/Encodings.java b/src/main/java/org/truffleruby/core/encoding/Encodings.java index d0f703fe6b59..abcb203a8d35 100644 --- a/src/main/java/org/truffleruby/core/encoding/Encodings.java +++ b/src/main/java/org/truffleruby/core/encoding/Encodings.java @@ -38,26 +38,22 @@ public final class Encodings { public static final int INITIAL_NUMBER_OF_ENCODINGS = EncodingDB.getEncodings().size(); public static final int MAX_NUMBER_OF_ENCODINGS = 256; + public static final int US_ASCII_INDEX = 0; public static final RubyEncoding US_ASCII = initializeUsAscii(); - private static final RubyEncoding[] BUILT_IN_ENCODINGS = initializeRubyEncodings(); - - public static final RubyEncoding BINARY = BUILT_IN_ENCODINGS[ASCIIEncoding.INSTANCE.getIndex()]; - public static final RubyEncoding UTF_8 = BUILT_IN_ENCODINGS[UTF8Encoding.INSTANCE.getIndex()]; - public static final RubyEncoding UTF16LE = BUILT_IN_ENCODINGS[UTF16LEEncoding.INSTANCE.getIndex()]; - public static final RubyEncoding UTF16BE = BUILT_IN_ENCODINGS[UTF16BEEncoding.INSTANCE.getIndex()]; - public static final RubyEncoding UTF32LE = BUILT_IN_ENCODINGS[UTF32LEEncoding.INSTANCE.getIndex()]; - public static final RubyEncoding UTF32BE = BUILT_IN_ENCODINGS[UTF32BEEncoding.INSTANCE.getIndex()]; - public static final RubyEncoding ISO_8859_1 = BUILT_IN_ENCODINGS[ISO8859_1Encoding.INSTANCE.getIndex()]; - public static final RubyEncoding UTF16_DUMMY = BUILT_IN_ENCODINGS[EncodingDB - .getEncodings() - .get(StringOperations.encodeAsciiBytes("UTF-16")) - .getEncoding() - .getIndex()]; - public static final RubyEncoding UTF32_DUMMY = BUILT_IN_ENCODINGS[EncodingDB - .getEncodings() - .get(StringOperations.encodeAsciiBytes("UTF-32")) - .getEncoding() - .getIndex()]; + static final RubyEncoding[] BUILT_IN_ENCODINGS = initializeRubyEncodings(); + private static final RubyEncoding[] BUILT_IN_ENCODINGS_BY_JCODING_INDEX = initializeBuiltinEncodingsByJCodingIndex(); + + public static final RubyEncoding BINARY = getBuiltInEncoding(ASCIIEncoding.INSTANCE); + public static final RubyEncoding UTF_8 = getBuiltInEncoding(UTF8Encoding.INSTANCE); + public static final RubyEncoding UTF16LE = getBuiltInEncoding(UTF16LEEncoding.INSTANCE); + public static final RubyEncoding UTF16BE = getBuiltInEncoding(UTF16BEEncoding.INSTANCE); + public static final RubyEncoding UTF32LE = getBuiltInEncoding(UTF32LEEncoding.INSTANCE); + public static final RubyEncoding UTF32BE = getBuiltInEncoding(UTF32BEEncoding.INSTANCE); + public static final RubyEncoding ISO_8859_1 = getBuiltInEncoding(ISO8859_1Encoding.INSTANCE); + public static final RubyEncoding UTF16_DUMMY = getBuiltInEncoding( + EncodingDB.getEncodings().get(StringOperations.encodeAsciiBytes("UTF-16")).getEncoding()); + public static final RubyEncoding UTF32_DUMMY = getBuiltInEncoding( + EncodingDB.getEncodings().get(StringOperations.encodeAsciiBytes("UTF-32")).getEncoding()); /** On Linux and macOS the filesystem encoding is always UTF-8 */ public static final RubyEncoding FILESYSTEM = UTF_8; @@ -69,28 +65,31 @@ public Encodings() { } private static RubyEncoding initializeUsAscii() { - final Encoding encoding = USASCIIEncoding.INSTANCE; - return new RubyEncoding(encoding.getIndex()); + return new RubyEncoding(US_ASCII_INDEX); } private static RubyEncoding[] initializeRubyEncodings() { final RubyEncoding[] encodings = new RubyEncoding[INITIAL_NUMBER_OF_ENCODINGS]; + + int index = US_ASCII_INDEX + 1; for (var entry : EncodingDB.getEncodings()) { final Encoding encoding = entry.getEncoding(); - final RubyEncoding rubyEncoding; if (encoding == USASCIIEncoding.INSTANCE) { - rubyEncoding = US_ASCII; + encodings[US_ASCII_INDEX] = US_ASCII; } else { TruffleString tstring = TStringConstants.TSTRING_CONSTANTS.get(encoding.toString()); if (tstring == null) { throw CompilerDirectives.shouldNotReachHere("no TStringConstants for " + encoding); } final ImmutableRubyString name = FrozenStringLiterals.createStringAndCacheLater(tstring, US_ASCII); - rubyEncoding = new RubyEncoding(encoding, name, encoding.getIndex()); + var rubyEncoding = new RubyEncoding(encoding, name, index); + encodings[index] = rubyEncoding; + index++; } - encodings[encoding.getIndex()] = rubyEncoding; } + + assert index == EncodingDB.getEncodings().size(); return encodings; } @@ -108,9 +107,19 @@ public static RubyEncoding newRubyEncoding(RubyLanguage language, Encoding encod return new RubyEncoding(encoding, string, index); } + public static RubyEncoding[] initializeBuiltinEncodingsByJCodingIndex() { + final RubyEncoding[] encodings = new RubyEncoding[INITIAL_NUMBER_OF_ENCODINGS]; + for (RubyEncoding encoding : BUILT_IN_ENCODINGS) { + // This and the usage in getBuiltInEncoding() below should be the only usages of org.jcodings.Encoding#getIndex(). + // That index is not deterministic and depends on classloading, so use it as little as possible. + encodings[encoding.jcoding.getIndex()] = encoding; + } + return encodings; + } + /** Should only be used when there is no other way, because this will ignore replicated and dummy encodings */ public static RubyEncoding getBuiltInEncoding(Encoding jcoding) { - var rubyEncoding = BUILT_IN_ENCODINGS[jcoding.getIndex()]; + var rubyEncoding = BUILT_IN_ENCODINGS_BY_JCODING_INDEX[jcoding.getIndex()]; assert rubyEncoding.jcoding == jcoding; return rubyEncoding; } From e74764e3ff2eb0c154fbf9271b62786a8a9342fe Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 15:29:07 +0100 Subject: [PATCH 18/28] Always pass a RubyEncoding to InterpolatedStringNode --- .../truffleruby/core/string/InterpolatedStringNode.java | 8 +------- src/main/java/org/truffleruby/parser/YARPTranslator.java | 4 ++-- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/truffleruby/core/string/InterpolatedStringNode.java b/src/main/java/org/truffleruby/core/string/InterpolatedStringNode.java index 2d599a3d7533..5a12a9e5047f 100644 --- a/src/main/java/org/truffleruby/core/string/InterpolatedStringNode.java +++ b/src/main/java/org/truffleruby/core/string/InterpolatedStringNode.java @@ -10,9 +10,7 @@ package org.truffleruby.core.string; import com.oracle.truffle.api.strings.TruffleString; -import org.jcodings.Encoding; import org.truffleruby.core.cast.ToSNode; -import org.truffleruby.core.encoding.Encodings; import org.truffleruby.core.encoding.RubyEncoding; import org.truffleruby.language.RubyContextSourceNode; @@ -31,11 +29,7 @@ public final class InterpolatedStringNode extends RubyContextSourceNode { private final RubyEncoding encoding; private final TruffleString emptyTString; - public InterpolatedStringNode(ToSNode[] children, Encoding encoding) { - this(children, Encodings.getBuiltInEncoding(encoding)); - } - - private InterpolatedStringNode(ToSNode[] children, RubyEncoding encoding) { + public InterpolatedStringNode(ToSNode[] children, RubyEncoding encoding) { assert children.length > 0; this.children = children; this.encoding = encoding; diff --git a/src/main/java/org/truffleruby/parser/YARPTranslator.java b/src/main/java/org/truffleruby/parser/YARPTranslator.java index a7d62e7e716b..9a0f853541d9 100644 --- a/src/main/java/org/truffleruby/parser/YARPTranslator.java +++ b/src/main/java/org/truffleruby/parser/YARPTranslator.java @@ -2424,14 +2424,14 @@ public RubyNode visitInterpolatedStringNode(Nodes.InterpolatedStringNode node) { final ToSNode[] children = translateInterpolatedParts(node.parts); - final RubyNode rubyNode = new InterpolatedStringNode(children, sourceEncoding.jcoding); + final RubyNode rubyNode = new InterpolatedStringNode(children, sourceEncoding); return assignPositionAndFlags(node, rubyNode); } @Override public RubyNode visitInterpolatedSymbolNode(Nodes.InterpolatedSymbolNode node) { final ToSNode[] children = translateInterpolatedParts(node.parts); - final RubyNode stringNode = new InterpolatedStringNode(children, sourceEncoding.jcoding); + final RubyNode stringNode = new InterpolatedStringNode(children, sourceEncoding); final RubyNode rubyNode = StringToSymbolNodeGen.create(stringNode); return assignPositionAndFlags(node, rubyNode); From d8325ae5fdbdfbb649657538eb9f7ecded939f22 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 15:29:37 +0100 Subject: [PATCH 19/28] Remove unuse BytesKey --- .../org/truffleruby/core/string/BytesKey.java | 50 ------------------- 1 file changed, 50 deletions(-) delete mode 100644 src/main/java/org/truffleruby/core/string/BytesKey.java diff --git a/src/main/java/org/truffleruby/core/string/BytesKey.java b/src/main/java/org/truffleruby/core/string/BytesKey.java deleted file mode 100644 index acc241b4fe51..000000000000 --- a/src/main/java/org/truffleruby/core/string/BytesKey.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2013, 2024 Oracle and/or its affiliates. All rights reserved. This - * code is released under a tri EPL/GPL/LGPL license. You can use it, - * redistribute it and/or modify it under the terms of the: - * - * Eclipse Public License version 2.0, or - * GNU General Public License version 2, or - * GNU Lesser General Public License version 2.1. - */ -package org.truffleruby.core.string; - -import java.util.Arrays; - -import org.jcodings.Encoding; -import org.truffleruby.core.encoding.Encodings; -import org.truffleruby.core.encoding.TStringUtils; - -public final class BytesKey { - - private final byte[] bytes; - private final Encoding encoding; - private final int bytesHashCode; - - public BytesKey(byte[] bytes, Encoding encoding) { - this.bytes = bytes; - this.encoding = encoding; - this.bytesHashCode = Arrays.hashCode(bytes); - } - - @Override - public int hashCode() { - return bytesHashCode; - } - - @Override - public boolean equals(Object o) { - if (o instanceof BytesKey) { - final BytesKey other = (BytesKey) o; - return ((encoding == other.encoding) || (encoding == null)) && Arrays.equals(bytes, other.bytes); - } - - return false; - } - - @Override - public String toString() { - return TStringUtils.fromByteArray(bytes, Encodings.getBuiltInEncoding(encoding)).toString(); - } - -} From 5b27d499a6075d9b77e4c13338dd3c8d79a5a84e Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 15:39:34 +0100 Subject: [PATCH 20/28] Move EncodingManager.getEncoding to Encodings.getBuiltInEncoding --- .../core/encoding/EncodingManager.java | 16 -------------- .../truffleruby/core/encoding/Encodings.java | 21 +++++++++++-------- .../parser/MagicCommentParser.java | 14 ++++++------- .../org/truffleruby/parser/YARPLoader.java | 9 ++++---- 4 files changed, 22 insertions(+), 38 deletions(-) diff --git a/src/main/java/org/truffleruby/core/encoding/EncodingManager.java b/src/main/java/org/truffleruby/core/encoding/EncodingManager.java index 72e31a3e548c..1ac2fbf5e722 100644 --- a/src/main/java/org/truffleruby/core/encoding/EncodingManager.java +++ b/src/main/java/org/truffleruby/core/encoding/EncodingManager.java @@ -182,22 +182,6 @@ private void initializeLocaleEncoding(TruffleNFIPlatform nfi, NativeConfiguratio localeEncoding = rubyEncoding; } - @TruffleBoundary - public static Encoding getEncoding(String name) { - byte[] nameBytes = StringOperations.encodeAsciiBytes(name); - EncodingDB.Entry entry = EncodingDB.getEncodings().get(nameBytes); - - if (entry == null) { - entry = EncodingDB.getAliases().get(nameBytes); - } - - if (entry != null) { - return entry.getEncoding(); - } - - return null; - } - public synchronized Object[] getEncodingList() { return ArrayUtils.copyOf(ENCODING_LIST_BY_ENCODING_INDEX, ENCODING_LIST_BY_ENCODING_INDEX.length); } diff --git a/src/main/java/org/truffleruby/core/encoding/Encodings.java b/src/main/java/org/truffleruby/core/encoding/Encodings.java index abcb203a8d35..43a1f22ada96 100644 --- a/src/main/java/org/truffleruby/core/encoding/Encodings.java +++ b/src/main/java/org/truffleruby/core/encoding/Encodings.java @@ -124,16 +124,19 @@ public static RubyEncoding getBuiltInEncoding(Encoding jcoding) { return rubyEncoding; } - /** Should only be used when there is no other way, because this will ignore replicated and dummy encodings */ - public static RubyEncoding getBuiltInEncoding(String encodingName) { - byte[] encodingNameBytes = encodingName.getBytes(StandardCharsets.ISO_8859_1); - var entry = EncodingDB.getEncodings().get(encodingNameBytes); + @TruffleBoundary + public static RubyEncoding getBuiltInEncoding(String name) { + byte[] nameBytes = StringOperations.encodeAsciiBytes(name); + EncodingDB.Entry entry = EncodingDB.getEncodings().get(nameBytes); + + if (entry == null) { + entry = EncodingDB.getAliases().get(nameBytes); + } + if (entry != null) { - var jcoding = entry.getEncoding(); - return getBuiltInEncoding(jcoding); - } else { - throw CompilerDirectives.shouldNotReachHere("Unknown encoding: " + encodingName); + return getBuiltInEncoding(entry.getEncoding()); } - } + return null; + } } diff --git a/src/main/java/org/truffleruby/parser/MagicCommentParser.java b/src/main/java/org/truffleruby/parser/MagicCommentParser.java index a7341b45df2d..71bf1fa542a5 100644 --- a/src/main/java/org/truffleruby/parser/MagicCommentParser.java +++ b/src/main/java/org/truffleruby/parser/MagicCommentParser.java @@ -14,9 +14,7 @@ import com.oracle.truffle.api.strings.InternalByteArray; import com.oracle.truffle.api.strings.TruffleString; -import org.jcodings.Encoding; import org.truffleruby.collections.Memo; -import org.truffleruby.core.encoding.EncodingManager; import org.truffleruby.core.encoding.Encodings; import org.truffleruby.core.encoding.RubyEncoding; import org.truffleruby.core.encoding.TStringUtils; @@ -95,9 +93,9 @@ public static RubyEncoding parseMagicEncodingComment(TStringWithEncoding source) parser_magic_comment(magicLine, 0, magicLineLength, (name, value) -> { if (isMagicEncodingComment(name)) { - Encoding jcoding = EncodingManager.getEncoding(value.toJavaStringUncached()); - if (jcoding != null) { - encoding.set(Encodings.getBuiltInEncoding(jcoding)); + RubyEncoding rubyEncoding = Encodings.getBuiltInEncoding(value.toJavaStringUncached()); + if (rubyEncoding != null) { + encoding.set(rubyEncoding); return true; } } @@ -107,9 +105,9 @@ public static RubyEncoding parseMagicEncodingComment(TStringWithEncoding source) if (encoding.get() == null) { TruffleString encodingName = get_file_encoding(magicLine); if (encodingName != null) { - Encoding jcoding = EncodingManager.getEncoding(encodingName.toJavaStringUncached()); - if (jcoding != null) { - encoding.set(Encodings.getBuiltInEncoding(jcoding)); + RubyEncoding rubyEncoding = Encodings.getBuiltInEncoding(encodingName.toJavaStringUncached()); + if (rubyEncoding != null) { + encoding.set(rubyEncoding); } } } diff --git a/src/main/java/org/truffleruby/parser/YARPLoader.java b/src/main/java/org/truffleruby/parser/YARPLoader.java index 66fedd02b6bb..d06e5ab3590b 100644 --- a/src/main/java/org/truffleruby/parser/YARPLoader.java +++ b/src/main/java/org/truffleruby/parser/YARPLoader.java @@ -51,18 +51,17 @@ public static ParseResult load(byte[] serialized, Nodes.Source source, RubySourc return new YARPLoader(serialized, source, rubySource).load(); } - private final RubySource rubySource; - private RubyEncoding encoding = null; + private final RubyEncoding encoding; public YARPLoader(byte[] serialized, Nodes.Source source, RubySource rubySource) { super(serialized, source); - this.rubySource = rubySource; + this.encoding = rubySource.getEncoding(); } @Override public Charset getEncodingCharset(String encodingName) { - encoding = Encodings.getBuiltInEncoding(encodingName); - assert encoding == rubySource.getEncoding(); + var rubyEncoding = Encodings.getBuiltInEncoding(encodingName); + assert rubyEncoding == encoding : rubyEncoding + " (" + encodingName + ") vs " + encoding; return null; // encodingCharset is not used } From 97230bdd9b97a0c12d5fc6738a150233b1130c94 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 15:59:58 +0100 Subject: [PATCH 21/28] Check actual values for encoding indices in C API specs --- spec/ruby/optional/capi/encoding_spec.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/ruby/optional/capi/encoding_spec.rb b/spec/ruby/optional/capi/encoding_spec.rb index 3532229574d3..b0c38d75a935 100644 --- a/spec/ruby/optional/capi/encoding_spec.rb +++ b/spec/ruby/optional/capi/encoding_spec.rb @@ -559,19 +559,19 @@ describe "rb_ascii8bit_encindex" do it "returns an index for the ASCII-8BIT encoding" do - @s.rb_ascii8bit_encindex().should >= 0 + @s.rb_ascii8bit_encindex().should == 0 end end describe "rb_utf8_encindex" do it "returns an index for the UTF-8 encoding" do - @s.rb_utf8_encindex().should >= 0 + @s.rb_utf8_encindex().should == 1 end end describe "rb_usascii_encindex" do it "returns an index for the US-ASCII encoding" do - @s.rb_usascii_encindex().should >= 0 + @s.rb_usascii_encindex().should == 2 end end From 9092f76508b607534d75671aa4917574cb44b6a6 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 16:00:21 +0100 Subject: [PATCH 22/28] Use the proper index for US-ASCII --- .../truffleruby/core/encoding/Encodings.java | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/truffleruby/core/encoding/Encodings.java b/src/main/java/org/truffleruby/core/encoding/Encodings.java index 43a1f22ada96..e95596156588 100644 --- a/src/main/java/org/truffleruby/core/encoding/Encodings.java +++ b/src/main/java/org/truffleruby/core/encoding/Encodings.java @@ -38,8 +38,8 @@ public final class Encodings { public static final int INITIAL_NUMBER_OF_ENCODINGS = EncodingDB.getEncodings().size(); public static final int MAX_NUMBER_OF_ENCODINGS = 256; - public static final int US_ASCII_INDEX = 0; - public static final RubyEncoding US_ASCII = initializeUsAscii(); + public static final int US_ASCII_INDEX = getUsAsciiIndex(); + public static final RubyEncoding US_ASCII = new RubyEncoding(US_ASCII_INDEX); static final RubyEncoding[] BUILT_IN_ENCODINGS = initializeRubyEncodings(); private static final RubyEncoding[] BUILT_IN_ENCODINGS_BY_JCODING_INDEX = initializeBuiltinEncodingsByJCodingIndex(); @@ -64,29 +64,39 @@ public final class Encodings { public Encodings() { } - private static RubyEncoding initializeUsAscii() { - return new RubyEncoding(US_ASCII_INDEX); + private static int getUsAsciiIndex() { + int index = 0; + for (var entry : EncodingDB.getEncodings()) { + if (entry.getEncoding() == USASCIIEncoding.INSTANCE) { + return index; + } + index++; + } + throw CompilerDirectives.shouldNotReachHere("No US-ASCII"); } private static RubyEncoding[] initializeRubyEncodings() { final RubyEncoding[] encodings = new RubyEncoding[INITIAL_NUMBER_OF_ENCODINGS]; - int index = US_ASCII_INDEX + 1; + int index = 0; for (var entry : EncodingDB.getEncodings()) { final Encoding encoding = entry.getEncoding(); + final RubyEncoding rubyEncoding; if (encoding == USASCIIEncoding.INSTANCE) { - encodings[US_ASCII_INDEX] = US_ASCII; + assert index == US_ASCII_INDEX; + rubyEncoding = US_ASCII; } else { TruffleString tstring = TStringConstants.TSTRING_CONSTANTS.get(encoding.toString()); if (tstring == null) { throw CompilerDirectives.shouldNotReachHere("no TStringConstants for " + encoding); } final ImmutableRubyString name = FrozenStringLiterals.createStringAndCacheLater(tstring, US_ASCII); - var rubyEncoding = new RubyEncoding(encoding, name, index); - encodings[index] = rubyEncoding; - index++; + rubyEncoding = new RubyEncoding(encoding, name, index); } + encodings[index] = rubyEncoding; + + index++; } assert index == EncodingDB.getEncodings().size(); From 04c2281bed670298f6cd005575327e353e4a402d Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 16:06:10 +0100 Subject: [PATCH 23/28] Fix typo --- src/options.yml | 2 +- .../java/org/truffleruby/shared/options/OptionsCatalog.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/options.yml b/src/options.yml index 1a40f8e8ed14..4bab882c59cb 100644 --- a/src/options.yml +++ b/src/options.yml @@ -118,7 +118,7 @@ EXPERT: BACKTRACES_OMIT_UNUSED: [backtraces-omit-unused, boolean, true, Omit backtraces that should be unused as they have pure rescue expressions] # Big Hash Strategy - BIG_HASH_STRATEGY_IS_BUCKETS: [buckets-big-hash, boolean, false, 'Whether to use chaining-style bukcets hash store for hash tables exceeding the small hash limit'] + BIG_HASH_STRATEGY_IS_BUCKETS: [buckets-big-hash, boolean, false, 'Whether to use chaining-style buckets hash store for hash tables exceeding the small hash limit'] # Print backtraces at key events BACKTRACE_ON_INTERRUPT: [backtraces-on-interrupt, boolean, false, Show the backtraces of all Threads on Ctrl+C] diff --git a/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java b/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java index 55e970051622..ae1a751b5120 100644 --- a/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java +++ b/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java @@ -503,7 +503,7 @@ public final class OptionsCatalog { public static final OptionDescriptor BIG_HASH_STRATEGY_IS_BUCKETS = OptionDescriptor .newBuilder(BIG_HASH_STRATEGY_IS_BUCKETS_KEY, "ruby.buckets-big-hash") - .help("Whether to use chaining-style bukcets hash store for hash tables exceeding the small hash limit") + .help("Whether to use chaining-style buckets hash store for hash tables exceeding the small hash limit") .category(OptionCategory.EXPERT) .stability(OptionStability.EXPERIMENTAL) .usageSyntax("") From 7918a6da98e35822534b5303779ca6cf172928e9 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Tue, 13 Feb 2024 16:06:23 +0100 Subject: [PATCH 24/28] Default to BucketsHashStore for the big hash storage strategy * CompactHashStore seems to be more prone to races: https://github.com/oracle/truffleruby/issues/3447 * Until a thread-safe Hash implementation is merged. --- src/main/java/org/truffleruby/options/LanguageOptions.java | 2 +- src/options.yml | 2 +- .../java/org/truffleruby/shared/options/OptionsCatalog.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/truffleruby/options/LanguageOptions.java b/src/main/java/org/truffleruby/options/LanguageOptions.java index e33f8cb642f8..610fa8d4bd4f 100644 --- a/src/main/java/org/truffleruby/options/LanguageOptions.java +++ b/src/main/java/org/truffleruby/options/LanguageOptions.java @@ -41,7 +41,7 @@ public final class LanguageOptions { public final boolean LAZY_TRANSLATION_USER; /** --backtraces-omit-unused=true */ public final boolean BACKTRACES_OMIT_UNUSED; - /** --buckets-big-hash=false */ + /** --buckets-big-hash=true */ public final boolean BIG_HASH_STRATEGY_IS_BUCKETS; /** --building-core-cexts=false */ public final boolean BUILDING_CORE_CEXTS; diff --git a/src/options.yml b/src/options.yml index 4bab882c59cb..6f507654e52e 100644 --- a/src/options.yml +++ b/src/options.yml @@ -118,7 +118,7 @@ EXPERT: BACKTRACES_OMIT_UNUSED: [backtraces-omit-unused, boolean, true, Omit backtraces that should be unused as they have pure rescue expressions] # Big Hash Strategy - BIG_HASH_STRATEGY_IS_BUCKETS: [buckets-big-hash, boolean, false, 'Whether to use chaining-style buckets hash store for hash tables exceeding the small hash limit'] + BIG_HASH_STRATEGY_IS_BUCKETS: [buckets-big-hash, boolean, true, 'Whether to use chaining-style buckets hash store for hash tables exceeding the small hash limit'] # Print backtraces at key events BACKTRACE_ON_INTERRUPT: [backtraces-on-interrupt, boolean, false, Show the backtraces of all Threads on Ctrl+C] diff --git a/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java b/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java index ae1a751b5120..70ccbb5363de 100644 --- a/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java +++ b/src/shared/java/org/truffleruby/shared/options/OptionsCatalog.java @@ -62,7 +62,7 @@ public final class OptionsCatalog { public static final OptionKey EXCEPTIONS_WARN_OUT_OF_MEMORY_KEY = new OptionKey<>(true); public static final OptionKey BACKTRACES_INTERLEAVE_JAVA_KEY = new OptionKey<>(false); public static final OptionKey BACKTRACES_OMIT_UNUSED_KEY = new OptionKey<>(true); - public static final OptionKey BIG_HASH_STRATEGY_IS_BUCKETS_KEY = new OptionKey<>(false); + public static final OptionKey BIG_HASH_STRATEGY_IS_BUCKETS_KEY = new OptionKey<>(true); public static final OptionKey BACKTRACE_ON_INTERRUPT_KEY = new OptionKey<>(false); public static final OptionKey BACKTRACE_ON_SIGALRM_KEY = new OptionKey<>(!EMBEDDED_KEY.getDefaultValue()); public static final OptionKey BACKTRACE_ON_RAISE_KEY = new OptionKey<>(false); From b7cb26e092e61f52c17e137ccaf64136c7ce7e5c Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Thu, 15 Feb 2024 14:00:33 +0100 Subject: [PATCH 25/28] getNativeStringCapacity() should - 4, the native string terminator length --- src/main/java/org/truffleruby/cext/CExtNodes.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/truffleruby/cext/CExtNodes.java b/src/main/java/org/truffleruby/cext/CExtNodes.java index 3407d5d76e3d..54e1bc7d0b71 100644 --- a/src/main/java/org/truffleruby/cext/CExtNodes.java +++ b/src/main/java/org/truffleruby/cext/CExtNodes.java @@ -157,23 +157,25 @@ public abstract class CExtNodes { public static final int RUBY_TAG_THROW = 0x7; public static final int RUBY_TAG_FATAL = 0x8; + /** We need up to 4 \0 bytes for UTF-32. Always use 4 for speed rather than checking the encoding min length. + * Corresponds to TERM_LEN() in MRI. */ + public static final int NATIVE_STRING_TERMINATOR_LENGTH = 4; + public static Pointer newNativeStringPointer(RubyLanguage language, RubyContext context, int capacity) { - // We need up to 4 \0 bytes for UTF-32. Always use 4 for speed rather than checking the encoding min length. - Pointer pointer = Pointer.mallocAutoRelease(language, context, capacity + 4); + Pointer pointer = Pointer.mallocAutoRelease(language, context, capacity + NATIVE_STRING_TERMINATOR_LENGTH); pointer.writeInt(capacity, 0); return pointer; } public static Pointer newZeroedNativeStringPointer(RubyLanguage language, RubyContext context, int capacity) { - // We need up to 4 \0 bytes for UTF-32. Always use 4 for speed rather than checking the encoding min length. - return Pointer.callocAutoRelease(language, context, capacity + 4); + return Pointer.callocAutoRelease(language, context, capacity + NATIVE_STRING_TERMINATOR_LENGTH); } private static long getNativeStringCapacity(Pointer pointer) { final long nativeBufferSize = pointer.getSize(); assert nativeBufferSize > 0; - // Do not count the extra byte for \0, like MRI. - return nativeBufferSize - 1; + // Do not count the extra terminator bytes, like MRI. + return nativeBufferSize - NATIVE_STRING_TERMINATOR_LENGTH; } @Primitive(name = "call_with_c_mutex_and_frame") From e13252de0f7bb2e1f601b28d8a8cebc235d62035 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Thu, 15 Feb 2024 15:19:35 +0100 Subject: [PATCH 26/28] Do not make the RubyString native when passed to a :string argument of a FFI call * See https://github.com/oracle/truffleruby/issues/3293#issuecomment-1944444642 and https://github.com/ffi/ffi/issues/1080 * As that could cause extra conversions to managed later on. --- CHANGELOG.md | 1 + lib/truffle/truffle/ffi_backend/function.rb | 10 +++- lib/truffle/truffle/fiddle_backend.rb | 3 +- .../java/org/truffleruby/cext/CExtNodes.java | 59 +++++++++++++------ .../format/convert/StringToPointerNode.java | 2 +- .../core/string/ImmutableRubyString.java | 11 ++-- 6 files changed, 58 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c2a8dedd571..fc0c80127670 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,7 @@ Performance: * Change the `Hash` representation from traditional buckets to a "compact hash table" for improved locality, performance and memory footprint (#3172, @moste00). * Optimize calls with `ruby2_keywords` forwarding by deciding it per call site instead of per callee thanks to [my fix in CRuby 3.2](https://bugs.ruby-lang.org/issues/18625) (@eregon). * Optimize feature loading when require is called with an absolute path to a .rb file (@rwstauner). +* Avoid extra copies for Strings passed as `:string` arguments to a FFI call and used later for Regexp matching (#3293, @eregon). Changes: diff --git a/lib/truffle/truffle/ffi_backend/function.rb b/lib/truffle/truffle/ffi_backend/function.rb index f0226b1ead3f..7219eddc0ef0 100644 --- a/lib/truffle/truffle/ffi_backend/function.rb +++ b/lib/truffle/truffle/ffi_backend/function.rb @@ -154,8 +154,12 @@ def free elsif FFI::Type::POINTER == type get_pointer_value(value) elsif FFI::Type::STRING == type - Truffle::Type.check_null_safe(value) unless Primitive.nil?(value) - get_pointer_value(value) + if Primitive.nil?(value) + Truffle::FFI::Pointer::NULL + else + Truffle::Type.check_null_safe(value) + Truffle::CExt.string_to_ffi_pointer_copy(value) + end elsif Primitive.is_a?(type, FFI::FunctionType) and Primitive.is_a?(value, Proc) callback(value, type) else @@ -198,7 +202,7 @@ def free elsif Primitive.nil?(value) Truffle::FFI::Pointer::NULL elsif Primitive.is_a?(value, String) - Truffle::CExt.string_to_ffi_pointer(value) + Truffle::CExt.string_to_ffi_pointer_inplace(value) elsif value.respond_to?(:to_ptr) Truffle::Type.coerce_to value, Truffle::FFI::Pointer, :to_ptr else diff --git a/lib/truffle/truffle/fiddle_backend.rb b/lib/truffle/truffle/fiddle_backend.rb index 230c4b20fd0c..8da281681da7 100644 --- a/lib/truffle/truffle/fiddle_backend.rb +++ b/lib/truffle/truffle/fiddle_backend.rb @@ -93,7 +93,8 @@ def self.convert_ruby_to_native(type, val) def self.get_pointer_value(val) if Primitive.is_a?(val, String) - Truffle::CExt.string_to_ffi_pointer(val) + # NOTE: Fiddle::TYPE_CONST_STRING wouldn't need inplace, but not defined yet by this file + Truffle::CExt.string_to_ffi_pointer_inplace(val) elsif Primitive.is_a?(val, Fiddle::Pointer) val.to_i elsif val.respond_to?(:to_ptr) diff --git a/src/main/java/org/truffleruby/cext/CExtNodes.java b/src/main/java/org/truffleruby/cext/CExtNodes.java index 54e1bc7d0b71..a386a869cb8b 100644 --- a/src/main/java/org/truffleruby/cext/CExtNodes.java +++ b/src/main/java/org/truffleruby/cext/CExtNodes.java @@ -13,6 +13,7 @@ import java.util.Arrays; import java.util.concurrent.locks.ReentrantLock; +import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.TruffleSafepoint; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.dsl.GenerateCached; @@ -714,7 +715,7 @@ public abstract static class RbEncCodeRangeClear extends CoreMethodArrayArgument @Specialization RubyString clearCodeRange(RubyString string, @Cached StringToNativeNode stringToNativeNode) { - stringToNativeNode.executeToNative(this, string); + stringToNativeNode.executeToNative(this, string, true); string.clearCodeRange(); return string; @@ -817,7 +818,7 @@ public abstract static class RbStrCapacityNode extends CoreMethodArrayArgumentsN @Specialization long capacity(Object string, @Cached StringToNativeNode stringToNativeNode) { - return getNativeStringCapacity(stringToNativeNode.executeToNative(this, string)); + return getNativeStringCapacity(stringToNativeNode.executeToNative(this, string, true)); } } @@ -830,7 +831,7 @@ RubyString strSetLen(RubyString string, int newByteLength, @Cached StringToNativeNode stringToNativeNode, @Cached MutableTruffleString.FromNativePointerNode fromNativePointerNode, @Cached InlinedConditionProfile minLengthOneProfile) { - var pointer = stringToNativeNode.executeToNative(this, string); + var pointer = stringToNativeNode.executeToNative(this, string, true); var encoding = libString.getEncoding(string); int minLength = encoding.jcoding.minLength(); @@ -860,7 +861,7 @@ RubyString rbStrResize(RubyString string, int newByteLength, @Cached RubyStringLibrary libString, @Cached StringToNativeNode stringToNativeNode, @Cached MutableTruffleString.FromNativePointerNode fromNativePointerNode) { - var pointer = stringToNativeNode.executeToNative(this, string); + var pointer = stringToNativeNode.executeToNative(this, string, true); var tencoding = libString.getTEncoding(string); int byteLength = string.tstring.byteLength(tencoding); @@ -889,7 +890,7 @@ RubyString trStrCapaResize(RubyString string, int newCapacity, @Cached RubyStringLibrary libString, @Cached StringToNativeNode stringToNativeNode, @Cached MutableTruffleString.FromNativePointerNode fromNativePointerNode) { - var pointer = stringToNativeNode.executeToNative(this, string); + var pointer = stringToNativeNode.executeToNative(this, string, true); var tencoding = libString.getTEncoding(string); if (getNativeStringCapacity(pointer) == newCapacity) { @@ -1327,24 +1328,29 @@ int rbHash(Object object, } } + /** If inplace is true, this node mutates the RubyString to use native memory. It should be avoided unless there is + * no other way because e.g. Regexp matching later on that String would then copy to managed byte[] back, and + * copying back-and-forth is quite expensive. OTOH if the String will need to be used as native memory again soon + * after and without needing to go to managed in between then it is valuable to avoid extra copies. */ @GenerateInline @GenerateCached(false) public abstract static class StringToNativeNode extends RubyBaseNode { - public abstract Pointer executeToNative(Node node, Object string); + public abstract Pointer executeToNative(Node node, Object string, boolean inplace); @Specialization - static Pointer toNative(Node node, RubyString string, + static Pointer toNative(Node node, RubyString string, boolean inplace, @Cached RubyStringLibrary libString, @Cached InlinedConditionProfile convertProfile, @Cached(inline = false) TruffleString.CopyToNativeMemoryNode copyToNativeMemoryNode, @Cached(inline = false) MutableTruffleString.FromNativePointerNode fromNativePointerNode, @Cached(inline = false) TruffleString.GetInternalNativePointerNode getInternalNativePointerNode) { + CompilerAsserts.partialEvaluationConstant(inplace); + var tstring = string.tstring; var tencoding = libString.getTEncoding(string); final Pointer pointer; - if (convertProfile.profile(node, tstring.isNative())) { assert tstring.isMutable(); pointer = (Pointer) getInternalNativePointerNode.execute(tstring, tencoding); @@ -1353,16 +1359,18 @@ static Pointer toNative(Node node, RubyString string, pointer = allocateAndCopyToNative(getLanguage(node), getContext(node), tstring, tencoding, byteLength, copyToNativeMemoryNode); - var nativeTString = fromNativePointerNode.execute(pointer, 0, byteLength, tencoding, false); - string.setTString(nativeTString); + if (inplace) { + var nativeTString = fromNativePointerNode.execute(pointer, 0, byteLength, tencoding, false); + string.setTString(nativeTString); + } } return pointer; } @Specialization - static Pointer toNativeImmutable(Node node, ImmutableRubyString string) { - return string.getNativeString(getLanguage(node)); + static Pointer toNativeImmutable(Node node, ImmutableRubyString string, boolean inplace) { + return string.getNativeString(getLanguage(node), getContext(node)); } public static Pointer allocateAndCopyToNative(RubyLanguage language, RubyContext context, @@ -1381,17 +1389,34 @@ public abstract static class StringPointerToNativeNode extends PrimitiveArrayArg @Specialization long toNative(Object string, @Cached StringToNativeNode stringToNativeNode) { - return stringToNativeNode.executeToNative(this, string).getAddress(); + return stringToNativeNode.executeToNative(this, string, true).getAddress(); + } + } + + @CoreMethod(names = "string_to_ffi_pointer_inplace", onSingleton = true, required = 1) + public abstract static class StringToFFIPointerInplaceNode extends CoreMethodArrayArgumentsNode { + + @Specialization + RubyPointer toFFIPointerInplace(Object string, + @Cached StringToNativeNode stringToNativeNode) { + var pointer = stringToNativeNode.executeToNative(this, string, true); + + final RubyPointer instance = new RubyPointer( + coreLibrary().truffleFFIPointerClass, + getLanguage().truffleFFIPointerShape, + pointer); + AllocationTracing.trace(instance, this); + return instance; } } - @CoreMethod(names = "string_to_ffi_pointer", onSingleton = true, required = 1) - public abstract static class StringToFFIPointerNode extends CoreMethodArrayArgumentsNode { + @CoreMethod(names = "string_to_ffi_pointer_copy", onSingleton = true, required = 1) + public abstract static class StringToFFIPointerCopyNode extends CoreMethodArrayArgumentsNode { @Specialization - RubyPointer toNative(Object string, + RubyPointer toFFIPointerCopy(Object string, @Cached StringToNativeNode stringToNativeNode) { - var pointer = stringToNativeNode.executeToNative(this, string); + var pointer = stringToNativeNode.executeToNative(this, string, false); final RubyPointer instance = new RubyPointer( coreLibrary().truffleFFIPointerClass, diff --git a/src/main/java/org/truffleruby/core/format/convert/StringToPointerNode.java b/src/main/java/org/truffleruby/core/format/convert/StringToPointerNode.java index 2e275a52c66f..4783d8ac49a7 100644 --- a/src/main/java/org/truffleruby/core/format/convert/StringToPointerNode.java +++ b/src/main/java/org/truffleruby/core/format/convert/StringToPointerNode.java @@ -42,7 +42,7 @@ static long toPointer(VirtualFrame frame, Object string, @Cached RubyStringLibrary strings, @Bind("this") Node node) { - final Pointer pointer = stringToNativeNode.executeToNative(node, string); + final Pointer pointer = stringToNativeNode.executeToNative(node, string, true); List associated = (List) frame.getObject(FormatFrameDescriptor.ASSOCIATED_SLOT); diff --git a/src/main/java/org/truffleruby/core/string/ImmutableRubyString.java b/src/main/java/org/truffleruby/core/string/ImmutableRubyString.java index d59a221cbc7c..886db9558b24 100644 --- a/src/main/java/org/truffleruby/core/string/ImmutableRubyString.java +++ b/src/main/java/org/truffleruby/core/string/ImmutableRubyString.java @@ -80,21 +80,20 @@ public boolean isNative() { } @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") - public Pointer getNativeString(RubyLanguage language) { + public Pointer getNativeString(RubyLanguage language, RubyContext context) { if (nativeString == null) { - return createNativeString(language); + return createNativeString(language, context); } return nativeString; } @TruffleBoundary - private synchronized Pointer createNativeString(RubyLanguage language) { + private synchronized Pointer createNativeString(RubyLanguage language, RubyContext context) { if (nativeString == null) { var tencoding = getEncodingUncached().tencoding; int byteLength = tstring.byteLength(tencoding); - nativeString = CExtNodes.StringToNativeNode.allocateAndCopyToNative(language, - RubyLanguage.getCurrentContext(), tstring, tencoding, byteLength, - TruffleString.CopyToNativeMemoryNode.getUncached()); + nativeString = CExtNodes.StringToNativeNode.allocateAndCopyToNative(language, context, tstring, tencoding, + byteLength, TruffleString.CopyToNativeMemoryNode.getUncached()); } return nativeString; } From 6ed0b6e13f9ee9b9d586bc424220c5b66f9469d1 Mon Sep 17 00:00:00 2001 From: ol-automation_ww Date: Fri, 16 Feb 2024 21:08:11 +0000 Subject: [PATCH 27/28] Update graal import. --- ci/common.jsonnet | 6 +++--- common.json | 28 ++++++++++++++-------------- mx.truffleruby/suite.py | 4 ++-- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/ci/common.jsonnet b/ci/common.jsonnet index 6437e7ea7880..56723c5129a4 100644 --- a/ci/common.jsonnet +++ b/ci/common.jsonnet @@ -67,8 +67,8 @@ local common_json = import "../common.json"; assert local _labsjdk = common_json.jdks["labsjdk-ee-latest"]; local _oraclejdk = common_json.jdks["oraclejdk-latest"]; - local _ov = "ee-%s+%s" % [_oraclejdk.version, _oraclejdk.build_id]; - local _lv = _labsjdk.version; + local _ov = _oraclejdk.build_id; + local _lv = std.strReplace(_labsjdk.version, "ee-", "jdk-"); # Skip the check if we are not using a labsjdk. This can happen on JDK integration branches. local no_labsjdk = _labsjdk.name != "labsjdk"; assert no_labsjdk || std.startsWith(_lv, _ov) : "update oraclejdk-latest to match labsjdk-ee-latest: %s+%s vs %s" % [_oraclejdk.version, _oraclejdk.build_id, _labsjdk.version]; @@ -116,7 +116,7 @@ local common_json = import "../common.json"; "linux-jdk19": { packages+: { "devkit:gcc11.2.0-OL6.4+1": "==0" }}, "linux-jdk20": { packages+: { "devkit:gcc11.2.0-OL6.4+1": "==0" }}, "linux-jdk21": { packages+: { "devkit:gcc11.2.0-OL6.4+1": "==0" }}, - "linux-jdk-latest": { packages+: { "devkit:gcc11.2.0-OL6.4+1": "==0" }}, + "linux-jdk-latest": { packages+: { "devkit:gcc13.2.0-OL6.4+1": "==0" }}, "linux-jdkLatest": self["linux-jdk-latest"], }, diff --git a/common.json b/common.json index 81f8df063eab..1ead3fc4c98b 100644 --- a/common.json +++ b/common.json @@ -4,15 +4,15 @@ "Jsonnet files should not include this file directly but use ci/common.jsonnet instead." ], - "mx_version": "7.7.3", + "mx_version": "7.11.0", "COMMENT.jdks": "When adding or removing JDKs keep in sync with JDKs in ci/common.jsonnet", "jdks": { - "galahad-jdk": {"name": "jpg-jdk", "version": "23", "build_id": "jdk-23+4", "platformspecific": true, "extrabundles": ["static-libs"]}, + "galahad-jdk": {"name": "jpg-jdk", "version": "23", "build_id": "jdk-23+9-626", "platformspecific": true, "extrabundles": ["static-libs"]}, - "oraclejdk11": {"name": "jpg-jdk", "version": "11.0.11", "build_id": "9", "release": true, "platformspecific": true, "extrabundles": ["static-libs"] }, + "oraclejdk11": {"name": "jpg-jdk", "version": "11.0.11", "build_id": "jdk-11.0.11+9", "platformspecific": true, "extrabundles": ["static-libs"] }, - "oraclejdk17": {"name": "jpg-jdk", "version": "17.0.7", "build_id": "8", "release": true, "platformspecific": true, "extrabundles": ["static-libs"]}, + "oraclejdk17": {"name": "jpg-jdk", "version": "17.0.7", "build_id": "jdk-17.0.7+8", "platformspecific": true, "extrabundles": ["static-libs"]}, "labsjdk-ce-17": {"name": "labsjdk", "version": "ce-17.0.7+4-jvmci-23.1-b02", "platformspecific": true }, "labsjdk-ce-17Debug": {"name": "labsjdk", "version": "ce-17.0.7+4-jvmci-23.1-b02-debug", "platformspecific": true }, "labsjdk-ce-17-llvm": {"name": "labsjdk", "version": "ce-17.0.7+4-jvmci-23.1-b02-sulong", "platformspecific": true }, @@ -20,7 +20,7 @@ "labsjdk-ee-17Debug": {"name": "labsjdk", "version": "ee-17.0.8+2-jvmci-23.1-b02-debug", "platformspecific": true }, "labsjdk-ee-17-llvm": {"name": "labsjdk", "version": "ee-17.0.8+2-jvmci-23.1-b02-sulong", "platformspecific": true }, - "oraclejdk19": {"name": "jpg-jdk", "version": "19", "build_id": "26", "release": true, "platformspecific": true, "extrabundles": ["static-libs"]}, + "oraclejdk19": {"name": "jpg-jdk", "version": "19.0.1", "build_id": "jdk-19.0.1+10", "platformspecific": true, "extrabundles": ["static-libs"]}, "labsjdk-ce-19": {"name": "labsjdk", "version": "ce-19.0.1+10-jvmci-23.0-b04", "platformspecific": true }, "labsjdk-ce-19Debug": {"name": "labsjdk", "version": "ce-19.0.1+10-jvmci-23.0-b04-debug", "platformspecific": true }, "labsjdk-ce-19-llvm": {"name": "labsjdk", "version": "ce-19.0.1+10-jvmci-23.0-b04-sulong", "platformspecific": true }, @@ -28,7 +28,7 @@ "labsjdk-ee-19Debug": {"name": "labsjdk", "version": "ee-19.0.2+7-jvmci-23.0-b05-debug", "platformspecific": true }, "labsjdk-ee-19-llvm": {"name": "labsjdk", "version": "ee-19.0.2+7-jvmci-23.0-b05-sulong", "platformspecific": true }, - "oraclejdk20": {"name": "jpg-jdk", "version": "20", "build_id": "34", "release": true, "platformspecific": true, "extrabundles": ["static-libs"]}, + "oraclejdk20": {"name": "jpg-jdk", "version": "20.0.1", "build_id": "jdk-20.0.1+9", "platformspecific": true, "extrabundles": ["static-libs"]}, "labsjdk-ce-20": {"name": "labsjdk", "version": "ce-20.0.1+9-jvmci-23.1-b02", "platformspecific": true }, "labsjdk-ce-20Debug": {"name": "labsjdk", "version": "ce-20.0.1+9-jvmci-23.1-b02-debug", "platformspecific": true }, "labsjdk-ce-20-llvm": {"name": "labsjdk", "version": "ce-20.0.1+9-jvmci-23.1-b02-sulong", "platformspecific": true }, @@ -36,7 +36,7 @@ "labsjdk-ee-20Debug": {"name": "labsjdk", "version": "ee-20.0.2+2-jvmci-23.1-b02-debug", "platformspecific": true }, "labsjdk-ee-20-llvm": {"name": "labsjdk", "version": "ee-20.0.2+2-jvmci-23.1-b02-sulong", "platformspecific": true }, - "oraclejdk21": {"name": "jpg-jdk", "version": "21", "build_id": "33", "release": true, "platformspecific": true, "extrabundles": ["static-libs"]}, + "oraclejdk21": {"name": "jpg-jdk", "version": "21.0.2", "build_id": "jdk-21.0.2+13", "platformspecific": true, "extrabundles": ["static-libs"]}, "labsjdk-ce-21": {"name": "labsjdk", "version": "ce-21.0.2+13-jvmci-23.1-b33", "platformspecific": true }, "labsjdk-ce-21Debug": {"name": "labsjdk", "version": "ce-21.0.2+13-jvmci-23.1-b33-debug", "platformspecific": true }, "labsjdk-ce-21-llvm": {"name": "labsjdk", "version": "ce-21.0.2+13-jvmci-23.1-b33-sulong", "platformspecific": true }, @@ -44,13 +44,13 @@ "labsjdk-ee-21Debug": {"name": "labsjdk", "version": "ee-21.0.2+13-jvmci-23.1-b33-debug", "platformspecific": true }, "labsjdk-ee-21-llvm": {"name": "labsjdk", "version": "ee-21.0.2+13-jvmci-23.1-b33-sulong", "platformspecific": true }, - "oraclejdk-latest": {"name": "jpg-jdk", "version": "23", "build_id": "8", "release": true, "platformspecific": true, "extrabundles": ["static-libs"]}, - "labsjdk-ce-latest": {"name": "labsjdk", "version": "ce-23+8-jvmci-b01", "platformspecific": true }, - "labsjdk-ce-latestDebug": {"name": "labsjdk", "version": "ce-23+8-jvmci-b01-debug", "platformspecific": true }, - "labsjdk-ce-latest-llvm": {"name": "labsjdk", "version": "ce-23+8-jvmci-b01-sulong", "platformspecific": true }, - "labsjdk-ee-latest": {"name": "labsjdk", "version": "ee-23+8-jvmci-b01", "platformspecific": true }, - "labsjdk-ee-latestDebug": {"name": "labsjdk", "version": "ee-23+8-jvmci-b01-debug", "platformspecific": true }, - "labsjdk-ee-latest-llvm": {"name": "labsjdk", "version": "ee-23+8-jvmci-b01-sulong", "platformspecific": true } + "oraclejdk-latest": {"name": "jpg-jdk", "version": "23", "build_id": "jdk-23+9", "platformspecific": true, "extrabundles": ["static-libs"]}, + "labsjdk-ce-latest": {"name": "labsjdk", "version": "ce-23+9-jvmci-b01", "platformspecific": true }, + "labsjdk-ce-latestDebug": {"name": "labsjdk", "version": "ce-23+9-jvmci-b01-debug", "platformspecific": true }, + "labsjdk-ce-latest-llvm": {"name": "labsjdk", "version": "ce-23+9-jvmci-b01-sulong", "platformspecific": true }, + "labsjdk-ee-latest": {"name": "labsjdk", "version": "ee-23+9-jvmci-b01", "platformspecific": true }, + "labsjdk-ee-latestDebug": {"name": "labsjdk", "version": "ee-23+9-jvmci-b01-debug", "platformspecific": true }, + "labsjdk-ee-latest-llvm": {"name": "labsjdk", "version": "ee-23+9-jvmci-b01-sulong", "platformspecific": true } }, "eclipse": { diff --git a/mx.truffleruby/suite.py b/mx.truffleruby/suite.py index 008d07b45e3f..ef025e75971a 100644 --- a/mx.truffleruby/suite.py +++ b/mx.truffleruby/suite.py @@ -20,7 +20,7 @@ { "name": "regex", "subdir": True, - "version": "2a2602417823173bd9952b943ffaa97a79714143", + "version": "6b2a6316c8165811a28d604ce11ca2f7103585ec", "urls": [ {"url": "https://github.com/oracle/graal.git", "kind": "git"}, {"url": "https://curio.ssw.jku.at/nexus/content/repositories/snapshots", "kind": "binary"}, @@ -29,7 +29,7 @@ { "name": "sulong", "subdir": True, - "version": "2a2602417823173bd9952b943ffaa97a79714143", + "version": "6b2a6316c8165811a28d604ce11ca2f7103585ec", "urls": [ {"url": "https://github.com/oracle/graal.git", "kind": "git"}, {"url": "https://curio.ssw.jku.at/nexus/content/repositories/snapshots", "kind": "binary"}, From f9b982ebbdb2e68b5c7761f00f589517bb39f9e7 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Mon, 19 Feb 2024 12:55:50 +0100 Subject: [PATCH 28/28] Update ffi version in 3rd_party_licenses.txt --- 3rd_party_licenses.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/3rd_party_licenses.txt b/3rd_party_licenses.txt index 086ddbd7f22d..ad468de0c3ab 100644 --- a/3rd_party_licenses.txt +++ b/3rd_party_licenses.txt @@ -1308,7 +1308,7 @@ of */ ================================================================================ -ffi 1.15.5 +ffi 1.16.3 Copyright (c) 2008-2016, Ruby FFI project contributors All rights reserved.