Skip to content

Backtrace lines can have stale encoding flags for non-ASCII method names and instance_eval file names #9879

Open

Description

@keithrbennett

(AI Generated)

JRuby sometimes builds backtrace strings whose cached encoding flags disagree with their bytes. Both repros below are self-contained and behave correctly on MRI 4.0.7; on JRuby the first also makes each_char yield nil, chars raise, and the tested Regexp gsub hang.

1. instance_eval(string, filename, line) with a non-ASCII file name

issue_repro1.rb:

FILENAME = "/tmp/é.rb"

l = Object.new.instance_eval("->{ raise 'x' }", FILENAME, 1)
line = begin
  l.call
rescue StandardError => e
  e.backtrace.first
end

puts line.inspect
puts "encoding: #{line.encoding}"
puts "valid_encoding?: #{line.valid_encoding?}"
puts "bytes: #{line.bytes.inspect}"

JRuby 10.1.0.0 output (bytes array trimmed):

"/tmp/é.rb:1:in 'block in (eval at /tmp/\xE9.rb:0)'"
encoding: UTF-8
valid_encoding?: true
bytes: [47, 116, ..., 195, 169, ..., 233, ...]

The leading file name is correct UTF-8 (195, 169 is é), but the (eval at ...) label contains a bare 0xE9, and the string still reports valid_encoding? == true. Expected: the string must not report valid_encoding? == true while containing a bare 0xE9. Ideally the label should contain the file name correctly encoded; a fix that only makes the flag truthful (valid_encoding? == false) would still leave the label bytes wrong.

The same (eval at ...) label appears with the class_eval(string, filename, line) and module_eval(string, filename, line) forms; eval(string, binding, filename, line) does not produce it.

The no-filename forms are affected too: with a non-ASCII script path, instance_eval/class_eval/module_eval produce a label like (eval at (eval at \xE9.rb:7):0) with valid_encoding? == true.

Which characters trigger the stale valid_encoding? depends on how the label is truncated (see the suspected cause below). In a 16-name matrix, é, ü ß, ệ, α and א leave the flag stale. あ, ł, ş, д, ا, क, ก, 漢, 中, 한 and 😀 also get a mangled label, but its bytes happen to be valid, so valid_encoding? is correct.

I am not asking JRuby to match MRI's label shape; the minimum requirement is bytes and flags that agree. Whether to keep the (eval at ...) label is a separate compatibility decision.

Consequences observed on JRuby 10.1.0.0 and 10.1.2.0 with identical results (the unbounded each_char and gsub timeout runs were done on those two only; the bounded each_char nil count and the chars crash were also confirmed on 10.0.x, as noted below):

  • line.each_char starts yielding nil at iteration 40; about half of subsequent iterations are nil. Without a break it did not finish within timeout 60.
  • line.chars raises Java::JavaLang::ArrayIndexOutOfBoundsException: Index 47 out of bounds for length 47:
    org.jruby.dist/org.jruby.RubyString.enumerateChars(RubyString.java:6413)
    org.jruby.dist/org.jruby.RubyString.chars(RubyString.java:6357)
    
  • line.gsub(Regexp.union(["é", "→"]), "x") did not return within timeout 60.
  • The hang is pattern-dependent: /é/ returns normally (it matches only the file name at the start of the line, not the bare 0xE9 in the label); /é|→/ and /e|é/ also hang; /./ raises NegativeArraySizeException: -1.
  • After a rescan (line.b.force_encoding(line.encoding)), the same gsub raises ArgumentError: invalid byte sequence in UTF-8 instead of hanging, so the stale flag is the trigger.
  • line.scrub returns the string unchanged. A copy rescanned with line.b.force_encoding(line.encoding) reports valid_encoding? == false, which confirms the cached flag on line is stale.

For reference, the consequence calls are:

line.each_char { |c| break if c.nil? }   # first nil at iteration 40
line.chars                               # ArrayIndexOutOfBoundsException
line.gsub(Regexp.union(["é", "→"]), "x") # does not return within 60 s

