TerminalRow.mSpaceUsed (short) overflows on terminals wider than 1023 columns, crashing setChar
Problem description
TerminalRow counts the Java chars used by a row in private short mSpaceUsed. A column can hold up to 32 chars: one supplementary code point (2 chars) plus MAX_COMBINING_CHARACTERS_PER_COLUMN (15) supplementary zero-width code points (2 chars each). On a terminal wider than 1023 columns, a program can make a row need more than Short.MAX_VALUE chars. mSpaceUsed += javaCharDifference (TerminalRow.java:235 at v0.118.3) then wraps negative, and the next setChar throws from System.arraycopy:
java.lang.ArrayIndexOutOfBoundsException: arraycopy: length -65410 is negative
at com.termux.terminal.TerminalRow.setChar(TerminalRow.java:229)
at com.termux.terminal.TerminalBuffer.setChar(TerminalBuffer.java:455)
at com.termux.terminal.TerminalEmulator.emitCodePoint(TerminalEmulator.java:2487)
at com.termux.terminal.TerminalEmulator.processCodePoint(TerminalEmulator.java:645)
at com.termux.terminal.TerminalEmulator.processByte(TerminalEmulator.java:532)
at com.termux.terminal.TerminalEmulator.append(TerminalEmulator.java:499)In an app, the emulator processes output on the main thread, so this exception would end the app's process. It can be triggered by output alone (cat of a crafted file, a remote SSH session), but only when the terminal is wider than 1023 columns, for example very small text on a very wide external display. We found it through CodeQL (java/implicit-cast-in-compound-assignment) and reproduced it with the JVM test below. We have not observed it on a device.
Steps to reproduce the behavior.
A test in terminal-emulator/src/test/java/com/termux/terminal/ reproduces it at tag v0.118.3 (commit 5b657c6adf4304e5198951ce815fe0205dcac29c):
public class RowCharCounterOverflowTest extends TerminalTestCase {
public void testRowCharCounterOverflow() {
StringBuilder cell = new StringBuilder();
cell.appendCodePoint(0x10000); // width 1, two Java chars
for (int i = 0; i < 15; i++) cell.appendCodePoint(0x1D167); // width 0, two Java chars each
StringBuilder row = new StringBuilder();
for (int column = 0; column < 1100; column++) row.append(cell);
withTerminalSized(1100, 3).enterString(row.toString()); // throws the exception above
}
}With 1000 columns, the same input uses 32000 chars and works.
What is the expected behavior?
Wide terminals should accept any output without an exception. Declaring mSpaceUsed as int would remove the limit. mText is already a char[], which grows as needed.
System information
- termux-app: v0.118.3 (commit 5b657c6),
terminal-emulatorlibrary, JVM unit test (Gradle, JDK 21) - Found while embedding the
terminal-emulatorandterminal-viewlibraries in another Apache/GPL-compatible Android app. That app works around it by limiting its terminal view to 1000 columns.
Source: termux/termux-app