GP-5742 Cleanup preferred CommentType enum use. Changed SARIF data component comment JSON serialization from int to String.

This commit is contained in:
ghidra1
2025-06-06 17:58:07 -04:00
parent 4a65e9af3b
commit 8c441250f5
211 changed files with 4627 additions and 4860 deletions
@@ -26,7 +26,7 @@ import ghidra.app.services.DebuggerTraceManagerService;
import ghidra.program.model.address.*;
import ghidra.program.model.data.PointerDataType;
import ghidra.program.model.lang.*;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.util.CodeUnitInsertionException;
@@ -236,8 +236,7 @@ public class PopulateDemoTrace extends GhidraScript {
return;
}
TraceCodeSpace code =
thread.getTrace().getCodeManager().getCodeRegisterSpace(thread, true);
TraceCodeSpace code = thread.getTrace().getCodeManager().getCodeRegisterSpace(thread, true);
code.definedUnits().clear(Lifespan.nowOn(tick), reg, TaskMonitor.DUMMY);
code.definedData().create(Lifespan.nowOn(tick), reg, PointerDataType.dataType);
}
@@ -344,20 +343,16 @@ public class PopulateDemoTrace extends GhidraScript {
*/
mainLabel = trace.getSymbolManager()
.labels()
.create(snap, null, addr(0x00400000),
"main", global, SourceType.USER_DEFINED);
.create(snap, null, addr(0x00400000), "main", global, SourceType.USER_DEFINED);
cloneLabel = trace.getSymbolManager()
.labels()
.create(snap, null, addr(0x00400060),
"clone", global, SourceType.USER_DEFINED);
.create(snap, null, addr(0x00400060), "clone", global, SourceType.USER_DEFINED);
childLabel = trace.getSymbolManager()
.labels()
.create(snap, null, addr(0x00400034),
"child", global, SourceType.USER_DEFINED);
.create(snap, null, addr(0x00400034), "child", global, SourceType.USER_DEFINED);
exitLabel = trace.getSymbolManager()
.labels()
.create(snap, null, addr(0x00400061),
"exit", global, SourceType.USER_DEFINED);
.create(snap, null, addr(0x00400061), "exit", global, SourceType.USER_DEFINED);
/**
* Note the use of getProgramView as a means of using components intended for Program
@@ -409,8 +404,7 @@ public class PopulateDemoTrace extends GhidraScript {
trace.getCodeManager()
.codeUnits()
.getAt(0, cloneLabel.getAddress())
.setComment(
CodeUnit.EOL_COMMENT, "Pretend this is a syscall");
.setComment(CommentType.EOL, "Pretend this is a syscall");
/**
* Stub out "exit"
@@ -419,8 +413,7 @@ public class PopulateDemoTrace extends GhidraScript {
trace.getCodeManager()
.codeUnits()
.getAt(0, exitLabel.getAddress())
.setComment(
CodeUnit.EOL_COMMENT, "Pretend this is a syscall");
.setComment(CommentType.EOL, "Pretend this is a syscall");
/**
* "Launch" the program by initializing RIP and RSP of the main thread
@@ -504,10 +497,10 @@ public class PopulateDemoTrace extends GhidraScript {
regs2.putBytes(snap, reg("RSP"),
buf.clear().putLong(STACK2_BOTTOM + stack2offset).flip());
regs2.putBytes(snap, reg("RAX"), buf.clear().putLong(1).flip());
memory.putBytes(snap, addr(STACK2_BOTTOM + stack2offset), buf.clear()
.putLong(
mainInstructions.get(pc2 = pc1).getAddress().getOffset())
.flip());
memory.putBytes(snap, addr(STACK2_BOTTOM + stack2offset),
buf.clear()
.putLong(mainInstructions.get(pc2 = pc1).getAddress().getOffset())
.flip());
placeRegUnits(snap, thread1);
placeRegUnits(snap, thread2);
@@ -309,12 +309,11 @@ public class DebuggerCopyPlan {
long off = addr.subtract(fromRange.getMinAddress());
Address dest = intoAddress.add(off);
// Ugly, but there's not MAX/MIN_COMMENT_TYPE
for (int i = CodeUnit.EOL_COMMENT; i <= CodeUnit.REPEATABLE_COMMENT; i++) {
String comment = fromListing.getComment(i, addr);
if (comment == null) {
continue;
for (CommentType type : CommentType.values()) {
String comment = fromListing.getComment(type, addr);
if (comment != null) {
intoListing.setComment(dest, type, comment);
}
intoListing.setComment(dest, i, comment);
}
}
}
@@ -144,16 +144,14 @@ public class AnalysisUnwoundFrame<T> extends AbstractUnwoundFrame<T> {
info.mapSavedRegisters(base, registerMap);
Address pcVal = info.computeNextPc(base, state, codeSpace, pc);
Address spVal = info.computeNextSp(base);
return unwinder.unwind(coordinates, level + 1, pcVal, spVal, state, registerMap,
monitor);
return unwinder.unwind(coordinates, level + 1, pcVal, spVal, state, registerMap, monitor);
}
@Override
protected Address applyBase(long offset) {
if (base == null) {
throw new UnwindException(
"Cannot compute stack address for offset %d.\nFrame error: %s".formatted(offset,
info.error().getMessage()),
throw new UnwindException("Cannot compute stack address for offset %d.\nFrame error: %s"
.formatted(offset, info.error().getMessage()),
info.error());
}
return base.add(offset);
@@ -191,8 +189,7 @@ public class AnalysisUnwoundFrame<T> extends AbstractUnwoundFrame<T> {
@Override
public String getDescription() {
return String.format("%s %s pc=%s sp=%s base=%s",
level, info.function(),
return String.format("%s %s pc=%s sp=%s base=%s", level, info.function(),
pcVal == null ? null : pcVal.toString(false),
spVal == null ? null : spVal.toString(false),
base == null ? null : base.toString(false));
@@ -353,7 +350,7 @@ public class AnalysisUnwoundFrame<T> extends AbstractUnwoundFrame<T> {
TraceData frame = trace.getCodeManager()
.definedData()
.create(span, spPlusParams, platform, structure);
frame.setComment(CodeUnit.PRE_COMMENT, getDescription());
frame.setComment(CommentType.PRE, getDescription());
TraceReferenceManager refs = trace.getReferenceManager();
refs.clearReferencesFrom(span, frame.getRange());
refs.clearReferencesTo(span, frame.getRange());
@@ -4,9 +4,9 @@
* 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.
@@ -95,7 +95,7 @@ public class ListingUnwoundFrame extends AbstractUnwoundFrame<WatchValue> {
*/
private static Integer getLevel(TraceData data) {
// TODO: Should this go into a property instead?
String comment = data.getComment(CodeUnit.PRE_COMMENT);
String comment = data.getComment(CommentType.PRE);
if (comment == null) {
return null;
}
@@ -213,7 +213,7 @@ public class ListingUnwoundFrame extends AbstractUnwoundFrame<WatchValue> {
@Override
public String getDescription() {
return frame.getComment(CodeUnit.PRE_COMMENT);
return frame.getComment(CommentType.PRE);
}
@Override
@@ -4,9 +4,9 @@
* 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.
@@ -76,8 +76,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
r.nextBytes(src);
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
memory.putBytes(0, tb.addr(0x55550000), ByteBuffer.wrap(src));
}
@@ -108,8 +108,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
memory.putBytes(0, tb.addr(0x55550000), ByteBuffer.allocate(4096));
memory.setState(0, tb.addr(0x55551000), TraceMemoryState.ERROR);
}
@@ -126,11 +126,9 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
IntRangeMap map =
program.getIntRangeMap(PropertyBasedBackgroundColorModel.COLOR_PROPERTY_NAME);
AddressSet staleSet =
map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_STALE.getRGB());
AddressSet staleSet = map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_STALE.getRGB());
assertEquals(tb.set(tb.range(stSpace, 0x00401001, 0x0040ffff)), staleSet);
AddressSet errorSet =
map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_ERROR.getRGB());
AddressSet errorSet = map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_ERROR.getRGB());
assertEquals(tb.set(tb.range(stSpace, 0x00401000, 0x00401000)), errorSet);
}
@@ -186,10 +184,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, trng, TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
InstructionIterator iit = asm.assemble(tb.addr(0x55550000),
"imm r0, #123",
"imm r1, #234",
"add r0, r1");
InstructionIterator iit =
asm.assemble(tb.addr(0x55550000), "imm r0, #123", "imm r1, #234", "add r0, r1");
assertTrue(iit.hasNext());
}
@@ -234,10 +230,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, trng, TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
InstructionIterator iit = asm.assemble(tb.addr(0x55550000),
"MOV RAX, 1234",
"MOV RCX, 2345",
"ADD RAX, RCX");
InstructionIterator iit =
asm.assemble(tb.addr(0x55550000), "MOV RAX, 1234", "MOV RCX, 2345", "ADD RAX, RCX");
assertTrue(iit.hasNext());
}
@@ -299,8 +293,7 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
"ADD EAX, ECX");
checkCtx = iit.next();
*/
memory.putBytes(0, tb.addr(0x55550000), tb.buf(
0xb8, 0xd2, 0x04, 0x00, 0x00, // MOV EAX,1234
memory.putBytes(0, tb.addr(0x55550000), tb.buf(0xb8, 0xd2, 0x04, 0x00, 0x00, // MOV EAX,1234
0xb9, 0x29, 0x09, 0x00, 0x00, // MOV ECX,2345
0x01, 0xc8 // ADD EAX,ECX
));
@@ -487,8 +480,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
DBTraceNamespaceSymbol global = tb.trace.getSymbolManager().getGlobalNamespace();
DBTraceLabelSymbolView labels = tb.trace.getSymbolManager().labels();
@@ -558,8 +551,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
DBTraceBreakpointManager breakpoints = tb.trace.getBreakpointManager();
breakpoints.placeBreakpoint("[1]", 0, tb.addr(0x55550123), List.of(),
@@ -571,8 +564,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) {
program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000,
(byte) 0, TaskMonitor.DUMMY, false);
.createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
false);
// Set up a collision. This is normal with relocations
program.getBookmarkManager()
.setBookmark(tb.addr(stSpace, 0x55550123), "BreakpointDisabled", "SW_EXECUTE;1",
@@ -611,8 +604,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
BookmarkManager bookmarks = view.getBookmarkManager();
bookmarks.defineType("TestType", DebuggerResources.ICON_DEBUGGER, Palette.BLUE, 1);
@@ -622,8 +615,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) {
program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000,
(byte) 0, TaskMonitor.DUMMY, false);
.createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
false);
AllCopiers.BOOKMARKS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr,
TaskMonitor.DUMMY);
@@ -659,27 +652,27 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".data", 0, tb.range(0x55560000, 0x5556ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.WRITE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
memory.createRegion(".data", 0, tb.range(0x55560000, 0x5556ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.WRITE);
ReferenceManager references = view.getReferenceManager();
references.addMemoryReference(tb.addr(0x55550123),
tb.addr(0x55550321), RefType.COMPUTED_CALL, SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55550123),
tb.addr(0x55560321), RefType.READ, SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55560123),
tb.addr(0x55550321), RefType.PARAM, SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55560123),
tb.addr(0x55560321), RefType.DATA, SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55550123), tb.addr(0x55550321),
RefType.COMPUTED_CALL, SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55550123), tb.addr(0x55560321), RefType.READ,
SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55560123), tb.addr(0x55550321), RefType.PARAM,
SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55560123), tb.addr(0x55560321), RefType.DATA,
SourceType.USER_DEFINED, -1);
}
Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) {
program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000,
(byte) 0, TaskMonitor.DUMMY, false);
.createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
false);
AllCopiers.REFERENCES.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr,
TaskMonitor.DUMMY);
@@ -710,19 +703,19 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff),
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.EXECUTE);
Listing listing = view.getListing();
listing.setComment(tb.addr(0x55550123), CodeUnit.EOL_COMMENT, "Test EOL Comment");
listing.setComment(tb.addr(0x55550321), CodeUnit.PLATE_COMMENT, "Test Plate Comment");
listing.setComment(tb.addr(0x55550123), CommentType.EOL, "Test EOL Comment");
listing.setComment(tb.addr(0x55550321), CommentType.PLATE, "Test Plate Comment");
}
Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) {
program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000,
(byte) 0, TaskMonitor.DUMMY, false);
.createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
false);
AllCopiers.COMMENTS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr,
TaskMonitor.DUMMY);
@@ -735,8 +728,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
assertEquals(Set.of(tb.addr(stSpace, 0x55550123), tb.addr(stSpace, 0x55550321)), addresses);
assertEquals("Test EOL Comment",
listing.getComment(CodeUnit.EOL_COMMENT, tb.addr(stSpace, 0x55550123)));
listing.getComment(CommentType.EOL, tb.addr(stSpace, 0x55550123)));
assertEquals("Test Plate Comment",
listing.getComment(CodeUnit.PLATE_COMMENT, tb.addr(stSpace, 0x55550321)));
listing.getComment(CommentType.PLATE, tb.addr(stSpace, 0x55550321)));
}
}
@@ -15,7 +15,7 @@
*/
package ghidra.trace.database.listing;
import static ghidra.lifecycle.Unfinished.TODO;
import static ghidra.lifecycle.Unfinished.*;
import java.nio.ByteBuffer;
import java.util.*;
@@ -27,6 +27,7 @@ import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRangeImpl;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.mem.*;
import ghidra.program.model.symbol.*;
import ghidra.trace.database.DBTrace;
@@ -128,9 +129,8 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override
default <T> T getProperty(String name, Class<T> valueClass) {
try (LockHold hold = LockHold.lock(getTrace().getReadWriteLock().readLock())) {
TracePropertyMap<? extends T> map =
getTrace().getInternalAddressPropertyManager()
.getPropertyMapExtends(name, valueClass);
TracePropertyMap<? extends T> map = getTrace().getInternalAddressPropertyManager()
.getPropertyMapExtends(name, valueClass);
if (map == null) {
return null;
}
@@ -250,17 +250,16 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
}
@Override
default void setComment(int commentType, String comment) {
default void setComment(CommentType commentType, String comment) {
if (getThread() != null) {
TODO(); // TODO: Comments in register space
}
getTrace().getCommentAdapter()
.setComment(getLifespan(), getAddress(), commentType,
comment);
.setComment(getLifespan(), getAddress(), commentType, comment);
}
@Override
default String getComment(int commentType) {
default String getComment(CommentType commentType) {
if (getThread() != null) {
// TODO: Comments in register space
return null;
@@ -269,12 +268,12 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
}
@Override
default void setCommentAsArray(int commentType, String[] comment) {
default void setCommentAsArray(CommentType commentType, String[] comment) {
setComment(commentType, DBTraceCommentAdapter.commentFromArray(comment));
}
@Override
default String[] getCommentAsArray(int commentType) {
default String[] getCommentAsArray(CommentType commentType) {
return DBTraceCommentAdapter.arrayFromComment(getComment(commentType));
}
@@ -297,16 +296,15 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override
default void addMnemonicReference(Address refAddr, RefType refType, SourceType sourceType) {
getTrace().getReferenceManager()
.addMemoryReference(getLifespan(), getAddress(), refAddr,
refType, sourceType, MNEMONIC);
.addMemoryReference(getLifespan(), getAddress(), refAddr, refType, sourceType,
MNEMONIC);
}
@Override
default void addOperandReference(int index, Address refAddr, RefType type,
SourceType sourceType) {
getTrace().getReferenceManager()
.addMemoryReference(getLifespan(), getAddress(), refAddr,
type, sourceType, index);
.addMemoryReference(getLifespan(), getAddress(), refAddr, type, sourceType, index);
}
@Override
@@ -319,16 +317,16 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
default void setStackReference(int opIndex, int offset, SourceType sourceType,
RefType refType) {
getTrace().getReferenceManager()
.addStackReference(getLifespan(), getAddress(), offset,
refType, sourceType, opIndex);
.addStackReference(getLifespan(), getAddress(), offset, refType, sourceType,
opIndex);
}
@Override
default void setRegisterReference(int opIndex, Register reg, SourceType sourceType,
RefType refType) {
getTrace().getReferenceManager()
.addRegisterReference(getLifespan(), getAddress(), reg,
refType, sourceType, opIndex);
.addRegisterReference(getLifespan(), getAddress(), reg, refType, sourceType,
opIndex);
}
@Override
@@ -346,8 +344,7 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override
default DBTraceReference getPrimaryReference(int index) {
return getTrace().getReferenceManager()
.getPrimaryReferenceFrom(getStartSnap(), getAddress(),
index);
.getPrimaryReferenceFrom(getStartSnap(), getAddress(), index);
}
@Override
@@ -359,10 +356,9 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override
default ReferenceIterator getReferenceIteratorTo() {
return new ReferenceIteratorAdapter(
getTrace().getReferenceManager()
.getReferencesTo(getStartSnap(), getAddress())
.iterator());
return new ReferenceIteratorAdapter(getTrace().getReferenceManager()
.getReferencesTo(getStartSnap(), getAddress())
.iterator());
}
@Override
@@ -377,9 +373,8 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override
default void removeOperandReference(int index, Address refAddr) {
TraceReference ref =
getTrace().getReferenceManager()
.getReference(getStartSnap(), getAddress(), refAddr, index);
TraceReference ref = getTrace().getReferenceManager()
.getReference(getStartSnap(), getAddress(), refAddr, index);
if (ref == null) {
return;
}
@@ -4,9 +4,9 @@
* 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.
@@ -25,7 +25,7 @@ import db.DBRecord;
import ghidra.framework.data.OpenMode;
import ghidra.program.model.address.*;
import ghidra.program.model.lang.Language;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Listing;
import ghidra.trace.database.DBTrace;
import ghidra.trace.database.DBTraceUtils;
@@ -52,8 +52,6 @@ import ghidra.util.task.TaskMonitor;
public class DBTraceCommentAdapter
extends DBTraceAddressSnapRangePropertyMap<DBTraceCommentEntry, DBTraceCommentEntry> {
protected static final String[] EMPTY_STRING_ARRAY = new String[] {};
protected static final int MIN_COMMENT_TYPE = CodeUnit.EOL_COMMENT;
protected static final int MAX_COMMENT_TYPE = CodeUnit.REPEATABLE_COMMENT;
/**
* A comment entry
@@ -136,15 +134,16 @@ public class DBTraceCommentAdapter
* @param commentType the type of comment as in {@link Listing#setComment(Address, int, String)}
* @param comment the comment
*/
public void setComment(Lifespan lifespan, Address address, int commentType, String comment) {
if (commentType < MIN_COMMENT_TYPE || commentType > MAX_COMMENT_TYPE) {
throw new IllegalArgumentException("commentType");
public void setComment(Lifespan lifespan, Address address, CommentType commentType,
String comment) {
if (commentType == null) {
throw new IllegalArgumentException("null commentType");
}
String oldValue = null;
try (LockHold hold = LockHold.lock(lock.writeLock())) {
for (DBTraceCommentEntry entry : reduce(TraceAddressSnapRangeQuery
.intersecting(new AddressRangeImpl(address, address), lifespan)).values()) {
if (entry.type == commentType) {
if (entry.type == commentType.ordinal()) {
if (entry.getLifespan().contains(lifespan.lmin())) {
oldValue = entry.comment;
}
@@ -153,7 +152,7 @@ public class DBTraceCommentAdapter
}
if (comment != null) {
DBTraceCommentEntry entry = put(address, lifespan, null);
entry.set((byte) commentType, comment);
entry.set((byte) commentType.ordinal(), comment);
}
}
trace.setChanged(new TraceChangeRecord<TraceAddressSnapRange, String>(
@@ -190,11 +189,11 @@ public class DBTraceCommentAdapter
* @param commentType the type of comment
* @return the comment text
*/
public String getComment(long snap, Address address, int commentType) {
public String getComment(long snap, Address address, CommentType commentType) {
try (LockHold hold = LockHold.lock(lock.readLock())) {
for (DBTraceCommentEntry entry : reduce(TraceAddressSnapRangeQuery.at(address, snap))
.values()) {
if (entry.type != commentType) {
if (entry.type != commentType.ordinal()) {
continue;
}
return entry.comment;
@@ -208,13 +207,13 @@ public class DBTraceCommentAdapter
*
* @param span the lifespan fo the box
* @param range the address range of the box
* @param commentType a comment type to clear, or {@link CodeUnit#NO_COMMENT} to clear all.
* @param commentType a comment type to clear, or null to clear all.
*/
public void clearComments(Lifespan span, AddressRange range, int commentType) {
public void clearComments(Lifespan span, AddressRange range, CommentType commentType) {
try (LockHold hold = LockHold.lock(lock.writeLock())) {
for (DBTraceCommentEntry entry : reduce(
TraceAddressSnapRangeQuery.intersecting(range, span)).values()) {
if (commentType == CodeUnit.NO_COMMENT || entry.type == commentType) {
if (commentType == null || entry.type == commentType.ordinal()) {
makeWay(entry, span);
}
}
@@ -145,8 +145,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
protected Comparator<CodeUnit> getUnitComparator(boolean forward) {
return forward
? (u1, u2) -> u1.getMinAddress().compareTo(u2.getMinAddress())
return forward ? (u1, u2) -> u1.getMinAddress().compareTo(u2.getMinAddress())
: (u1, u2) -> -u1.getMinAddress().compareTo(u2.getMinAddress());
}
@@ -160,8 +159,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
protected AddressSet getAddressSet(Address start, boolean forward) {
AddressFactory factory = program.getAddressFactory();
AddressSetView all = program.getAllAddresses();
return forward
? factory.getAddressSet(start, all.getMaxAddress())
return forward ? factory.getAddressSet(start, all.getMaxAddress())
: factory.getAddressSet(all.getMinAddress(), start);
}
@@ -184,8 +182,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
protected Iterator<? extends TraceInstruction> getInstructionIterator(boolean forward) {
return getTopCodeIterator(
s -> codeOperations.instructions().get(s, forward).iterator(), forward);
return getTopCodeIterator(s -> codeOperations.instructions().get(s, forward).iterator(),
forward);
}
protected Iterator<? extends TraceData> getDefinedDataIterator(Address start, boolean forward) {
@@ -195,13 +193,13 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
protected Iterator<? extends TraceData> getDefinedDataIterator(AddressSetView set,
boolean forward) {
return getTopCodeIterator(
s -> codeOperations.definedData().get(s, set, forward).iterator(), forward);
return getTopCodeIterator(s -> codeOperations.definedData().get(s, set, forward).iterator(),
forward);
}
protected Iterator<? extends TraceData> getDefinedDataIterator(boolean forward) {
return getTopCodeIterator(
s -> codeOperations.definedData().get(s, forward).iterator(), forward);
return getTopCodeIterator(s -> codeOperations.definedData().get(s, forward).iterator(),
forward);
}
protected Iterator<? extends TraceCodeUnit> getDefinedUnitIterator(Address start,
@@ -226,8 +224,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
defStart = defUnit.getMinAddress();
}
}
Iterator<AddressRange> defIter = IteratorUtils.transformedIterator(
getDefinedUnitIterator(defStart, forward), u -> u.getRange());
Iterator<AddressRange> defIter = IteratorUtils
.transformedIterator(getDefinedUnitIterator(defStart, forward), u -> u.getRange());
AddressRangeIterator undefIter =
AddressRangeIterators.subtract(set.iterator(forward), defIter, start, forward);
AddressIteratorAdapter undefAddrIter = new AddressIteratorAdapter(undefIter, forward);
@@ -236,8 +234,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
protected AddressRangeIterator getUndefinedRangeIterator(AddressSetView set, boolean forward) {
Iterator<AddressRange> defIter = IteratorUtils.transformedIterator(
getDefinedUnitIterator(set, forward), u -> u.getRange());
Iterator<AddressRange> defIter = IteratorUtils
.transformedIterator(getDefinedUnitIterator(set, forward), u -> u.getRange());
return AddressRangeIterators.subtract(set.iterator(forward), defIter,
forward ? set.getMinAddress() : set.getMaxAddress(), forward);
}
@@ -267,17 +265,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
protected Iterator<TraceCodeUnit> getCodeUnitIterator(AddressSetView set, boolean forward) {
return new MergeSortingIterator<>(List.of(
getDefinedUnitIterator(set, forward),
getUndefinedDataIterator(set, forward)),
return new MergeSortingIterator<>(
List.of(getDefinedUnitIterator(set, forward), getUndefinedDataIterator(set, forward)),
getUnitComparator(forward));
}
protected Iterator<TraceCodeUnit> getCodeUnitIterator(Address start, boolean forward) {
return new MergeSortingIterator<>(List.of(
getDefinedUnitIterator(start, forward),
getUndefinedDataIterator(start, forward)),
getUnitComparator(forward));
return new MergeSortingIterator<>(List.of(getDefinedUnitIterator(start, forward),
getUndefinedDataIterator(start, forward)), getUnitComparator(forward));
}
protected Iterator<TraceCodeUnit> getCodeUnitIterator(boolean forward) {
@@ -286,17 +281,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
protected Iterator<TraceData> getDataIterator(AddressSetView set, boolean forward) {
return new MergeSortingIterator<>(List.of(
getDefinedDataIterator(set, forward),
getUndefinedDataIterator(set, forward)),
return new MergeSortingIterator<>(
List.of(getDefinedDataIterator(set, forward), getUndefinedDataIterator(set, forward)),
getUnitComparator(forward));
}
protected Iterator<TraceData> getDataIterator(Address start, boolean forward) {
return new MergeSortingIterator<>(List.of(
getDefinedDataIterator(start, forward),
getUndefinedDataIterator(start, forward)),
getUnitComparator(forward));
return new MergeSortingIterator<>(List.of(getDefinedDataIterator(start, forward),
getUndefinedDataIterator(start, forward)), getUnitComparator(forward));
}
protected Iterator<TraceData> getDataIterator(boolean forward) {
@@ -355,11 +347,12 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
return new WrappingCodeUnitIterator(Collections.emptyIterator());
}
// TODO: The property map doesn't heed forking.
return new WrappingCodeUnitIterator(NestedIterator.start(
map.getAddressSetView(Lifespan.at(program.snap)).iterator(forward),
rng -> getTopCodeIterator(
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
return new WrappingCodeUnitIterator(
NestedIterator
.start(map.getAddressSetView(Lifespan.at(program.snap)).iterator(forward),
rng -> getTopCodeIterator(
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
}
@Override
@@ -377,11 +370,12 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
return new WrappingCodeUnitIterator(Collections.emptyIterator());
}
// TODO: The property map doesn't heed forking.
return new WrappingCodeUnitIterator(NestedIterator.start(
map.getAddressSetView(Lifespan.at(program.snap)).iterator(addr, forward),
rng -> getTopCodeIterator(
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
return new WrappingCodeUnitIterator(
NestedIterator
.start(map.getAddressSetView(Lifespan.at(program.snap)).iterator(addr, forward),
rng -> getTopCodeIterator(
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
}
@Override
@@ -404,31 +398,30 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
new IntersectionAddressSetView(map.getAddressSetView(Lifespan.at(program.snap)),
addrSet).iterator(forward),
rng -> getTopCodeIterator(
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(), forward)));
}
protected AddressSetView getCommentAddresses(int commentType, AddressSetView addrSet) {
return new IntersectionAddressSetView(addrSet, program.viewport.unionedAddresses(
s -> program.trace.getCommentAdapter()
.getAddressSetView(Lifespan.at(s), e -> e.getType() == commentType)));
protected AddressSetView getCommentAddresses(CommentType commentType, AddressSetView addrSet) {
return new IntersectionAddressSetView(addrSet,
program.viewport.unionedAddresses(s -> program.trace.getCommentAdapter()
.getAddressSetView(Lifespan.at(s), e -> e.getType() == commentType.ordinal())));
}
protected AddressSetView getCommentAddresses(AddressSetView addrSet) {
return new IntersectionAddressSetView(addrSet, program.viewport.unionedAddresses(
s -> program.trace.getCommentAdapter()
.getAddressSetView(Lifespan.at(s))));
s -> program.trace.getCommentAdapter().getAddressSetView(Lifespan.at(s))));
}
@Override
public CodeUnitIterator getCommentCodeUnitIterator(int commentType, AddressSetView addrSet) {
public CodeUnitIterator getCommentCodeUnitIterator(CommentType commentType,
AddressSetView addrSet) {
return new WrappingCodeUnitIterator(
getCodeUnitIterator(getCommentAddresses(commentType, addrSet), true));
}
@Override
public AddressIterator getCommentAddressIterator(int commentType, AddressSetView addrSet,
boolean forward) {
public AddressIterator getCommentAddressIterator(CommentType commentType,
AddressSetView addrSet, boolean forward) {
return getCommentAddresses(commentType, addrSet).getAddresses(forward);
}
@@ -439,13 +432,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
@Override
public long getCommentAddressCount() {
return program.viewport.unionedAddresses(
s -> program.trace.getCommentAdapter().getAddressSetView(Lifespan.at(s)))
return program.viewport
.unionedAddresses(
s -> program.trace.getCommentAdapter().getAddressSetView(Lifespan.at(s)))
.getNumAddresses();
}
@Override
public String getComment(int commentType, Address address) {
public String getComment(CommentType commentType, Address address) {
try (LockHold hold = program.trace.lockRead()) {
return program.viewport.getTop(
s -> program.trace.getCommentAdapter().getComment(s, address, commentType));
@@ -463,10 +457,9 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
@Override
public void setComment(Address address, int commentType, String comment) {
public void setComment(Address address, CommentType commentType, String comment) {
program.trace.getCommentAdapter()
.setComment(Lifespan.nowOn(program.snap), address,
commentType, comment);
.setComment(Lifespan.nowOn(program.snap), address, commentType, comment);
}
@Override
@@ -787,7 +780,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
public void clearComments(Address startAddr, Address endAddr) {
program.trace.getCommentAdapter()
.clearComments(Lifespan.nowOn(program.snap),
new AddressRangeImpl(startAddr, endAddr), CodeUnit.NO_COMMENT);
new AddressRangeImpl(startAddr, endAddr), null);
}
@Override
@@ -957,7 +950,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
}
@Override
public CommentHistory[] getCommentHistory(Address addr, int commentType) {
public CommentHistory[] getCommentHistory(Address addr, CommentType commentType) {
return new CommentHistory[] {};
}
}
@@ -341,7 +341,7 @@ public class DBTraceProgramView implements TraceProgramView {
return;
}
queues.fireEvent(
new CommentChangeRecord(commentType.ordinal(), range.getX1(), oldValue, newValue));
new CommentChangeRecord(commentType, range.getX1(), oldValue, newValue));
}
private void commentEolChanged(TraceAddressSpace space, TraceAddressSnapRange range,
@@ -19,7 +19,7 @@ import java.util.*;
import ghidra.framework.model.EventType;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.trace.database.target.DBTraceObject;
import ghidra.trace.database.target.DBTraceObjectInterface;
import ghidra.trace.model.Lifespan;
@@ -117,9 +117,7 @@ public class DBTraceObjectStackFrame implements TraceObjectStackFrame, DBTraceOb
try (LockHold hold = object.getTrace().lockRead()) {
Address pc = getProgramCounter(snap);
return pc == null ? null
: object.getTrace()
.getCommentAdapter()
.getComment(snap, pc, CodeUnit.EOL_COMMENT);
: object.getTrace().getCommentAdapter().getComment(snap, pc, CommentType.EOL);
}
}
@@ -130,8 +128,8 @@ public class DBTraceObjectStackFrame implements TraceObjectStackFrame, DBTraceOb
TraceObjectValue pcAttr = object.getValue(snap, TraceObjectStackFrame.KEY_PC);
object.getTrace()
.getCommentAdapter()
.setComment(pcAttr.getLifespan(), (Address) pcAttr.getValue(),
CodeUnit.EOL_COMMENT, comment);
.setComment(pcAttr.getLifespan(), (Address) pcAttr.getValue(), CommentType.EOL,
comment);
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -18,7 +18,7 @@ package ghidra.trace.util;
import ghidra.docking.settings.Settings;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.ProgramFragment;
import ghidra.trace.model.Trace;
import ghidra.trace.model.bookmark.TraceBookmark;
@@ -150,13 +150,13 @@ public interface TraceEvents {
* @param commentType the comment type
* @return the event type
*/
static TraceCommentEvent byCommentType(int commentType) {
static TraceCommentEvent byCommentType(CommentType commentType) {
return switch (commentType) {
case CodeUnit.PLATE_COMMENT -> PLATE_COMMENT_CHANGED;
case CodeUnit.PRE_COMMENT -> PRE_COMMENT_CHANGED;
case CodeUnit.POST_COMMENT -> POST_COMMENT_CHANGED;
case CodeUnit.EOL_COMMENT -> EOL_COMMENT_CHANGED;
case CodeUnit.REPEATABLE_COMMENT -> REPEATABLE_COMMENT_CHANGED;
case CommentType.PLATE -> PLATE_COMMENT_CHANGED;
case CommentType.PRE -> PRE_COMMENT_CHANGED;
case CommentType.POST -> POST_COMMENT_CHANGED;
case CommentType.EOL -> EOL_COMMENT_CHANGED;
case CommentType.REPEATABLE -> REPEATABLE_COMMENT_CHANGED;
default -> throw new AssertionError();
};
}
@@ -4,9 +4,9 @@
* 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.
@@ -18,7 +18,6 @@ package ghidra.trace.database.listing;
import static org.junit.Assert.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.*;
@@ -210,8 +209,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) {
b.trace.getMemoryManager()
.addRegion(".text", Lifespan.nowOn(0),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ);
.addRegion(".text", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
TraceMemoryFlag.READ);
}
assertEquals("00004004", ins.getAddressString(false, false));
@@ -364,13 +363,10 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
}
@Test
public void testDetectNewCommentTypes()
throws IllegalArgumentException, IllegalAccessException {
for (Field f : CodeUnit.class.getFields()) {
if (f.getName().endsWith("_COMMENT")) {
if (f.getInt(null) > CodeUnit.REPEATABLE_COMMENT) {
fail("It appears a new comment type was added");
}
public void testDetectNewCommentTypes() {
for (CommentType type : CommentType.values()) {
if (type.ordinal() > CommentType.REPEATABLE.ordinal()) {
fail("It appears a new comment type was added");
}
}
}
@@ -385,7 +381,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
}
try (Transaction tx = b.startTransaction()) {
i4004.setComment(CodeUnit.NO_COMMENT, "Shouldn't work");
i4004.setComment(null, "Shouldn't work");
fail();
}
catch (IllegalArgumentException e) {
@@ -399,28 +395,28 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
// pass
}
assertNull(i4004.getComment(CodeUnit.EOL_COMMENT));
assertNull(i4004.getComment(CommentType.EOL));
try (Transaction tx = b.startTransaction()) {
i4004.setComment(CodeUnit.EOL_COMMENT, "My EOL Comment");
i4004.setComment(CommentType.EOL, "My EOL Comment");
}
assertEquals("My EOL Comment", i4004.getComment(CodeUnit.EOL_COMMENT));
assertNull(i4006.getComment(CodeUnit.EOL_COMMENT));
assertEquals("My EOL Comment", i4004.getComment(CommentType.EOL));
assertNull(i4006.getComment(CommentType.EOL));
assertArrayEquals(EMPTY_STRING_ARRAY, i4004.getCommentAsArray(CodeUnit.PRE_COMMENT));
assertArrayEquals(EMPTY_STRING_ARRAY, i4004.getCommentAsArray(CommentType.PRE));
try (Transaction tx = b.startTransaction()) {
i4004.setCommentAsArray(CodeUnit.PRE_COMMENT, new String[] { "My", "Pre", "Comment" });
i4004.setCommentAsArray(CommentType.PRE, new String[] { "My", "Pre", "Comment" });
}
assertEquals("My EOL Comment", i4004.getComment(CodeUnit.EOL_COMMENT));
assertEquals("My EOL Comment", i4004.getComment(CommentType.EOL));
assertArrayEquals(new String[] { "My", "Pre", "Comment" },
i4004.getCommentAsArray(CodeUnit.PRE_COMMENT));
assertArrayEquals(EMPTY_STRING_ARRAY, i4006.getCommentAsArray(CodeUnit.PRE_COMMENT));
assertEquals("My\nPre\nComment", i4004.getComment(CodeUnit.PRE_COMMENT));
i4004.getCommentAsArray(CommentType.PRE));
assertArrayEquals(EMPTY_STRING_ARRAY, i4006.getCommentAsArray(CommentType.PRE));
assertEquals("My\nPre\nComment", i4004.getComment(CommentType.PRE));
try (Transaction tx = b.startTransaction()) {
i4004.setCommentAsArray(CodeUnit.PRE_COMMENT, null);
i4006.setCommentAsArray(CodeUnit.PRE_COMMENT, null); // NOP
i4004.setCommentAsArray(CommentType.PRE, null);
i4006.setCommentAsArray(CommentType.PRE, null); // NOP
}
assertNull(i4004.getComment(CodeUnit.PRE_COMMENT));
assertNull(i4004.getComment(CommentType.PRE));
TraceInstruction i4004_10;
DBTraceCommentAdapter commentAdapter = b.trace.getCommentAdapter();
@@ -436,25 +432,24 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
assertEquals(Lifespan.nowOn(0), c4004.getLifespan());
i4004_10 = b.addInstruction(10, b.addr(0x4004), b.host);
i4004_10.setComment(CodeUnit.PRE_COMMENT, "Get this back in the mix");
i4004_10.setComment(CodeUnit.EOL_COMMENT, "A different comment");
i4004_10.setComment(CommentType.PRE, "Get this back in the mix");
i4004_10.setComment(CommentType.EOL, "A different comment");
}
assertEquals(Lifespan.span(0, 9), c4004.getLifespan());
assertEquals("My EOL Comment", i4004.getComment(CodeUnit.EOL_COMMENT));
assertEquals("My EOL Comment", i4004.getComment(CommentType.EOL));
try (Transaction tx = b.startTransaction()) {
commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000),
CodeUnit.EOL_COMMENT);
CommentType.EOL);
}
assertNull(i4004.getComment(CodeUnit.EOL_COMMENT));
assertEquals("Get this back in the mix", i4004_10.getComment(CodeUnit.PRE_COMMENT));
assertNull(i4004.getComment(CommentType.EOL));
assertEquals("Get this back in the mix", i4004_10.getComment(CommentType.PRE));
try (Transaction tx = b.startTransaction()) {
commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000),
CodeUnit.NO_COMMENT);
commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000), null);
}
assertNull(i4004.getComment(CodeUnit.EOL_COMMENT));
assertNull(i4004_10.getComment(CodeUnit.PRE_COMMENT));
assertNull(i4004.getComment(CommentType.EOL));
assertNull(i4004_10.getComment(CommentType.PRE));
}
@Test
@@ -579,9 +574,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
DBTraceReference refTo;
try (Transaction tx = b.startTransaction()) {
refTo = b.trace.getReferenceManager()
.addMemoryReference(Lifespan.ALL, b.addr(0x3000),
b.addr(0x4004), RefType.COMPUTED_JUMP, SourceType.USER_DEFINED,
CodeUnit.MNEMONIC);
.addMemoryReference(Lifespan.ALL, b.addr(0x3000), b.addr(0x4004),
RefType.COMPUTED_JUMP, SourceType.USER_DEFINED, CodeUnit.MNEMONIC);
}
assertEquals(Set.of(refTo), set((Iterator<Reference>) i4004.getReferenceIteratorTo()));
@@ -636,8 +630,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
thread = b.getOrAddThread("Thread 1", 0);
DBTraceCodeSpace regCode = manager.getCodeRegisterSpace(thread, true);
data = regCode.definedData()
.create(Lifespan.nowOn(0), b.language.getRegister("r4"),
LongDataType.dataType);
.create(Lifespan.nowOn(0), b.language.getRegister("r4"), LongDataType.dataType);
// getForRegister requires unit to match size
undReg = regCode.undefinedData().getAt(0, b.language.getRegister("r5").getAddress());
}
@@ -832,8 +825,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) {
// StringDataType accesses memory via program view, so "block" must exist
b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ);
.addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
TraceMemoryFlag.READ);
dl4000 = b.addData(0, b.addr(0x4000), LongDataType.dataType, b.buf(1, 2, 3, 4));
dp4006 = b.addData(0, b.addr(0x4006), PointerDataType.dataType,
@@ -970,8 +963,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) {
// Disassembler's new cacheing in mem-buffer uses program view, so "block" must exist
b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ);
.addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
TraceMemoryFlag.READ);
i4004 = b.addInstruction(0, b.addr(0x4004), b.host, b.buf(0xc8, 0x47));
assertEquals("add r4,#0x7", i4004.toString());
@@ -1074,8 +1067,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
i4004.addOperandReference(1, b.addr(0x5000), RefType.DATA_IND, SourceType.USER_DEFINED);
// TODO: This should probably be default for first/only reference
b.trace.getReferenceManager()
.getReference(0, b.addr(0x4004), b.addr(0x5000),
1)
.getReference(0, b.addr(0x4004), b.addr(0x5000), 1)
.setPrimary(true);
}
assertEquals(OperandType.ADDRESS | OperandType.SCALAR, i4004.getOperandType(1));
@@ -1247,8 +1239,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) {
// Disassembler's new cacheing in mem-buffer uses program view, so "block" must exist
b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ);
.addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
TraceMemoryFlag.READ);
guest = b.trace.getPlatformManager().addGuestPlatform(x86.getDefaultCompilerSpec());
guest.addMappedRange(b.addr(0x0000), b.addr(guest, 0x0000), 1L << 32);
@@ -1378,8 +1370,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
thread = b.getOrAddThread("Thread 1", 0);
DBTraceCodeSpace regCode = manager.getCodeRegisterSpace(thread, true);
dR4 = regCode.definedData()
.create(Lifespan.nowOn(0), b.language.getRegister("r4"),
myStruct);
.create(Lifespan.nowOn(0), b.language.getRegister("r4"), myStruct);
}
myStruct = (Structure) b.trace.getDataTypeManager().getDataType("/myStruct");
myTypedef = (TypeDef) b.trace.getDataTypeManager().getDataType("/myTypedef");
@@ -1603,8 +1594,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) {
// StringDataType accesses memory via program view, so "block" must exist
b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ);
.addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
TraceMemoryFlag.READ);
d4000 = b.addData(0, b.addr(0x4000), LongDataType.dataType, b.buf(1, 2, 3, 4));
d4004 = b.addData(0, b.addr(0x4004), myStruct, b.buf(5, 6, 7, 8, 9));
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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.
@@ -18,17 +17,16 @@
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.listing.*;
public class AddCommentToProgramScript extends GhidraScript {
@Override
public void run() throws Exception {
Address minAddress = currentProgram.getMinAddress();
Listing listing = currentProgram.getListing();
CodeUnit codeUnit = listing.getCodeUnitAt( minAddress );
codeUnit.setComment( CodeUnit.PLATE_COMMENT, "AddCommentToProgramScript - This is an added comment!" );
}
@Override
public void run() throws Exception {
Address minAddress = currentProgram.getMinAddress();
Listing listing = currentProgram.getListing();
CodeUnit codeUnit = listing.getCodeUnitAt(minAddress);
codeUnit.setComment(CommentType.PLATE,
"AddCommentToProgramScript - This is an added comment!");
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -31,7 +31,7 @@
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.symbol.*;
@@ -147,14 +147,14 @@ public class AutoRenameSimpleLabels extends GhidraScript {
// now also propogate the repeatable comment up as well
String comment = currentProgram.getListing().getComment(CodeUnit.REPEATABLE_COMMENT,
operand_addr);
String comment =
currentProgram.getListing().getComment(CommentType.REPEATABLE, operand_addr);
if (comment != null) {
if (currentProgram.getListing().getComment(CodeUnit.REPEATABLE_COMMENT,
startAddr) == null) {
if (currentProgram.getListing()
.getComment(CommentType.REPEATABLE, startAddr) == null) {
//println("updating comment for " + operand +" is " + comment);
currentProgram.getListing().setComment(startAddr,
CodeUnit.REPEATABLE_COMMENT, comment);
currentProgram.getListing()
.setComment(startAddr, CommentType.REPEATABLE, comment);
}
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -19,37 +19,37 @@
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.listing.*;
public class DeleteDeadDefaultPlatesScript extends GhidraScript {
private static String DEAD_PLATE = " DEAD";
/* (non-Javadoc)
* @see ghidra.app.script.GhidraScript#run()
*/
@Override
public void run() throws Exception {
public void run() throws Exception {
Listing listing = currentProgram.getListing();
AddressSetView set = currentProgram.getMemory();
if (currentSelection != null && !currentSelection.isEmpty()) {
set = currentSelection;
}
int updateCount=0;
AddressIterator iter = listing.getCommentAddressIterator(CodeUnit.PLATE_COMMENT, set, true);
int updateCount = 0;
AddressIterator iter = listing.getCommentAddressIterator(CommentType.PLATE, set, true);
while (iter.hasNext()) {
Address addr = iter.next();
CodeUnit cu = listing.getCodeUnitAt(addr);
if (cu != null) {
String[] comment = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT);
String[] comment = cu.getCommentAsArray(CommentType.PLATE);
if (comment.length == 1 && comment[0].equals(DEAD_PLATE)) {
cu.setComment(CodeUnit.PLATE_COMMENT, null);
cu.setComment(CommentType.PLATE, null);
++updateCount;
}
}
}
if (updateCount > 0) {
String cmt = updateCount > 1? "comments" : "comment";
String cmt = updateCount > 1 ? "comments" : "comment";
println("Removed " + updateCount + " default plate " + cmt + ".");
}
else {
@@ -4,9 +4,9 @@
* 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.
@@ -19,37 +19,37 @@
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.listing.*;
public class DeleteEmptyPlateCommentsScript extends GhidraScript {
private static String EMPTY_PLATE = "";
/* (non-Javadoc)
* @see ghidra.app.script.GhidraScript#run()
*/
@Override
public void run() throws Exception {
public void run() throws Exception {
Listing listing = currentProgram.getListing();
AddressSetView set = currentProgram.getMemory();
if (currentSelection != null && !currentSelection.isEmpty()) {
set = currentSelection;
}
int updateCount=0;
AddressIterator iter = listing.getCommentAddressIterator(CodeUnit.PLATE_COMMENT, set, true);
int updateCount = 0;
AddressIterator iter = listing.getCommentAddressIterator(CommentType.PLATE, set, true);
while (iter.hasNext()) {
Address addr = iter.next();
CodeUnit cu = listing.getCodeUnitAt(addr);
if (cu != null) {
String[] comment = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT);
String[] comment = cu.getCommentAsArray(CommentType.PLATE);
if (comment.length == 1 && comment[0].equals(EMPTY_PLATE)) {
cu.setComment(CodeUnit.PLATE_COMMENT, null);
cu.setComment(CommentType.PLATE, null);
++updateCount;
}
}
}
if (updateCount > 0) {
String cmt = updateCount > 1? "comments" : "comment";
String cmt = updateCount > 1 ? "comments" : "comment";
println("Removed " + updateCount + " emtpy plate " + cmt + ".");
}
else {
@@ -4,9 +4,9 @@
* 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.
@@ -18,38 +18,36 @@
//@category Update
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressIterator;
import ghidra.program.model.address.AddressSetView;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
public class DeleteExitCommentsScript extends GhidraScript {
private static String EXIT_COMMENT = " Exit **********\r\n ";
/* (non-Javadoc)
* @see ghidra.app.script.GhidraScript#run()
*/
@Override
public void run() throws Exception {
public void run() throws Exception {
Listing listing = currentProgram.getListing();
AddressSetView set = currentProgram.getMemory();
if (currentSelection != null && !currentSelection.isEmpty()) {
set = currentSelection;
}
int updateCount=0;
AddressIterator iter = listing.getCommentAddressIterator(CodeUnit.POST_COMMENT, set, true);
int updateCount = 0;
AddressIterator iter = listing.getCommentAddressIterator(CommentType.POST, set, true);
while (iter.hasNext()) {
Address addr = iter.next();
CodeUnit cu = listing.getCodeUnitAt(addr);
String[] comment = cu.getCommentAsArray(CodeUnit.POST_COMMENT);
String[] comment = cu.getCommentAsArray(CommentType.POST);
if (comment.length == 1 && comment[0].endsWith(EXIT_COMMENT)) {
cu.setComment(CodeUnit.POST_COMMENT, null);
cu.setComment(CommentType.POST, null);
++updateCount;
}
}
if (updateCount > 0) {
String cmt = updateCount > 1? "comments" : "comment";
String cmt = updateCount > 1 ? "comments" : "comment";
println("Removed " + updateCount + " exit post " + cmt + ".");
}
else {
@@ -4,9 +4,9 @@
* 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.
@@ -27,6 +27,7 @@ import java.util.List;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.mem.Memory;
import ghidra.util.exception.CancelledException;
@@ -72,14 +73,14 @@ public class LocateMemoryAddressesForFileOffset extends GhidraScript {
println("File offset " + Long.toHexString(fileOffset) +
" is associated with memory block:address " + memBlockName + ":" + addr.toString());
CodeUnit myCodeUnit = currentProgram.getListing().getCodeUnitContaining(addr);
String comment = myCodeUnit.getComment(0);
String comment = myCodeUnit.getComment(CommentType.EOL);
if (comment == null) {
myCodeUnit.setComment(0,
myCodeUnit.setComment(CommentType.EOL,
this.getScriptName() + ": File offset: " + Long.toHexString(fileOffset) +
", Memory block:address " + memBlockName + ":" + addr.toString());
}
else {
myCodeUnit.setComment(0,
myCodeUnit.setComment(CommentType.EOL,
comment + ", " + this.getScriptName() + ": File offset: " +
Long.toHexString(fileOffset) + ", Memory block:address " + memBlockName + ":" +
addr.toString());
@@ -4,9 +4,9 @@
* 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.
@@ -48,8 +48,7 @@ import ghidra.program.model.block.CodeBlock;
import ghidra.program.model.block.PartitionCodeSubModel;
import ghidra.program.model.data.DataType;
import ghidra.program.model.lang.*;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.*;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode;
import ghidra.program.model.symbol.*;
@@ -180,7 +179,8 @@ public class MultiInstructionMemReference extends GhidraScript {
public boolean evaluateReference(VarnodeContext context, Instruction instr, int pcodeop,
Address address, int size, DataType dataType, RefType refType) {
return super.evaluateReference(context, instr, pcodeop, address, size, dataType, refType);
return super.evaluateReference(context, instr, pcodeop, address, size, dataType,
refType);
}
private boolean checkInstructionMatch(final int opIdx, boolean input,
@@ -287,7 +287,7 @@ public class MultiInstructionMemReference extends GhidraScript {
}
Address lastSetLocation = context.getLastSetLocation(singleRegister, null);
String comment = instr.getComment(Instruction.EOL_COMMENT);
String comment = instr.getComment(CommentType.EOL);
if (comment == null) {
comment = "";
}
@@ -300,7 +300,7 @@ public class MultiInstructionMemReference extends GhidraScript {
return false;
}
comment = (comment.trim().length() == 0 ? markup : comment + "\n" + markup);
instr.setComment(Instruction.EOL_COMMENT, comment);
instr.setComment(CommentType.EOL, comment);
return false;
}
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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.
@@ -19,168 +18,141 @@
// function's plate comment.
//@category Analysis
import java.util.*;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.*;
import java.util.*;
public class RegisterTouchesPerFunction extends GhidraScript {
private final static String DIVIDER =
"*************************************************************\r\n";
public class RegisterTouchesPerFunction extends GhidraScript
{
private final static String DIVIDER = "*************************************************************\r\n";
@Override
public void run() throws Exception {
Listing l = this.currentProgram.getListing();
@Override
public void run() throws Exception
{
Listing l = this.currentProgram.getListing();
if (this.askYesNo("Function Analysis - Register Touches", "Analyze complete listing?")) {
FunctionIterator fi = l.getFunctions(true);
while (fi.hasNext() && !monitor.isCancelled()) {
doAnalysis(l, fi.next());
}
}
else {
doAnalysis(l, l.getFunctionContaining(this.currentAddress));
}
}
if (this.askYesNo("Function Analysis - Register Touches",
"Analyze complete listing?"))
{
FunctionIterator fi = l.getFunctions(true);
while (fi.hasNext() && !monitor.isCancelled())
{
doAnalysis(l, fi.next());
}
}
else
{
doAnalysis(l, l.getFunctionContaining(this.currentAddress));
}
}
private void doAnalysis(Listing list, Function func) {
if (func == null) {
println("No function to analyze.");
return;
}
HashSet<String> affected, accessed;
Vector<String> restored;
Stack<String> pushPops;
boolean reviewRestored = false;
Instruction inst;
InstructionIterator iIter;
private void doAnalysis(Listing list, Function func)
{
if (func == null) {
println("No function to analyze.");
return;
}
HashSet<String> affected, accessed;
Vector<String> restored;
Stack<String> pushPops;
boolean reviewRestored = false;
Instruction inst;
InstructionIterator iIter;
monitor.setMessage("Analyzing registers in " + func.getName());
monitor.setMessage("Analyzing registers in " + func.getName());
String comment = list.getComment(CodeUnit.PLATE_COMMENT, func.getBody().getMinAddress());
String comment = list.getComment(CommentType.PLATE, func.getBody().getMinAddress());
if (comment != null && comment.indexOf("TOUCHED REGISTER SUMMARY") > -1)
return;
if (comment != null && comment.indexOf("TOUCHED REGISTER SUMMARY") > -1)
return;
pushPops = new Stack<String>();
affected = new HashSet<String>();
accessed = new HashSet<String>();
restored = new Vector<String>();
pushPops = new Stack<String>();
affected = new HashSet<String>();
accessed = new HashSet<String>();
restored = new Vector<String>();
iIter = list.getInstructions(func.getBody(), true);
while (iIter.hasNext() && !monitor.isCancelled())
{
inst = iIter.next();
iIter = list.getInstructions(func.getBody(), true);
Object o[] = inst.getResultObjects();
for (int i = 0; i < o.length; i++)
{
if (o[i] instanceof Register)
{
String name = ((Register) o[i]).getName();
while (iIter.hasNext() && !monitor.isCancelled()) {
inst = iIter.next();
if (inst.getMnemonicString().equalsIgnoreCase("pop"))
{
if (!name.equalsIgnoreCase("mult_addr")
&& !name.equalsIgnoreCase("sp"))
{
if (pushPops.size() > 0)
{
restored.add(pushPops.pop() + "->" + name);
}
else
{
reviewRestored = true;
}
}
}
else
{
affected.add(name);
}
}
}
o = inst.getInputObjects();
Object o[] = inst.getResultObjects();
for (Object element : o) {
if (element instanceof Register) {
String name = ((Register) element).getName();
for (int i = 0; i < o.length; i++)
{
if (o[i] instanceof Register)
{
String name = ((Register) o[i]).getName();
if (inst.getMnemonicString().equalsIgnoreCase("push"))
{
if (!name.equalsIgnoreCase("mult_addr")
&& !name.equalsIgnoreCase("sp"))
{
pushPops.push(name);
}
}
else
{
accessed.add(name);
}
}
}
}
if (inst.getMnemonicString().equalsIgnoreCase("pop")) {
if (!name.equalsIgnoreCase("mult_addr") && !name.equalsIgnoreCase("sp")) {
if (pushPops.size() > 0) {
restored.add(pushPops.pop() + "->" + name);
}
else {
reviewRestored = true;
}
}
}
else {
affected.add(name);
}
}
}
o = inst.getInputObjects();
StringBuffer buffer = new StringBuffer();
if (comment != null) {
buffer.append(comment);
buffer.append("\r\n");
buffer.append(DIVIDER);
}
buffer.append("TOUCHED REGISTER SUMMARY:\r\n");
buffer.append(DIVIDER);
buffer.append("Register(s) Affected:\r\n");
buffer.append(getString(affected, 8));
buffer.append(DIVIDER);
buffer.append("Register(s) Accessed:\r\n");
buffer.append(getString(accessed, 8));
buffer.append(DIVIDER);
buffer.append("Register(s) Restored:\r\n");
buffer.append(getString(restored, 4));
for (Object element : o) {
if (element instanceof Register) {
String name = ((Register) element).getName();
if (inst.getMnemonicString().equalsIgnoreCase("push")) {
if (!name.equalsIgnoreCase("mult_addr") && !name.equalsIgnoreCase("sp")) {
pushPops.push(name);
}
}
else {
accessed.add(name);
}
}
}
}
if(reviewRestored)
{
buffer.append("##Review - due to branches this list may not be accurate\r\n");
println(func.getName() + " - Review - due to branches this list may not be accurate");
}
buffer.append(DIVIDER);
StringBuffer buffer = new StringBuffer();
if (comment != null) {
buffer.append(comment);
buffer.append("\r\n");
buffer.append(DIVIDER);
}
buffer.append("TOUCHED REGISTER SUMMARY:\r\n");
buffer.append(DIVIDER);
buffer.append("Register(s) Affected:\r\n");
buffer.append(getString(affected, 8));
buffer.append(DIVIDER);
buffer.append("Register(s) Accessed:\r\n");
buffer.append(getString(accessed, 8));
buffer.append(DIVIDER);
buffer.append("Register(s) Restored:\r\n");
buffer.append(getString(restored, 4));
if (pushPops.size() > 0)
{
if (reviewRestored) {
buffer.append("##Review - due to branches this list may not be accurate\r\n");
println(func.getName() + " - Review - due to branches this list may not be accurate");
}
buffer.append(DIVIDER);
buffer.append("Registers Remaining on Stack:\r\n");
buffer.append(" "+getString(pushPops, 8));
}
if (pushPops.size() > 0) {
list.setComment(func.getEntryPoint(), CodeUnit.PLATE_COMMENT, buffer.toString());
}
buffer.append("Registers Remaining on Stack:\r\n");
buffer.append(" " + getString(pushPops, 8));
}
private String getString(Collection<String> c, int itemsPerLine)
{
TreeSet<Object> ts = new TreeSet<Object>(c);
String temp = ts.toString();
temp = temp.substring(1, temp.length() - 1);
int i = 0;
int commaCount = 0;
while ((i = temp.indexOf(',', i + 1)) >= 0)
{
commaCount++;
if (commaCount % itemsPerLine == 0)
temp = temp.substring(0, i + 1) + "\r\n"
+ temp.substring(i + 1).trim();
}
list.setComment(func.getEntryPoint(), CommentType.PLATE, buffer.toString());
}
return temp + "\r\n";
}
private String getString(Collection<String> c, int itemsPerLine) {
TreeSet<Object> ts = new TreeSet<Object>(c);
String temp = ts.toString();
temp = temp.substring(1, temp.length() - 1);
int i = 0;
int commaCount = 0;
while ((i = temp.indexOf(',', i + 1)) >= 0) {
commaCount++;
if (commaCount % itemsPerLine == 0)
temp = temp.substring(0, i + 1) + "\r\n" + temp.substring(i + 1).trim();
}
return temp + "\r\n";
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -38,7 +38,7 @@ import java.util.List;
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.mem.Memory;
import ghidra.program.model.symbol.*;
@@ -60,8 +60,8 @@ public class ZapBCTRScript extends GhidraScript {
}
// first try input as class and search for symbol "<class>::__vtbl"
List<Symbol> symbols = currentProgram.getSymbolTable().getSymbols("__vtbl",
getNamespace(null, classNameOrAddr));
List<Symbol> symbols = currentProgram.getSymbolTable()
.getSymbols("__vtbl", getNamespace(null, classNameOrAddr));
// if symbol found, then vtblAddr is the symbol's address
if (symbols.size() == 1) {
vtblAddr = symbols.get(0).getAddress();
@@ -99,9 +99,9 @@ public class ZapBCTRScript extends GhidraScript {
// insert funcName as EOL comment and
// add a mnemonic ref from instAddr to funcAddr
listing.setComment(instAddr, CodeUnit.EOL_COMMENT, funcName);
listing.getInstructionAt(instAddr).addMnemonicReference(funcAddr, RefType.COMPUTED_CALL,
SourceType.USER_DEFINED);
listing.setComment(instAddr, CommentType.EOL, funcName);
listing.getInstructionAt(instAddr)
.addMnemonicReference(funcAddr, RefType.COMPUTED_CALL, SourceType.USER_DEFINED);
/* old code that replaces the 'bctr' with a 'bl'
int code = 0x48000001 | ((int)displacement & 0x3ffffff);
@@ -4,9 +4,9 @@
* 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.
@@ -25,10 +25,9 @@ import ghidra.program.model.listing.*;
public class AppendCommentCmd implements Command<Program> {
private Address address;
private int commentType;
private CommentType commentType;
private String comment;
private String separator;
private String cmdName;
private String message;
/**
@@ -40,17 +39,30 @@ public class AppendCommentCmd implements Command<Program> {
* @param separator characters to separate the new comment from the previous comment when
* concatenating.
*/
@Deprecated(forRemoval = true, since = "11.4")
public AppendCommentCmd(Address addr, int commentType, String comment, String separator) {
this(addr, CommentType.valueOf(commentType), comment, separator);
}
/**
* Construct command
* @param addr address of code unit where comment will be placed
* @param commentType comment type
* @param comment comment for code unit, should not be null
* @param separator characters to separate the new comment from the previous comment when
* concatenating.
*/
public AppendCommentCmd(Address addr, CommentType commentType, String comment,
String separator) {
this.address = addr;
this.commentType = commentType;
this.comment = comment;
this.separator = separator;
cmdName = "Append Comment";
}
@Override
public String getName() {
return cmdName;
return "Append Comment";
}
@Override
@@ -4,9 +4,9 @@
* 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.
@@ -325,24 +325,24 @@ public class CodeUnitInfoPasteCmd implements Command<Program> {
String[] repeatableComment = info.getRepeatableComment();
if (plateComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT);
cu.setCommentAsArray(CodeUnit.PLATE_COMMENT, appendComment(oldComment, plateComment));
String[] oldComment = cu.getCommentAsArray(CommentType.PLATE);
cu.setCommentAsArray(CommentType.PLATE, appendComment(oldComment, plateComment));
}
if (preComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.PRE_COMMENT);
cu.setCommentAsArray(CodeUnit.PRE_COMMENT, appendComment(oldComment, preComment));
String[] oldComment = cu.getCommentAsArray(CommentType.PRE);
cu.setCommentAsArray(CommentType.PRE, appendComment(oldComment, preComment));
}
if (postComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.POST_COMMENT);
cu.setCommentAsArray(CodeUnit.POST_COMMENT, appendComment(oldComment, postComment));
String[] oldComment = cu.getCommentAsArray(CommentType.POST);
cu.setCommentAsArray(CommentType.POST, appendComment(oldComment, postComment));
}
if (eolComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.EOL_COMMENT);
cu.setCommentAsArray(CodeUnit.EOL_COMMENT, appendComment(oldComment, eolComment));
String[] oldComment = cu.getCommentAsArray(CommentType.EOL);
cu.setCommentAsArray(CommentType.EOL, appendComment(oldComment, eolComment));
}
if (repeatableComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.REPEATABLE_COMMENT);
cu.setCommentAsArray(CodeUnit.REPEATABLE_COMMENT,
String[] oldComment = cu.getCommentAsArray(CommentType.REPEATABLE);
cu.setCommentAsArray(CommentType.REPEATABLE,
appendComment(oldComment, repeatableComment));
}
}
@@ -26,7 +26,7 @@ import ghidra.program.model.listing.*;
public class SetCommentCmd implements Command<Program> {
private Address address;
private int commentType;
private CommentType commentType;
private String comment;
private String cmdName;
private String message;
@@ -37,7 +37,18 @@ public class SetCommentCmd implements Command<Program> {
* @param commentType valid comment type (see CodeUnit)
* @param comment comment for code unit
*/
@Deprecated(forRemoval = true, since = "11.4")
public SetCommentCmd(Address addr, int commentType, String comment) {
this(addr, CommentType.valueOf(commentType), comment);
}
/**
* Construct command
* @param addr address of code unit where comment will be placed
* @param commentType valid comment type (see CodeUnit)
* @param comment comment for code unit
*/
public SetCommentCmd(Address addr, CommentType commentType, String comment) {
this.address = addr;
this.commentType = commentType;
this.comment = comment;
@@ -112,12 +123,11 @@ public class SetCommentCmd implements Command<Program> {
* @param program the program being analyzed
* @param addr the address where data is created
* @param comment the comment about the data
* @param commentType the type of comment ({@link CodeUnit#PLATE_COMMENT},
* {@link CodeUnit#PRE_COMMENT}, {@link CodeUnit#EOL_COMMENT}, {@link CodeUnit#POST_COMMENT},
* {@link CodeUnit#REPEATABLE_COMMENT})
* @param commentType the type of comment
*/
public static void createComment(Program program, Address addr, String comment,
int commentType) {
CommentType commentType) {
SetCommentCmd commentCmd = new SetCommentCmd(addr, commentType, comment);
commentCmd.applyTo(program);
}
@@ -4,9 +4,9 @@
* 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.
@@ -83,31 +83,31 @@ public class SetCommentsCmd implements Command<Program> {
CodeUnit cu = getCodeUnit(program);
if (cu != null) {
if (commentChanged(cu.getComment(CodeUnit.PRE_COMMENT), preComment)) {
if (commentChanged(cu.getComment(CommentType.PRE), preComment)) {
String updatedPreComment = CommentUtils.fixupAnnotations(preComment, program);
updatedPreComment = CommentUtils.sanitize(updatedPreComment);
cu.setComment(CodeUnit.PRE_COMMENT, updatedPreComment);
cu.setComment(CommentType.PRE, updatedPreComment);
}
if (commentChanged(cu.getComment(CodeUnit.POST_COMMENT), postComment)) {
if (commentChanged(cu.getComment(CommentType.POST), postComment)) {
String updatedPostComment = CommentUtils.fixupAnnotations(postComment, program);
updatedPostComment = CommentUtils.sanitize(updatedPostComment);
cu.setComment(CodeUnit.POST_COMMENT, updatedPostComment);
cu.setComment(CommentType.POST, updatedPostComment);
}
if (commentChanged(cu.getComment(CodeUnit.EOL_COMMENT), eolComment)) {
if (commentChanged(cu.getComment(CommentType.EOL), eolComment)) {
String updatedEOLComment = CommentUtils.fixupAnnotations(eolComment, program);
updatedEOLComment = CommentUtils.sanitize(updatedEOLComment);
cu.setComment(CodeUnit.EOL_COMMENT, updatedEOLComment);
cu.setComment(CommentType.EOL, updatedEOLComment);
}
if (commentChanged(cu.getComment(CodeUnit.PLATE_COMMENT), plateComment)) {
if (commentChanged(cu.getComment(CommentType.PLATE), plateComment)) {
String updatedPlateComment = CommentUtils.fixupAnnotations(plateComment, program);
updatedPlateComment = CommentUtils.sanitize(updatedPlateComment);
cu.setComment(CodeUnit.PLATE_COMMENT, updatedPlateComment);
cu.setComment(CommentType.PLATE, updatedPlateComment);
}
if (commentChanged(cu.getComment(CodeUnit.REPEATABLE_COMMENT), repeatableComment)) {
if (commentChanged(cu.getComment(CommentType.REPEATABLE), repeatableComment)) {
String updatedRepeatableComment =
CommentUtils.fixupAnnotations(repeatableComment, program);
updatedRepeatableComment = CommentUtils.sanitize(updatedRepeatableComment);
cu.setComment(CodeUnit.REPEATABLE_COMMENT, updatedRepeatableComment);
cu.setComment(CommentType.REPEATABLE, updatedRepeatableComment);
}
}
return true;
@@ -184,7 +184,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
createFragment(sectionDT.getName(), sectionStart, sectionDT.getLength());
CodeUnit cu = listing.getCodeUnitAt(addr(offset));
cu.setComment(CodeUnit.PLATE_COMMENT,
cu.setComment(CommentType.PLATE,
"#" + i + ") " + name + " at 0x" + Long.toHexString(sections[i].getAddress()));
if (sections[i].getType() == ElfSectionHeaderConstants.SHT_NOBITS ||
@@ -203,7 +203,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
}
cu = listing.getCodeUnitAt(dataStart);
cu.setComment(CodeUnit.PRE_COMMENT, sections[i].getNameAsString() + " Size: 0x" +
cu.setComment(CommentType.PRE, sections[i].getNameAsString() + " Size: 0x" +
Long.toHexString(sections[i].getSize()));
}
}
@@ -228,7 +228,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
for (int i = 0; i < programHeaders.length; i++) {
monitor.checkCancelled();
Data d = array.getComponent(i);
d.setComment(CodeUnit.EOL_COMMENT, programHeaders[i].getComment());
d.setComment(CommentType.EOL, programHeaders[i].getComment());
Address addr = addr(programHeaders[i].getOffset());
@@ -238,8 +238,8 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
private void processInterpretor(ElfHeader elf, ByteProvider provider, Program program)
throws CancelledException {
for (ElfProgramHeader programHeader : elf.getProgramHeaders(
ElfProgramHeaderConstants.PT_INTERP)) {
for (ElfProgramHeader programHeader : elf
.getProgramHeaders(ElfProgramHeaderConstants.PT_INTERP)) {
monitor.checkCancelled();
long offset = programHeader.getOffset();
if (offset == 0) {
@@ -292,7 +292,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
dynamicType != null ? (dynamicType.name + " - " + dynamicType.description)
: ("DT_0x" + StringUtilities.pad(Integer.toHexString(tagType), '0', 8));
dynamicData.setComment(CodeUnit.EOL_COMMENT, comment);
dynamicData.setComment(CommentType.EOL, comment);
Data valueData = dynamicData.getComponent(1);
@@ -323,7 +323,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
if (dynamicStringTable != null) {
String str = dynamicStringTable.readString(reader, dynamic.getValue());
if (str != null && str.length() != 0) {
data.setComment(CodeUnit.EOL_COMMENT, str);
data.setComment(CommentType.EOL, str);
}
}
}
@@ -339,8 +339,8 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
}
Address refAddr = addr(programLoadHeader.getOffset(dynamicRefAddr));
program.getReferenceManager().addMemoryReference(fromAddr, refAddr, RefType.DATA,
SourceType.ANALYSIS, 0);
program.getReferenceManager()
.addMemoryReference(fromAddr, refAddr, RefType.DATA, SourceType.ANALYSIS, 0);
try {
createLabel(refAddr, "_" + dynamic.getTagAsString(), true, SourceType.ANALYSIS);
@@ -384,7 +384,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
try {
Address currAddr = symbolTableAddr.add(j * symbolTable2.getEntrySize());
listing.setComment(currAddr, CodeUnit.EOL_COMMENT,
listing.setComment(currAddr, CommentType.EOL,
name + " at 0x" + Long.toHexString(symbols[j].getValue()));
}
catch (Exception e) {
@@ -418,7 +418,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
createData(relocationTableAddress, dataType);
}
else {
listing.setComment(relocationTableAddress, CodeUnit.PRE_COMMENT,
listing.setComment(relocationTableAddress, CommentType.PRE,
"ELF Relocation Table (markup not yet supported)");
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -105,6 +105,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {
CliStreamMetadata metadataStream = metadataRoot.getMetadataStream();
InstructionIterator instIter = program.getListing().getInstructions(set, true);
while (instIter.hasNext()) {
monitor.checkCancelled();
try {
Instruction inst = instIter.next();
/* Base Instructions (Partition II.3) */
@@ -194,7 +195,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {
int strIndex = (int) strIndexOp.getUnsignedValue();
inst.setComment(CodeUnit.EOL_COMMENT,
inst.setComment(CommentType.EOL,
"\"" + metaStream.getUserStringsStream().getUserString(strIndex) + "\"");
}
@@ -229,7 +230,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {
private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow,
String prependComment, String appendComment, CliStreamMetadata stream) {
inst.setComment(CodeUnit.EOL_COMMENT, String.format("%s%s%s", prependComment,
inst.setComment(CommentType.EOL, String.format("%s%s%s", prependComment,
tableRow.getShortRepresentation(stream), appendComment));
}
@@ -166,8 +166,7 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
"Golang symbol analyzer: scheduling RTTI propagation after reference analysis");
aam.schedule(new PropagateRttiBackgroundCommand(goBinary, markupSession),
PROP_RTTI_PRIORITY.priority());
Msg.info(this,
"Golang symbol analyzer: scheduling closure function fixup");
Msg.info(this, "Golang symbol analyzer: scheduling closure function fixup");
aam.schedule(new FixClosureFuncArgsBackgroundCommand(goBinary),
FIX_CLOSURES_PRIORITY.priority());
}
@@ -328,8 +327,7 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
: null;
String typeStr = typeStructAddr != null
? AddressAnnotatedStringHandler.createAddressAnnotationString(
typeStructAddr,
recvType.getName())
typeStructAddr, recvType.getName())
: funcDefResult.symbolName().receiverString();
markupSession.appendComment(func, "",
"Golang method in type %s".formatted(typeStr));
@@ -354,7 +352,6 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
.formatted(functionSignatureFromMethod));
}
private void fixGcWriteBarrierFunctions() {
if (GoConstants.GCWRITE_BUFFERED_VERS.contains(goBinary.getGoVer())) {
fixGcWriteBarrierBufferedFunctions();
@@ -390,8 +387,7 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
func = funcData != null ? funcData.getFunction() : null;
if (func != null) {
func.updateFunction(ccname, retVal, List.of(),
FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true,
SourceType.ANALYSIS);
FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS);
}
}
}
@@ -460,9 +456,9 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
DataType voidPtr = program.getDataTypeManager().getPointer(VoidDataType.dataType);
GoFuncData duffzeroFuncdata = goBinary.getFunctionByName("runtime.duffzero");
Function duffzeroFunc = duffzeroFuncdata != null
? funcMgr.getFunctionAt(duffzeroFuncdata.getFuncAddress())
: null;
Function duffzeroFunc =
duffzeroFuncdata != null ? funcMgr.getFunctionAt(duffzeroFuncdata.getFuncAddress())
: null;
List<Variable> duffzeroParams = regInfo.getDuffzeroParams(program);
if (duffzeroFunc != null && !duffzeroParams.isEmpty()) {
// NOTE: some go archs don't create duffzero functions. See
@@ -489,15 +485,14 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
}
GoFuncData duffcopyFuncdata = goBinary.getFunctionByName("runtime.duffcopy");
Function duffcopyFunc = duffcopyFuncdata != null
? funcMgr.getFunctionAt(duffcopyFuncdata.getFuncAddress())
: null;
Function duffcopyFunc =
duffcopyFuncdata != null ? funcMgr.getFunctionAt(duffcopyFuncdata.getFuncAddress())
: null;
if (duffcopyFuncdata != null &&
goBinary.hasCallingConvention(GOLANG_DUFFCOPY_CALLINGCONVENTION_NAME)) {
try {
List<Variable> params =
List.of(new ParameterImpl("dest", voidPtr, program),
new ParameterImpl("src", voidPtr, program));
List<Variable> params = List.of(new ParameterImpl("dest", voidPtr, program),
new ParameterImpl("src", voidPtr, program));
duffcopyFunc.updateFunction(GOLANG_DUFFCOPY_CALLINGCONVENTION_NAME,
new ReturnParameterImpl(VoidDataType.dataType, program), params,
FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS);
@@ -672,13 +667,13 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
func.setName(duffFunc.getName() + "_" + func.getEntryPoint(),
SourceType.ANALYSIS);
func.setParentNamespace(funcNS);
FunctionUpdateType fut = duffFunc.hasCustomVariableStorage()
? FunctionUpdateType.CUSTOM_STORAGE
: FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS;
FunctionUpdateType fut =
duffFunc.hasCustomVariableStorage() ? FunctionUpdateType.CUSTOM_STORAGE
: FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS;
func.updateFunction(ccName, duffFunc.getReturn(),
Arrays.asList(duffFunc.getParameters()), fut, true, SourceType.ANALYSIS);
if (duffComment != null && !duffComment.isBlank()) {
new SetCommentCmd(func.getEntryPoint(), CodeUnit.PLATE_COMMENT, duffComment)
new SetCommentCmd(func.getEntryPoint(), CommentType.PLATE, duffComment)
.applyTo(program);
}
}
@@ -1079,8 +1074,8 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
}
record CallSiteInfo(Reference ref, Function callingFunc, Function calledFunc,
Register register,
java.util.function.Function<GoType, DataType> returnTypeMapper) {}
Register register, java.util.function.Function<GoType, DataType> returnTypeMapper) {
}
private GoRttiMapper goBinary;
private Program program;
@@ -4,9 +4,9 @@
* 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.
@@ -62,9 +62,8 @@ public class MingwRelocationAnalyzer extends AbstractAnalyzer {
if (!program.hasExclusiveAccess()) {
// Exclusive access required since relocation table lacks merge support
if (!alreadyProcessed(program)) {
Msg.error(this,
NAME + " analyzer disabled; requires exclusive access to " +
program.getDomainFile());
Msg.error(this, NAME + " analyzer disabled; requires exclusive access to " +
program.getDomainFile());
}
return false;
}
@@ -226,11 +225,9 @@ class MinGWPseudoRelocationHandler {
static boolean isSupportedProgram(Program program) {
Language language = program.getLanguage();
int size = language.getLanguageDescription().getSize();
return "x86".equals(language.getProcessor().toString()) &&
(size == 32 || size == 64) &&
return "x86".equals(language.getProcessor().toString()) && (size == 32 || size == 64) &&
"windows".equals(program.getCompilerSpec().getCompilerSpecID().toString()) &&
CompilerEnum.GCC.label.equals(program.getCompiler()) &&
getRDataBlock(program) != null;
CompilerEnum.GCC.label.equals(program.getCompiler()) && getRDataBlock(program) != null;
}
private static MemoryBlock getRDataBlock(Program program) {
@@ -252,7 +249,6 @@ class MinGWPseudoRelocationHandler {
}
}
boolean processRelocations(MessageLog log, TaskMonitor monitor) throws CancelledException {
Address pdwListBeginAddr = relocList.getListStartAddress();
@@ -297,8 +293,8 @@ class MinGWPseudoRelocationHandler {
boolean success;
switch (version) {
case RP_VERSION_V1:
success = relocateV1(pdwListBeginAddr, (int) (size / OLD_STYLE_ENTRY_SIZE), log,
monitor);
success =
relocateV1(pdwListBeginAddr, (int) (size / OLD_STYLE_ENTRY_SIZE), log, monitor);
break;
case RP_VERSION_V2:
success = relocateV2(pdwListBeginAddr, (int) (size / NEW_STYLE_ENTRY_HEADER_SIZE),
@@ -369,8 +365,7 @@ class MinGWPseudoRelocationHandler {
return existingEntry;
}
Reference ref =
program.getReferenceManager().getPrimaryReferenceFrom(iatEntryAddr, 0);
Reference ref = program.getReferenceManager().getPrimaryReferenceFrom(iatEntryAddr, 0);
if (!ref.isExternalReference()) {
return null;
}
@@ -380,8 +375,7 @@ class MinGWPseudoRelocationHandler {
return null;
}
ExternalLocation extLoc =
program.getExternalManager().getExternalLocation(extSym);
ExternalLocation extLoc = program.getExternalManager().getExternalLocation(extSym);
if (extLoc == null) {
return null;
}
@@ -410,7 +404,7 @@ class MinGWPseudoRelocationHandler {
else {
// TODO: Not sure how to preserve relationship to external symbol
// which refers to Library
listing.setComment(nextExtAddr, CodeUnit.PLATE_COMMENT,
listing.setComment(nextExtAddr, CommentType.PLATE,
"External Location: " + extSym.getName(true));
String name = extLoc.getOriginalImportedName();
boolean demangle = true;
@@ -583,12 +577,12 @@ class MinGWPseudoRelocationHandler {
}
if (addend != 0) {
ElfRelocationHandler.warnExternalOffsetRelocation(program,
targetAddr, pointerValue, symbolName, addend, null);
ElfRelocationHandler.warnExternalOffsetRelocation(program, targetAddr,
pointerValue, symbolName, addend, null);
if (!memory.getBlock(targetAddr).isExecute()) {
// assume pointer if not in execute block
ElfRelocationHandler.applyComponentOffsetPointer(program,
targetAddr, addend);
ElfRelocationHandler.applyComponentOffsetPointer(program, targetAddr,
addend);
}
}
}
@@ -624,8 +618,7 @@ class MinGWPseudoRelocationHandler {
ClearDataMode.CLEAR_ALL_CONFLICT_DATA);
}
catch (CodeUnitInsertionException e) {
log.appendMsg(
"Failed to markup Mingw pseudo-relocation List at: " + pdwListBeginAddr);
log.appendMsg("Failed to markup Mingw pseudo-relocation List at: " + pdwListBeginAddr);
}
return true;
}
@@ -640,8 +633,8 @@ class MinGWPseudoRelocationHandler {
relocHeaderStruct.add(DWordDataType.dataType, "version", null);
try {
DataUtilities.createData(program, relocHeaderAddr, relocHeaderStruct, -1,
false, ClearDataMode.CLEAR_ALL_CONFLICT_DATA);
DataUtilities.createData(program, relocHeaderAddr, relocHeaderStruct, -1, false,
ClearDataMode.CLEAR_ALL_CONFLICT_DATA);
}
catch (CodeUnitInsertionException e) {
log.appendMsg(
@@ -4,9 +4,9 @@
* 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.
@@ -31,7 +31,7 @@ import ghidra.util.task.TaskMonitor;
public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private static final String DESCRIPTION =
"An analyzer for extracting _objc_msgSend information.";
"An analyzer for extracting _objc_msgSend information.";
private static final String NAME = "Objective-C Message";
@@ -87,7 +87,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
return;
}
InstructionIterator instructionIterator =
program.getListing().getInstructions(function.getBody(), true);
program.getListing().getInstructions(function.getBody(), true);
while (instructionIterator.hasNext()) {
if (monitor.isCancelled()) {
break;
@@ -96,7 +96,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
Instruction instruction = instructionIterator.next();
if (isCallingObjcMsgSend(instruction)) {
String eolComment = instruction.getComment(CodeUnit.EOL_COMMENT);
String eolComment = instruction.getComment(CommentType.EOL);
if (eolComment != null) {//if a comment already exists, ignore...
continue;
@@ -126,8 +126,8 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private boolean isObjcNameMatch(Symbol symbol) {
String name = symbol.getName();
return name.startsWith(ObjectiveC1_Constants.OBJC_MSG_SEND) ||
name.equals(ObjectiveC1_Constants.READ_UNIX2003) ||
name.startsWith("thunk" + ObjectiveC1_Constants.OBJC_MSG_SEND);
name.equals(ObjectiveC1_Constants.READ_UNIX2003) ||
name.startsWith("thunk" + ObjectiveC1_Constants.OBJC_MSG_SEND);
}
private class CurrentState {
@@ -224,7 +224,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
pullNameThrough(state, toAddress, null);
if (state.isValid()) {
instruction.setComment(CodeUnit.EOL_COMMENT, state.toString());
instruction.setComment(CommentType.EOL, state.toString());
setReference(fromAddress, state);
break;
}
@@ -310,7 +310,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private boolean isClassBlock(MemoryBlock block) {
return block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_CLASS_REFS) ||
block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_CLASS);
block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_CLASS);
}
private boolean isValidInstruction(Instruction instruction) {
@@ -4,9 +4,9 @@
* 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.
@@ -44,6 +44,7 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
setPriority(AnalysisPriority.FORMAT_ANALYSIS.after());
}
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
throws CancelledException {
AddressIterator iterator = set.getAddresses(true);
@@ -63,6 +64,7 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
return true;
}
@Override
public boolean canAnalyze(Program program) {
return ObjectiveC2_Constants.isObjectiveC2(program);
}
@@ -81,7 +83,7 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
Instruction instruction = instructionIterator.next();
if (isCallingObjcMsgSend(instruction)) {
String eolComment = instruction.getComment(CodeUnit.EOL_COMMENT);
String eolComment = instruction.getComment(CommentType.EOL);
if (eolComment != null) {//if a comment already exists, ignore...
continue;
@@ -194,8 +196,8 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
}
if (currentClass != null && currentMethod != null) {
instruction.setComment(CodeUnit.EOL_COMMENT, "[" + currentClass + " " +
currentMethod + "]");
instruction.setComment(CommentType.EOL,
"[" + currentClass + " " + currentMethod + "]");
break;
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -185,7 +185,7 @@ public class CreateBookmarkDialog extends DialogComponentProvider {
}
private String getEolComment(CodeUnit codeUnit) {
String comment = codeUnit.getComment(CodeUnit.EOL_COMMENT);
String comment = codeUnit.getComment(CommentType.EOL);
if (comment == null) {
return "";
}
@@ -66,7 +66,7 @@ public class CodeBrowserClipboardProvider extends ByteCopier
implements ClipboardContentProviderService, OptionsChangeListener {
protected static final PaintContext PAINT_CONTEXT = new PaintContext();
private static int[] COMMENT_TYPES = CommentTypes.getTypes();
private static int[] COMMENT_TYPESx = CommentTypes.getTypes();
public static final ClipboardType ADDRESS_TEXT_TYPE =
new ClipboardType(DataFlavor.stringFlavor, "Address");
@@ -757,7 +757,7 @@ public class CodeBrowserClipboardProvider extends ByteCopier
if (currentLocation instanceof CommentFieldLocation) {
CommentFieldLocation commentFieldLocation = (CommentFieldLocation) currentLocation;
Address address = commentFieldLocation.getAddress();
int commentType = commentFieldLocation.getCommentType();
CommentType commentType = commentFieldLocation.getCommentType();
SetCommentCmd cmd = new SetCommentCmd(address, commentType, string);
return tool.execute(cmd, currentProgram);
}
@@ -802,11 +802,10 @@ public class CodeBrowserClipboardProvider extends ByteCopier
}
private void setCommentInfo(CodeUnit cu, CodeUnitInfo info) {
for (int element : COMMENT_TYPES) {
String[] comments = cu.getCommentAsArray(element);
for (CommentType type : CommentType.values()) {
String[] comments = cu.getCommentAsArray(type);
if (comments != null && comments.length > 0) {
info.setComment(element, comments);
info.setComment(type, comments);
}
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -22,6 +22,7 @@ import javax.swing.*;
import docking.DialogComponentProvider;
import ghidra.app.util.HelpTopics;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.util.HelpLocation;
/**
@@ -37,7 +38,7 @@ public class CommentHistoryDialog extends DialogComponentProvider {
private CommentHistoryPanel platePanel;
private CommentHistoryPanel repeatablePanel;
CommentHistoryDialog(CodeUnit cu, int initialCommentType) {
CommentHistoryDialog(CodeUnit cu, CommentType initialCommentType) {
super("Show Comment History");
setHelpLocation(new HelpLocation(HelpTopics.COMMENTS, "Show_Comment_History"));
addWorkPanel(buildMainPanel(cu, initialCommentType));
@@ -45,7 +46,7 @@ public class CommentHistoryDialog extends DialogComponentProvider {
setPreferredSize(500, 300);
}
private JPanel buildMainPanel(CodeUnit cu, int initialCommentType) {
private JPanel buildMainPanel(CodeUnit cu, CommentType initialCommentType) {
JPanel mainPanel = new JPanel(new BorderLayout());
tabbedPane = new JTabbedPane();
mainPanel.add(tabbedPane);
@@ -55,11 +56,11 @@ public class CommentHistoryDialog extends DialogComponentProvider {
// corresponding tab. This will cause a screen reader to read the history for a tab
// when it is selected.
eolPanel = new CommentHistoryPanel(CodeUnit.EOL_COMMENT, cu);
prePanel = new CommentHistoryPanel(CodeUnit.PRE_COMMENT, cu);
postPanel = new CommentHistoryPanel(CodeUnit.POST_COMMENT, cu);
platePanel = new CommentHistoryPanel(CodeUnit.PLATE_COMMENT, cu);
repeatablePanel = new CommentHistoryPanel(CodeUnit.REPEATABLE_COMMENT, cu);
eolPanel = new CommentHistoryPanel(CommentType.EOL, cu);
prePanel = new CommentHistoryPanel(CommentType.PRE, cu);
postPanel = new CommentHistoryPanel(CommentType.POST, cu);
platePanel = new CommentHistoryPanel(CommentType.PLATE, cu);
repeatablePanel = new CommentHistoryPanel(CommentType.REPEATABLE, cu);
addTab(" EOL Comment ", eolPanel);
addTab(" Pre Comment ", prePanel);
@@ -4,9 +4,9 @@
* 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.
@@ -44,9 +44,9 @@ class CommentHistoryPanel extends JPanel {
private StyledDocument doc;
private JTextPane textPane;
private int commentType;
private CommentType commentType;
CommentHistoryPanel(int commentType, CodeUnit cu) {
CommentHistoryPanel(CommentType commentType, CodeUnit cu) {
super(new BorderLayout());
setUpAttributes();
@@ -15,123 +15,129 @@
*/
package ghidra.app.plugin.core.comments;
import ghidra.app.context.*;
import ghidra.framework.*;
import ghidra.program.model.listing.*;
import ghidra.program.util.*;
import ghidra.util.*;
import java.awt.event.KeyEvent;
import java.awt.event.*;
import docking.*;
import docking.ActionContext;
import docking.action.*;
import ghidra.app.context.ListingActionContext;
import ghidra.app.context.ProgramLocationActionContext;
import ghidra.framework.PluggableServiceRegistry;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.util.*;
import ghidra.util.HelpLocation;
public class CommentsActionFactory {
static {
PluggableServiceRegistry.registerPluggableService(CommentsActionFactory.class, new CommentsActionFactory());
}
static {
PluggableServiceRegistry.registerPluggableService(CommentsActionFactory.class,
new CommentsActionFactory());
}
public static DockingAction getSetCommentsAction(CommentsDialog dialog,
String name, String actionName, int commentType) {
CommentsActionFactory factory = PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doGetSetCommentsAction(dialog, name, actionName, commentType);
}
public static DockingAction getSetCommentsAction(CommentsDialog dialog, String name,
String actionName, CommentType commentType) {
CommentsActionFactory factory =
PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doGetSetCommentsAction(dialog, name, actionName, commentType);
}
public static DockingAction getEditCommentsAction(CommentsDialog dialog,
String name) {
CommentsActionFactory factory = PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doGetEditCommentsAction(dialog, name);
}
public static DockingAction getEditCommentsAction(CommentsDialog dialog, String name) {
CommentsActionFactory factory =
PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doGetEditCommentsAction(dialog, name);
}
public static boolean isCommentSupported(ProgramLocation loc) {
CommentsActionFactory factory = PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doIsCommentSupported(loc);
public static boolean isCommentSupported(ProgramLocation loc) {
CommentsActionFactory factory =
PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doIsCommentSupported(loc);
}
}
protected DockingAction doGetSetCommentsAction(CommentsDialog dialog,
String name, String actionName, int commentType) {
return new SetCommentsAction(dialog, name, actionName, commentType);
}
protected DockingAction doGetSetCommentsAction(CommentsDialog dialog, String name,
String actionName, CommentType commentType) {
return new SetCommentsAction(dialog, name, actionName, commentType);
}
protected DockingAction doGetEditCommentsAction(CommentsDialog dialog,
String name) {
return new EditCommentsAction(dialog, name);
}
protected DockingAction doGetEditCommentsAction(CommentsDialog dialog, String name) {
return new EditCommentsAction(dialog, name);
}
protected boolean doIsCommentSupported(ProgramLocation loc) {
if (loc == null || loc.getAddress() == null) {
return false;
}
return ((loc instanceof CodeUnitLocation) || ((loc instanceof FunctionLocation) && !(loc instanceof VariableLocation)));
}
protected boolean doIsCommentSupported(ProgramLocation loc) {
if (loc == null || loc.getAddress() == null) {
return false;
}
return ((loc instanceof CodeUnitLocation) ||
((loc instanceof FunctionLocation) && !(loc instanceof VariableLocation)));
}
private static class SetCommentsAction extends DockingAction {
private final CommentsDialog dialog;
private final int commentType;
private static class SetCommentsAction extends DockingAction {
private final CommentsDialog dialog;
private final CommentType commentType; // may be null for Generic Comment
SetCommentsAction(CommentsDialog dialog, String name,
String actionName, int commentType) {
super(actionName, name);
this.dialog = dialog;
this.commentType = commentType;
setPopupMenuData(new MenuData(new String[] { "Comments",
actionName + "..." }, "comments"));
setHelpLocation(new HelpLocation("CommentsPlugin", "Edit_Comments"));
}
SetCommentsAction(CommentsDialog dialog, String name, String actionName,
CommentType commentType) {
super(actionName, name);
this.dialog = dialog;
this.commentType = commentType;
setPopupMenuData(
new MenuData(new String[] { "Comments", actionName + "..." }, "comments"));
setHelpLocation(new HelpLocation("CommentsPlugin", "Edit_Comments"));
}
protected int getEditCommentType(ActionContext context) {
return commentType;
}
/**
* {@return comment type or null for Generic Comment}
* @param context action context
*/
protected CommentType getEditCommentType(ActionContext context) {
return commentType;
}
@Override
public void actionPerformed(ActionContext context) {
CodeUnit cu = getCodeUnit(context);
int type = getEditCommentType(context);
dialog.showDialog(cu, type);
}
@Override
public void actionPerformed(ActionContext context) {
CodeUnit cu = getCodeUnit(context);
CommentType type = getEditCommentType(context);
dialog.showDialog(cu, type);
}
@Override
public boolean isEnabledForContext(ActionContext actionContext) {
ProgramLocation loc = getLocationForContext(actionContext);
if (!isCommentSupported(loc)) {
return false;
}
return CommentTypeUtils.isCommentAllowed(getCodeUnit(actionContext), loc);
}
@Override
public boolean isEnabledForContext(ActionContext actionContext) {
ProgramLocation loc = getLocationForContext(actionContext);
if (!isCommentSupported(loc)) {
return false;
}
return CommentTypeUtils.isCommentAllowed(getCodeUnit(actionContext), loc);
}
@Override
public boolean isValidContext(ActionContext context) {
return (context instanceof ListingActionContext);
}
@Override
public boolean isValidContext(ActionContext context) {
return (context instanceof ListingActionContext);
}
protected CodeUnit getCodeUnit(ActionContext actionContext) {
ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext;
return context.getCodeUnit();
}
protected CodeUnit getCodeUnit(ActionContext actionContext) {
ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext;
return context.getCodeUnit();
}
protected ProgramLocation getLocationForContext(
ActionContext actionContext) {
ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext;
return context.getLocation();
}
}
protected ProgramLocation getLocationForContext(ActionContext actionContext) {
ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext;
return context.getLocation();
}
}
private static class EditCommentsAction extends SetCommentsAction {
// Edit Comments Action info
private final static String[] EDIT_MENUPATH = new String[] {
"Comments", "Set..." };
private static class EditCommentsAction extends SetCommentsAction {
// Edit Comments Action info
private final static String[] EDIT_MENUPATH = new String[] { "Comments", "Set..." };
EditCommentsAction(CommentsDialog dialog, String name) {
super(dialog, name, "Edit Comments", CodeUnit.NO_COMMENT);
setPopupMenuData(new MenuData(EDIT_MENUPATH, "comments"));
setKeyBindingData(new KeyBindingData(KeyEvent.VK_SEMICOLON, 0));
}
EditCommentsAction(CommentsDialog dialog, String name) {
super(dialog, name, "Edit Comments", null);
setPopupMenuData(new MenuData(EDIT_MENUPATH, "comments"));
setKeyBindingData(new KeyBindingData(KeyEvent.VK_SEMICOLON, 0));
}
@Override
protected int getEditCommentType(ActionContext context) {
CodeUnit cu = getCodeUnit(context);
return CommentTypeUtils.getCommentType(cu, getLocationForContext(context), CodeUnit.NO_COMMENT);
}
}
@Override
protected CommentType getEditCommentType(ActionContext context) {
CodeUnit cu = getCodeUnit(context);
return CommentTypeUtils.getCommentType(cu, getLocationForContext(context), null);
}
}
}
@@ -35,7 +35,9 @@ import ghidra.app.util.viewer.field.AnnotatedStringHandler;
import ghidra.app.util.viewer.field.CommentUtils;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.util.HelpLocation;
import ghidra.util.exception.AssertException;
/**
* Dialog for setting the comments for a CodeUnit.
@@ -89,15 +91,15 @@ public class CommentsDialog extends ReusableDialogComponentProvider implements K
* @param cu code unit
* @param type comment type
*/
void showDialog(CodeUnit cu, int type) {
void showDialog(CodeUnit cu, CommentType type) {
setTitle("Set Comment(s) at Address " + cu.getMinAddress());
codeUnit = cu;
preComment = cu.getComment(CodeUnit.PRE_COMMENT);
postComment = cu.getComment(CodeUnit.POST_COMMENT);
eolComment = cu.getComment(CodeUnit.EOL_COMMENT);
plateComment = cu.getComment(CodeUnit.PLATE_COMMENT);
repeatableComment = cu.getComment(CodeUnit.REPEATABLE_COMMENT);
preComment = cu.getComment(CommentType.PRE);
postComment = cu.getComment(CommentType.POST);
eolComment = cu.getComment(CommentType.EOL);
plateComment = cu.getComment(CommentType.PLATE);
repeatableComment = cu.getComment(CommentType.REPEATABLE);
preComment = (preComment == null) ? "" : preComment;
postComment = (postComment == null) ? "" : postComment;
@@ -133,23 +135,29 @@ public class CommentsDialog extends ReusableDialogComponentProvider implements K
tool.showDialog(this);
}
void setCommentType(int type) {
void setCommentType(CommentType type) {
if (type == null) {
tab.setSelectedIndex(0);
return;
}
switch (type) {
case CodeUnit.EOL_COMMENT:
case CommentType.EOL:
tab.setSelectedIndex(0);
break;
case CodeUnit.PRE_COMMENT:
case CommentType.PRE:
tab.setSelectedIndex(1);
break;
case CodeUnit.POST_COMMENT:
case CommentType.POST:
tab.setSelectedIndex(2);
break;
case CodeUnit.PLATE_COMMENT:
case CommentType.PLATE:
tab.setSelectedIndex(3);
break;
case CodeUnit.REPEATABLE_COMMENT:
case CommentType.REPEATABLE:
tab.setSelectedIndex(4);
break;
default:
throw new AssertException("Unsupported comment type: " + type.name());
}
}
@@ -27,8 +27,7 @@ import ghidra.app.plugin.PluginCategoryNames;
import ghidra.framework.options.*;
import ghidra.framework.plugintool.*;
import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Program;
import ghidra.program.model.listing.*;
import ghidra.program.util.*;
import ghidra.util.HelpLocation;
@@ -129,7 +128,7 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
* @param loc the {@link ProgramLocation} for which to delete the comment
*/
void deleteComments(Program program, ProgramLocation loc) {
int commentType = CommentTypeUtils.getCommentType(null, loc, CodeUnit.EOL_COMMENT);
CommentType commentType = CommentTypeUtils.getCommentType(null, loc, CommentType.EOL);
SetCommentCmd cmd = new SetCommentCmd(loc.getByteAddress(), commentType, null);
tool.execute(cmd, program);
}
@@ -138,8 +137,8 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
if (codeUnit == null) {
return false;
}
int commentType = CommentTypeUtils.getCommentType(null, loc, CodeUnit.NO_COMMENT);
return (commentType != CodeUnit.NO_COMMENT && codeUnit.getComment(commentType) != null);
CommentType commentType = CommentTypeUtils.getCommentType(null, loc, null);
return (commentType != null && codeUnit.getComment(commentType) != null);
}
////////////////////////////////////////////////////////////////
@@ -151,23 +150,23 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
editAction = CommentsActionFactory.getEditCommentsAction(dialog, name);
tool.addAction(editAction);
preCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Pre Comment", CodeUnit.PRE_COMMENT);
"Set Pre Comment", CommentType.PRE);
tool.addAction(preCommentEditAction);
postCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Post Comment", CodeUnit.POST_COMMENT);
"Set Post Comment", CommentType.POST);
tool.addAction(postCommentEditAction);
plateCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Plate Comment", CodeUnit.PLATE_COMMENT);
"Set Plate Comment", CommentType.PLATE);
tool.addAction(plateCommentEditAction);
eolCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set EOL Comment", CodeUnit.EOL_COMMENT);
"Set EOL Comment", CommentType.EOL);
tool.addAction(eolCommentEditAction);
repeatableCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Repeatable Comment", CodeUnit.REPEATABLE_COMMENT);
"Set Repeatable Comment", CommentType.REPEATABLE);
tool.addAction(repeatableCommentEditAction);
deleteAction = new ListingContextAction("Delete Comments", pluginName) {
@@ -215,7 +214,8 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
else {
historyAction.getPopupMenuData().setMenuPath(HISTORY_MENUPATH);
}
historyAction.setEnabled(CommentTypeUtils.isCommentAllowed(context.getCodeUnit(), loc));
historyAction
.setEnabled(CommentTypeUtils.isCommentAllowed(context.getCodeUnit(), loc));
return true;
}
};
@@ -227,7 +227,7 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
private void showCommentHistory(ListingActionContext context) {
CodeUnit cu = context.getCodeUnit();
ProgramLocation loc = context.getLocation();
int commentType = CommentTypeUtils.getCommentType(null, loc, CodeUnit.EOL_COMMENT);
CommentType commentType = CommentTypeUtils.getCommentType(null, loc, CommentType.EOL);
CommentHistoryDialog historyDialog = new CommentHistoryDialog(cu, commentType);
tool.showDialog(historyDialog, context.getComponentProvider());
}
@@ -254,31 +254,34 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
}
CommentFieldLocation cfLoc = (CommentFieldLocation) loc;
int type = cfLoc.getCommentType();
CommentType type = cfLoc.getCommentType();
switch (type) {
case CodeUnit.PRE_COMMENT:
case PRE:
action.getPopupMenuData()
.setMenuPath(
new String[] { "Comments", actionString + " Pre-Comment" + endString });
break;
case CodeUnit.POST_COMMENT:
case POST:
action.getPopupMenuData()
.setMenuPath(new String[] { "Comments",
actionString + " Post-Comment" + endString });
break;
case CodeUnit.EOL_COMMENT:
case EOL:
action.getPopupMenuData()
.setMenuPath(
new String[] { "Comments", actionString + " EOL Comment" + endString });
break;
case CodeUnit.REPEATABLE_COMMENT:
case REPEATABLE:
action.getPopupMenuData()
.setMenuPath(new String[] { "Comments",
actionString + " Repeatable Comment" + endString });
break;
default:
break;
}
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -16,13 +16,14 @@
package ghidra.app.plugin.core.commentwindow;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType;
class CommentRowObject implements Comparable<CommentRowObject> {
private final Address address;
private final int commentType;
private final CommentType commentType;
CommentRowObject(Address address, int commentType) {
CommentRowObject(Address address, CommentType commentType) {
this.address = address;
this.commentType = commentType;
}
@@ -31,7 +32,7 @@ class CommentRowObject implements Comparable<CommentRowObject> {
return address;
}
int getCommentType() {
CommentType getCommentType() {
return commentType;
}
@@ -40,7 +41,7 @@ class CommentRowObject implements Comparable<CommentRowObject> {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + commentType;
result = prime * result + commentType.hashCode();
return result;
}
@@ -75,7 +76,7 @@ class CommentRowObject implements Comparable<CommentRowObject> {
int result = address.compareTo(o.address);
if (result == 0) {
result = commentType - o.commentType;
result = commentType.compareTo(o.commentType);
}
return result;
}
@@ -4,9 +4,9 @@
* 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.
@@ -94,26 +94,26 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
continue;
}
if (cu.getComment(CodeUnit.PRE_COMMENT) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.PRE_COMMENT));
if (cu.getComment(CommentType.PRE) != null) {
accumulator.add(new CommentRowObject(commentAddr, CommentType.PRE));
}
if (cu.getComment(CodeUnit.POST_COMMENT) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.POST_COMMENT));
if (cu.getComment(CommentType.POST) != null) {
accumulator.add(new CommentRowObject(commentAddr, CommentType.POST));
}
if (cu.getComment(CodeUnit.EOL_COMMENT) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.EOL_COMMENT));
if (cu.getComment(CommentType.EOL) != null) {
accumulator.add(new CommentRowObject(commentAddr, CommentType.EOL));
}
if (cu.getComment(CodeUnit.PLATE_COMMENT) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.PLATE_COMMENT));
if (cu.getComment(CommentType.PLATE) != null) {
accumulator.add(new CommentRowObject(commentAddr, CommentType.PLATE));
}
if (cu.getComment(CodeUnit.REPEATABLE_COMMENT) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.REPEATABLE_COMMENT));
if (cu.getComment(CommentType.REPEATABLE) != null) {
accumulator.add(new CommentRowObject(commentAddr, CommentType.REPEATABLE));
}
}
}
void commentAdded(Address addr, int commentType) {
void commentAdded(Address addr, CommentType commentType) {
String comment = listing.getComment(commentType, addr);
if (comment == null) {
@@ -125,7 +125,7 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
}
void commentRemoved(Address addr, int commentType) {
void commentRemoved(Address addr, CommentType commentType) {
removeObject(new CommentRowObject(addr, commentType));
}
@@ -161,23 +161,23 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
}
@Override
public String getValue(CommentRowObject rowObject, Settings settings, Program program,
public String getValue(CommentRowObject rowObject, Settings settings, Program p,
ServiceProvider provider) throws IllegalArgumentException {
String returnString = "";
if (rowObject.getCommentType() == CodeUnit.EOL_COMMENT) {
if (rowObject.getCommentType() == CommentType.EOL) {
return "EOL Comment";
}
if (rowObject.getCommentType() == CodeUnit.PLATE_COMMENT) {
if (rowObject.getCommentType() == CommentType.PLATE) {
return "Plate Comment";
}
if (rowObject.getCommentType() == CodeUnit.PRE_COMMENT) {
if (rowObject.getCommentType() == CommentType.PRE) {
return "Pre Comment";
}
if (rowObject.getCommentType() == CodeUnit.POST_COMMENT) {
if (rowObject.getCommentType() == CommentType.POST) {
return "Post Comment";
}
if (rowObject.getCommentType() == CodeUnit.REPEATABLE_COMMENT) {
if (rowObject.getCommentType() == CommentType.REPEATABLE) {
return "Repeatable Comment";
}
return returnString;
@@ -198,7 +198,7 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
}
@Override
public String getValue(CommentRowObject rowObject, Settings settings, Program program,
public String getValue(CommentRowObject rowObject, Settings settings, Program p,
ServiceProvider provider) throws IllegalArgumentException {
String comment = getCommentForRowObject(rowObject);
return comment;
@@ -4,9 +4,9 @@
* 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.
@@ -30,6 +30,7 @@ import ghidra.framework.plugintool.PluginInfo;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program;
import ghidra.program.util.CommentChangeRecord;
import ghidra.program.util.ProgramSelection;
@@ -94,7 +95,7 @@ public class CommentWindowPlugin extends ProgramPlugin {
}
private void handleCommentChanged(CommentChangeRecord ccr) {
int commentType = ccr.getCommentType();
CommentType commentType = ccr.getCommentType();
String oldComment = ccr.getOldComment();
String newComment = ccr.getNewComment();
Address commentAddress = ccr.getStart();
@@ -4,9 +4,9 @@
* 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.
@@ -25,6 +25,7 @@ import javax.swing.table.JTableHeader;
import docking.ActionContext;
import ghidra.framework.plugintool.ComponentProviderAdapter;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program;
import ghidra.util.HelpLocation;
import ghidra.util.table.*;
@@ -153,13 +154,13 @@ class CommentWindowProvider extends ComponentProviderAdapter {
}
}
void commentAdded(Address address, int commentType) {
void commentAdded(Address address, CommentType commentType) {
if (isVisible()) {
commentModel.commentAdded(address, commentType);
}
}
void commentRemoved(Address address, int commentType) {
void commentRemoved(Address address, CommentType commentType) {
if (isVisible()) {
commentModel.commentRemoved(address, commentType);
}
@@ -4,9 +4,9 @@
* 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.
@@ -97,7 +97,6 @@ public class AddressTable {
this.skipAmount = skipAmount;
this.shiftedAddr = shiftedAddr;
}
/**
* Create a new address table from any remaining table entries starting at startPos
@@ -388,8 +387,7 @@ public class AddressTable {
Address lastAddress = null;
DataType ptrDT = program.getDataTypeManager()
.addDataType(
PointerDataType.getPointer(null, addrSize), null);
.addDataType(PointerDataType.getPointer(null, addrSize), null);
for (int i = 0; i < tableSize; i++) {
Address loc = tableAddr.add(i * addrSize);
try {
@@ -472,8 +470,8 @@ public class AddressTable {
if (!flagNewCode || !newCodeFound) {
// create a case label
if (!ftype.isCall()) {
AddLabelCmd lcmd = new AddLabelCmd(target,
caseName + Integer.toHexString(i), true, SourceType.ANALYSIS);
AddLabelCmd lcmd = new AddLabelCmd(target, caseName + Integer.toHexString(i),
true, SourceType.ANALYSIS);
switchLabelList.add(lcmd);
}
@@ -496,7 +494,7 @@ public class AddressTable {
}
if (comment != null) {
program.getListing().setComment(topAddress, CodeUnit.EOL_COMMENT, comment);
program.getListing().setComment(topAddress, CommentType.EOL, comment);
}
if (flagNewCode && newCodeFound) {
@@ -574,8 +572,9 @@ public class AddressTable {
// not putting switch into functions anymore
// program.getSymbolTable().getNamespace(start_inst.getMinAddress());
try {
space = program.getSymbolTable().createNameSpace(null,
"switch_" + start_inst.getMinAddress(), SourceType.ANALYSIS);
space = program.getSymbolTable()
.createNameSpace(null, "switch_" + start_inst.getMinAddress(),
SourceType.ANALYSIS);
}
catch (DuplicateNameException e) {
// just go with default space
@@ -607,8 +606,8 @@ public class AddressTable {
}
// make sure the reference is associated with this symbol
Symbol s = program.getSymbolTable().getGlobalSymbol(tableNameLabel.getLabelName(),
tableNameLabel.getLabelAddr());
Symbol s = program.getSymbolTable()
.getGlobalSymbol(tableNameLabel.getLabelName(), tableNameLabel.getLabelAddr());
for (int op = 0; op < start_inst.getNumOperands(); op++) {
Reference fromRefs[] = start_inst.getOperandReferences(op);
for (Reference fromRef : fromRefs) {
@@ -1233,12 +1232,12 @@ public class AddressTable {
continue;
}
}
// undefined data is OK, could be a pointer
if (data.getDataType() instanceof Undefined) {
continue;
}
// data intersects, calculate valid entries and stop looking
if (pointerSet.intersects(dataAddr, data.getMaxAddress())) {
count = (int) (dataAddr.subtract(topAddr) / (addrSize + skipAmount));
@@ -28,11 +28,11 @@ import ghidra.util.StringUtilities;
public class CommentFieldSearcher extends ProgramDatabaseFieldSearcher {
private AddressIterator iterator;
private final int commentType;
private final CommentType commentType;
private Program program;
public CommentFieldSearcher(Program program, ProgramLocation startLoc, AddressSetView set,
boolean forward, Pattern pattern, int commentType) {
boolean forward, Pattern pattern, CommentType commentType) {
super(pattern, forward, startLoc, set);
this.commentType = commentType;
@@ -89,16 +89,16 @@ public class CommentFieldSearcher extends ProgramDatabaseFieldSearcher {
int charOffset = getRelativeCharOffset(index, rowIndex, comments);
int[] dataPath = getDataComponentPath(address);
switch (commentType) {
case CodeUnit.EOL_COMMENT:
case EOL:
return new EolCommentFieldLocation(program, address, dataPath, comments, rowIndex,
charOffset, rowIndex);
case CodeUnit.PLATE_COMMENT:
case PLATE:
return new PlateFieldLocation(program, address, dataPath, rowIndex, charOffset,
comments, rowIndex);
case CodeUnit.REPEATABLE_COMMENT:
case REPEATABLE:
return new RepeatableCommentFieldLocation(program, address, dataPath, comments,
rowIndex, charOffset, rowIndex); // TODO One of searchStrIndex parameters is wrong.
case CodeUnit.POST_COMMENT:
case POST:
return new PostCommentFieldLocation(program, address, dataPath, comments, rowIndex,
charOffset);
default:
@@ -4,9 +4,9 @@
* 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.
@@ -23,7 +23,7 @@ import ghidra.app.plugin.core.searchtext.Searcher;
import ghidra.app.util.viewer.field.BrowserCodeUnitFormat;
import ghidra.framework.plugintool.ServiceProvider;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program;
import ghidra.program.util.ProgramLocation;
import ghidra.util.UserSearchUtils;
@@ -181,7 +181,7 @@ public class ProgramDatabaseSearcher implements Searcher {
if (options.searchComments()) {
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.PLATE_COMMENT));
pattern, CommentType.PLATE));
}
if (options.searchFunctions()) {
searchers.add(
@@ -189,7 +189,7 @@ public class ProgramDatabaseSearcher implements Searcher {
}
if (options.searchComments()) {
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.PRE_COMMENT));
pattern, CommentType.PRE));
}
if (options.searchLabels()) {
searchers.add(
@@ -209,10 +209,9 @@ public class ProgramDatabaseSearcher implements Searcher {
program, adjustedStart, trimmedSet, forward, pattern, format));
}
if (options.searchBothInstructionMnemonicAndOperands()) {
searchers.add(
InstructionMnemonicOperandFieldSearcher
.createInstructionMnemonicAndOperandFieldSearcher(
program, adjustedStart, trimmedSet, forward, pattern, format));
searchers.add(InstructionMnemonicOperandFieldSearcher
.createInstructionMnemonicAndOperandFieldSearcher(program, adjustedStart,
trimmedSet, forward, pattern, format));
}
if (options.searchOnlyInstructionMnemonics()) {
searchers.add(
@@ -226,11 +225,11 @@ public class ProgramDatabaseSearcher implements Searcher {
}
if (options.searchComments()) {
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.EOL_COMMENT));
pattern, CommentType.EOL));
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.REPEATABLE_COMMENT));
pattern, CommentType.REPEATABLE));
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.POST_COMMENT));
pattern, CommentType.POST));
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -19,7 +19,7 @@ import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.cmd.data.CreateDataCmd;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program;
import ghidra.program.model.util.CodeUnitInsertionException;
import ghidra.util.task.TaskMonitor;
@@ -100,12 +100,10 @@ public abstract class GccAnalysisClass {
* @param addr the address where data is created
* @param dt the type for the data
* @param comment the comment about the data
* @param commentType the type of comment ({@link CodeUnit#PLATE_COMMENT},
* {@link CodeUnit#PRE_COMMENT}, {@link CodeUnit#EOL_COMMENT}, {@link CodeUnit#POST_COMMENT},
* {@link CodeUnit#REPEATABLE_COMMENT})
* @param commentType the type of comment
*/
protected static void createAndCommentData(Program program, Address addr, DataType dt,
String comment, int commentType) {
String comment, CommentType commentType) {
createData(program, addr, dt);
SetCommentCmd.createComment(program, addr, comment, commentType);
}
@@ -4,9 +4,9 @@
* 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.
@@ -46,14 +46,12 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
public static final String DESCRIPTION =
"Locates and annotates exception-handling infrastructure installed by the GCC compiler";
protected static final String OPTION_NAME_CREATE_TRY_CATCH_COMMENTS =
"Create Try Catch Comments";
private static final String OPTION_DESCRIPTION_CREATE_TRY_CATCH_COMMENTS =
protected static final String OPTION_NAME_CREATE_TRY_CATCHS = "Create Try Catch Comments";
private static final String OPTION_DESCRIPTION_CREATE_TRY_CATCHS =
"Selecting this check box causes the analyzer to create comments in the " +
"disassembly listing for the try and catch code.";
private static final boolean OPTION_DEFAULT_CREATE_TRY_CATCH_COMMENTS_ENABLED = true;
private boolean createTryCatchCommentsEnabled =
OPTION_DEFAULT_CREATE_TRY_CATCH_COMMENTS_ENABLED;
private static final boolean OPTION_DEFAULT_CREATE_TRY_CATCHS_ENABLED = true;
private boolean createTryCatchCommentsEnabled = OPTION_DEFAULT_CREATE_TRY_CATCHS_ENABLED;
private Set<Program> visitedPrograms = new HashSet<>();
private AutoAnalysisManagerListener analysisListener =
@@ -288,11 +286,11 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
Address csMaxAddr = callSite.getMaxAddress();
String startTryComment = "try { // try from " + csMinAddr + " to " + csMaxAddr +
" has its CatchHandler @ " + lpAddr;
String existingComment = program.getListing().getComment(CodeUnit.PRE_COMMENT, csMinAddr);
String existingComment = program.getListing().getComment(CommentType.PRE, csMinAddr);
if (existingComment == null || !existingComment.contains(startTryComment)) {
String mergedComment = StringUtilities.mergeStrings(existingComment, startTryComment);
SetCommentCmd setCommentCmd =
new SetCommentCmd(csMinAddr, CodeUnit.PRE_COMMENT, mergedComment);
new SetCommentCmd(csMinAddr, CommentType.PRE, mergedComment);
setCommentCmd.applyTo(program);
}
}
@@ -304,12 +302,11 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
if (csMaxCodeUnit != null) {
Address commentAddr = csMaxCodeUnit.getMinAddress();
String endTryComment = "} // end try from " + csMinAddr + " to " + csMaxAddr;
String existingComment =
program.getListing().getComment(CodeUnit.POST_COMMENT, commentAddr);
String existingComment = program.getListing().getComment(CommentType.POST, commentAddr);
if (existingComment == null || !existingComment.contains(endTryComment)) {
String mergedComment = StringUtilities.mergeStrings(existingComment, endTryComment);
SetCommentCmd setCommentCmd =
new SetCommentCmd(commentAddr, CodeUnit.POST_COMMENT, mergedComment);
new SetCommentCmd(commentAddr, CommentType.POST, mergedComment);
setCommentCmd.applyTo(program);
}
}
@@ -322,11 +319,10 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
typeInfos.stream().map(a -> getCatchParamInfo(a)).collect(Collectors.joining(", "));
String startCatchComment =
"catch(" + typeString + ") { ... } // from try @ " + csAddr + " with catch @ " + lpAddr;
String existingComment = program.getListing().getComment(CodeUnit.PRE_COMMENT, lpAddr);
String existingComment = program.getListing().getComment(CommentType.PRE, lpAddr);
if (existingComment == null || !existingComment.contains(startCatchComment)) {
String mergedComment = StringUtilities.mergeStrings(existingComment, startCatchComment);
SetCommentCmd setCommentCmd =
new SetCommentCmd(lpAddr, CodeUnit.PRE_COMMENT, mergedComment);
SetCommentCmd setCommentCmd = new SetCommentCmd(lpAddr, CommentType.PRE, mergedComment);
setCommentCmd.applyTo(program);
}
}
@@ -346,12 +342,12 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
// // TODO If we can determine the length of the catch handler we could mark its end too.
// Address lpMaxAddr = ?;
// String endCatchComment = "} // end catchHandler()";
// String existingComment = program.getListing().getComment(CodeUnit.POST_COMMENT, lpMaxAddr);
// String existingComment = program.getListing().getComment(CommentType.POST, lpMaxAddr);
// if (existingComment == null || !existingComment.contains(endCatchComment)) {
// String mergedComment =
// StringUtilities.mergeStrings(existingComment, endCatchComment);
// SetCommentCmd setCommentCmd =
// new SetCommentCmd(lpMaxAddr, CodeUnit.POST_COMMENT, endCatchComment);
// new SetCommentCmd(lpMaxAddr, CommentType.POST, endCatchComment);
// setCommentCmd.applyTo(program);
// }
}
@@ -429,14 +425,14 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
@Override
public void registerOptions(Options options, Program program) {
options.registerOption(OPTION_NAME_CREATE_TRY_CATCH_COMMENTS, createTryCatchCommentsEnabled,
null, OPTION_DESCRIPTION_CREATE_TRY_CATCH_COMMENTS);
options.registerOption(OPTION_NAME_CREATE_TRY_CATCHS, createTryCatchCommentsEnabled, null,
OPTION_DESCRIPTION_CREATE_TRY_CATCHS);
}
@Override
public void optionsChanged(Options options, Program program) {
createTryCatchCommentsEnabled = options.getBoolean(OPTION_NAME_CREATE_TRY_CATCH_COMMENTS,
createTryCatchCommentsEnabled);
createTryCatchCommentsEnabled =
options.getBoolean(OPTION_NAME_CREATE_TRY_CATCHS, createTryCatchCommentsEnabled);
}
}
@@ -5,9 +5,9 @@
* 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.
@@ -24,7 +24,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.RegionDescriptor;
import ghidra.app.plugin.exceptionhandlers.gcc.structures.ehFrame.*;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.ByteDataType;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.mem.MemoryBlock;
@@ -176,8 +176,7 @@ abstract class AbstractFrameSection implements CieSource {
private void createPlateComment(Address curAddress, String fdeComment) {
SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.PLATE_COMMENT, fdeComment);
SetCommentCmd commentCmd = new SetCommentCmd(curAddress, CommentType.PLATE, fdeComment);
commentCmd.applyTo(program);
}
}
@@ -4,9 +4,9 @@
* 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.
@@ -22,7 +22,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.structures.ehFrame.*;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressOutOfBoundsException;
import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.mem.MemoryBlock;
@@ -127,7 +127,7 @@ public class EhFrameHeaderSection {
dataCmd.applyTo(program);
SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.EOL_COMMENT, "Encoded FDE count");
new SetCommentCmd(curAddress, CommentType.EOL, "Encoded FDE count");
commentCmd.applyTo(program);
curAddress = curAddress.add(ctx.getEncodedLength());
@@ -160,8 +160,8 @@ public class EhFrameHeaderSection {
DwarfDecodeContext ctx = new DwarfDecodeContext(program, curAddress, curMemBlock);
Address frmPtrAddr = frmPtrDecoder.decodeAddress(ctx);
program.getReferenceManager().addMemoryReference(curAddress, frmPtrAddr, RefType.DATA,
SourceType.ANALYSIS, 0);
program.getReferenceManager()
.addMemoryReference(curAddress, frmPtrAddr, RefType.DATA, SourceType.ANALYSIS, 0);
DataType frmPtrDataType = frmPtrDecoder.getDataType(program);
@@ -169,7 +169,7 @@ public class EhFrameHeaderSection {
dataCmd.applyTo(program);
SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.EOL_COMMENT, "Encoded eh_frame_ptr");
new SetCommentCmd(curAddress, CommentType.EOL, "Encoded eh_frame_ptr");
commentCmd.applyTo(program);
curAddress = curAddress.add(ctx.getEncodedLength());
@@ -185,8 +185,8 @@ public class EhFrameHeaderSection {
}
private void createFdeTable(Address curAddress, ExceptionHandlerFrameHeader eh_frame_hdr,
int fdeTableCnt, TaskMonitor monitor) throws MemoryAccessException,
ExceptionHandlerFrameException {
int fdeTableCnt, TaskMonitor monitor)
throws MemoryAccessException, ExceptionHandlerFrameException {
/* Build the Frame Descriptor Entry Table */
int fdeTblEnc = eh_frame_hdr.getEh_FrameTableEncoding();
@@ -196,7 +196,7 @@ public class EhFrameHeaderSection {
fde_table.create(curAddress, fdeTblDecoder, fdeTableCnt);
SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.PLATE_COMMENT, "Frame Description Entry Table");
new SetCommentCmd(curAddress, CommentType.PLATE, "Frame Description Entry Table");
commentCmd.applyTo(program);
}
@@ -4,9 +4,9 @@
* 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.
@@ -134,7 +134,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure.
*/
String comment = "(CIE) Length";
createAndCommentData(program, addr, dwordDT, comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, dwordDT, comment, CommentType.EOL);
program.getMemory().getBytes(addr, enc_length);
curSize += DWORD_LEN;
@@ -161,7 +161,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure.
*/
String comment = "(CIE) ID";
createAndCommentData(program, addr, dwordDT, comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, dwordDT, comment, CommentType.EOL);
program.getMemory().getBytes(addr, enc_cieId);
cieId = (int) GccAnalysisUtils.readDWord(program, addr);
@@ -184,7 +184,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure.
*/
String comment = "(CIE) Version";
createAndCommentData(program, addr, new ByteDataType(), comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, new ByteDataType(), comment, CommentType.EOL);
version = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN;
@@ -208,7 +208,7 @@ public class Cie extends GccAnalysisClass {
* and sets an appropriate comment for the new structure.
*/
String comment = "(CIE) Augmentation String";
createAndCommentData(program, addr, new StringDataType(), comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, new StringDataType(), comment, CommentType.EOL);
Data dataAt = program.getListing().getDataAt(addr);
if (dataAt == null) {
throw new ExceptionHandlerFrameException(
@@ -236,7 +236,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure.
*/
String comment = "(CIE) Pointer Size";
createAndCommentData(program, addr, new ByteDataType(), comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, new ByteDataType(), comment, CommentType.EOL);
ptrSize = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN;
@@ -258,7 +258,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure.
*/
String comment = "(CIE) Segment Size";
createAndCommentData(program, addr, new ByteDataType(), comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, new ByteDataType(), comment, CommentType.EOL);
segmentSize = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN;
@@ -285,7 +285,7 @@ public class Cie extends GccAnalysisClass {
codeAlignFactor = (int) uleb128.asLong();
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT);
CommentType.EOL);
curSize += uleb128.getLength();
@@ -312,7 +312,7 @@ public class Cie extends GccAnalysisClass {
dataAlignFactor = (int) sleb128.asLong();
createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT);
CommentType.EOL);
curSize += sleb128.getLength();
@@ -356,7 +356,7 @@ public class Cie extends GccAnalysisClass {
}
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
curSize += encodedLen;
return addr.add(encodedLen);
@@ -382,7 +382,7 @@ public class Cie extends GccAnalysisClass {
augmentationDataLength = (int) uleb128.asLong();
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT);
CommentType.EOL);
curSize += uleb128.getLength();
@@ -430,8 +430,7 @@ public class Cie extends GccAnalysisClass {
initialInstructionCount = intLength - curSize;
arrayCmd = new CreateArrayCmd(addr, initialInstructionCount, new ByteDataType(), BYTE_LEN);
arrayCmd.applyTo(program);
SetCommentCmd.createComment(program, addr, "(CIE) Initial Instructions",
CodeUnit.EOL_COMMENT);
SetCommentCmd.createComment(program, addr, "(CIE) Initial Instructions", CommentType.EOL);
initialInstructions = new byte[initialInstructionCount];
int numBytesRead = program.getMemory().getBytes(addr, initialInstructions);
@@ -525,8 +524,8 @@ public class Cie extends GccAnalysisClass {
}
private void markEndOfFrame(Address addr) {
createAndCommentData(program, addr, dwordDT, "End of Frame", CodeUnit.EOL_COMMENT);
SetCommentCmd commentCmd = new SetCommentCmd(addr, CodeUnit.PLATE_COMMENT, "END OF FRAME");
createAndCommentData(program, addr, dwordDT, "End of Frame", CommentType.EOL);
SetCommentCmd commentCmd = new SetCommentCmd(addr, CommentType.PLATE, "END OF FRAME");
commentCmd.applyTo(program);
}
@@ -549,7 +548,7 @@ public class Cie extends GccAnalysisClass {
if (intLength == 0xffffffff) {
hasExtLength = true;
String comment = "(CIE) Extended Length";
createAndCommentData(program, addr, new QWordDataType(), comment, CodeUnit.EOL_COMMENT);
createAndCommentData(program, addr, new QWordDataType(), comment, CommentType.EOL);
program.getMemory().getBytes(addr, enc_extLength);
addr = addr.add(QWORD_LEN);
curSize += QWORD_LEN;
@@ -620,7 +619,7 @@ public class Cie extends GccAnalysisClass {
String lsdaComment = "(CIE Augmentation Data) LSDA Personality Function Pointer Encoding";
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
new DwarfEncodingModeDataType(), lsdaComment, CodeUnit.EOL_COMMENT);
new DwarfEncodingModeDataType(), lsdaComment, CommentType.EOL);
}
private void processFdeEncoding(Address augmentationDataAddr, int augmentationDataIndex,
@@ -630,7 +629,7 @@ public class Cie extends GccAnalysisClass {
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
new DwarfEncodingModeDataType(), "(CIE Augmentation Data) FDE Encoding",
CodeUnit.EOL_COMMENT);
CommentType.EOL);
}
private DwarfEHDecoder processPersonalityEncoding(Address augmentationDataAddr,
@@ -643,7 +642,7 @@ public class Cie extends GccAnalysisClass {
String prsnltyComment = "(CIE Augmentation Data) Personality Function Pointer Encoding";
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
new DwarfEncodingModeDataType(), prsnltyComment, CodeUnit.EOL_COMMENT);
new DwarfEncodingModeDataType(), prsnltyComment, CommentType.EOL);
return personalityDecoder;
}
@@ -660,11 +659,11 @@ public class Cie extends GccAnalysisClass {
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
prnsFuncPtrDt,
"(CIE Augmentation Data) Personality Function Pointer (" + personalityFuncAddr + ")",
CodeUnit.EOL_COMMENT);
CommentType.EOL);
program.getReferenceManager().addMemoryReference(
augmentationDataAddr.add(augmentationDataIndex), personalityFuncAddr, RefType.DATA,
SourceType.ANALYSIS, 0);
program.getReferenceManager()
.addMemoryReference(augmentationDataAddr.add(augmentationDataIndex),
personalityFuncAddr, RefType.DATA, SourceType.ANALYSIS, 0);
return personalityDecodeContext;
}

Some files were not shown because too many files have changed in this diff Show More