MRI 4.0.7 prints /tmp/é.rb:1:in 'block in <main>' (MRI does not add an (eval at ...) label here), with 32 characters, no nil from each_char, and gsub returns normally.

2. A method with a non-ASCII name

issue_repro2.rb:

class C
  def 検証する(_x)
    raise "x"
  end
end

line = begin
  C.new.検証する(1)
rescue StandardError => e
  e.backtrace.first
end

puts "line.inspect: #{line.inspect}"
puts "line.encoding: #{line.encoding}"
puts "line.valid_encoding?: #{line.valid_encoding?}"
puts "line.ascii_only?: #{line.ascii_only?}"

out = line.encode(Encoding::US_ASCII, invalid: :replace, undef: :replace)
puts "out.bytes: #{out.bytes.inspect}"
puts "out.encoding: #{out.encoding}"
puts "out.ascii_only?: #{out.ascii_only?}"
puts "out.valid_encoding?: #{out.valid_encoding?}"

JRuby 10.1.0.0 output (bytes array trimmed):

line.inspect: "issue_repro2.rb:3:in '検証する'"
line.encoding: UTF-8
line.valid_encoding?: true
line.ascii_only?: true
out.bytes: [105, ..., 230, 164, 156, 232, 168, 188, 227, 129, 153, 227, 130, 139, 39]
out.encoding: US-ASCII
out.ascii_only?: false
out.valid_encoding?: false

Expected: line.ascii_only? should be false, and encode(US-ASCII) should replace the non-ASCII name (MRI produces 'C#????'). Actual: ascii_only? is true, so encode appears to take its "already ASCII" shortcut and returns the original non-ASCII bytes tagged as US-ASCII.

