Ghidra is a software reverse engineering (SRE) framework
GP-1148 fix ConsoleTextPane to not hog swing thread. Fixes #3251
dev74736824ff03f76c0c
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/framework/main/ConsoleTextPane.java b/Ghidra/Features/Base/src/main/java/ghidra/framework/main/ConsoleTextPane.javaindex 8457f2e2db..4c9212a952 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/framework/main/ConsoleTextPane.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/framework/main/ConsoleTextPane.java@@ -17,7 +17,7 @@ package ghidra.framework.main;import java.awt.Color;import java.awt.Font;-import java.util.*;+import java.util.LinkedList;import javax.swing.JTextPane;import javax.swing.text.*;@@ -42,27 +42,25 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListenerprivate static final String OPTIONS_NAME = "Console";private static final String MAXIMUM_CHARACTERS_OPTION_NAME = "Character Limit";- private static final String TRUNCTION_FACTOR_OPTION_NAME = "Truncation Factor";- private static final int QUEUED_MESSAGE_LIMIT = 20;- private static int MAXIMUM_CHARS = 50000;+ private static final String TRUNCATION_FACTOR_OPTION_NAME = "Truncation Factor";+ private static final int DEFAULT_MAXIMUM_CHARS = 50000;+ private static final int MINIMUM_MAXIMUM_CHARS = 1000;+ private static final int MAX_UPDATE_INTERVAL_MS = 100;/** % of characters to delete when truncation is necessary */- private static double TRUNCTION_FACTOR = .10;+ private static double DEFAULT_TRUNCATION_FACTOR = .10;private static SimpleAttributeSet outputAttributeSet;private static SimpleAttributeSet errorAttributeSet;- private SwingUpdateManager updateManager = new SwingUpdateManager(1, 500, () -> doUpdate());+ // don't update more than once per second if lots of messages are being written+ private SwingUpdateManager updateManager = new SwingUpdateManager(100, 1000, () -> doUpdate());- private List<MessageWrapper> messageList =- Collections.synchronizedList(new LinkedList<MessageWrapper>());- private ConsoleListener listener;+ private LinkedList<MessageWrapper> messageList = new LinkedList<>();private boolean scrollLock;- private int maximumCharacterLimit = MAXIMUM_CHARS;- private double truncationFactor = TRUNCTION_FACTOR;- private int truncationAmount = (int) (MAXIMUM_CHARS * TRUNCTION_FACTOR);- private int queuedMessageCount;+ private int maximumCharacterLimit = DEFAULT_MAXIMUM_CHARS;+ private double truncationFactor = DEFAULT_TRUNCATION_FACTOR;public ConsoleTextPane(PluginTool tool) {createAttribtues();@@ -78,26 +76,22 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListenerupdateCaretSelectionPolicy(lock);}- public void setConsoleListener(ConsoleListener listener) {- this.listener = listener;- }-public void addMessage(String message) {- doAddMessage(new MessageWrapper(message, true));+ doAddMessage(new MessageWrapper(message));}public void addPartialMessage(String message) {- doAddMessage(new MessageWrapper(message, false));+ doAddMessage(new MessageWrapper(message));}public void addErrorMessage(String message) {- doAddMessage(new ErrorMessage(message, true));+ doAddMessage(new ErrorMessage(message));}@Overridepublic void optionsChanged(ToolOptions options, String name, Object oldValue, Object newValue) {if (MAXIMUM_CHARACTERS_OPTION_NAME.equals(name) ||- TRUNCTION_FACTOR_OPTION_NAME.equals(name)) {+ TRUNCATION_FACTOR_OPTION_NAME.equals(name)) {updateFromOptions(options);}}@@ -106,11 +100,11 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListener//==================================================================================================private void initOptions(Options options) {- options.registerOption(MAXIMUM_CHARACTERS_OPTION_NAME, MAXIMUM_CHARS, null,+ options.registerOption(MAXIMUM_CHARACTERS_OPTION_NAME, DEFAULT_MAXIMUM_CHARS, null,"The maximum number of " +"characters to display before truncating characters from the top of the console.");- options.registerOption(TRUNCTION_FACTOR_OPTION_NAME, TRUNCTION_FACTOR, null,+ options.registerOption(TRUNCATION_FACTOR_OPTION_NAME, DEFAULT_TRUNCATION_FACTOR, null,"The factor (when multiplied by the " + MAXIMUM_CHARACTERS_OPTION_NAME +") by which to remove characters when truncating is necessary.");@@ -118,14 +112,17 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListener}private void updateFromOptions(Options options) {- int newLimit = options.getInt(MAXIMUM_CHARACTERS_OPTION_NAME, MAXIMUM_CHARS);- truncationFactor = options.getDouble(TRUNCTION_FACTOR_OPTION_NAME, TRUNCTION_FACTOR);+ int newLimit = options.getInt(MAXIMUM_CHARACTERS_OPTION_NAME, DEFAULT_MAXIMUM_CHARS);+ truncationFactor = options.getDouble(TRUNCATION_FACTOR_OPTION_NAME, DEFAULT_TRUNCATION_FACTOR);setMaximumCharacterLimit(newLimit);}void setMaximumCharacterLimit(int limit) {- maximumCharacterLimit = limit;- truncationAmount = (int) (maximumCharacterLimit * truncationFactor);+ maximumCharacterLimit = Math.max(limit, MINIMUM_MAXIMUM_CHARS);+ }++ int getMaximumCharacterLimit() {+ return maximumCharacterLimit;}// keeps the caret from automatically scrolling to the bottom@@ -142,13 +139,17 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListener}}- private void doAddMessage(MessageWrapper messageWrapper) {- messageList.add(messageWrapper);- updateManager.update();- if (queuedMessageCount++ > QUEUED_MESSAGE_LIMIT) {- queuedMessageCount = 0;- Thread.yield();+ private void doAddMessage(MessageWrapper newMessage) {+ synchronized (messageList) {+ if ( !messageList.isEmpty() ) {+ MessageWrapper lastMessage = messageList.getLast();+ if (lastMessage.merge(newMessage)) {+ return;+ }+ }+ messageList.add(newMessage);}+ updateManager.update();}@Override@@ -171,21 +172,31 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListenerStyledDocument styledDocument = (StyledDocument) document;int length = document.getLength();- for (int i = 0; i < length; i++) {+ for (int i = 0; i < length;) {Element element = styledDocument.getCharacterElement(i);- AttributeSet attributes = element.getAttributes();+ int elementStart = i;+ int elementLen = element.getEndOffset() - elementStart;+ i = element.getEndOffset();++ // get the name of the old AttributeSet and use that to pick the new live+ // AttributeSet that was updated.+ AttributeSet replacementAttributeSet = getAttributeSetByName(+ (String) element.getAttributes().getAttribute(CUSTOM_ATTRIBUTE_KEY));+ styledDocument.setCharacterAttributes(elementStart, elementLen, replacementAttributeSet,+ true);+ }+ }- Object attribute = attributes.getAttribute(CUSTOM_ATTRIBUTE_KEY);- if (OUTPUT_ATTRIBUTE_VALUE.equals(attribute)) {- styledDocument.setCharacterAttributes(i, 1, outputAttributeSet, true);- }- else if (ERROR_ATTRIBUTE_VALUE.equals(attribute)) {- styledDocument.setCharacterAttributes(i, 1, errorAttributeSet, true);- }- else {- // we found an attribute type that we do not know about- throw new AssertException("Unexpected attribute type for text");- }+ private AttributeSet getAttributeSetByName(String attributeSetName) {+ if (OUTPUT_ATTRIBUTE_VALUE.equals(attributeSetName)) {+ return outputAttributeSet;+ }+ else if (ERROR_ATTRIBUTE_VALUE.equals(attributeSetName)) {+ return errorAttributeSet;+ }+ else {+ // we found an attribute type that we do not know about+ throw new AssertException("Unexpected attribute type for text");}}@@ -211,72 +222,61 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListenererrorAttributeSet.addAttribute(StyleConstants.Foreground, Color.RED);}- private void insertString(String message, AttributeSet attributeSet) {- Document document = getDocument();- int offset = document.getLength();-- try {- document.insertString(offset, message, attributeSet);+ private void doUpdate() {+ long stopMS = System.currentTimeMillis() + MAX_UPDATE_INTERVAL_MS;++ // track the caret manually because removing the text where the caret is located+ // will reset the caret position to 0, even with the update police NEVER_UPDATE.+ int caretPos = getCaretPosition();+ boolean caretInvalidated = false;+ synchronized (messageList) {+ // Holding the sync lock on the messageList will block the thread producing+ // messages while we clear the queue. This is desirable to throttle a run-away+ // GhidraScript.+ while (!messageList.isEmpty() && (System.currentTimeMillis() < stopMS)) {+ MessageWrapper msg = messageList.removeFirst();+ caretInvalidated |= appendString(msg.getMessage(), msg.getAttributes());+ }+ if (!messageList.isEmpty()) {+ updateManager.updateLater();+ }}- catch (BadLocationException e) {- Msg.debug(this, "Unexpected exception updating text", e);+ if (!scrollLock || caretInvalidated) {+ // manually set the caret position because it was+ // 1) invalidated (even though scroll lock was true), or+ // 2) is tracking the bottom of the console (normal mode)+ int newDocLen = getDocument().getLength();+ setCaretPosition(scrollLock ? Math.min(caretPos, newDocLen) : newDocLen);}}- private void doUpdate() {- for (int i = 0; !messageList.isEmpty(); i++) {- MessageWrapper messageWrapper = messageList.remove(0);- String message = messageWrapper.getMessage();- insertString(message, messageWrapper.getAttributes());-- validateCapacity();+ private boolean appendString(CharSequence message, AttributeSet attributeSet) {- notifyListener(messageWrapper);-- if (i % 1000 == 0) { // force a repaint if we do a large volume of work- paintImmediately(getBounds());- }+ // cap message size before update+ if (message.length() > maximumCharacterLimit) {+ int delta = message.length() - maximumCharacterLimit;+ message = message.subSequence(delta, message.length());}- updateView();- }-- private void notifyListener(MessageWrapper messageWrapper) {- if (listener != null) {- if (messageWrapper.isDoNewline()) {- listener.putln(messageWrapper.getMessage(),- (messageWrapper instanceof ErrorMessage));- }- else {- listener.put(messageWrapper.getMessage(), (messageWrapper instanceof ErrorMessage));+ try {+ Document document = getDocument();+ int overage = document.getLength() + message.length() - maximumCharacterLimit;+ if (overage <= 0) {+ document.insertString(document.getLength(), message.toString(), attributeSet);+ return false;}- }- }- private void updateView() {- if (scrollLock) {- return;+ // trim the excess text that will result when inserting the new message+ int truncationAmount = (int) (maximumCharacterLimit * truncationFactor);+ int docToTrim = Math.min(overage + truncationAmount, document.getLength());+ int caretPos = getCaretPosition();+ document.remove(0, docToTrim);+ document.insertString(document.getLength(), message.toString(), attributeSet);+ return caretPos < docToTrim;}-- Document doc = getDocument();- int length = doc.getLength();- setCaretPosition(length);- }-- private void validateCapacity() {- Document doc = getDocument();- int length = doc.getLength();- if (length > maximumCharacterLimit) {- // we need to account for any accumulation over our limit when deciding how much- // text to remove- int overage = length - maximumCharacterLimit;- int totalToTrim = overage + truncationAmount;- try {- doc.remove(0, totalToTrim);- }- catch (BadLocationException e) {- Msg.debug(this, "Unexpected exception updating text", e);- }+ catch (BadLocationException e) {+ Msg.debug(this, "Unexpected exception updating text", e);+ return false;}}@@ -289,23 +289,25 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListener//==================================================================================================private static class MessageWrapper {- private final String message;- private final boolean doNewline;+ private final StringBuilder message;- private MessageWrapper(String message, boolean doNewline) {+ private MessageWrapper(String message) {if (message == null) {throw new AssertException("Attempted to log a null message.");}- this.message = message;- this.doNewline = doNewline;+ this.message = new StringBuilder(message);}- public boolean isDoNewline() {- return doNewline;+ CharSequence getMessage() {+ return message;}- String getMessage() {- return message;+ boolean merge(MessageWrapper other) {+ if (getClass() != other.getClass()) {+ return false;+ }+ message.append(other.message);+ return true;}AttributeSet getAttributes() {@@ -314,8 +316,8 @@ public class ConsoleTextPane extends JTextPane implements OptionsChangeListener}private static class ErrorMessage extends MessageWrapper {- private ErrorMessage(String message, boolean doNewline) {- super(message, doNewline);+ private ErrorMessage(String message) {+ super(message);}@Overridediff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/framework/main/ConsoleTextPaneTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/framework/main/ConsoleTextPaneTest.javaindex 474c0daacd..69e4c55f19 100644--- a/Ghidra/Features/Base/src/test.slow/java/ghidra/framework/main/ConsoleTextPaneTest.java+++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/framework/main/ConsoleTextPaneTest.java@@ -15,7 +15,7 @@*/package ghidra.framework.main;-import static org.junit.Assert.assertEquals;+import static org.junit.Assert.*;import java.util.function.Supplier;@@ -133,8 +133,11 @@ public class ConsoleTextPaneTest {private void printEnoughLinesToOverflowTheMaxCharCount(ConsoleTextPane text) {AbstractGenericTest.runSwing(() -> {- for (int i = 0; i < 20; i++) {- text.addMessage("Run " + runNumber + " - line " + (i + 1) + '\n');+ int charsWritten = 0;+ for (int i = 0; charsWritten < text.getMaximumCharacterLimit(); i++) {+ String msg = "Run " + runNumber + " - line " + (i + 1) + '\n';+ charsWritten += msg.length();+ text.addMessage(msg);}});