Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-3945 TokenIterator and brace highlighting

caheckman0a1b1ed76b6c
diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangToken.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangToken.java
index 1018864087..042ae6392c 100644
--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangToken.java
+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangToken.java
@@ -19,6 +19,7 @@ import static ghidra.program.model.pcode.AttributeId.*;
import static ghidra.program.model.pcode.ElementId.*;
import java.awt.Color;
+import java.util.Iterator;
import java.util.List;
//import ghidra.app.plugin.core.decompile.*;
@@ -319,4 +320,14 @@ public class ClangToken implements ClangNode {
public PcodeOp getPcodeOp() {
return null;
}
+
+ /**
+ * Get an iterator over tokens starting with this ClangToken. Tokens are returned in normal
+ * display order (forward=true) or in the reverse of normal display order (forward=false)
+ * @param forward is true for forward iterator, false for a backward iterator
+ * @return the Iterator object
+ */
+ public Iterator<ClangToken> iterator(boolean forward) {
+ return new TokenIterator(this, forward);
+ }
}
diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangTokenGroup.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangTokenGroup.java
index c796dd4e58..aa22cc498a 100644
--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangTokenGroup.java
+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/ClangTokenGroup.java
@@ -191,6 +191,17 @@ public class ClangTokenGroup implements ClangNode, Iterable<ClangNode> {
return tokgroup.iterator();
}
+ /**
+ * Create iterator across all ClangToken objects in this group.
+ * The iterator will run over tokens in display order (forward=true) or in reverse of
+ * display order (forward=false)
+ * @param forward is true for a forward iterator, false for a backward iterator
+ * @return the iterator
+ */
+ public Iterator<ClangToken> tokenIterator(boolean forward) {
+ return new TokenIterator(this, forward);
+ }
+
/**
* Gets a stream over this group's children
* @return a stream of this group's children
diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/TokenIterator.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/TokenIterator.java
new file mode 100644
index 0000000000..aa4b1717cd
--- /dev/null
+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/TokenIterator.java
@@ -0,0 +1,192 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.decompiler;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+/**
+ * An iterator over ClangToken objects. The iterator walks a tree of ClangNode objects based on
+ * the Parent() and Child() methods, returning successive ClangNode leaf objects that are also
+ * ClangToken objects. The iterator can run either forward or backward over the tokens.
+ *
+ * The constructor TokenIterator(ClangToken,int) initializes the iterator to start at the given
+ * token, which can be in the middle of the sequence.
+ */
+public class TokenIterator implements Iterator<ClangToken> {
+
+ private ClangTokenGroup[] nodeStack; // Ancestry of current ClangToken
+ private ClangToken currentToken; // Current ClangToken
+ private int[] indexStack; // Indices into ClangTokenGroup
+ private int depth; // Depth of current token
+ private int direction; // -1 = iterating backward 1 = iterating forward
+
+ /**
+ * Expand the arrays holding the node stack so that at least one more ClangNode can be added
+ */
+ private void expand() {
+ int size = (nodeStack.length < 256) ? nodeStack.length * 2 : nodeStack.length + 512;
+ ClangTokenGroup[] newNodeStack = new ClangTokenGroup[size];
+ int[] newIndexStack = new int[size];
+ System.arraycopy(nodeStack, 0, newNodeStack, 0, nodeStack.length);
+ System.arraycopy(indexStack, 0, newIndexStack, 0, indexStack.length);
+ nodeStack = newNodeStack;
+ indexStack = newIndexStack;
+ }
+
+ /**
+ * Add a new ClangTokenGroup to the node stack
+ * @param group is the new group being pushed
+ */
+ private void pushGroup(ClangTokenGroup group) {
+ depth += 1;
+ if (depth >= nodeStack.length) {
+ expand();
+ }
+ nodeStack[depth] = group;
+ indexStack[depth] = (direction < 0) ? group.numChildren() - 1 : 0;
+ }
+
+ /**
+ * Backtrack until:
+ * - all indices indicate a proper child for their respective token group
+ * Then push forward until:
+ * - the active node at the current depth is a ClangToken
+ */
+ private void normalize() {
+ int index = indexStack[depth];
+ if (index < 0) {
+ depth -= 1;
+ if (depth < 0) {
+ currentToken = null;
+ return;
+ }
+ indexStack[depth] -= 1;
+ normalize();
+ return;
+ }
+ ClangTokenGroup group = nodeStack[depth];
+ if (index >= group.numChildren()) {
+ depth -= 1;
+ if (depth < 0) {
+ currentToken = null;
+ return;
+ }
+ indexStack[depth] += 1;
+ normalize();
+ return;
+ }
+ ClangNode node = group.Child(index);
+ if (node instanceof ClangToken) {
+ currentToken = (ClangToken) node;
+ return;
+ }
+ pushGroup((ClangTokenGroup) node);
+ normalize();
+ }
+
+ /**
+ * Update the node stack so that it points to the next ClangToken. The next token is either
+ * the predecessor or the successor depending on the direction setting (-1 or 1) respectively.
+ * currentToken is set to the next token. If there is no next token, currentToken is set to null.
+ */
+ private void advanceToken() {
+ if (currentToken == null) {
+ return;
+ }
+ indexStack[depth] += direction;
+ normalize();
+ }
+
+ private static int findIndex(ClangNode group, ClangNode node) {
+ for (int i = 0; i < group.numChildren(); ++i) {
+ if (group.Child(i) == node) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Initialize an iterator to a point to a specific ClangToken, which may be anywhere in the sequence.
+ * @param token is the specific ClangToken
+ * @param forward is true for a forward iterator, false for a backward iterator
+ */
+ public TokenIterator(ClangToken token, boolean forward) {
+ ArrayList<ClangTokenGroup> groupList = new ArrayList<>();
+ ClangNode node = token.Parent();
+ while (node != null) {
+ groupList.add((ClangTokenGroup) node);
+ node = node.Parent();
+ }
+ nodeStack = new ClangTokenGroup[groupList.size()];
+ indexStack = new int[groupList.size()];
+ node = token;
+ for (int i = 0; i < nodeStack.length; ++i) {
+ ClangTokenGroup group = groupList.get(i);
+ nodeStack[nodeStack.length - 1 - i] = group;
+ indexStack[nodeStack.length - 1 - i] = findIndex(group, node);
+ node = group;
+ }
+ currentToken = token;
+ direction = forward ? 1 : -1;
+ depth = nodeStack.length - 1;
+ }
+
+ /**
+ * Create iterator across all tokens under the given ClangTokenGroup. The iterator will walk the
+ * entire tree of token groups under the given group. The iterator will run over tokens in display
+ * order (forward=true) or in reverse of display order (forward=false)
+ * @param group is the given ClangTokenGroup
+ * @param forward is true for a forward iterator, false for a backward iterator
+ */
+ public TokenIterator(ClangTokenGroup group, boolean forward) {
+ ArrayList<ClangTokenGroup> groupList = new ArrayList<>();
+ ClangNode node = group;
+ while (node instanceof ClangTokenGroup) {
+ ClangTokenGroup curGroup = (ClangTokenGroup) node;
+ groupList.add(curGroup);
+ if (forward) {
+ node = curGroup.Child(0);
+ }
+ else {
+ node = curGroup.Child(curGroup.numChildren() - 1);
+ }
+ }
+ nodeStack = new ClangTokenGroup[groupList.size()];
+ indexStack = new int[groupList.size()];
+ groupList.toArray(nodeStack);
+ for (int i = 0; i < indexStack.length; ++i) {
+ indexStack[i] = forward ? 0 : nodeStack[i].numChildren() - 1;
+ }
+ currentToken = (ClangToken) node;
+ direction = forward ? 1 : -1;
+ depth = nodeStack.length - 1;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return (currentToken != null);
+ }
+
+ @Override
+ public ClangToken next() {
+ ClangToken res = currentToken;
+ advanceToken();
+ return res;
+ }
+
+}
diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/component/DecompilerUtils.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/component/DecompilerUtils.java
index 59ddfc767c..11d586c87b 100644
--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/component/DecompilerUtils.java
+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/component/DecompilerUtils.java
@@ -579,119 +579,64 @@ public class DecompilerUtils {
*/
public static ClangSyntaxToken getNextBrace(ClangToken startToken, boolean forward) {
- ClangNode parent = startToken.Parent();
- List<ClangNode> list = new ArrayList<>();
-
- ClangNode node = parent;
- while (node != null) {
- parent = node;
- node = node.Parent();
- }
-
- parent.flatten(list);
-
- String desiredBrace = "}"; // going down/forward, look for the containing closing brace
- if (!forward) {
- desiredBrace = "{"; // going up/backward, look for the containing closing brace
- Collections.reverse(list);
- }
-
- ClangSyntaxToken brace = moveToNextBrace(startToken, list, desiredBrace, forward);
- return brace;
- }
-
- private static ClangSyntaxToken moveToNextBrace(ClangToken startToken, List<ClangNode> list,
- String targetBrace, boolean forward) {
-
- int balance = 0;
- int index = list.indexOf(startToken);
- int start = index + 1;
- for (int i = start; i < list.size(); i++) {
-
- ClangToken token = (ClangToken) list.get(i);
- if (!(token instanceof ClangSyntaxToken)) {
- continue;
- }
-
- ClangSyntaxToken syntaxToken = (ClangSyntaxToken) token;
- if (!isBrace(syntaxToken)) {
- continue;
- }
-
- String nextBrace = syntaxToken.getText();
- if (!targetBrace.equals(nextBrace)) { // opposite brace
- balance++;
- continue;
- }
-
- // matching brace; see if it is balanced
- if (balance == 0) {
- return syntaxToken; // found an unmatched brace of the type we are seeking
+ int targetBalance = forward ? -1 : 1;
+ Iterator<ClangToken> iter = startToken.iterator(forward);
+ iter.next(); // skip the token itself;
+ int nestLevel = 0;
+ while (iter.hasNext()) {
+ ClangToken token = iter.next();
+ if (token instanceof ClangSyntaxToken) {
+ String text = token.getText();
+ if (text.equals("{")) {
+ nestLevel += 1;
+ if (nestLevel == targetBalance) {
+ return (ClangSyntaxToken) token;
+ }
+ }
+ else if (text.equals("}")) {
+ nestLevel -= 1;
+ if (nestLevel == targetBalance) {
+ return (ClangSyntaxToken) token;
+ }
+ }
}
- balance--;
}
-
return null;
}
+ /**
+ * Find the matching brace, '{' or '}', for the given brace token, taking into account brace nesting.
+ * For an open brace, search forward to find the corresponding close brace.
+ * For a close brace, search backward to find the corresponding open brace.
+ * @param startToken is the given brace token
+ * @return the match brace token or null if there is no match
+ */
public static ClangSyntaxToken getMatchingBrace(ClangSyntaxToken startToken) {
- ClangNode parent = startToken.Parent();
- List<ClangNode> list = new ArrayList<>();
- parent.flatten(list);
-
- String text = startToken.getText();
- boolean forward = "}".equals(text);
- if (!forward) {
- Collections.reverse(list);
- }
-
- Stack<ClangSyntaxToken> braceStack = new Stack<>();
- for (ClangNode element : list) {
- ClangToken token = (ClangToken) element;
- if (!(token instanceof ClangSyntaxToken)) {
- continue;
- }
-
- ClangSyntaxToken syntaxToken = (ClangSyntaxToken) token;
- if (startToken == syntaxToken) {
-
- if (braceStack.isEmpty()) {
- return null; // this can happen if the start token has a bad parent values
+ boolean direction = "{".equals(startToken.getText());
+ Iterator<ClangToken> iter = startToken.iterator(direction);
+ int nestLevel = 0;
+ while (iter.hasNext()) {
+ ClangToken token = iter.next();
+ if (token instanceof ClangSyntaxToken) {
+ String text = token.getText();
+ if (text.equals("{")) {
+ nestLevel += 1;
+ if (nestLevel == 0) {
+ return (ClangSyntaxToken) token;
+ }
+ }
+ else if (text.equals("}")) {
+ nestLevel -= 1;
+ if (nestLevel == 0) {
+ return (ClangSyntaxToken) token;
+ }
}
-
- // found our starting token, take the current value on the stack
- ClangSyntaxToken matchingBrace = braceStack.pop();
- return matchingBrace;
- }
-
- if (!isBrace(syntaxToken)) {
- continue;
- }
-
- if (braceStack.isEmpty()) {
- braceStack.push(syntaxToken);
- continue;
- }
-
- ClangSyntaxToken lastToken = braceStack.peek();
- if (isMatchingBrace(lastToken, syntaxToken)) {
- braceStack.pop();
- }
- else {
- braceStack.push(syntaxToken);
}
}
return null;
}
- public static boolean isMatchingBrace(ClangSyntaxToken braceToken,
- ClangSyntaxToken otherBraceToken) {
- String brace = braceToken.getText();
- String otherBrace = otherBraceToken.getText();
- return !brace.equals(otherBrace);
- }
-
public static boolean isBrace(ClangToken token) {
String text = token.getText();
return "{".equals(text) || "}".equals(text);