(JRuby's label is '検証する'; MRI's is 'C#検証する'. The flags are the issue; the missing C# prefix is a separate compatibility difference and is not part of this report.)

I reproduced the wrong ascii_only? on 10.1.0.0 for Latin, Greek, Cyrillic, Hebrew, Arabic, Devanagari, Thai, Japanese, Chinese, Korean and emoji method names. The two flag bugs (wrong valid_encoding? and wrong ascii_only?), the nil from each_char, and the chars crash reproduce on 10.0.0.1, 10.0.1.0, 10.0.2.0 and 10.1.0.0.

Related prior art (not duplicates)

#8711 (the fix for #8710) introduced the same-size/7-bit heuristic in catString (the false branch later became CR_VALID). #4828 is the same Java-String-to-symbol low-byte truncation path (ByteList.plain, US-ASCII); the 9.2 fix covered parser-created symbols, but the Java-String path here remains. #8316 (fixed by #8318) is the same family of stale valid_encoding? after injecting invalid bytes, but through string mutation rather than backtrace construction. #1361 is the same chars crash site, but with a genuinely invalid US-ASCII string; it was fixed in 1.7.11. None of these covers these backtrace labels.

Suspected cause (from reading the 10.1.0.0 source, not verified by a patch)

RubyStackTraceElement.to_s_mri builds the line by appending the file name with catString and then appending the method-name bytes with cat(ByteList):

https://github.com/jruby/jruby/blob/10.1.0.0/core/src/main/java/org/jruby/runtime/backtrace/RubyStackTraceElement.java#L86-L98

catString sets the code range from the file name alone:

ByteList other = encodeBytelist(str, UTF8);
catWithCodeRange(other, other.realSize() == str.length() ? CR_7BIT : CR_VALID);

https://github.com/jruby/jruby/blob/10.1.0.0/core/src/main/java/org/jruby/RubyString.java#L1707-L1712

cat(ByteList) then copies the method-name bytes without updating the code range:

https://github.com/jruby/jruby/blob/10.1.0.0/core/src/main/java/org/jruby/RubyString.java#L1718-L1723

So the final code range reflects only the file name. For an ASCII file name it is CR_7BIT, so appending a non-ASCII method name leaves ascii_only? == true (repro 2). For a non-ASCII file name it is CR_VALID, so appending invalid bytes leaves valid_encoding? == true (repro 1).

The eval name itself is built in Interpreter.evalName (Interpreter.java:229-231). The filename form used above goes through the three-argument RubyBasicObject.specificEval (RubyBasicObject.java:2025-2033), which reads the filename at line 2030 and decrements the supplied line at 2031; the no-filename overload uses the caller's file at RubyBasicObject.java:1972-1973. RubyKernel uses the binding filename at RubyKernel.java:1309. For block frames, to_s_mri also calls catString("block in "), but that does not change the coderange analysis.

Separately, the (eval at ...) label itself appears to be created from a Java String as a symbol through RubySymbol.symbolBytesFromString, which uses ByteList.plain (raw ISO-8859-1) and labels the result US-ASCII:

https://github.com/jruby/jruby/blob/10.1.0.0/core/src/main/java/org/jruby/RubySymbol.java#L975-L977

That explains the byte truncation: each UTF-16 code unit is reduced to its low byte, e.g. é → 0xE9, ệ → 0xC7, 😀 → 0x3D 0x00. It also explains why non-ASCII characters whose low byte is ASCII (e.g. あ → B) produce a mangled label without an invalid-valid_encoding? symptom.

These look like two independent defects: fixing the coderange alone would leave the label bytes mangled, and fixing the symbol conversion alone would leave the non-ASCII method-name flag bug.

Impact

Code that walks backtrace characters, for example to sanitize error output to ASCII, can hang, crash, or silently skip conversion when a backtrace contains a non-ASCII eval label or method name.

Environment

  • JRuby 10.0.0.1, 10.0.1.0, 10.0.2.0 (Ruby 3.4.2), 10.1.0.0 and 10.1.2.0 (Ruby 4.0.0; 10.1.2.0 is the latest release at the time of writing)
  • OpenJDK 25.0.4.1+1-1-26.04.4-Ubuntu
  • Ubuntu 26.04.1 LTS, x86_64, LANG=en_US.UTF-8
  • MRI 4.0.7 (2026-09-15 revision 229531a6cf) +PRISM as the control

On 10.1.2.0, from the jruby-bin-10.1.2.0.tar.gz GitHub release asset (checksum matches the published .sha512; jruby -v prints jruby 10.1.2.0 (4.0.0) 2026-09-30 c6d2b769d0, while the 10.1.2.0 tag points at 36cf8bbe87), I re-ran both repros, chars, the unbounded each_char (still running after 20 s with about half the iterations nil; timeout exit status 124) and the Regexp.union gsub (timeout 60 exit status 124). /./ still raises NegativeArraySizeException: -1, /é|→/ and /e|é/ gave no result within 20 s, and the 16-name file-name matrix and the 11-name method-name matrix give the same results as on 10.1.0.0. The source links above are to the 10.1.0.0 tag. I did not test 10.0.7.0, 10.1.1.0 or 9.4.x.

Activity

  1. headius commented on Oct 26, 2026

    @headius
    Member

    The problem is how the final backtrace gets constructed; the method name ("eval at /tmp/é.rb") gets turned into a Symbol using US-ASCII encoding, which causes the é to get mangled when displayed.

    I have some ideas for a fix.

  2. headius commented on Oct 26, 2026

    @headius
    Member

    #9887 fixes your instance_eval case as well as the additional exception output when attempting to render a backtrace for methods like def é.... We'll see how it impacts CI.

    The tricky part here is that in order to preserve the original encoding of identifiers, the RubySymbol table keys off the raw bytes. It is expected the raw bytes will always be used to look up those symbol objects. If the identifier is being used to make further method calls, we want it to reflect the original raw bytes, but if it is being used for JVM stack traces or text output, we need it to be properly decoded. The two goals may not be compatible in all cases (e.g. a properly-rendered JVM stack trace may always need to use properly-decoded method name, making that name unusable for further method calling).

  3. added this to the JRuby 10.0.x milestone on Oct 27, 2026
  4. headius commented on Oct 27, 2026

    @headius
    Member

    The first attempt to fix this in #9887 exposes a number of places we really need these identifiers to be the "raw" form. A targeted fix just for the instance_eval example might be possible in the short term, but generally speaking it will be may be difficult for us to both:

    • support arbitrary encodings for Symbols
    • properly decode symbolic identifiers for Java purposes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions