diff --git a/Ghidra/Debug/Debugger/ghidra_scripts/PopulateDemoTrace.java b/Ghidra/Debug/Debugger/ghidra_scripts/PopulateDemoTrace.java index c050947e5e..a53fa6e066 100644 --- a/Ghidra/Debug/Debugger/ghidra_scripts/PopulateDemoTrace.java +++ b/Ghidra/Debug/Debugger/ghidra_scripts/PopulateDemoTrace.java @@ -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 @@ -502,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); diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlan.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlan.java index f818f6096a..5e708c6669 100644 --- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlan.java +++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlan.java @@ -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); } } } diff --git a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/AnalysisUnwoundFrame.java b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/AnalysisUnwoundFrame.java index ac867c5ff6..74929354bd 100644 --- a/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/AnalysisUnwoundFrame.java +++ b/Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/stack/AnalysisUnwoundFrame.java @@ -144,16 +144,14 @@ public class AnalysisUnwoundFrame extends AbstractUnwoundFrame { 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 extends AbstractUnwoundFrame { @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)); diff --git a/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlanTest.java b/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlanTest.java index 985b9ab0dd..3e3bf474eb 100644 --- a/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlanTest.java +++ b/Ghidra/Debug/Debugger/src/test/java/ghidra/app/plugin/core/debug/gui/copying/DebuggerCopyPlanTest.java @@ -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,8 +703,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); Listing listing = view.getListing(); listing.setComment(tb.addr(0x55550123), CommentType.EOL, "Test EOL Comment"); @@ -721,8 +714,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.COMMENTS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr, TaskMonitor.DUMMY); diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCodeUnitAdapter.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCodeUnitAdapter.java index 0a7da73bed..ef6abe410d 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCodeUnitAdapter.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCodeUnitAdapter.java @@ -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 getProperty(String name, Class valueClass) { try (LockHold hold = LockHold.lock(getTrace().getReadWriteLock().readLock())) { - TracePropertyMap map = - getTrace().getInternalAddressPropertyManager() - .getPropertyMapExtends(name, valueClass); + TracePropertyMap 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; } diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCommentAdapter.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCommentAdapter.java index 188319f070..ef8e115444 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCommentAdapter.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/listing/DBTraceCommentAdapter.java @@ -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 { 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( @@ -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); } } diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/AbstractDBTraceProgramViewListing.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/AbstractDBTraceProgramViewListing.java index a4a765d09a..24ca72b1b7 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/AbstractDBTraceProgramViewListing.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/AbstractDBTraceProgramViewListing.java @@ -145,8 +145,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV } protected Comparator 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 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 getDefinedDataIterator(Address start, boolean forward) { @@ -195,13 +193,13 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV protected Iterator 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 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 getDefinedUnitIterator(Address start, @@ -226,8 +224,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV defStart = defUnit.getMinAddress(); } } - Iterator defIter = IteratorUtils.transformedIterator( - getDefinedUnitIterator(defStart, forward), u -> u.getRange()); + Iterator 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 defIter = IteratorUtils.transformedIterator( - getDefinedUnitIterator(set, forward), u -> u.getRange()); + Iterator 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 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 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 getCodeUnitIterator(boolean forward) { @@ -286,17 +281,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV } protected Iterator 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 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 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[] {}; } } diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramView.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramView.java index 3bb1130189..303a4a2089 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramView.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/program/DBTraceProgramView.java @@ -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, diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/stack/DBTraceObjectStackFrame.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/stack/DBTraceObjectStackFrame.java index 7aa32aee7f..d24e508407 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/stack/DBTraceObjectStackFrame.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/database/stack/DBTraceObjectStackFrame.java @@ -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); } } diff --git a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/util/TraceEvents.java b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/util/TraceEvents.java index 3ff1d33435..607bc3ff10 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/util/TraceEvents.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/main/java/ghidra/trace/util/TraceEvents.java @@ -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(); }; } diff --git a/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/listing/DBTraceCodeUnitTest.java b/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/listing/DBTraceCodeUnitTest.java index 3ec509a081..5bd7818d5e 100644 --- a/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/listing/DBTraceCodeUnitTest.java +++ b/Ghidra/Debug/Framework-TraceModeling/src/test/java/ghidra/trace/database/listing/DBTraceCodeUnitTest.java @@ -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) { @@ -408,7 +404,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest 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(CommentType.EOL)); assertArrayEquals(new String[] { "My", "Pre", "Comment" }, @@ -417,8 +413,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest 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(CommentType.PRE)); @@ -444,14 +440,13 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest try (Transaction tx = b.startTransaction()) { commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000), - CodeUnit.EOL_COMMENT); + CommentType.EOL); } 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(CommentType.EOL)); assertNull(i4004_10.getComment(CommentType.PRE)); @@ -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) 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)); diff --git a/Ghidra/Features/Base/ghidra_scripts/AddCommentToProgramScript.java b/Ghidra/Features/Base/ghidra_scripts/AddCommentToProgramScript.java index 87e7a3102e..c147438358 100644 --- a/Ghidra/Features/Base/ghidra_scripts/AddCommentToProgramScript.java +++ b/Ghidra/Features/Base/ghidra_scripts/AddCommentToProgramScript.java @@ -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!"); + } } diff --git a/Ghidra/Features/Base/ghidra_scripts/AutoRenameSimpleLabels.java b/Ghidra/Features/Base/ghidra_scripts/AutoRenameSimpleLabels.java index 24970531e2..376453b6a4 100644 --- a/Ghidra/Features/Base/ghidra_scripts/AutoRenameSimpleLabels.java +++ b/Ghidra/Features/Base/ghidra_scripts/AutoRenameSimpleLabels.java @@ -49,7 +49,6 @@ public class AutoRenameSimpleLabels extends GhidraScript { @Override public void run() throws Exception { - String tmpString = "\nScript: AutoRenameSimpleLabels() \n"; //get listing of symbols SymbolIterator iter = currentProgram.getSymbolTable().getAllSymbols(true); @@ -147,15 +146,13 @@ public class AutoRenameSimpleLabels extends GhidraScript { // now also propogate the repeatable comment up as well - String comment = currentProgram.getListing().getComment(CommentType.REPEATABLE, - operand_addr); - if (comment != null) { - if (currentProgram.getListing().getComment(CommentType.REPEATABLE, - startAddr) == null) { - //println("updating comment for " + operand +" is " + comment); - currentProgram.getListing() - .setComment(startAddr, CommentType.REPEATABLE, comment); - } + String comment = + currentProgram.getListing().getComment(CommentType.REPEATABLE, operand_addr); + if (comment != null && currentProgram.getListing() + .getComment(CommentType.REPEATABLE, startAddr) == null) { + //println("updating comment for " + operand +" is " + comment); + currentProgram.getListing() + .setComment(startAddr, CommentType.REPEATABLE, comment); } } } diff --git a/Ghidra/Features/Base/ghidra_scripts/DeleteDeadDefaultPlatesScript.java b/Ghidra/Features/Base/ghidra_scripts/DeleteDeadDefaultPlatesScript.java index bf8a46eccc..cc5fe05f97 100644 --- a/Ghidra/Features/Base/ghidra_scripts/DeleteDeadDefaultPlatesScript.java +++ b/Ghidra/Features/Base/ghidra_scripts/DeleteDeadDefaultPlatesScript.java @@ -24,17 +24,16 @@ 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; + + int updateCount = 0; AddressIterator iter = listing.getCommentAddressIterator(CommentType.PLATE, set, true); while (iter.hasNext()) { Address addr = iter.next(); @@ -48,7 +47,7 @@ public class DeleteDeadDefaultPlatesScript extends GhidraScript { } } if (updateCount > 0) { - String cmt = updateCount > 1? "comments" : "comment"; + String cmt = updateCount > 1 ? "comments" : "comment"; println("Removed " + updateCount + " default plate " + cmt + "."); } else { diff --git a/Ghidra/Features/Base/ghidra_scripts/DeleteEmptyPlateCommentsScript.java b/Ghidra/Features/Base/ghidra_scripts/DeleteEmptyPlateCommentsScript.java index 9906d3f23b..2767069f4c 100644 --- a/Ghidra/Features/Base/ghidra_scripts/DeleteEmptyPlateCommentsScript.java +++ b/Ghidra/Features/Base/ghidra_scripts/DeleteEmptyPlateCommentsScript.java @@ -24,17 +24,16 @@ 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; + + int updateCount = 0; AddressIterator iter = listing.getCommentAddressIterator(CommentType.PLATE, set, true); while (iter.hasNext()) { Address addr = iter.next(); @@ -48,7 +47,7 @@ public class DeleteEmptyPlateCommentsScript extends GhidraScript { } } if (updateCount > 0) { - String cmt = updateCount > 1? "comments" : "comment"; + String cmt = updateCount > 1 ? "comments" : "comment"; println("Removed " + updateCount + " emtpy plate " + cmt + "."); } else { diff --git a/Ghidra/Features/Base/ghidra_scripts/DeleteExitCommentsScript.java b/Ghidra/Features/Base/ghidra_scripts/DeleteExitCommentsScript.java index 10d61e2a72..c4ffd412ed 100644 --- a/Ghidra/Features/Base/ghidra_scripts/DeleteExitCommentsScript.java +++ b/Ghidra/Features/Base/ghidra_scripts/DeleteExitCommentsScript.java @@ -24,17 +24,16 @@ 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; + + int updateCount = 0; AddressIterator iter = listing.getCommentAddressIterator(CommentType.POST, set, true); while (iter.hasNext()) { Address addr = iter.next(); @@ -46,7 +45,7 @@ public class DeleteExitCommentsScript extends GhidraScript { } } if (updateCount > 0) { - String cmt = updateCount > 1? "comments" : "comment"; + String cmt = updateCount > 1 ? "comments" : "comment"; println("Removed " + updateCount + " exit post " + cmt + "."); } else { diff --git a/Ghidra/Features/Base/ghidra_scripts/LocateMemoryAddressesForFileOffset.java b/Ghidra/Features/Base/ghidra_scripts/LocateMemoryAddressesForFileOffset.java index 9e7114f954..08ba0d85aa 100644 --- a/Ghidra/Features/Base/ghidra_scripts/LocateMemoryAddressesForFileOffset.java +++ b/Ghidra/Features/Base/ghidra_scripts/LocateMemoryAddressesForFileOffset.java @@ -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()); diff --git a/Ghidra/Features/Base/ghidra_scripts/MultiInstructionMemReference.java b/Ghidra/Features/Base/ghidra_scripts/MultiInstructionMemReference.java index 04dc9c79fa..f6943f5d5f 100644 --- a/Ghidra/Features/Base/ghidra_scripts/MultiInstructionMemReference.java +++ b/Ghidra/Features/Base/ghidra_scripts/MultiInstructionMemReference.java @@ -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; } diff --git a/Ghidra/Features/Base/ghidra_scripts/RegisterTouchesPerFunction.java b/Ghidra/Features/Base/ghidra_scripts/RegisterTouchesPerFunction.java index 7fa677657c..3b6f57bebe 100644 --- a/Ghidra/Features/Base/ghidra_scripts/RegisterTouchesPerFunction.java +++ b/Ghidra/Features/Base/ghidra_scripts/RegisterTouchesPerFunction.java @@ -18,168 +18,140 @@ // 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.*; -public class RegisterTouchesPerFunction extends GhidraScript -{ - private final static String DIVIDER = "*************************************************************\r\n"; +public class RegisterTouchesPerFunction extends GhidraScript { - @Override - public void run() throws Exception - { - Listing l = this.currentProgram.getListing(); + private final static String DIVIDER = + "*************************************************************\r\n"; - 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)); - } - } + @Override + public void run() throws Exception { + Listing l = this.currentProgram.getListing(); - private void doAnalysis(Listing list, Function func) - { - if (func == null) { - println("No function to analyze."); - return; - } - HashSet affected, accessed; - Vector restored; - Stack pushPops; - boolean reviewRestored = false; - Instruction inst; - InstructionIterator iIter; - - monitor.setMessage("Analyzing registers in " + func.getName()); + 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)); + } + } - String comment = list.getComment(CommentType.PLATE, func.getBody().getMinAddress()); + private void doAnalysis(Listing list, Function func) { + if (func == null) { + println("No function to analyze."); + return; + } + HashSet affected, accessed; + Vector restored; + Stack pushPops; + boolean reviewRestored = false; + Instruction inst; + InstructionIterator iIter; - if (comment != null && comment.indexOf("TOUCHED REGISTER SUMMARY") > -1) - return; + monitor.setMessage("Analyzing registers in " + func.getName()); - pushPops = new Stack(); - affected = new HashSet(); - accessed = new HashSet(); - restored = new Vector(); + String comment = list.getComment(CommentType.PLATE, func.getBody().getMinAddress()); + if (comment != null && comment.indexOf("TOUCHED REGISTER SUMMARY") > -1) + return; - iIter = list.getInstructions(func.getBody(), true); - - while (iIter.hasNext() && !monitor.isCancelled()) - { - inst = iIter.next(); + pushPops = new Stack(); + affected = new HashSet(); + accessed = new HashSet(); + restored = new Vector(); - Object o[] = inst.getResultObjects(); - for (int i = 0; i < o.length; i++) - { - if (o[i] instanceof Register) - { - String name = ((Register) o[i]).getName(); + iIter = list.getInstructions(func.getBody(), true); - 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(); + while (iIter.hasNext() && !monitor.isCancelled()) { + inst = iIter.next(); - 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); - } - } - } - } + Object o[] = inst.getResultObjects(); + for (Object element : o) { + if (element instanceof Register) { + String name = ((Register) element).getName(); - 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 (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(); - 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); + 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 (pushPops.size() > 0) - { + 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)); - buffer.append("Registers Remaining on Stack:\r\n"); - buffer.append(" "+getString(pushPops, 8)); - } + 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); + + if (pushPops.size() > 0) { + buffer.append("Registers Remaining on Stack:\r\n"); + buffer.append(" " + getString(pushPops, 8)); + } list.setComment(func.getEntryPoint(), CommentType.PLATE, buffer.toString()); - } + } - private String getString(Collection c, int itemsPerLine) - { - TreeSet ts = new TreeSet(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(); - } + private String getString(Collection c, int itemsPerLine) { + TreeSet ts = new TreeSet(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"; - } + return temp + "\r\n"; + } } diff --git a/Ghidra/Features/Base/ghidra_scripts/ZapBCTRScript.java b/Ghidra/Features/Base/ghidra_scripts/ZapBCTRScript.java index 2f69d92448..6d52da9d96 100644 --- a/Ghidra/Features/Base/ghidra_scripts/ZapBCTRScript.java +++ b/Ghidra/Features/Base/ghidra_scripts/ZapBCTRScript.java @@ -60,8 +60,8 @@ public class ZapBCTRScript extends GhidraScript { } // first try input as class and search for symbol "::__vtbl" - List symbols = currentProgram.getSymbolTable().getSymbols("__vtbl", - getNamespace(null, classNameOrAddr)); + List 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(); @@ -100,8 +100,8 @@ public class ZapBCTRScript extends GhidraScript { // insert funcName as EOL comment and // add a mnemonic ref from instAddr to funcAddr listing.setComment(instAddr, CommentType.EOL, funcName); - listing.getInstructionAt(instAddr).addMnemonicReference(funcAddr, RefType.COMPUTED_CALL, - SourceType.USER_DEFINED); + 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); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/AppendCommentCmd.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/AppendCommentCmd.java index 4679289592..43ffd1e71b 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/AppendCommentCmd.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/AppendCommentCmd.java @@ -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 { 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 { * @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 diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/CodeUnitInfoPasteCmd.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/CodeUnitInfoPasteCmd.java index 3fffbcafb6..6bf71da51a 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/CodeUnitInfoPasteCmd.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/CodeUnitInfoPasteCmd.java @@ -326,23 +326,23 @@ public class CodeUnitInfoPasteCmd implements Command { if (plateComment != null) { String[] oldComment = cu.getCommentAsArray(CommentType.PLATE); - cu.setCommentAsArray(CodeUnit.PLATE_COMMENT, appendComment(oldComment, plateComment)); + cu.setCommentAsArray(CommentType.PLATE, appendComment(oldComment, plateComment)); } if (preComment != null) { String[] oldComment = cu.getCommentAsArray(CommentType.PRE); - cu.setCommentAsArray(CodeUnit.PRE_COMMENT, appendComment(oldComment, preComment)); + cu.setCommentAsArray(CommentType.PRE, appendComment(oldComment, preComment)); } if (postComment != null) { String[] oldComment = cu.getCommentAsArray(CommentType.POST); - cu.setCommentAsArray(CodeUnit.POST_COMMENT, appendComment(oldComment, postComment)); + cu.setCommentAsArray(CommentType.POST, appendComment(oldComment, postComment)); } if (eolComment != null) { String[] oldComment = cu.getCommentAsArray(CommentType.EOL); - cu.setCommentAsArray(CodeUnit.EOL_COMMENT, appendComment(oldComment, eolComment)); + cu.setCommentAsArray(CommentType.EOL, appendComment(oldComment, eolComment)); } if (repeatableComment != null) { String[] oldComment = cu.getCommentAsArray(CommentType.REPEATABLE); - cu.setCommentAsArray(CodeUnit.REPEATABLE_COMMENT, + cu.setCommentAsArray(CommentType.REPEATABLE, appendComment(oldComment, repeatableComment)); } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/SetCommentCmd.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/SetCommentCmd.java index cb9c2eeef7..ee87a17e44 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/SetCommentCmd.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/comments/SetCommentCmd.java @@ -38,12 +38,9 @@ public class SetCommentCmd implements Command { * @param comment comment for code unit * @deprecated Use {@link #SetCommentCmd(Address, CommentType, String)} instead */ - @Deprecated + @Deprecated(forRemoval = true, since = "11.4") public SetCommentCmd(Address addr, int commentType, String comment) { - this.address = addr; - this.commentType = CommentType.values()[commentType]; - this.comment = comment; - cmdName = comment == null ? "Delete Comment" : "Set Comment"; + this(addr, CommentType.valueOf(commentType), comment); } /** @@ -132,11 +129,11 @@ public class SetCommentCmd implements Command { * {@link CodeUnit#REPEATABLE_COMMENT}) * @deprecated Use {@link #createComment(Program, Address, String, CommentType)} instead */ - @Deprecated + @Deprecated(forRemoval = true, since = "11.4") public static void createComment(Program program, Address addr, String comment, int commentType) { SetCommentCmd commentCmd = - new SetCommentCmd(addr, CommentType.values()[commentType], comment); + new SetCommentCmd(addr, CommentType.valueOf(commentType), comment); commentCmd.applyTo(program); } @@ -147,9 +144,7 @@ public class SetCommentCmd implements Command { * @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 CommentType#PLATE}, - * {@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, CommentType commentType) { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java index 979706047c..fbdaa16ab4 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/cmd/formats/ElfBinaryAnalysisCommand.java @@ -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) { @@ -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); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java index 2849a09382..083c0a4677 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/CliMetadataTokenAnalyzer.java @@ -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) */ diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/GolangSymbolAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/GolangSymbolAnalyzer.java index 8dbdc8d971..d7458e6527 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/GolangSymbolAnalyzer.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/GolangSymbolAnalyzer.java @@ -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 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 params = - List.of(new ParameterImpl("dest", voidPtr, program), - new ParameterImpl("src", voidPtr, program)); + List 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,9 +667,9 @@ 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()) { @@ -1079,8 +1074,8 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer { } record CallSiteInfo(Reference ref, Function callingFunc, Function calledFunc, - Register register, - java.util.function.Function returnTypeMapper) {} + Register register, java.util.function.Function returnTypeMapper) { + } private GoRttiMapper goBinary; private Program program; diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MingwRelocationAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MingwRelocationAnalyzer.java index d5e723d526..78b3420715 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MingwRelocationAnalyzer.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/MingwRelocationAnalyzer.java @@ -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; } @@ -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( diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC1_MessageAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC1_MessageAnalyzer.java index f53a739628..767184b30b 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC1_MessageAnalyzer.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC1_MessageAnalyzer.java @@ -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"; @@ -88,7 +88,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; @@ -127,8 +127,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 { @@ -309,7 +309,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) { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC2_MessageAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC2_MessageAnalyzer.java index 3b3ad62363..cea28e6f76 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC2_MessageAnalyzer.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/analysis/ObjectiveC2_MessageAnalyzer.java @@ -196,8 +196,8 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer { } if (currentClass != null && currentMethod != null) { - instruction.setComment(CommentType.EOL, "[" + currentClass + " " + - currentMethod + "]"); + instruction.setComment(CommentType.EOL, + "[" + currentClass + " " + currentMethod + "]"); break; } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java index c39bd541fb..a969247b59 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/clipboard/CodeBrowserClipboardProvider.java @@ -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); } } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryDialog.java index 757585a9f3..6129b40ec3 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryDialog.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryDialog.java @@ -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); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryPanel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryPanel.java index 841e0bac8e..fc6ec64923 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryPanel.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentHistoryPanel.java @@ -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(); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsActionFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsActionFactory.java index 35f954ded2..f722bdf5bc 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsActionFactory.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsActionFactory.java @@ -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); + } + } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsDialog.java index 77205b313c..200d4817d1 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsDialog.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsDialog.java @@ -37,6 +37,7 @@ 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. @@ -90,7 +91,7 @@ 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; @@ -134,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()); } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsPlugin.java index 7fe90c63c8..5f13f80390 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsPlugin.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/comments/CommentsPlugin.java @@ -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; } } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentRowObject.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentRowObject.java index 791fd6e5c6..0cbed7690b 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentRowObject.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentRowObject.java @@ -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 { 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 { return address; } - int getCommentType() { + CommentType getCommentType() { return commentType; } @@ -40,7 +41,7 @@ class CommentRowObject implements Comparable { 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 { int result = address.compareTo(o.address); if (result == 0) { - result = commentType - o.commentType; + result = commentType.compareTo(o.commentType); } return result; } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentTableModel.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentTableModel.java index f4df7503b3..8bf7c092cc 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentTableModel.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentTableModel.java @@ -95,25 +95,25 @@ class CommentTableModel extends AddressBasedTableModel { } if (cu.getComment(CommentType.PRE) != null) { - accumulator.add(new CommentRowObject(commentAddr, CodeUnit.PRE_COMMENT)); + accumulator.add(new CommentRowObject(commentAddr, CommentType.PRE)); } if (cu.getComment(CommentType.POST) != null) { - accumulator.add(new CommentRowObject(commentAddr, CodeUnit.POST_COMMENT)); + accumulator.add(new CommentRowObject(commentAddr, CommentType.POST)); } if (cu.getComment(CommentType.EOL) != null) { - accumulator.add(new CommentRowObject(commentAddr, CodeUnit.EOL_COMMENT)); + accumulator.add(new CommentRowObject(commentAddr, CommentType.EOL)); } if (cu.getComment(CommentType.PLATE) != null) { - accumulator.add(new CommentRowObject(commentAddr, CodeUnit.PLATE_COMMENT)); + accumulator.add(new CommentRowObject(commentAddr, CommentType.PLATE)); } if (cu.getComment(CommentType.REPEATABLE) != null) { - accumulator.add(new CommentRowObject(commentAddr, CodeUnit.REPEATABLE_COMMENT)); + 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 { } - 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 { } @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 { } @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; diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowPlugin.java index 356e6c283d..661122b960 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowPlugin.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowPlugin.java @@ -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(); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowProvider.java index 16cf6f6206..a1e4b8193d 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowProvider.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/commentwindow/CommentWindowProvider.java @@ -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); } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/AddressTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/AddressTable.java index c973d96928..4579981de5 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/AddressTable.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/disassembler/AddressTable.java @@ -98,7 +98,6 @@ public class AddressTable { this.skipAmount = skipAmount; this.shiftedAddr = shiftedAddr; } - /** * Create a new address table from any remaining table entries starting at startPos @@ -389,8 +388,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 { @@ -473,8 +471,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); } @@ -575,8 +573,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 @@ -608,8 +607,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) { @@ -1234,12 +1233,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)); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/CommentFieldSearcher.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/CommentFieldSearcher.java index b8f3f44623..5466860c63 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/CommentFieldSearcher.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/CommentFieldSearcher.java @@ -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: diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/ProgramDatabaseSearcher.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/ProgramDatabaseSearcher.java index 934290d80c..94d61bea72 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/ProgramDatabaseSearcher.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchtext/databasesearcher/ProgramDatabaseSearcher.java @@ -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)); } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccAnalysisClass.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccAnalysisClass.java index 30a69177bf..5b1e5ddb7c 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccAnalysisClass.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccAnalysisClass.java @@ -100,7 +100,7 @@ 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 {@link CommentType type of comment } + * @param commentType the type of comment */ protected static void createAndCommentData(Program program, Address addr, DataType dt, String comment, CommentType commentType) { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccExceptionAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccExceptionAnalyzer.java index 67878f8a7b..51658f0ce5 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccExceptionAnalyzer.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/GccExceptionAnalyzer.java @@ -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 visitedPrograms = new HashSet<>(); private AutoAnalysisManagerListener analysisListener = @@ -304,8 +302,7 @@ 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(CommentType.POST, commentAddr); + String existingComment = program.getListing().getComment(CommentType.POST, commentAddr); if (existingComment == null || !existingComment.contains(endTryComment)) { String mergedComment = StringUtilities.mergeStrings(existingComment, endTryComment); SetCommentCmd setCommentCmd = @@ -350,7 +347,7 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer { // String mergedComment = // StringUtilities.mergeStrings(existingComment, endCatchComment); // SetCommentCmd setCommentCmd = -// new SetCommentCmd(lpMaxAddr, CodeUnit.POST_COMMENT, endCatchComment); +// new SetCommentCmd(lpMaxAddr, CommentType.POST, endCatchComment); // setCommentCmd.applyTo(program); // } } @@ -428,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); } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/sections/EhFrameHeaderSection.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/sections/EhFrameHeaderSection.java index 04b9a15c30..df27d3e79e 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/sections/EhFrameHeaderSection.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/sections/EhFrameHeaderSection.java @@ -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); @@ -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(); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/Cie.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/Cie.java index d90e99d074..b7023ec82f 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/Cie.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/Cie.java @@ -661,9 +661,9 @@ public class Cie extends GccAnalysisClass { "(CIE Augmentation Data) Personality Function Pointer (" + personalityFuncAddr + ")", 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; } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/ExceptionHandlerFrameHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/ExceptionHandlerFrameHeader.java index 0a12ac49a4..a77a5bc6b0 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/ExceptionHandlerFrameHeader.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/ehFrame/ExceptionHandlerFrameHeader.java @@ -38,7 +38,7 @@ import ghidra.util.task.TaskMonitor; * */ public class ExceptionHandlerFrameHeader { - + /* Class Members */ private TaskMonitor monitor; private Program prog; @@ -47,7 +47,7 @@ public class ExceptionHandlerFrameHeader { private int eh_FramePtrEncoding; private int eh_FrameDescEntryCntEncoding; private int eh_FrameTableEncoding; - + /** * Constructor for an ExceptionHandlerFrameHeader. * @param monitor a status monitor for indicating progress or allowing a task to be cancelled. @@ -74,11 +74,11 @@ public class ExceptionHandlerFrameHeader { */ public void addToDataTypeManager() { DataTypeManager dtManager = prog.getDataTypeManager(); - + /* Add the ehFrameHdr Structure to the dataTypeManager */ - dtManager.addDataType(ehFrameHdrStruct, DataTypeConflictHandler.REPLACE_HANDLER ); + dtManager.addDataType(ehFrameHdrStruct, DataTypeConflictHandler.REPLACE_HANDLER); } - + /** * Method that creates an Exception Handler Frame Header Structure * at the address specified by 'addr'. If addr is 'null', this method returns without creating @@ -90,20 +90,20 @@ public class ExceptionHandlerFrameHeader { */ public void create(Address addr) throws MemoryAccessException, AddressOutOfBoundsException { CreateStructureCmd dataCmd = null; - + if (addr == null || monitor.isCancelled()) { return; } - + /* Create a new structure at the start of the .eh_frame_hdr section */ - dataCmd = new CreateStructureCmd( ehFrameHdrStruct, addr ); + dataCmd = new CreateStructureCmd(ehFrameHdrStruct, addr); dataCmd.applyTo(prog); - + /* Set a comment on the newly created structure */ SetCommentCmd commentCmd = new SetCommentCmd(addr, CommentType.PLATE, "Exception Handler Frame Header"); commentCmd.applyTo(prog); - + // Set the class members accordingly eh_version = prog.getMemory().getByte(addr) & 0xFF; eh_FramePtrEncoding = prog.getMemory().getByte(addr.add(1)) & 0xFF; diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAActionTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAActionTable.java index 94d368ca61..00c05223bb 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAActionTable.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAActionTable.java @@ -76,7 +76,7 @@ public class LSDAActionTable { monitor.setMessage("Creating LSDA Action Table"); LSDAActionRecord rec = null; - + while (address.compareTo(maxAddress) <= 0) { rec = new LSDAActionRecord(monitor, program, region, this); rec.create(address); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDACallSiteRecord.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDACallSiteRecord.java index c9e98a6cdf..5736962a48 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDACallSiteRecord.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDACallSiteRecord.java @@ -100,13 +100,15 @@ public class LSDACallSiteRecord extends GccAnalysisClass { commentCmd.applyTo(program); if (program.getMemory().contains(callSiteBaseAddr)) { - program.getReferenceManager().addMemoryReference(callSiteDataAddr, callSiteBaseAddr, - RefType.DATA, SourceType.ANALYSIS, 0); + program.getReferenceManager() + .addMemoryReference(callSiteDataAddr, callSiteBaseAddr, RefType.DATA, + SourceType.ANALYSIS, 0); } if (program.getMemory().contains(landingPadAddr)) { - program.getReferenceManager().addMemoryReference(lpDataAddr, landingPadAddr, - RefType.DATA, SourceType.ANALYSIS, 0); + program.getReferenceManager() + .addMemoryReference(lpDataAddr, landingPadAddr, RefType.DATA, + SourceType.ANALYSIS, 0); } nextAddress = addr; diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAHeader.java index 1564d93738..753132f237 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAHeader.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDAHeader.java @@ -40,7 +40,6 @@ public class LSDAHeader extends GccAnalysisClass { static final int OMITTED_ENCODING_TYPE = 0xFF; - /* Class Members */ private RegionDescriptor region; diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATable.java index 254dd286b4..9f34b15d59 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATable.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATable.java @@ -78,8 +78,7 @@ public class LSDATable { * @param region the region of the program associated with this table * @throws MemoryAccessException if memory couldn't be accessed for the LSDA table */ - public void create(Address tableAddr, RegionDescriptor region) - throws MemoryAccessException { + public void create(Address tableAddr, RegionDescriptor region) throws MemoryAccessException { region.setLSDATable(this); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATypeTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATypeTable.java index 595569f91d..a3de98912b 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATypeTable.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/exceptionhandlers/gcc/structures/gccexcepttable/LSDATypeTable.java @@ -94,8 +94,9 @@ public class LSDATypeTable extends GccAnalysisClass { createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL); if (typeRef.getOffset() != 0) { - program.getReferenceManager().addMemoryReference(addr, typeRef, RefType.DATA, - SourceType.ANALYSIS, 0); + program.getReferenceManager() + .addMemoryReference(addr, typeRef, RefType.DATA, SourceType.ANALYSIS, + 0); } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScript.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScript.java index 200c20416e..05c05db374 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScript.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScript.java @@ -3928,8 +3928,7 @@ public abstract class GhidraScript extends FlatProgramAPI { * @see #getRepeatableComment(Address) */ public String getRepeatableCommentAsRendered(Address address) { - String comment = - currentProgram.getListing().getComment(CommentType.REPEATABLE, address); + String comment = currentProgram.getListing().getComment(CommentType.REPEATABLE, address); PluginTool tool = state.getTool(); if (tool != null) { comment = CommentUtils.getDisplayString(comment, currentProgram); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/CodeUnitInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/CodeUnitInfo.java index df3ce70075..b40b92fa5c 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/CodeUnitInfo.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/CodeUnitInfo.java @@ -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. @@ -16,14 +15,14 @@ */ package ghidra.app.util; +import java.util.ArrayList; +import java.util.List; + import ghidra.program.model.address.Address; import ghidra.program.model.listing.*; import ghidra.program.model.pcode.Varnode; import ghidra.program.model.symbol.*; -import java.util.ArrayList; -import java.util.List; - /** * Container object to keep a relative index, label, and comments. Used * in a list for copying/pasting labels and comments from one program to @@ -91,23 +90,23 @@ public class CodeUnitInfo { List scopeSymSourceList = new ArrayList(); List otherSymList = new ArrayList(); List otherSymSourceList = new ArrayList(); - for (int i = 0; i < symbols.length; i++) { - SymbolType symbolType = symbols[i].getSymbolType(); - if (symbols[i].isDynamic()) { + for (Symbol symbol : symbols) { + SymbolType symbolType = symbol.getSymbolType(); + if (symbol.isDynamic()) { hasDynamicSymbol = true; } - else if (symbols[i].isPrimary()) { - primarySymbolName = symbols[i].getName(); - primarySymbolSource = symbols[i].getSource(); + else if (symbol.isPrimary()) { + primarySymbolName = symbol.getName(); + primarySymbolSource = symbol.getSource(); primarySymbolInFunctionScope = (symbolType == SymbolType.FUNCTION); } else if (symbolType == SymbolType.FUNCTION) { - scopeSymList.add(symbols[i].getName()); - scopeSymSourceList.add(symbols[i].getSource()); + scopeSymList.add(symbol.getName()); + scopeSymSourceList.add(symbol.getSource()); } else { - otherSymList.add(symbols[i].getName()); - otherSymSourceList.add(symbols[i].getSource()); + otherSymList.add(symbol.getName()); + otherSymSourceList.add(symbol.getSource()); } } functionScopeSymbolNames = new String[scopeSymList.size()]; @@ -122,30 +121,34 @@ public class CodeUnitInfo { /** * Set the comment to be transferred. - * @param commentType CodeUnit.PRE_COMMENT, POST_COMMENT, - * PLATE_COMMENT, EOL_COMMENT, or REPEATABLE. + * @param commentType comment type * @param comment comment */ - public void setComment(int commentType, String[] comment) { + public void setComment(CommentType commentType, String[] comment) { switch (commentType) { - case CodeUnit.PLATE_COMMENT: + case PLATE: plateComment = comment; break; - case CodeUnit.PRE_COMMENT: + case PRE: preComment = comment; break; - case CodeUnit.POST_COMMENT: + case POST: postComment = comment; break; - case CodeUnit.REPEATABLE_COMMENT: + case REPEATABLE: repeatableComment = comment; break; - case CodeUnit.EOL_COMMENT: + case EOL: eolComment = comment; + break; + + default: + throw new IllegalArgumentException( + "Unsupported comment type: " + commentType.name()); } } @@ -387,17 +390,17 @@ public class CodeUnitInfo { */ private void setNonStackVarInfo(Variable[] vars) { int variableIndex = 0; - for (int i = 0; i < vars.length; i++) { - if (vars[i].isStackVariable()) { + for (Variable var : vars) { + if (var.isStackVariable()) { continue; // skip stack variables } - varNames[variableIndex] = vars[i].getName(); - varSources[variableIndex] = vars[i].getSource(); - Varnode firstVarnode = vars[i].getFirstStorageVarnode(); + varNames[variableIndex] = var.getName(); + varSources[variableIndex] = var.getSource(); + Varnode firstVarnode = var.getFirstStorageVarnode(); varAddrs[variableIndex] = firstVarnode != null ? firstVarnode.getAddress() : Address.NO_ADDRESS; - varFUOffsets[variableIndex] = vars[i].getFirstUseOffset(); - varComments[variableIndex] = vars[i].getComment(); + varFUOffsets[variableIndex] = var.getFirstUseOffset(); + varComments[variableIndex] = var.getComment(); ++variableIndex; } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/CommentTypes.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/CommentTypes.java index 49319a0166..adfbf98277 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/CommentTypes.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/CommentTypes.java @@ -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. @@ -22,26 +21,30 @@ import ghidra.program.model.listing.CodeUnit; * Class with a convenience method to get an array of the CodeUnit * comment types. The method is useful to loop through the comment types * once you have a code unit. + * @deprecated the {@link CommentType enum should be used in place of integers} */ +@Deprecated(forRemoval = true, since = "11.4") public class CommentTypes { - private static int[] COMMENT_TYPES; - private static int NUMBER_OF_COMMENT_TYPES=5; - - CommentTypes() { - } - static { - COMMENT_TYPES = new int[NUMBER_OF_COMMENT_TYPES]; + private static int[] COMMENT_TYPES; + private static int NUMBER_OF_COMMENT_TYPES = 5; + + CommentTypes() { + } + + static { + COMMENT_TYPES = new int[NUMBER_OF_COMMENT_TYPES]; COMMENT_TYPES[0] = CodeUnit.PRE_COMMENT; COMMENT_TYPES[1] = CodeUnit.POST_COMMENT; COMMENT_TYPES[2] = CodeUnit.EOL_COMMENT; - COMMENT_TYPES[3] = CodeUnit.PLATE_COMMENT; - COMMENT_TYPES[4] = CodeUnit.REPEATABLE_COMMENT; - } + COMMENT_TYPES[3] = CodeUnit.PLATE_COMMENT; + COMMENT_TYPES[4] = CodeUnit.REPEATABLE_COMMENT; + } + /** * Get an array containing the comment types on a code unit. */ public static int[] getTypes() { return COMMENT_TYPES; } -} +} diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/EolComments.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/EolComments.java index 47fda9dc55..6e49c524b0 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/EolComments.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/EolComments.java @@ -101,8 +101,7 @@ public class EolComments { } private void loadEols() { - Collection comments = - Arrays.asList(codeUnit.getCommentAsArray(CommentType.EOL)); + Collection comments = Arrays.asList(codeUnit.getCommentAsArray(CommentType.EOL)); addStrings(comments, eols); } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/DWARFUtil.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/DWARFUtil.java index 4de673100f..c119832b58 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/DWARFUtil.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/DWARFUtil.java @@ -78,15 +78,15 @@ public class DWARFUtil { */ public static Field getStaticFinalFieldWithValue(Class clazz, long value) { Field[] fields = clazz.getDeclaredFields(); - for (int i = 0; i < fields.length; i++) { - if ((!Modifier.isFinal(fields[i].getModifiers())) || - (!Modifier.isStatic(fields[i].getModifiers()))) { + for (Field field : fields) { + if ((!Modifier.isFinal(field.getModifiers())) || + (!Modifier.isStatic(field.getModifiers()))) { continue; } try { - long fieldValue = fields[i].getLong(null); + long fieldValue = field.getLong(null); if (fieldValue == value) { - return fields[i]; + return field; } } catch (IllegalArgumentException | IllegalAccessException e) { @@ -98,10 +98,6 @@ public class DWARFUtil { //-------------------------------------- - - - - private static Pattern MANGLED_NESTING_REGEX = Pattern.compile("(.*_Z)?N([0-9]+.*)"); /** @@ -286,8 +282,7 @@ public class DWARFUtil { String memberName = childDIEA.getName(); int memberOffset = 0; try { - memberOffset = - childDIEA.parseDataMemberOffset(DW_AT_data_member_location, 0); + memberOffset = childDIEA.parseDataMemberOffset(DW_AT_data_member_location, 0); } catch (DWARFExpressionException | IOException e) { // ignore, leave as default value 0 @@ -359,7 +354,7 @@ public class DWARFUtil { return; } } - AppendCommentCmd cmd = new AppendCommentCmd(address, commentType.ordinal(), + AppendCommentCmd cmd = new AppendCommentCmd(address, commentType, Objects.requireNonNullElse(prefix, "") + comment, sep); cmd.applyTo(program); } @@ -398,8 +393,7 @@ public class DWARFUtil { } DIEAggregate funcDIEA = paramDIEA.getParent(); - DWARFAttributeValue dwATObjectPointer = - funcDIEA.getAttribute(DW_AT_object_pointer); + DWARFAttributeValue dwATObjectPointer = funcDIEA.getAttribute(DW_AT_object_pointer); if (dwATObjectPointer != null && dwATObjectPointer instanceof DWARFNumericAttribute dnum && paramDIEA.hasOffset(dnum.getUnsignedValue())) { return true; @@ -442,8 +436,7 @@ public class DWARFUtil { public static ResourceFile getLanguageExternalFile(Language lang, String name) throws IOException { String filename = getLanguageExternalNameValue(lang, name); - return filename != null - ? new ResourceFile(getLanguageDefinitionDirectory(lang), filename) + return filename != null ? new ResourceFile(getLanguageDefinitionDirectory(lang), filename) : null; } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java index 2af0abaa94..0cee6c777b 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/info/NoteGnuProperty.java @@ -82,7 +82,8 @@ public class NoteGnuProperty extends ElfNote { /** * Contains the information of an individual note property. */ - public record NotePropertyElement(int type, String typeName, String value, int length) {} + public record NotePropertyElement(int type, String typeName, String value, int length) { + } private static NotePropertyElement readNextNotePropertyElement(BinaryReader reader, int intSize) throws IOException { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DataDirectory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DataDirectory.java index f2813710e4..3681e23f27 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DataDirectory.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/DataDirectory.java @@ -120,8 +120,8 @@ public abstract class DataDirectory implements PeMarkupable { } protected void createDirectoryBookmark(Program program, Address addr) { - program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "PE Header", - getDirectoryName()); + program.getBookmarkManager() + .setBookmark(addr, BookmarkType.INFO, "PE Header", getDirectoryName()); } protected void setBookmark(Program prog, Address addr, String comment) { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java index 68b261b54f..b5cd0f55c3 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/pe/cli/tables/CliTableMethodDef.java @@ -439,13 +439,13 @@ public class CliTableMethodDef extends CliAbstractTable { // Create the function, if already created, update the existing function Function func = funcMgr.getFunctionAt(startAddr); if (func == null) { - func = funcMgr - .createFunction(funcName, startAddr, funcAddrSet, SourceType.ANALYSIS); + func = funcMgr.createFunction(funcName, startAddr, funcAddrSet, + SourceType.ANALYSIS); } func.setReturnType(returnType, SourceType.ANALYSIS); - func.updateFunction(null, null, FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, - true, SourceType.ANALYSIS, parameters); - + func.updateFunction(null, null, FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, + SourceType.ANALYSIS, parameters); + markToPreventIncorrectProcessorDisassembly(program, methodRow, startAddr, endAddr); } catch (CodeUnitInsertionException e) { @@ -503,9 +503,9 @@ public class CliTableMethodDef extends CliAbstractTable { * @param endAddr end address of the function * @throws CodeUnitInsertionException couldn't create dagta. */ - private void markToPreventIncorrectProcessorDisassembly(Program program, CliMethodDefRow methodRow, - Address startAddr, Address endAddr) throws CodeUnitInsertionException { - + private void markToPreventIncorrectProcessorDisassembly(Program program, + CliMethodDefRow methodRow, Address startAddr, Address endAddr) + throws CodeUnitInsertionException { PrototypeModel cliCallingConvention = program.getLanguage() .getDefaultCompilerSpec() @@ -520,7 +520,7 @@ public class CliTableMethodDef extends CliAbstractTable { int codeLength = (int) endAddr.subtract(startAddr) + 1; ArrayDataType codeDT = new ArrayDataType(BYTE, codeLength, 1); data = listing.createData(startAddr, codeDT); - + // comment the type of code that should appear here data.setComment(CommentType.PRE, (methodRow.isManaged() ? ".NET CLR Managed Code" : "Native Code")); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledAddressTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledAddressTable.java index 6838b9b47b..5b6fb87137 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledAddressTable.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/demangler/DemangledAddressTable.java @@ -96,9 +96,8 @@ public class DemangledAddressTable extends DemangledObject { Listing listing = program.getListing(); if (program.getMemory().isExternalBlockAddress(address)) { - Msg.warn(this, - "Unable to fully apply external demangled Address Table at " + address + ": " + - s.getName(true)); + Msg.warn(this, "Unable to fully apply external demangled Address Table at " + address + + ": " + s.getName(true)); listing.setComment(address, CommentType.EOL, "WARNING: Unable to apply demangled Address Table"); return true; // don't complain diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/exporter/ProgramTextWriter.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/exporter/ProgramTextWriter.java index 597516c9ba..70738eae46 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/exporter/ProgramTextWriter.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/exporter/ProgramTextWriter.java @@ -355,9 +355,8 @@ class ProgramTextWriter { return; } - int len = options.getAddrWidth() + options.getBytesWidth() + - options.getPreMnemonicWidth() + options.getMnemonicWidth() + - options.getOperandWidth(); + int len = options.getAddrWidth() + options.getBytesWidth() + options.getPreMnemonicWidth() + + options.getMnemonicWidth() + options.getOperandWidth(); String fill = genFill(len); for (int i = 0; i < comments.size(); ++i) { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/AbstractPeDebugLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/AbstractPeDebugLoader.java index c3ac90448f..0a6e29fb2f 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/AbstractPeDebugLoader.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/AbstractPeDebugLoader.java @@ -94,8 +94,8 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader { maps.add(postCommentMap); maps.add(eolCommentMap); - int[] types = new int[] { CodeUnit.PLATE_COMMENT, CodeUnit.PRE_COMMENT, - CodeUnit.POST_COMMENT, CodeUnit.EOL_COMMENT }; + CommentType[] types = new CommentType[] { CommentType.PLATE, CommentType.PRE, + CommentType.POST, CommentType.EOL }; String[] typeNames = new String[] { "PLATE", "PRE", "POST", "EOL" }; int index = 0; for (HashMap map : maps) { @@ -273,7 +273,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader { //log.appendMsg("Unable to demangle: "+name); } if (builder.length() > 0) { - setComment(CodeUnit.PLATE_COMMENT, address, builder.toString()); + setComment(CommentType.PLATE, address, builder.toString()); } } @@ -295,11 +295,11 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader { Address startAddr = addr.add(Conv.intToLong(starts[k])); String cmt = "START-> " + file.getName() + ": " + "?"; - setComment(CodeUnit.PRE_COMMENT, startAddr, cmt); + setComment(CommentType.PRE, startAddr, cmt); Address endAddr = addr.add(Conv.intToLong(ends[k])); cmt = "END-> " + file.getName() + ": " + "?"; - setComment(CodeUnit.PRE_COMMENT, endAddr, cmt); + setComment(CommentType.PRE, endAddr, cmt); if (monitor.isCancelled()) { return; @@ -380,8 +380,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader { } protected boolean processDebugCoffSymbol(DebugCOFFSymbol symbol, NTHeader ntHeader, - Map sectionToAddress, Program program, - TaskMonitor monitor) { + Map sectionToAddress, Program program, TaskMonitor monitor) { if (symbol.getSectionNumber() == 0) { return true; @@ -453,7 +452,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader { if (aux == null) { continue; } - setComment(CodeUnit.PRE_COMMENT, address, aux.toString()); + setComment(CommentType.PRE, address, aux.toString()); } return true; @@ -499,54 +498,57 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader { private void addLineComment(Address addr, int line) { String cmt = addr + " -> " + "Line #" + line; - setComment(CodeUnit.PRE_COMMENT, addr, cmt); + setComment(CommentType.PRE, addr, cmt); } - protected boolean hasComment(int type, Address address) { + protected boolean hasComment(CommentType type, Address address) { switch (type) { - case CodeUnit.PLATE_COMMENT: + case PLATE: return plateCommentMap.get(address) != null; - case CodeUnit.PRE_COMMENT: + case PRE: return preCommentMap.get(address) != null; - case CodeUnit.POST_COMMENT: + case POST: return postCommentMap.get(address) != null; - case CodeUnit.EOL_COMMENT: + case EOL: return eolCommentMap.get(address) != null; + default: + throw new IllegalArgumentException("Unsupported comment type: " + type.name()); } - return false; } - protected void setComment(int type, Address address, String comment) { + protected void setComment(CommentType type, Address address, String comment) { StringBuffer buffer = null; switch (type) { - case CodeUnit.PLATE_COMMENT: + case CommentType.PLATE: buffer = plateCommentMap.get(address); if (buffer == null) { buffer = new StringBuffer(); plateCommentMap.put(address, buffer); } break; - case CodeUnit.PRE_COMMENT: + case CommentType.PRE: buffer = preCommentMap.get(address); if (buffer == null) { buffer = new StringBuffer(); preCommentMap.put(address, buffer); } break; - case CodeUnit.POST_COMMENT: + case CommentType.POST: buffer = postCommentMap.get(address); if (buffer == null) { buffer = new StringBuffer(); postCommentMap.put(address, buffer); } break; - case CodeUnit.EOL_COMMENT: + case CommentType.EOL: buffer = eolCommentMap.get(address); if (buffer == null) { buffer = new StringBuffer(); eolCommentMap.put(address, buffer); } break; + default: + throw new IllegalArgumentException("Unsupported comment type: " + type.name()); } if (buffer != null) { if (buffer.length() > 0) { diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java index 1254cb0e10..54d0888fb4 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java @@ -550,13 +550,13 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper { // Scalar scalar = (Scalar)data.getValue(); // switch ((int)scalar.getValue()) { // case GNU_Constants.VER_NDX_LOCAL: -// data.setComment(Data.EOL_COMMENT, symbols[index].getNameAsString()+ " - local version"); +// data.setComment(Data.EOL, symbols[index].getNameAsString()+ " - local version"); // break; // case GNU_Constants.VER_NDX_GLOBAL: -// data.setComment(Data.EOL_COMMENT, symbols[index].getNameAsString()+ " - global version"); +// data.setComment(Data.EOL, symbols[index].getNameAsString()+ " - global version"); // break; // default: -// data.setComment(Data.EOL_COMMENT, symbols[index].getNameAsString()+ " - ??"); +// data.setComment(Data.EOL, symbols[index].getNameAsString()+ " - ??"); // break; // } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java index c42b9a74db..a0883c05fd 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/PeLoader.java @@ -254,7 +254,7 @@ public class PeLoader extends AbstractPeDebugLoader { dt = section.toDataType(); DataUtilities.createData(program, start, dt, -1, DataUtilities.ClearDataMode.CHECK_FOR_SPACE); - setComment(CodeUnit.EOL_COMMENT, start, section.getName()); + setComment(CommentType.EOL, start, section.getName()); start = start.add(dt.getLength()); } } @@ -383,7 +383,7 @@ public class PeLoader extends AbstractPeDebugLoader { Address address = space.getAddress(addr); - setComment(CodeUnit.PRE_COMMENT, address, importInfo.getComment()); + setComment(CommentType.PRE, address, importInfo.getComment()); Data data = listing.getDefinedDataAt(address); if (data != null && data.isPointer()) { @@ -547,7 +547,7 @@ public class PeLoader extends AbstractPeDebugLoader { } Address address = space.getAddress(export.getAddress()); - setComment(CodeUnit.PRE_COMMENT, address, export.getComment()); + setComment(CommentType.PRE, address, export.getComment()); symTable.addExternalEntryPoint(address); String name = export.getName(); @@ -713,9 +713,8 @@ public class PeLoader extends AbstractPeDebugLoader { int dataSize = (virtualSize > 0 || rawDataSize < 0) ? virtualSize : 0; if (dataSize > 0) { if (block != null) { - MemoryBlock paddingBlock = - MemoryBlockUtils.createInitializedBlock(prog, false, sectionName, - address, dataSize, "", "", r, w, x, log); + MemoryBlock paddingBlock = MemoryBlockUtils.createInitializedBlock(prog, + false, sectionName, address, dataSize, "", "", r, w, x, log); if (paddingBlock != null) { try { prog.getMemory().join(block, paddingBlock); @@ -992,7 +991,7 @@ public class PeLoader extends AbstractPeDebugLoader { catch (CancelledException e) { // Move on } - + // Check for Swift List sectionNames = Arrays.stream(pe.getNTHeader().getFileHeader().getSectionHeaders()) diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PlateFieldFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PlateFieldFactory.java index ac22c8e826..a8fb997b50 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PlateFieldFactory.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PlateFieldFactory.java @@ -166,9 +166,8 @@ public class PlateFieldFactory extends FieldFactory { ListingFieldHighlightFactoryAdapter hlFactory = new ListingFieldHighlightFactoryAdapter(hlProvider); - PlateFieldTextField textField = - new PlateFieldTextField(elements, this, proxy, startX, width, commentText, isClipped, - hlFactory); + PlateFieldTextField textField = new PlateFieldTextField(elements, this, proxy, startX, + width, commentText, isClipped, hlFactory); PlateListingTextField listingField = new PlateListingTextField(proxy, textField, hlFactory); return listingField; } @@ -256,8 +255,8 @@ public class PlateFieldFactory extends FieldFactory { commentsList.add(CommentUtils.parseTextForAnnotations(c, p, prototype, row++)); } for (String offcut : offcutComments) { - AttributedString as = new AttributedString(offcut, CommentColors.OFFCUT, - getMetrics(style), false, null); + AttributedString as = + new AttributedString(offcut, CommentColors.OFFCUT, getMetrics(style), false, null); commentsList.add(new TextFieldElement(as, commentsList.size(), 0)); } @@ -540,7 +539,7 @@ public class PlateFieldFactory extends FieldFactory { } CommentFieldLocation commentLocation = (CommentFieldLocation) programLoc; - if (commentLocation.getCommentType() != CodeUnit.PLATE_COMMENT) { + if (commentLocation.getCommentType() != CommentType.PLATE) { return null; } @@ -603,8 +602,8 @@ public class PlateFieldFactory extends FieldFactory { @Override public FieldFactory newInstance(FieldFormatModel formatModel, - ListingHighlightProvider hsProvider, - ToolOptions toolOptions, ToolOptions fieldOptions) { + ListingHighlightProvider hsProvider, ToolOptions toolOptions, + ToolOptions fieldOptions) { return new PlateFieldFactory(formatModel, hsProvider, toolOptions, fieldOptions); } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PostCommentFieldFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PostCommentFieldFactory.java index d2cd6ab2a1..5c8d616019 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PostCommentFieldFactory.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PostCommentFieldFactory.java @@ -313,7 +313,7 @@ public class PostCommentFieldFactory extends FieldFactory { } CommentFieldLocation loc = (CommentFieldLocation) programLoc; - if (loc.getCommentType() != CodeUnit.POST_COMMENT) { + if (loc.getCommentType() != CommentType.POST) { return null; } return new FieldLocation(index, fieldNum, loc.getRow(), loc.getCharOffset()); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PreCommentFieldFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PreCommentFieldFactory.java index 631a9346fe..8a63d822c3 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PreCommentFieldFactory.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/PreCommentFieldFactory.java @@ -153,7 +153,7 @@ public class PreCommentFieldFactory extends FieldFactory { cpath = ((Data) cu).getComponentPath(); } return new CommentFieldLocation(cu.getProgram(), cu.getMinAddress(), cpath, comment, - CodeUnit.PRE_COMMENT, row, col); + CommentType.PRE, row, col); } @Override @@ -164,7 +164,7 @@ public class PreCommentFieldFactory extends FieldFactory { } CommentFieldLocation loc = (CommentFieldLocation) programLoc; - if (loc.getCommentType() != CodeUnit.PRE_COMMENT) { + if (loc.getCommentType() != CommentType.PRE) { return null; } return new FieldLocation(index, fieldNum, loc.getRow(), loc.getCharOffset()); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/CommentsXmlMgr.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/CommentsXmlMgr.java index 6cb3d24a8e..9e67502e12 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/CommentsXmlMgr.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/CommentsXmlMgr.java @@ -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. @@ -16,11 +15,16 @@ */ package ghidra.app.util.xml; -import ghidra.app.util.CommentTypes; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + import ghidra.app.util.importer.MessageLog; import ghidra.program.model.address.*; import ghidra.program.model.listing.*; import ghidra.util.XmlProgramUtilities; +import ghidra.util.exception.AssertException; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; import ghidra.util.xml.XmlAttributes; @@ -28,8 +32,6 @@ import ghidra.util.xml.XmlWriter; import ghidra.xml.XmlElement; import ghidra.xml.XmlPullParser; -import java.io.IOException; - /** * XML manager for all types of comments. */ @@ -39,31 +41,31 @@ class CommentsXmlMgr { private AddressFactory factory; private Listing listing; - private static int[] COMMENT_TYPES; - private static String[] COMMENT_TAGS; + private static Map COMMENT_TAGS; static { - COMMENT_TYPES = CommentTypes.getTypes(); - COMMENT_TAGS = new String[COMMENT_TYPES.length]; - for (int i = 0; i < COMMENT_TAGS.length; i++) { + COMMENT_TAGS = new HashMap<>(); + for (CommentType type : CommentType.values()) { - switch (COMMENT_TYPES[i]) { - case CodeUnit.PRE_COMMENT: - COMMENT_TAGS[i] = "pre"; + switch (type) { + case CommentType.PRE: + COMMENT_TAGS.put(type, "pre"); break; - case CodeUnit.POST_COMMENT: - COMMENT_TAGS[i] = "post"; + case CommentType.POST: + COMMENT_TAGS.put(type, "post"); break; - case CodeUnit.EOL_COMMENT: - COMMENT_TAGS[i] = "end-of-line"; + case CommentType.EOL: + COMMENT_TAGS.put(type, "end-of-line"); break; - case CodeUnit.PLATE_COMMENT: - COMMENT_TAGS[i] = "plate"; + case CommentType.PLATE: + COMMENT_TAGS.put(type, "plate"); break; - case CodeUnit.REPEATABLE_COMMENT: - COMMENT_TAGS[i] = "repeatable"; + case CommentType.REPEATABLE: + COMMENT_TAGS.put(type, "repeatable"); break; + default: + throw new AssertException("Unsupported comment type: " + type.name()); } } } @@ -79,9 +81,11 @@ class CommentsXmlMgr { * Process the entry point section of the XML file. * @param parser xml reader * @param monitor monitor that can be canceled + * @throws AddressFormatException + * @throws CancelledException */ - void read(XmlPullParser parser, TaskMonitor monitor) throws AddressFormatException, - CancelledException { + void read(XmlPullParser parser, TaskMonitor monitor) + throws AddressFormatException, CancelledException { XmlElement element = parser.next(); while (true) { if (monitor.isCancelled()) { @@ -103,9 +107,10 @@ class CommentsXmlMgr { * @param set address set that is either the entire program or a selection * @param monitor monitor that can be canceled * should be written - * @throws IOException + * @throws CancelledException if task is cancelled */ - void write(XmlWriter writer, AddressSetView set, TaskMonitor monitor) throws CancelledException { + void write(XmlWriter writer, AddressSetView set, TaskMonitor monitor) + throws CancelledException { monitor.setMessage("Writing COMMENTS ..."); if (set == null) { @@ -117,17 +122,15 @@ class CommentsXmlMgr { CodeUnitIterator iter = listing.getCodeUnitIterator(CodeUnit.COMMENT_PROPERTY, set, true); while (iter.hasNext()) { - if (monitor.isCancelled()) { - throw new CancelledException(); - } + monitor.checkCancelled(); CodeUnit cu = iter.next(); - for (int i = 0; i < COMMENT_TYPES.length; i++) { + for (CommentType type : CommentType.values()) { if (monitor.isCancelled()) { return; } - String comments = cu.getComment(COMMENT_TYPES[i]); + String comments = cu.getComment(type); if (comments != null) { - writeComment(writer, cu.getMinAddress(), COMMENT_TAGS[i], comments); + writeComment(writer, cu.getMinAddress(), COMMENT_TAGS.get(type), comments); } } } @@ -143,8 +146,8 @@ class CommentsXmlMgr { } try { String typeStr = element.getAttribute("TYPE"); - int commentType = getCommentType(typeStr); - if (commentType < 0) { + CommentType commentType = getCommentType(typeStr); + if (commentType == null) { log.appendMsg("Unknown comment type: " + typeStr); parser.discardSubTree(element); return; @@ -180,12 +183,15 @@ class CommentsXmlMgr { writer.writeElement("COMMENT", attrs, comments); } - private int getCommentType(String typeStr) { - for (int i = 0; i < COMMENT_TAGS.length; i++) { - if (COMMENT_TAGS[i].equals(typeStr)) { - return COMMENT_TYPES[i]; + private CommentType getCommentType(String typeStr) { + if (StringUtils.isBlank(typeStr)) { + return null; + } + for (CommentType type : CommentType.values()) { + if (typeStr.equals(COMMENT_TAGS.get(type))) { + return type; } } - return -1; // unknown comment + return null; // unknown comment } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/features/base/replace/items/UpdateCommentQuickFix.java b/Ghidra/Features/Base/src/main/java/ghidra/features/base/replace/items/UpdateCommentQuickFix.java index b15f03480e..e0ea49734a 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/features/base/replace/items/UpdateCommentQuickFix.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/features/base/replace/items/UpdateCommentQuickFix.java @@ -20,6 +20,7 @@ import ghidra.program.model.address.Address; import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; import ghidra.program.util.*; +import ghidra.util.exception.AssertException; /** * QuickFix for updating listing comments. @@ -80,11 +81,11 @@ public class UpdateCommentQuickFix extends QuickFix { case POST: return new PostCommentFieldLocation(program, address, null, null, 0, 0); case PRE: - return new CommentFieldLocation(program, address, null, null, type.ordinal(), 0, 0); + return new CommentFieldLocation(program, address, null, null, type, 0, 0); case REPEATABLE: return new RepeatableCommentFieldLocation(program, address, null, null, 0, 0, 0); default: - return null; + throw new AssertException("Unsupported comment type: " + type.name()); } } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java index 1e701b4432..13fda9b7cd 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/program/database/ProgramBuilder.java @@ -933,15 +933,15 @@ public class ProgramBuilder { }); } + @Deprecated(forRemoval = true, since = "11.4") public void createComment(String address, String comment, int commentType) { - CommentType type = CommentType.values()[commentType]; - createComment(address, comment, type); + createComment(address, comment, CommentType.valueOf(commentType)); } - public void createComment(String address, String comment, CommentType type) { + public void createComment(String address, String comment, CommentType commentType) { tx(() -> { Listing listing = program.getListing(); - listing.setComment(addr(address), type, comment); + listing.setComment(addr(address), commentType, comment); }); } @@ -1109,10 +1109,9 @@ public class ProgramBuilder { } return tx(() -> { - FileBytes fileBytes = - program.getMemory() - .createFileBytes("test", 0, size, new ByteArrayInputStream(bytes), - TaskMonitor.DUMMY); + FileBytes fileBytes = program.getMemory() + .createFileBytes("test", 0, size, new ByteArrayInputStream(bytes), + TaskMonitor.DUMMY); return fileBytes; }); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/flatapi/FlatProgramAPI.java b/Ghidra/Features/Base/src/main/java/ghidra/program/flatapi/FlatProgramAPI.java index a97f9bf462..5546bfdbca 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/program/flatapi/FlatProgramAPI.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/program/flatapi/FlatProgramAPI.java @@ -319,8 +319,8 @@ public class FlatProgramAPI { * @param bookmarks true if bookmarks should be cleared * @return true if the address set was successfully cleared */ - public final boolean clearListing(AddressSetView set, boolean instructions, - boolean data, boolean symbols, boolean comments, boolean properties, boolean functions, + public final boolean clearListing(AddressSetView set, boolean instructions, boolean data, + boolean symbols, boolean comments, boolean properties, boolean functions, boolean registers, boolean equates, boolean userReferences, boolean analysisReferences, boolean importReferences, boolean defaultReferences, boolean bookmarks) { @@ -358,12 +358,10 @@ public class FlatProgramAPI { long length, boolean overlay) throws Exception { if (input == null) { return currentProgram.getMemory() - .createUninitializedBlock(name, start, length, - overlay); + .createUninitializedBlock(name, start, length, overlay); } return currentProgram.getMemory() - .createInitializedBlock(name, start, input, length, - monitor, overlay); + .createInitializedBlock(name, start, input, length, monitor, overlay); } /** @@ -379,8 +377,7 @@ public class FlatProgramAPI { boolean overlay) throws Exception { ByteArrayInputStream input = new ByteArrayInputStream(bytes); return currentProgram.getMemory() - .createInitializedBlock(name, start, input, bytes.length, - monitor, overlay); + .createInitializedBlock(name, start, input, bytes.length, monitor, overlay); } /** @@ -1940,8 +1937,7 @@ public class FlatProgramAPI { public final Reference addInstructionXref(Address from, Address to, int opIndex, FlowType type) { return currentProgram.getReferenceManager() - .addMemoryReference(from, to, type, - SourceType.USER_DEFINED, opIndex); + .addMemoryReference(from, to, type, SourceType.USER_DEFINED, opIndex); } /** @@ -2401,8 +2397,7 @@ public class FlatProgramAPI { */ public final Equate getEquate(Instruction instruction, int operandIndex, long value) { return currentProgram.getEquateTable() - .getEquate(instruction.getMinAddress(), operandIndex, - value); + .getEquate(instruction.getMinAddress(), operandIndex, value); } /** @@ -2413,8 +2408,7 @@ public class FlatProgramAPI { */ public final List getEquates(Instruction instruction, int operandIndex) { return currentProgram.getEquateTable() - .getEquates(instruction.getMinAddress(), - operandIndex); + .getEquates(instruction.getMinAddress(), operandIndex); } /** @@ -2426,8 +2420,7 @@ public class FlatProgramAPI { Object obj = data.getValue(); if (obj instanceof Scalar) { return currentProgram.getEquateTable() - .getEquate(data.getMinAddress(), 0, - ((Scalar) obj).getValue()); + .getEquate(data.getMinAddress(), 0, ((Scalar) obj).getValue()); } return null; } diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiff.java b/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiff.java index 8f3c30c140..71c83e5636 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiff.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiff.java @@ -643,32 +643,32 @@ public class ProgramDiff { case ProgramDiffFilter.EOL_COMMENT_DIFFS: monitorMsg = "Checking End of Line Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.EOL_COMMENT, addrs, - new CommentTypeComparator(CodeUnit.EOL_COMMENT), monitor); + as = getCommentDiffs(CommentType.EOL, addrs, + new CommentTypeComparator(CommentType.EOL), monitor); break; case ProgramDiffFilter.REPEATABLE_COMMENT_DIFFS: monitorMsg = "Checking Repeatable Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.REPEATABLE_COMMENT, addrs, - new CommentTypeComparator(CodeUnit.REPEATABLE_COMMENT), monitor); + as = getCommentDiffs(CommentType.REPEATABLE, addrs, + new CommentTypeComparator(CommentType.REPEATABLE), monitor); break; case ProgramDiffFilter.PRE_COMMENT_DIFFS: monitorMsg = "Checking Pre-Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.PRE_COMMENT, addrs, - new CommentTypeComparator(CodeUnit.PRE_COMMENT), monitor); + as = getCommentDiffs(CommentType.PRE, addrs, + new CommentTypeComparator(CommentType.PRE), monitor); break; case ProgramDiffFilter.POST_COMMENT_DIFFS: monitorMsg = "Checking Post-Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.POST_COMMENT, addrs, - new CommentTypeComparator(CodeUnit.POST_COMMENT), monitor); + as = getCommentDiffs(CommentType.POST, addrs, + new CommentTypeComparator(CommentType.POST), monitor); break; case ProgramDiffFilter.PLATE_COMMENT_DIFFS: monitorMsg = "Checking Plate Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.PLATE_COMMENT, addrs, - new CommentTypeComparator(CodeUnit.PLATE_COMMENT), monitor); + as = getCommentDiffs(CommentType.PLATE, addrs, + new CommentTypeComparator(CommentType.PLATE), monitor); break; case ProgramDiffFilter.REFERENCE_DIFFS: monitorMsg = "Checking Reference Differences"; @@ -926,32 +926,32 @@ public class ProgramDiff { case ProgramDiffFilter.EOL_COMMENT_DIFFS: monitorMsg = "Checking End of Line Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.EOL_COMMENT, checkAddressSet, - new CommentTypeComparator(CodeUnit.EOL_COMMENT), monitor); + as = getCommentDiffs(CommentType.EOL, checkAddressSet, + new CommentTypeComparator(CommentType.EOL), monitor); break; case ProgramDiffFilter.REPEATABLE_COMMENT_DIFFS: monitorMsg = "Checking Repeatable Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.REPEATABLE_COMMENT, checkAddressSet, - new CommentTypeComparator(CodeUnit.REPEATABLE_COMMENT), monitor); + as = getCommentDiffs(CommentType.REPEATABLE, checkAddressSet, + new CommentTypeComparator(CommentType.REPEATABLE), monitor); break; case ProgramDiffFilter.PRE_COMMENT_DIFFS: monitorMsg = "Checking Pre-Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.PRE_COMMENT, checkAddressSet, - new CommentTypeComparator(CodeUnit.PRE_COMMENT), monitor); + as = getCommentDiffs(CommentType.PRE, checkAddressSet, + new CommentTypeComparator(CommentType.PRE), monitor); break; case ProgramDiffFilter.POST_COMMENT_DIFFS: monitorMsg = "Checking Post-Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.POST_COMMENT, checkAddressSet, - new CommentTypeComparator(CodeUnit.POST_COMMENT), monitor); + as = getCommentDiffs(CommentType.POST, checkAddressSet, + new CommentTypeComparator(CommentType.POST), monitor); break; case ProgramDiffFilter.PLATE_COMMENT_DIFFS: monitorMsg = "Checking Plate Comment Differences"; monitor.setMessage(monitorMsg); - as = getCommentDiffs(CodeUnit.PLATE_COMMENT, checkAddressSet, - new CommentTypeComparator(CodeUnit.PLATE_COMMENT), monitor); + as = getCommentDiffs(CommentType.PLATE, checkAddressSet, + new CommentTypeComparator(CommentType.PLATE), monitor); break; case ProgramDiffFilter.REFERENCE_DIFFS: monitorMsg = "Checking Reference Differences"; @@ -1773,7 +1773,7 @@ public class ProgramDiff { * Determines the code unit addresses where there are differences of the * indicated type between program1 and program2. * @param cuiType the type of difference on the code unit. These are defined - * in CodeUnit. (i.e. CodeUnit.EOL_COMMENT_PROPERTY). + * in CodeUnit. (i.e. CommentType.EOL_PROPERTY). * @param addressSet the addresses to check for differences. * The addresses in this address set should be derived from program1. * @param c the comparator to use for determining where the differences are. @@ -1798,7 +1798,7 @@ public class ProgramDiff { * Determines the code unit addresses where there are comment differences of the * indicated type between program1 and program2. * @param commentType the type of comment. These are defined - * in CodeUnit. (i.e. CodeUnit.EOL_COMMENT). + * in CodeUnit. (i.e. CommentType.EOL). * @param addressSet the addresses to check for differences. * The addresses in this address set should be derived from program1. * @param c the comparator to use for determining where the differences are. @@ -1810,7 +1810,7 @@ public class ProgramDiff { * The addresses in this address set are derived from program1. * @throws CancelledException if the user cancelled the Diff. */ - private AddressSet getCommentDiffs(int commentType, AddressSetView addressSet, + private AddressSet getCommentDiffs(CommentType commentType, AddressSetView addressSet, CommentTypeComparator c, TaskMonitor monitor) throws CancelledException { AddressIterator iter1 = listing1.getCommentAddressIterator(commentType, addressSet, true); AddressSet addressSet2 = DiffUtility.getCompatibleAddressSet(addressSet, program2); @@ -2638,13 +2638,13 @@ public class ProgramDiff { private class CommentTypeComparator extends ProgramDiffComparatorImpl
{ /** * the type of comment to compare - *
CodeUnit.PLATE_COMMENT - *
CodeUnit.PRE_COMMENT - *
CodeUnit.EOL_COMMENT - *
CodeUnit.REPEATABLE_COMMENT - *
CodeUnit.POST_COMMENT + *
CommentType.PLATE + *
CommentType.PRE + *
CommentType.EOL + *
CommentType.REPEATABLE + *
CommentType.POST */ - int type; + CommentType type; private Listing comparatorListing1; private Listing comparatorListing2; @@ -2652,7 +2652,7 @@ public class ProgramDiff { * Generic constructor for comparing program differences. * @param type the comment type */ - private CommentTypeComparator(int type) { + private CommentTypeComparator(CommentType type) { this.type = type; comparatorListing1 = program1.getListing(); comparatorListing2 = program2.getListing(); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiffDetails.java b/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiffDetails.java index 536bbca498..d071ea3fd1 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiffDetails.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramDiffDetails.java @@ -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. @@ -1398,19 +1398,19 @@ public class ProgramDiffDetails { } private void addEOLCommentDetails() { - hasEolCommentDiffs = addSpecificCommentDetails(CodeUnit.EOL_COMMENT, "EOL-Comment"); + hasEolCommentDiffs = addSpecificCommentDetails(CommentType.EOL, "EOL-Comment"); } private void addPreCommentDetails() { - hasPreCommentDiffs = addSpecificCommentDetails(CodeUnit.PRE_COMMENT, "Pre-Comment"); + hasPreCommentDiffs = addSpecificCommentDetails(CommentType.PRE, "Pre-Comment"); } private void addPostCommentDetails() { - hasPostCommentDiffs = addSpecificCommentDetails(CodeUnit.POST_COMMENT, "Post-Comment"); + hasPostCommentDiffs = addSpecificCommentDetails(CommentType.POST, "Post-Comment"); } private void addPlateCommentDetails() { - hasPlateCommentDiffs = addSpecificCommentDetails(CodeUnit.PLATE_COMMENT, "Plate-Comment"); + hasPlateCommentDiffs = addSpecificCommentDetails(CommentType.PLATE, "Plate-Comment"); } /** @@ -1455,7 +1455,7 @@ public class ProgramDiffDetails { private void addRepeatableCommentDetails() { hasRepeatableCommentDiffs = - addSpecificCommentDetails(CodeUnit.REPEATABLE_COMMENT, "Repeatable-Comment"); + addSpecificCommentDetails(CommentType.REPEATABLE, "Repeatable-Comment"); } /** @@ -1490,7 +1490,7 @@ public class ProgramDiffDetails { return retString; } - private boolean addSpecificCommentDetails(int commentType, String commentName) { + private boolean addSpecificCommentDetails(CommentType commentType, String commentName) { boolean hasCommentDiff = false; try { for (Address p1Address = minP1Address; p1Address diff --git a/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramMerge.java b/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramMerge.java index 299b482ae0..c1c0fafe3d 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramMerge.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/program/util/ProgramMerge.java @@ -1546,30 +1546,30 @@ public class ProgramMerge { } String typeStr = "Unknown"; - int cuCommentType; + CommentType cuCommentType; switch (type) { case ProgramMergeFilter.PLATE_COMMENTS: typeStr = "Plate"; - cuCommentType = CodeUnit.PLATE_COMMENT; + cuCommentType = CommentType.PLATE; break; case ProgramMergeFilter.PRE_COMMENTS: typeStr = "Pre"; - cuCommentType = CodeUnit.PRE_COMMENT; + cuCommentType = CommentType.PRE; break; case ProgramMergeFilter.EOL_COMMENTS: typeStr = "EOL"; - cuCommentType = CodeUnit.EOL_COMMENT; + cuCommentType = CommentType.EOL; break; case ProgramMergeFilter.REPEATABLE_COMMENTS: typeStr = "Repeatable"; - cuCommentType = CodeUnit.REPEATABLE_COMMENT; + cuCommentType = CommentType.REPEATABLE; break; case ProgramMergeFilter.POST_COMMENTS: typeStr = "Post"; - cuCommentType = CodeUnit.POST_COMMENT; + cuCommentType = CommentType.POST; break; default: - throw new AssertException("Unrecognized comment type: " + type); + throw new AssertException("Unsupported comment type: " + type); } monitor.setMessage("Applying " + typeStr + " comments..."); @@ -1604,11 +1604,11 @@ public class ProgramMerge { * mergeComments merges the comment of the indicated * type in program1 with the comment in program2 at the specified address. * @param commentType comment type to merge (from CodeUnit class). - *
EOL_COMMENT, PRE_COMMENT, POST_COMMENT, REPEATABLE_COMMENT, OR PLATE_COMMENT. + *
EOL, PRE, POST, REPEATABLE, OR PLATE. * @param originAddress the address * This address should be derived from the origin program. */ - public void mergeComments(int commentType, Address originAddress) { + public void mergeComments(CommentType commentType, Address originAddress) { Address resultAddress = originToResultTranslator.getAddress(originAddress); String resultComment = resultListing.getComment(commentType, resultAddress); String origComment = originListing.getComment(commentType, originAddress); @@ -1620,11 +1620,11 @@ public class ProgramMerge { * replaceComment replaces the comment of the indicated * type in program1 with the comment in program2 at the specified address. * @param commentType comment type to replace (from CodeUnit class). - *
EOL_COMMENT, PRE_COMMENT, POST_COMMENT, REPEATABLE_COMMENT, OR PLATE_COMMENT. + *
EOL, PRE, POST, REPEATABLE, OR PLATE. * @param originAddress the address * This address should be derived from the origin program. */ - public void replaceComment(int commentType, Address originAddress) { + public void replaceComment(CommentType commentType, Address originAddress) { Address resultAddress = originToResultTranslator.getAddress(originAddress); String origComment = originListing.getComment(commentType, originAddress); resultListing.setComment(resultAddress, commentType, origComment); diff --git a/Ghidra/Features/Base/src/main/java/ghidra/test/ClassicSampleX86ProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/test/ClassicSampleX86ProgramBuilder.java index 4ff6903bea..f838853c9e 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/test/ClassicSampleX86ProgramBuilder.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/test/ClassicSampleX86ProgramBuilder.java @@ -234,7 +234,7 @@ public class ClassicSampleX86ProgramBuilder extends ProgramBuilder { // // Comments // - createComment("0x0100415a", "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); + createComment("0x0100415a", "Repeatable Comment", CommentType.REPEATABLE); // // References diff --git a/Ghidra/Features/Base/src/main/java/ghidra/util/table/field/EOLCommentTableColumn.java b/Ghidra/Features/Base/src/main/java/ghidra/util/table/field/EOLCommentTableColumn.java index 86f1c39295..dc9c7f114c 100644 --- a/Ghidra/Features/Base/src/main/java/ghidra/util/table/field/EOLCommentTableColumn.java +++ b/Ghidra/Features/Base/src/main/java/ghidra/util/table/field/EOLCommentTableColumn.java @@ -26,8 +26,8 @@ import ghidra.program.util.*; * This table column displays the Label for either the program location or the address * associated with a row in the table. */ -public class EOLCommentTableColumn extends - ProgramLocationTableColumnExtensionPoint { +public class EOLCommentTableColumn + extends ProgramLocationTableColumnExtensionPoint { @Override public ProgramLocation getProgramLocation(ProgramLocation rowObject, Settings settings, @@ -35,7 +35,8 @@ public class EOLCommentTableColumn extends String comment = getEOLComment(rowObject, program); if (comment != null) { - return new EolCommentFieldLocation(program, rowObject.getAddress(), null, null, 0, 0, 0); + return new EolCommentFieldLocation(program, rowObject.getAddress(), null, null, 0, 0, + 0); } return rowObject; } diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CodeUnitMergeManager1Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CodeUnitMergeManager1Test.java index 963ad14140..f6557c2b6c 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CodeUnitMergeManager1Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CodeUnitMergeManager1Test.java @@ -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 ghidra.program.database.ProgramModifierListener; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressSet; import ghidra.program.model.data.*; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Instruction; import ghidra.program.model.mem.*; import ghidra.program.model.symbol.SourceType; @@ -46,8 +46,8 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { super(); } -@Test - public void testAddLatestInstr() throws Exception { + @Test + public void testAddLatestInstr() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -64,12 +64,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e1"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e1"))); } -@Test - public void testAddMyInstr() throws Exception { + @Test + public void testAddMyInstr() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -86,12 +86,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e1"))); + assertSameCodeUnits(resultProgram, myProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e1"))); } -@Test - public void testAddLatestData() throws Exception { + @Test + public void testAddLatestData() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -108,12 +108,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013da"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013da"))); } -@Test - public void testAddMyData() throws Exception { + @Test + public void testAddMyData() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -130,12 +130,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, myProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testAddLatestInstrMyDataPickLatest() throws Exception { + @Test + public void testAddLatestInstrMyDataPickLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -153,12 +153,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_LATEST); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testAddLatestInstrMyDataPickMy() throws Exception { + @Test + public void testAddLatestInstrMyDataPickMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -176,12 +176,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_MY); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e4"))); + assertSameCodeUnits(resultProgram, myProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e4"))); } -@Test - public void testAddLatestInstrMyDataPickOrig() throws Exception { + @Test + public void testAddLatestInstrMyDataPickOrig() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -199,12 +199,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_ORIGINAL); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e4"))); + assertSameCodeUnits(resultProgram, originalProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e4"))); } -@Test - public void testAddLatestDataMyInstrPickLatest() throws Exception { + @Test + public void testAddLatestDataMyInstrPickLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -222,14 +222,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_LATEST); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e4"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e4"))); } -@Test - public void testAddLatestDataMyInstrPickMy() throws Exception { + @Test + public void testAddLatestDataMyInstrPickMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { createData(program, "0x10013d9", new DWordDataType()); @@ -245,14 +245,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_MY); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, myProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testAddLatestDataMyInstrPickOrig() throws Exception { + @Test + public void testAddLatestDataMyInstrPickOrig() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { createData(program, "0x10013d9", new TerminatedStringDataType()); @@ -268,14 +268,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_ORIGINAL); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e4"))); + assertSameCodeUnits(resultProgram, originalProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e4"))); } -@Test - public void testAddLatestInstrMyInstrPickLatest() throws Exception { + @Test + public void testAddLatestInstrMyInstrPickLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { disassemble(program, "0x10013d9", "0x10013e1"); @@ -291,12 +291,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_LATEST); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e2"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e2"))); } -@Test - public void testAddLatestInstrMyInstrPickMy() throws Exception { + @Test + public void testAddLatestInstrMyInstrPickMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -314,12 +314,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_MY); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e2"))); + assertSameCodeUnits(resultProgram, myProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e2"))); } -@Test - public void testAddLatestInstrMyInstrPickOrig() throws Exception { + @Test + public void testAddLatestInstrMyInstrPickOrig() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -337,14 +337,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_ORIGINAL); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e2"))); + assertSameCodeUnits(resultProgram, originalProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e2"))); } -@Test - public void testAddLatestDataMyDataPickLatest() throws Exception { + @Test + public void testAddLatestDataMyDataPickLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { createData(program, "0x10013d9", new WordDataType()); @@ -360,14 +360,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_LATEST); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testAddLatestDataMyDataPickMy() throws Exception { + @Test + public void testAddLatestDataMyDataPickMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { createData(program, "0x10013d9", new WordDataType()); @@ -383,14 +383,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_MY); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, myProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testAddLatestDataMyDataPickOrig() throws Exception { + @Test + public void testAddLatestDataMyDataPickOrig() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { createData(program, "0x10013d9", new WordDataType()); @@ -406,12 +406,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_ORIGINAL); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, originalProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testSameInstrLatestMy() throws Exception { + @Test + public void testSameInstrLatestMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override public void modifyLatest(ProgramDB program) { @@ -427,14 +427,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013e1"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013e1"))); } -@Test - public void testSameDataLatestMy() throws Exception { + @Test + public void testSameDataLatestMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { createData(program, "0x10013d9", new DWordDataType()); @@ -449,34 +449,38 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); waitForMergeCompletion(); - assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), - addr("0x10013dc"))); + assertSameCodeUnits(resultProgram, latestProgram, + new AddressSet(addr("0x10013d9"), addr("0x10013dc"))); } -@Test - public void testMergeCodeUnitsOriginal() throws Exception { + @Test + public void testMergeCodeUnitsOriginal() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { try { // Clear Code Units from 1002312 to 1002320 - program.getListing().clearCodeUnits(addr(program, "0x1002312"), - addr(program, "0x1002320"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"), + false); // Clear Code Units from 1002390 to 1002394 - program.getListing().clearCodeUnits(addr(program, "0x1002390"), - addr(program, "0x1002394"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"), + false); // Put a label @ from 10023be-10023c2 to create a conflict with the code unit. - program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", - SourceType.USER_DEFINED); + program.getSymbolTable() + .createLabel(addr(program, "0x10023be"), "LabelABC", + SourceType.USER_DEFINED); // Put an Ascii at 10080d0 program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); // Put a Float at 10080db - program.getListing().createData(addr(program, "0x10080db"), new FloatDataType()); + program.getListing() + .createData(addr(program, "0x10080db"), new FloatDataType()); Memory mem = program.getMemory(); MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); @@ -503,17 +507,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { public void modifyPrivate(ProgramDB program) { try { // Clear Code Units from 100231d to 1002328 - program.getListing().clearCodeUnits(addr(program, "0x100231d"), - addr(program, "0x1002328"), false); - assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); + program.getListing() + .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"), + false); + assertTrue(!(program.getListing() + .getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); // Put a comment @ 1002390-1002394 to create a conflict with the code unit. - program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( - CodeUnit.EOL_COMMENT, "EOL comment"); + program.getListing() + .getCodeUnitAt(addr(program, "0x1002390")) + .setComment(CommentType.EOL, "EOL comment"); // Clear Code Units from 10023be to 10023c2 - program.getListing().clearCodeUnits(addr(program, "0x10023be"), - addr(program, "0x10023c2"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"), + false); // Put a structure at 10080d0 to 10080d3 StructureDataType struct = new StructureDataType("Item", 4); @@ -524,8 +532,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); // Clear Code Units from 100652a to 100652a - program.getListing().clearCodeUnits(addr(program, "0x100652a"), - addr(program, "0x100652a"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"), + false); } catch (CodeUnitInsertionException e) { e.printStackTrace(); @@ -556,30 +565,34 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { assertSameCodeUnits(resultProgram, latestProgram, latestAddrs); } -@Test - public void testMergeCodeUnitsLatest() throws Exception { + @Test + public void testMergeCodeUnitsLatest() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { try { // Clear Code Units from 1002312 to 1002320 - program.getListing().clearCodeUnits(addr(program, "0x1002312"), - addr(program, "0x1002320"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"), + false); // Clear Code Units from 1002390 to 1002394 - program.getListing().clearCodeUnits(addr(program, "0x1002390"), - addr(program, "0x1002394"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"), + false); // Put a label @ from 10023be-10023c2 to create a conflict with the code unit. - program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", - SourceType.USER_DEFINED); + program.getSymbolTable() + .createLabel(addr(program, "0x10023be"), "LabelABC", + SourceType.USER_DEFINED); // Put an Ascii at 10080d0 program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); // Put a Float at 10080db - program.getListing().createData(addr(program, "0x10080db"), new FloatDataType()); + program.getListing() + .createData(addr(program, "0x10080db"), new FloatDataType()); Memory mem = program.getMemory(); MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); @@ -606,17 +619,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { public void modifyPrivate(ProgramDB program) { try { // Clear Code Units from 100231d to 1002328 - program.getListing().clearCodeUnits(addr(program, "0x100231d"), - addr(program, "0x1002328"), false); - assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); + program.getListing() + .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"), + false); + assertTrue(!(program.getListing() + .getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); // Put a comment @ 1002390-1002394 to create a conflict with the code unit. - program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( - CodeUnit.EOL_COMMENT, "EOL comment"); + program.getListing() + .getCodeUnitAt(addr(program, "0x1002390")) + .setComment(CommentType.EOL, "EOL comment"); // Clear Code Units from 10023be to 10023c2 - program.getListing().clearCodeUnits(addr(program, "0x10023be"), - addr(program, "0x10023c2"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"), + false); // Put a structure at 10080d0 to 10080d3 StructureDataType struct = new StructureDataType("Item", 4); @@ -627,8 +644,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); // Clear Code Units from 100652a to 100652a - program.getListing().clearCodeUnits(addr(program, "0x100652a"), - addr(program, "0x100652a"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"), + false); } catch (CodeUnitInsertionException e) { @@ -654,30 +672,34 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { } -@Test - public void testMergeCodeUnitsMine() throws Exception { + @Test + public void testMergeCodeUnitsMine() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { try { // Clear Code Units from 1002312 to 1002320 - program.getListing().clearCodeUnits(addr(program, "0x1002312"), - addr(program, "0x1002320"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"), + false); // Clear Code Units from 1002390 to 1002394 - program.getListing().clearCodeUnits(addr(program, "0x1002390"), - addr(program, "0x1002394"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"), + false); // Put a label @ from 10023be-10023c2 to create a conflict with the code unit. - program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", - SourceType.USER_DEFINED); + program.getSymbolTable() + .createLabel(addr(program, "0x10023be"), "LabelABC", + SourceType.USER_DEFINED); // Put an Ascii at 10080d0 program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); // Put a Float at 10080db - program.getListing().createData(addr(program, "0x10080db"), new FloatDataType()); + program.getListing() + .createData(addr(program, "0x10080db"), new FloatDataType()); Memory mem = program.getMemory(); MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); @@ -704,17 +726,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { public void modifyPrivate(ProgramDB program) { try { // Clear Code Units from 100231d to 1002328 - program.getListing().clearCodeUnits(addr(program, "0x100231d"), - addr(program, "0x1002328"), false); - assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); + program.getListing() + .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"), + false); + assertTrue(!(program.getListing() + .getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); // Put a comment @ 1002390-1002394 to create a conflict with the code unit. - program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( - CodeUnit.EOL_COMMENT, "EOL comment"); + program.getListing() + .getCodeUnitAt(addr(program, "0x1002390")) + .setComment(CommentType.EOL, "EOL comment"); // Clear Code Units from 10023be to 10023c2 - program.getListing().clearCodeUnits(addr(program, "0x10023be"), - addr(program, "0x10023c2"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"), + false); // Put a structure at 10080d0 to 10080d3 StructureDataType struct = new StructureDataType("Item", 4); @@ -725,8 +751,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); // Clear Code Units from 100652a to 100652a - program.getListing().clearCodeUnits(addr(program, "0x100652a"), - addr(program, "0x100652a"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"), + false); } catch (CodeUnitInsertionException e) { e.printStackTrace(); @@ -755,8 +782,8 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { assertSameCodeUnits(resultProgram, latestProgram, latestAddrs); } -@Test - public void testMergeCodeUnitsUseForAllPickLatest() throws Exception { + @Test + public void testMergeCodeUnitsUseForAllPickLatest() throws Exception { setupUseForAll(); executeMerge(ASK_USER); // auto set is [0100231d, 01002328] [010023be, 010023c2] [010080e2, 010080e3] @@ -778,27 +805,31 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { private void setupUseForAll() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { - + @Override public void modifyLatest(ProgramDB program) { try { // Clear Code Units from 1002312 to 1002320 - program.getListing().clearCodeUnits(addr(program, "0x1002312"), - addr(program, "0x1002320"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"), + false); // Clear Code Units from 1002390 to 1002394 - program.getListing().clearCodeUnits(addr(program, "0x1002390"), - addr(program, "0x1002394"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"), + false); // Put a label @ from 10023be-10023c2 to create a conflict with the code unit. - program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", - SourceType.USER_DEFINED); + program.getSymbolTable() + .createLabel(addr(program, "0x10023be"), "LabelABC", + SourceType.USER_DEFINED); // Put an Ascii at 10080d0 program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); // Put a Float at 10080db - program.getListing().createData(addr(program, "0x10080db"), new FloatDataType()); + program.getListing() + .createData(addr(program, "0x10080db"), new FloatDataType()); Memory mem = program.getMemory(); MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); @@ -825,17 +856,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { public void modifyPrivate(ProgramDB program) { try { // Clear Code Units from 100231d to 1002328 - program.getListing().clearCodeUnits(addr(program, "0x100231d"), - addr(program, "0x1002328"), false); - assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); + program.getListing() + .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"), + false); + assertTrue(!(program.getListing() + .getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); // Put a comment @ 1002390-1002394 to create a conflict with the code unit. - program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( - CodeUnit.EOL_COMMENT, "EOL comment"); + program.getListing() + .getCodeUnitAt(addr(program, "0x1002390")) + .setComment(CommentType.EOL, "EOL comment"); // Clear Code Units from 10023be to 10023c2 - program.getListing().clearCodeUnits(addr(program, "0x10023be"), - addr(program, "0x10023c2"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"), + false); // Put a structure at 10080d0 to 10080d3 StructureDataType struct = new StructureDataType("Item", 4); @@ -846,8 +881,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); // Clear Code Units from 100652a to 100652a - program.getListing().clearCodeUnits(addr(program, "0x100652a"), - addr(program, "0x100652a"), false); + program.getListing() + .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"), + false); } catch (CodeUnitInsertionException e) { e.printStackTrace(); @@ -856,8 +892,8 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest { }); } -@Test - public void testMergeCodeUnitsUseForAllPickMine() throws Exception { + @Test + public void testMergeCodeUnitsUseForAllPickMine() throws Exception { setupUseForAll(); executeMerge(ASK_USER); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager1Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager1Test.java index c4949cb63b..a49dda69ae 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager1Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager1Test.java @@ -844,7 +844,7 @@ public class CommentMergeManager1Test extends AbstractListingMergeManagerTest { cu.setComment(CommentType.PLATE, "Plate Comment"); cu.setComment(CommentType.REPEATABLE, "Repeatable Comment"); } - + @Override public void modifyPrivate(ProgramDB program) { Listing listing = program.getListing(); @@ -1079,7 +1079,7 @@ public class CommentMergeManager1Test extends AbstractListingMergeManagerTest { cu.setComment(CommentType.PLATE, "Latest Plate Comment"); cu.setComment(CommentType.REPEATABLE, "Latest Repeatable Comment"); } - + @Override public void modifyPrivate(ProgramDB program) { Listing listing = program.getListing(); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager2Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager2Test.java index 9d9fcb703d..c4ea75f7d2 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager2Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/CommentMergeManager2Test.java @@ -35,8 +35,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { super(); } -@Test - public void testMergeCommentsLatest() throws Exception { + @Test + public void testMergeCommentsLatest() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { @Override @@ -127,8 +127,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("Latest Repeatable Comment", cu.getComment(CommentType.REPEATABLE)); } -@Test - public void testMergeCommentsMy() throws Exception { + @Test + public void testMergeCommentsMy() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { @Override @@ -220,8 +220,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("My Repeatable Comment", cu.getComment(CommentType.REPEATABLE)); } -@Test - public void testMergeCommentsBoth() throws Exception { + @Test + public void testMergeCommentsBoth() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { @Override @@ -296,8 +296,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { "Plate Comment"); // Repeatable Comment @ 100284a - assertEquals( - listing.getCodeUnitAt(addr("0x100284a")).getComment(CommentType.REPEATABLE), + assertEquals(listing.getCodeUnitAt(addr("0x100284a")).getComment(CommentType.REPEATABLE), "Repeatable Comment"); // Latest has comment @@ -318,8 +317,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { cu.getComment(CommentType.REPEATABLE)); } -@Test - public void testMergeCommentsAskUser() throws Exception { + @Test + public void testMergeCommentsAskUser() throws Exception { mtf.initialize("notepad", new ProgramModifierListener() { @Override @@ -400,8 +399,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { "Plate Comment"); // Repeatable Comment @ 100284a - assertEquals( - listing.getCodeUnitAt(addr("0x100284a")).getComment(CommentType.REPEATABLE), + assertEquals(listing.getCodeUnitAt(addr("0x100284a")).getComment(CommentType.REPEATABLE), "Repeatable Comment"); // Latest has comment @@ -418,8 +416,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("My Post Comment", cu.getComment(CommentType.POST)); } -@Test - public void testDeleteMy() throws Exception { + @Test + public void testDeleteMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -453,8 +451,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertNull(cu.getComment(CommentType.POST)); } -@Test - public void testDeleteLatest() throws Exception { + @Test + public void testDeleteLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -488,8 +486,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertNull(cu.getComment(CommentType.POST)); } -@Test - public void testDeleteBoth() throws Exception { + @Test + public void testDeleteBoth() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -530,8 +528,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertNull(cu.getComment(CommentType.POST)); } -@Test - public void testChangeLatestDeleteMyPickLatest() throws Exception { + @Test + public void testChangeLatestDeleteMyPickLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -577,8 +575,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("Latest Post Comment", cu.getComment(CommentType.POST)); } -@Test - public void testChangeLatestDeleteMyPickMy() throws Exception { + @Test + public void testChangeLatestDeleteMyPickMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -624,8 +622,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertNull(cu.getComment(CommentType.POST)); } -@Test - public void testChangeMyDeleteLatestPickLatest() throws Exception { + @Test + public void testChangeMyDeleteLatestPickLatest() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -671,8 +669,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertNull(cu.getComment(CommentType.POST)); } -@Test - public void testChangeMyDeleteLatestPickMy() throws Exception { + @Test + public void testChangeMyDeleteLatestPickMy() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -718,8 +716,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("My Post Comment", cu.getComment(CommentType.POST)); } -@Test - public void testAddUnInitNoConflict() throws Exception { + @Test + public void testAddUnInitNoConflict() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -784,8 +782,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("My Post Comment", cu.getComment(CommentType.POST)); } -@Test - public void testAddUnInitWithConflict() throws Exception { + @Test + public void testAddUnInitWithConflict() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -874,8 +872,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("My Repeatable Comment", cu.getComment(CommentType.REPEATABLE)); assertEquals("My Post Comment", cu.getComment(CommentType.POST)); cu = listing.getCodeUnitAt(addr("0x1008608")); - assertEquals("Latest Plate Comment\nMy Plate Comment", - cu.getComment(CommentType.PLATE)); + assertEquals("Latest Plate Comment\nMy Plate Comment", cu.getComment(CommentType.PLATE)); assertEquals("Latest Pre Comment\nMy Pre Comment", cu.getComment(CommentType.PRE)); assertEquals("Latest EOL Comment\nMy EOL Comment", cu.getComment(CommentType.EOL)); assertEquals("Latest Repeatable Comment\nMy Repeatable Comment", @@ -883,8 +880,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("Latest Post Comment\nMy Post Comment", cu.getComment(CommentType.POST)); } -@Test - public void testAddCommentInsideCodeUnit() throws Exception { + @Test + public void testAddCommentInsideCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -930,8 +927,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("Pre", listing.getComment(CommentType.PRE, addr("0x10065e3"))); assertEquals("Post", listing.getComment(CommentType.POST, addr("0x10065e3"))); assertEquals("Plate", listing.getComment(CommentType.PLATE, addr("0x10065e3"))); - assertEquals("Repeatable", - listing.getComment(CommentType.REPEATABLE, addr("0x10065e3"))); + assertEquals("Repeatable", listing.getComment(CommentType.REPEATABLE, addr("0x10065e3"))); cu = listing.getCodeUnitContaining(addr("0x10065e9")); assertEquals(addr("0x10065e8"), cu.getMinAddress()); @@ -941,12 +937,11 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals("Pre2", listing.getComment(CommentType.PRE, addr("0x10065e9"))); assertEquals("Post2", listing.getComment(CommentType.POST, addr("0x10065e9"))); assertEquals("Plate2", listing.getComment(CommentType.PLATE, addr("0x10065e9"))); - assertEquals("Repeatable2", - listing.getComment(CommentType.REPEATABLE, addr("0x10065e9"))); + assertEquals("Repeatable2", listing.getComment(CommentType.REPEATABLE, addr("0x10065e9"))); } -@Test - public void testChangeLatestCommentInsideMyCodeUnit() throws Exception { + @Test + public void testChangeLatestCommentInsideMyCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -965,8 +960,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { @Override public void modifyPrivate(ProgramDB program) { disassemble(program, - new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), - false); + new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), false); } }); @@ -982,23 +976,20 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertTrue(cu instanceof Instruction); assertEquals("New EOL Comment", listing.getComment(CommentType.EOL, addr("0x1002040"))); assertEquals("New Pre Comment", listing.getComment(CommentType.PRE, addr("0x1002040"))); - assertEquals("New Post Comment", - listing.getComment(CommentType.POST, addr("0x1002040"))); - assertEquals("New Plate Comment", - listing.getComment(CommentType.PLATE, addr("0x1002040"))); + assertEquals("New Post Comment", listing.getComment(CommentType.POST, addr("0x1002040"))); + assertEquals("New Plate Comment", listing.getComment(CommentType.PLATE, addr("0x1002040"))); assertEquals("New Repeatable Comment", listing.getComment(CommentType.REPEATABLE, addr("0x1002040"))); } -@Test - public void testChangeMyCommentInsideLatestCodeUnit() throws Exception { + @Test + public void testChangeMyCommentInsideLatestCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override public void modifyLatest(ProgramDB program) { disassemble(program, - new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), - false); + new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), false); } @Override @@ -1027,16 +1018,14 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertTrue(cu instanceof Instruction); assertEquals("New EOL Comment", listing.getComment(CommentType.EOL, addr("0x1002040"))); assertEquals("New Pre Comment", listing.getComment(CommentType.PRE, addr("0x1002040"))); - assertEquals("New Post Comment", - listing.getComment(CommentType.POST, addr("0x1002040"))); - assertEquals("New Plate Comment", - listing.getComment(CommentType.PLATE, addr("0x1002040"))); + assertEquals("New Post Comment", listing.getComment(CommentType.POST, addr("0x1002040"))); + assertEquals("New Plate Comment", listing.getComment(CommentType.PLATE, addr("0x1002040"))); assertEquals("New Repeatable Comment", listing.getComment(CommentType.REPEATABLE, addr("0x1002040"))); } -@Test - public void testRemoveCommentInsideMyCodeUnit() throws Exception { + @Test + public void testRemoveCommentInsideMyCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -1050,8 +1039,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { Listing listing = program.getListing(); listing.setComment(addr(program, "0x1002040"), CommentType.PRE, null); disassemble(program, - new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), - false); + new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), false); } }); @@ -1073,8 +1061,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { listing.getComment(CommentType.REPEATABLE, addr("0x1002040"))); } -@Test - public void testRemoveCommentInsideLatestCodeUnit() throws Exception { + @Test + public void testRemoveCommentInsideLatestCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -1082,8 +1070,7 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { Listing listing = program.getListing(); listing.setComment(addr(program, "0x1002040"), CommentType.POST, null); disassemble(program, - new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), - false); + new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), false); } @Override @@ -1111,8 +1098,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { listing.getComment(CommentType.REPEATABLE, addr("0x1002040"))); } -@Test - public void testChangeCommentInsideMyCodeUnit() throws Exception { + @Test + public void testChangeCommentInsideMyCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override @@ -1141,15 +1128,15 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { listing.setComment(addr(program, "0x1002040"), CommentType.REPEATABLE, "New Repeatable Comment"); disassemble(program, - new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), - false); + new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), false); } }); executeMerge(ASK_USER); chooseVerticalCheckBoxes(new String[] { LATEST_CHECK_BOX_NAME }); // Pre chooseVerticalCheckBoxes(new String[] { CHECKED_OUT_CHECK_BOX_NAME }); // EOL - chooseVerticalCheckBoxes(new String[] { LATEST_CHECK_BOX_NAME, CHECKED_OUT_CHECK_BOX_NAME }); // Post + chooseVerticalCheckBoxes( + new String[] { LATEST_CHECK_BOX_NAME, CHECKED_OUT_CHECK_BOX_NAME }); // Post waitForMergeCompletion(); Listing listing = resultProgram.getListing(); @@ -1160,26 +1147,23 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { assertEquals(2, cu.getLength()); assertTrue(cu instanceof Instruction); assertEquals("My EOL Comment", listing.getComment(CommentType.EOL, addr("0x1002040"))); - assertEquals("Latest Pre Comment", - listing.getComment(CommentType.PRE, addr("0x1002040"))); + assertEquals("Latest Pre Comment", listing.getComment(CommentType.PRE, addr("0x1002040"))); assertEquals("Latest Post Comment\nMy Post Comment", listing.getComment(CommentType.POST, addr("0x1002040"))); - assertEquals("New Plate Comment", - listing.getComment(CommentType.PLATE, addr("0x1002040"))); + assertEquals("New Plate Comment", listing.getComment(CommentType.PLATE, addr("0x1002040"))); assertEquals("New Repeatable Comment", listing.getComment(CommentType.REPEATABLE, addr("0x1002040"))); } -@Test - public void testChangeCommentInsideLatestCodeUnit() throws Exception { + @Test + public void testChangeCommentInsideLatestCodeUnit() throws Exception { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { @Override public void modifyLatest(ProgramDB program) { Listing listing = program.getListing(); disassemble(program, - new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), - false); + new AddressSet(addr(program, "0x100203e"), addr(program, "0x1002043")), false); listing.setComment(addr(program, "0x1002040"), CommentType.EOL, "New EOL Comment"); listing.setComment(addr(program, "0x1002040"), CommentType.PRE, "New Pre Comment"); listing.setComment(addr(program, "0x1002040"), CommentType.POST, @@ -1206,7 +1190,8 @@ public class CommentMergeManager2Test extends AbstractListingMergeManagerTest { executeMerge(ASK_USER); chooseVerticalCheckBoxes(new String[] { LATEST_CHECK_BOX_NAME }); // Plate chooseVerticalCheckBoxes(new String[] { CHECKED_OUT_CHECK_BOX_NAME }); // Repeatable - chooseVerticalCheckBoxes(new String[] { LATEST_CHECK_BOX_NAME, CHECKED_OUT_CHECK_BOX_NAME }); // Post + chooseVerticalCheckBoxes( + new String[] { LATEST_CHECK_BOX_NAME, CHECKED_OUT_CHECK_BOX_NAME }); // Post waitForMergeCompletion(); Listing listing = resultProgram.getListing(); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteCommentsTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteCommentsTest.java index 8ee73a4066..bf61353ae3 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteCommentsTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteCommentsTest.java @@ -77,13 +77,13 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { builder.createLabel("0x31b", "RSTOR()"); builder.addBytesFallthrough("0x0326"); - builder.createComment("0x0326", "Hey There", CodeUnit.EOL_COMMENT); - builder.createComment("0x0182", "SAVE register 'I'", CodeUnit.EOL_COMMENT); - builder.createComment("0x0334", "Set the SP to RAM:ESAV", CodeUnit.EOL_COMMENT); - builder.createComment("0x0335", "RESTORE register 'DE'", CodeUnit.EOL_COMMENT); - builder.createComment("0x0336", "RESTORE register 'BC'", CodeUnit.EOL_COMMENT); - builder.createComment("0x0337", "RESTORE register 'A' and FLAGS", CodeUnit.EOL_COMMENT); - builder.createComment("0x0338", "RESTORE register 'SP'", CodeUnit.EOL_COMMENT); + builder.createComment("0x0326", "Hey There", CommentType.EOL); + builder.createComment("0x0182", "SAVE register 'I'", CommentType.EOL); + builder.createComment("0x0334", "Set the SP to RAM:ESAV", CommentType.EOL); + builder.createComment("0x0335", "RESTORE register 'DE'", CommentType.EOL); + builder.createComment("0x0336", "RESTORE register 'BC'", CommentType.EOL); + builder.createComment("0x0337", "RESTORE register 'A' and FLAGS", CommentType.EOL); + builder.createComment("0x0338", "RESTORE register 'SP'", CommentType.EOL); builder.createMemoryReference("0x1000", "0x331", RefType.UNCONDITIONAL_JUMP, SourceType.DEFAULT); @@ -197,8 +197,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { int transactionID = programOne.startTransaction("test"); programOne.getSymbolTable() - .createLabel(addr(programOne, 0x032a), "MyLabel", - SourceType.USER_DEFINED); + .createLabel(addr(programOne, 0x032a), "MyLabel", SourceType.USER_DEFINED); programOne.endTransaction(transactionID, true); goTo(toolTwo, 0x0326); @@ -389,8 +388,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { // in Browser(1) change default label at 331 to JUNK int transactionID = programOne.startTransaction("test"); programOne.getSymbolTable() - .createLabel(addr(programOne, 0x0331), "JUNK", - SourceType.USER_DEFINED); + .createLabel(addr(programOne, 0x0331), "JUNK", SourceType.USER_DEFINED); programOne.endTransaction(transactionID, true); // // in Browser(1) go to 331 @@ -431,8 +429,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { // in program 2, create a second label, JUNK2, at 0331 int transactionID = programOne.startTransaction("test"); programOne.getSymbolTable() - .createLabel(addr(programOne, 0x331), "JUNK2", - SourceType.USER_DEFINED); + .createLabel(addr(programOne, 0x331), "JUNK2", SourceType.USER_DEFINED); programOne.endTransaction(transactionID, true); // in Browser(2) select 331 through 334, contains "RSR10" @@ -480,8 +477,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { public void testPasteWhereUserLabelExists() throws Exception { int transactionID = programOne.startTransaction("test"); programOne.getSymbolTable() - .createLabel(addr(programOne, 0x331), "JUNK2", - SourceType.USER_DEFINED); + .createLabel(addr(programOne, 0x331), "JUNK2", SourceType.USER_DEFINED); programOne.endTransaction(transactionID, true); // in Browser(2) select 331 through 334, contains "RSR10" @@ -593,16 +589,14 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { cb.goToField(addr(programOne, 0x0331), LabelFieldFactory.FIELD_NAME, 0, 0); f = (ListingTextField) cb.getCurrentField(); assertEquals(programOne.getSymbolTable() - .getSymbol("LAB_00000331", addr(programOne, 0x0331), - null) + .getSymbol("LAB_00000331", addr(programOne, 0x0331), null) .getName(), f.getText()); cb.goToField(addr(programOne, 0x031b), LabelFieldFactory.FIELD_NAME, 0, 0); f = (ListingTextField) cb.getCurrentField(); assertEquals(programOne.getSymbolTable() - .getSymbol("LAB_0000031b", addr(programOne, 0x031b), - null) + .getSymbol("LAB_0000031b", addr(programOne, 0x031b), null) .getName(), f.getText()); @@ -629,8 +623,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { int transactionID = programOne.startTransaction("test"); String name = SymbolUtilities.getDefaultFunctionName(min); programOne.getListing() - .createFunction(name, min, new AddressSet(min, max), - SourceType.USER_DEFINED); + .createFunction(name, min, new AddressSet(min, max), SourceType.USER_DEFINED); programOne.endTransaction(transactionID, true); programOne.flushEvents(); waitForSwing(); @@ -722,8 +715,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { private void copyToolTwoLabels() { ClipboardPlugin plugin = getPlugin(toolTwo, ClipboardPlugin.class); - ClipboardContentProviderService service = - getClipboardService(plugin); + ClipboardContentProviderService service = getClipboardService(plugin); DockingAction action = getLocalAction(service, "Copy Special", plugin); assertNotNull(action); assertEnabled(action, cb2.getProvider()); @@ -826,8 +818,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { waitForSwing(); } - private ClipboardContentProviderService getClipboardService( - ClipboardPlugin clipboardPlugin) { + private ClipboardContentProviderService getClipboardService(ClipboardPlugin clipboardPlugin) { Map serviceMap = (Map) getInstanceField("serviceActionMap", clipboardPlugin); Set keySet = serviceMap.keySet(); for (Object name : keySet) { @@ -855,10 +846,9 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest { } private void assertEnabled(DockingActionIf action, ComponentProvider provider) { - boolean isEnabled = - runSwing(() -> { - return action.isEnabledForContext(provider.getActionContext(null)); - }); + boolean isEnabled = runSwing(() -> { + return action.isEnabledForContext(provider.getActionContext(null)); + }); assertTrue("Action was not enabled when it should be", isEnabled); } } diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteFunctionInfoTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteFunctionInfoTest.java index 71624f029a..8aa54af8c1 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteFunctionInfoTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/clipboard/CopyPasteFunctionInfoTest.java @@ -87,7 +87,7 @@ public class CopyPasteFunctionInfoTest extends AbstractGhidraHeadedIntegrationTe builder.createFunction("0x1006420"); builder.createEntryPoint("0x1006420", "entry"); builder.createFunction("0x1004700"); - builder.createComment("0x1006420", "FUNCTION", CodeUnit.PLATE_COMMENT); + builder.createComment("0x1006420", "FUNCTION", CommentType.PLATE); DataType dt = Undefined4DataType.dataType; Parameter p = new ParameterImpl(null, dt, builder.getProgram()); builder.createEmptyFunction("BOB", "0x1004260", 1, dt, p, p, p, p, p, p, p, p, p, p, p, p, diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/codebrowser/CodeBrowserOptionsTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/codebrowser/CodeBrowserOptionsTest.java index 99af5a6bc3..597a4892ba 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/codebrowser/CodeBrowserOptionsTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/codebrowser/CodeBrowserOptionsTest.java @@ -621,8 +621,8 @@ public class CodeBrowserOptionsTest extends AbstractGhidraHeadedIntegrationTest SourceType.USER_DEFINED, 0, false); tool.execute(addRefCmd, program); - SetCommentCmd commentRefCmd = new SetCommentCmd(otherRefAddress, - CommentType.REPEATABLE, "Mem ref line1.\n" + ""); + SetCommentCmd commentRefCmd = + new SetCommentCmd(otherRefAddress, CommentType.REPEATABLE, "Mem ref line1.\n" + ""); tool.execute(commentRefCmd, program); // these values are all DEFAULT, by default; set them in case that changes in the future diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/comments/CommentsPluginTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/comments/CommentsPluginTest.java index 5703975369..00cc19a252 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/comments/CommentsPluginTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/comments/CommentsPluginTest.java @@ -61,9 +61,6 @@ import ghidra.util.task.TaskMonitor; public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { - private final static int[] TYPES = new int[] { CodeUnit.EOL_COMMENT, CodeUnit.PRE_COMMENT, - CodeUnit.POST_COMMENT, CodeUnit.PLATE_COMMENT, CodeUnit.REPEATABLE_COMMENT, }; - private final static String PRE = "This is a PRE comment."; private final static String POST = "This is a POST comment."; private final static String EOL = "This is a EOL comment."; @@ -132,7 +129,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Data subData1 = data.getComponent(0); assertEquals(new WordDataType().getName(), subData1.getDataType().getName()); String comment1 = "aaa bbb ccc ddd eee"; - setAt(addr, CodeUnit.EOL_COMMENT, comment1, "OK"); + setAt(addr, CommentType.EOL, comment1, "OK"); assertEquals(comment1, subData1.getComment(CommentType.EOL)); browser.goToField(addr(0x10080a2), "+", 0, 0); @@ -146,7 +143,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Data subData = data.getComponent(1).getComponent(0); assertEquals(new FloatDataType().getName(), subData.getDataType().getName()); String comment = "This is a comment on a structure element."; - setAt(addr, CodeUnit.EOL_COMMENT, comment, "OK"); + setAt(addr, CommentType.EOL, comment, "OK"); assertEquals(comment, subData.getComment(CommentType.EOL)); browser.goToField(addr(0x010080a2), EolCommentFieldFactory.FIELD_NAME, 0, 0); @@ -183,11 +180,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006420); - for (int element : TYPES) { + for (CommentType type : CommentType.values()) { - tx(program, () -> program.getListing().setComment(addr, element, "Test" + element)); + tx(program, () -> program.getListing().setComment(addr, type, "Test" + type)); - sendProgramLocation(addr, element); + sendProgramLocation(addr, type); performAction(editAction, browser.getProvider(), false); waitForSwing(); @@ -198,7 +195,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { JTabbedPane tab = findComponent(dialog.getComponent(), JTabbedPane.class); assertNotNull(tab); - assertEquals(element, tab.getSelectedIndex()); + assertEquals(type.ordinal(), tab.getSelectedIndex()); pressButtonByText(dialog.getComponent(), "Dismiss", false); waitForSwing(); @@ -238,7 +235,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { tool2.firePluginEvent(new OpenProgramPluginEvent("Test", program)); Address addr = addr(0x01006420); - sendProgramLocation(addr, CodeUnit.EOL_COMMENT); + sendProgramLocation(addr, CommentType.EOL); String comment = "Drag and Drop is a direct manipulation gesture\n" + "found in many Graphical User Interface\n" + @@ -246,7 +243,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { "between two entities logically associated with\n" + "presentation elements in the GUI.\n"; - setAt(addr, CodeUnit.EOL_COMMENT, comment, "OK"); + setAt(addr, CommentType.EOL, comment, "OK"); setFieldWidth(browser, EolCommentFieldFactory.FIELD_NAME, 100); @@ -275,7 +272,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.PRE_COMMENT, PRE, "OK"); + setAt(addr, CommentType.PRE, PRE, "OK"); assertEquals(PRE, cu.getComment(CommentType.PRE)); undo(program); assertNull(cu.getComment(CommentType.PRE)); @@ -290,7 +287,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.POST_COMMENT, POST, "OK"); + setAt(addr, CommentType.POST, POST, "OK"); assertEquals(POST, cu.getComment(CommentType.POST)); undo(program); assertNull(cu.getComment(CommentType.POST)); @@ -305,7 +302,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.EOL_COMMENT, EOL, "OK"); + setAt(addr, CommentType.EOL, EOL, "OK"); assertEquals(EOL, cu.getComment(CommentType.EOL)); undo(program); assertNull(cu.getComment(CommentType.EOL)); @@ -321,7 +318,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { resetFormatOptions(browser); Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.PLATE_COMMENT, PLATE, "OK"); + setAt(addr, CommentType.PLATE, PLATE, "OK"); assertEquals(PLATE, cu.getComment(CommentType.PLATE)); undo(program); assertNull(cu.getComment(CommentType.PLATE)); @@ -337,7 +334,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.REPEATABLE_COMMENT, REPEAT, "OK"); + setAt(addr, CommentType.REPEATABLE, REPEAT, "OK"); assertEquals(REPEAT, cu.getComment(CommentType.REPEATABLE)); undo(program); assertNull(cu.getComment(CommentType.REPEATABLE)); @@ -354,7 +351,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { CodeUnit cu = program.getListing().getCodeUnitAt(addr); String longComment = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\n"; - setAt(addr, CodeUnit.REPEATABLE_COMMENT, longComment, "OK"); + setAt(addr, CommentType.REPEATABLE, longComment, "OK"); assertEquals(longComment, cu.getComment(CommentType.REPEATABLE)); // this fails when excepting @@ -367,11 +364,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.PRE_COMMENT, PRE, "OK"); - setAt(addr, CodeUnit.POST_COMMENT, POST, "OK"); - setAt(addr, CodeUnit.EOL_COMMENT, EOL, "OK"); - setAt(addr, CodeUnit.PLATE_COMMENT, PLATE, "OK"); - setAt(addr, CodeUnit.REPEATABLE_COMMENT, REPEAT, "OK"); + setAt(addr, CommentType.PRE, PRE, "OK"); + setAt(addr, CommentType.POST, POST, "OK"); + setAt(addr, CommentType.EOL, EOL, "OK"); + setAt(addr, CommentType.PLATE, PLATE, "OK"); + setAt(addr, CommentType.REPEATABLE, REPEAT, "OK"); assertEquals(PRE, cu.getComment(CommentType.PRE)); assertEquals(POST, cu.getComment(CommentType.POST)); @@ -401,7 +398,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006000); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.REPEATABLE_COMMENT, "Bla bla bla", "Apply"); + setAt(addr, CommentType.REPEATABLE, "Bla bla bla", "Apply"); final CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class); assertNotNull(commentsDialog); pressButtonByText(commentsDialog.getComponent(), "Dismiss", false); @@ -415,8 +412,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0xf0001300); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.PRE_COMMENT, PRE, "OK"); - setAt(addr, CodeUnit.PRE_COMMENT, PRE_U, "OK"); + setAt(addr, CommentType.PRE, PRE, "OK"); + setAt(addr, CommentType.PRE, PRE_U, "OK"); undo(program); assertEquals(PRE, cu.getComment(CommentType.PRE)); redo(program); @@ -428,7 +425,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006000); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.POST_COMMENT, "Bla bla bla", "Dismiss"); + setAt(addr, CommentType.POST, "Bla bla bla", "Dismiss"); CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class); OptionDialog saveDialog = waitForDialogComponent(OptionDialog.class); assertNotNull(saveDialog); @@ -448,7 +445,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006000); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.POST_COMMENT, "Bla bla bla", "Dismiss"); + setAt(addr, CommentType.POST, "Bla bla bla", "Dismiss"); CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class); assertNotNull(commentsDialog); OptionDialog saveDialog = waitForDialogComponent(OptionDialog.class); @@ -469,7 +466,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x01006000); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.POST_COMMENT, "Bla bla bla", "Dismiss"); + setAt(addr, CommentType.POST, "Bla bla bla", "Dismiss"); CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class); assertNotNull(commentsDialog); @@ -493,9 +490,9 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0xf0000250); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.PLATE_COMMENT, PLATE, "OK"); + setAt(addr, CommentType.PLATE, PLATE, "OK"); assertEquals(PLATE, cu.getComment(CommentType.PLATE)); - removeAt(addr, CodeUnit.PLATE_COMMENT); + removeAt(addr, CommentType.PLATE); assertNull(cu.getComment(CommentType.PLATE)); undo(program); assertEquals(PLATE, cu.getComment(CommentType.PLATE)); @@ -508,11 +505,10 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { openX86ProgramInTool(); Address addr = addr(0x0100bbbb); - setAt(addr, CodeUnit.EOL_COMMENT, EOL, "OK"); - setAt(addr, CodeUnit.EOL_COMMENT, EOL_U, "OK"); + setAt(addr, CommentType.EOL, EOL, "OK"); + setAt(addr, CommentType.EOL, EOL_U, "OK"); - CommentHistory[] history = - program.getListing().getCommentHistory(addr, CodeUnit.EOL_COMMENT); + CommentHistory[] history = program.getListing().getCommentHistory(addr, CommentType.EOL); assertEquals(2, history.length); for (int i = 0; i < history.length; i++) { @@ -542,7 +538,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { String comment = buffer.toString(); Address addr = addr(0x01006000); CodeUnit cu = program.getListing().getCodeUnitAt(addr); - setAt(addr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(addr, CommentType.PRE, comment, "OK"); assertEquals(comment, cu.getComment(CommentType.PRE)); } @@ -555,7 +551,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { String comment = "This is a comment with address " + commentAddress + " in it."; CommentsDialog dialog = editComment(addr(0x01006990)); - JTextArea commentTextArea = getTextArea(dialog, CodeUnit.EOL_COMMENT); + JTextArea commentTextArea = getTextArea(dialog, CommentType.EOL); runSwing(() -> { commentTextArea.setText(comment); @@ -585,7 +581,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr); String comment = "This is a comment DAT_01008094 with a label in it."; - setAt(srcAddr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(srcAddr, CommentType.PRE, comment, "OK"); assertEquals(comment, cu.getComment(CommentType.PRE)); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23); @@ -602,7 +598,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr); String comment = "This is a comment 01008094 with an address in it."; - setAt(srcAddr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(srcAddr, CommentType.PRE, comment, "OK"); assertEquals(comment, cu.getComment(CommentType.PRE)); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23); @@ -622,7 +618,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Address srcAddr = addr(0x01006990); String comment = "This is a comment {@sym DAT_01008094} with an annotation in it."; - setAt(srcAddr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(srcAddr, CommentType.PRE, comment, "OK"); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23); click(browser, 2); @@ -638,7 +634,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Address srcAddr = addr(0x01006990); String comment = "This is a comment {@sym Deadpool::Bob} with an annotation in it."; - setAt(srcAddr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(srcAddr, CommentType.PRE, comment, "OK"); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 20); click(browser, 2); @@ -654,7 +650,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Address srcAddr = addr(0x01006990); String comment = "This is a symbol {@program Test@Deadpool::Bob} annotation."; - setAt(srcAddr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(srcAddr, CommentType.PRE, comment, "OK"); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23); click(browser, 2); @@ -677,7 +673,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr); String comment = "This is a comment DAT_* with a wildcard in it."; - setAt(srcAddr, CodeUnit.PRE_COMMENT, comment, "OK"); + setAt(srcAddr, CommentType.PRE, comment, "OK"); assertEquals(comment, cu.getComment(CommentType.PRE)); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 19); @@ -709,7 +705,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { AddressSpace extmemSpace = af.getAddressSpace("EXTMEM"); Address addr = extmemSpace.getAddress(0); - setAt(addr, CodeUnit.PLATE_COMMENT, "Around the world in 80 days.", "OK"); + setAt(addr, CommentType.PLATE, "Around the world in 80 days.", "OK"); browser.goToField(addr, PlateFieldFactory.FIELD_NAME, 1, 22); click(browser, 2); @@ -723,7 +719,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { Address addr = addr(0x01006420); CodeUnit cu = program.getListing().getCodeUnitAt(addr); String tabComment = "abcd\tdefg\n\t1\t2\t3\t4"; - setAt(addr, CodeUnit.PLATE_COMMENT, tabComment, "OK"); + setAt(addr, CommentType.PLATE, tabComment, "OK"); // space comment is exactly the same; i.e. make sure that no tab conversion happens String spaceComment = "abcd\tdefg\n\t1\t2\t3\t4"; @@ -790,12 +786,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { String illegal = "null\0 comment"; String legal = "null comment"; - setAt(addr, CodeUnit.PRE_COMMENT, illegal, "OK"); + setAt(addr, CommentType.PRE, illegal, "OK"); assertEquals(legal, cu.getComment(CommentType.PRE)); } - private void setAt(Address addr, int commentType, String comment, String nameOfButtonToClick) - throws Exception { + private void setAt(Address addr, CommentType commentType, String comment, + String nameOfButtonToClick) throws Exception { CommentsDialog dialog = editComment(addr); assertEquals("Set Comment(s) at Address " + addr.toString(), dialog.getTitle()); @@ -817,7 +813,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { return waitForDialogComponent(CommentsDialog.class); } - private JTextArea getTextArea(CommentsDialog dialog, int commentType) { + private JTextArea getTextArea(CommentsDialog dialog, CommentType commentType) { runSwing(() -> dialog.setCommentType(commentType)); waitForSwing(); @@ -829,7 +825,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { return textArea; } - private void removeAt(Address addr, int commentType) throws Exception { + private void removeAt(Address addr, CommentType commentType) throws Exception { sendProgramLocation(addr, commentType); performAction(deleteAction, browser.getProvider(), false); waitForSwing(); @@ -839,11 +835,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset); } - private ProgramLocation sendProgramLocation(Address addr, int type) { + private ProgramLocation sendProgramLocation(Address addr, CommentType type) { CodeUnit cu = program.getListing().getCodeUnitAt(addr); String[] comment = cu.getCommentAsArray(type); - ProgramLocation loc = type == CodeUnit.EOL_COMMENT + ProgramLocation loc = type == CommentType.EOL ? new EolCommentFieldLocation(program, addr, null, comment, 0, 0, 0) : new CommentFieldLocation(program, addr, null, comment, type, 0, 0); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/commentwindow/CommentWindowPluginTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/commentwindow/CommentWindowPluginTest.java index 4ea6f13112..5093b87b45 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/commentwindow/CommentWindowPluginTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/commentwindow/CommentWindowPluginTest.java @@ -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. @@ -29,7 +29,7 @@ import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin; import ghidra.app.services.ProgramManager; import ghidra.framework.plugintool.PluginTool; 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.test.*; @@ -79,11 +79,11 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest ClassicSampleX86ProgramBuilder builder = new ClassicSampleX86ProgramBuilder(); program = builder.getProgram(); - builder.createComment("01006420", "test EOL comment", CodeUnit.EOL_COMMENT); - builder.createComment("01008004", "test Pre comment", CodeUnit.PRE_COMMENT); - builder.createComment("0100b2b", "test Post comment", CodeUnit.POST_COMMENT); - builder.createComment("010018a0", "test Plate comment", CodeUnit.PLATE_COMMENT); - builder.createComment("010018cf", "test Repeatable comment", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("01006420", "test EOL comment", CommentType.EOL); + builder.createComment("01008004", "test Pre comment", CommentType.PRE); + builder.createComment("0100b2b", "test Post comment", CommentType.POST); + builder.createComment("010018a0", "test Plate comment", CommentType.PLATE); + builder.createComment("010018cf", "test Repeatable comment", CommentType.REPEATABLE); ProgramManager pm = tool.getService(ProgramManager.class); pm.openProgram(program.getDomainFile()); @@ -144,7 +144,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest assertEquals(5, numComments); - addComment(addr("0x01001000"), CodeUnit.EOL_COMMENT, "Added EOL Comment"); + addComment(addr("0x01001000"), CommentType.EOL, "Added EOL Comment"); assertRowCount(6); @@ -169,7 +169,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest assertEquals("test EOL comment", getTableComment(rowIndex)); // Then set the comment to a different value - setComment(addr("0x01006420"), CodeUnit.EOL_COMMENT, "Changed EOL Comment"); + setComment(addr("0x01006420"), CommentType.EOL, "Changed EOL Comment"); // Test to see if the changed comment is in the table assertEquals("Changed EOL Comment", getTableComment(rowIndex)); @@ -193,7 +193,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest loadProgram("notepad"); } - private void addComment(Address addr, int commentType, String comment) { + private void addComment(Address addr, CommentType commentType, String comment) { int id = program.startTransaction(testName.getMethodName()); try { program.getListing().setComment(addr, commentType, comment); @@ -230,7 +230,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest return commentTable.getValueAt(rowIndex, CommentTableModel.COMMENT_COL).toString(); } - private void setComment(Address addr, int commentType, String comment) { + private void setComment(Address addr, CommentType commentType, String comment) { int id = program.startTransaction(testName.getMethodName()); try { program.getListing().setComment(addr, commentType, comment); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/disassembler/ClearTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/disassembler/ClearTest.java index 4af7ac41f4..5716a9472c 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/disassembler/ClearTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/disassembler/ClearTest.java @@ -566,7 +566,7 @@ public class ClearTest extends AbstractGhidraHeadedIntegrationTest { public void testClearComments() throws Exception { assertTrue(cb.goToField(addr("0x10022cc"), "Bytes", 0, 4)); - SetCommentCmd cmd =new SetCommentCmd(addr("0x10022cc"), CommentType.EOL, "my comment"); + SetCommentCmd cmd = new SetCommentCmd(addr("0x10022cc"), CommentType.EOL, "my comment"); applyCmd(program, cmd); performAction(clearWithOptionsAction, cb.getProvider(), false); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/progmgr/MultiTabPluginTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/progmgr/MultiTabPluginTest.java index cb054658bd..09c75a9c78 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/progmgr/MultiTabPluginTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/progmgr/MultiTabPluginTest.java @@ -383,8 +383,8 @@ public class MultiTabPluginTest extends AbstractGhidraHeadedIntegrationTest { String newName = "myNewLogin"; renameProgramFile(p, newName); ArrayList changeRecs = new ArrayList<>(); - changeRecs.add( - new DomainObjectChangeRecord(DomainObjectEvent.RENAMED, oldName, p.getName())); + changeRecs + .add(new DomainObjectChangeRecord(DomainObjectEvent.RENAMED, oldName, p.getName())); DomainObjectChangedEvent ev = new DomainObjectChangedEvent(p, changeRecs); runSwing(() -> env.getPlugin(MultiTabPlugin.class).domainObjectChanged(ev)); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/FindAndReplaceCommentScriptTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/FindAndReplaceCommentScriptTest.java index df52281fa7..36f397000b 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/FindAndReplaceCommentScriptTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/script/FindAndReplaceCommentScriptTest.java @@ -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. @@ -37,8 +37,7 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra private static final String FIND_DIALOG_TITLE = "Enter Search String"; private static final String REPLACE_DIALOG_TITLE = "Enter Replace String"; - private static final int[] COMMENT_TYPES = { CodeUnit.EOL_COMMENT, CodeUnit.PRE_COMMENT, - CodeUnit.POST_COMMENT, CodeUnit.PLATE_COMMENT, CodeUnit.REPEATABLE_COMMENT }; + private static final int SCRIPT_TIMEOUT = 100000; private TestEnv env; @@ -65,19 +64,18 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra builder = new ToyProgramBuilder("ReplaceCommentTest", true, this); builder.createMemory(".text", "0x1001000", 0x4000); - builder.createComment("0x01001000", "EOL Comment", CodeUnit.EOL_COMMENT); - builder.createComment("0x01001100", "Pre Comment", CodeUnit.PRE_COMMENT); - builder.createComment("0x01001200", "Post Comment", CodeUnit.POST_COMMENT); - builder.createComment("0x01001300", "Plate Comment", CodeUnit.PLATE_COMMENT); - builder.createComment("0x01001400", "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); - builder.createComment("0x01001500", "EOL Comment Repeated", CodeUnit.EOL_COMMENT); - builder.createComment("0x01001600", "EOL Comment Repeated", CodeUnit.EOL_COMMENT); - builder.createComment("0x01001700", "Generic Comment Repeated", CodeUnit.EOL_COMMENT); - builder.createComment("0x01001800", "Generic Comment Repeated", CodeUnit.PRE_COMMENT); - builder.createComment("0x01001900", "Generic Comment Repeated", CodeUnit.POST_COMMENT); - builder.createComment("0x01002000", "Generic Comment Repeated", CodeUnit.PLATE_COMMENT); - builder.createComment("0x01002100", "Generic Comment Repeated", - CodeUnit.REPEATABLE_COMMENT); + builder.createComment("0x01001000", "EOL Comment", CommentType.EOL); + builder.createComment("0x01001100", "Pre Comment", CommentType.PRE); + builder.createComment("0x01001200", "Post Comment", CommentType.POST); + builder.createComment("0x01001300", "Plate Comment", CommentType.PLATE); + builder.createComment("0x01001400", "Repeatable Comment", CommentType.REPEATABLE); + builder.createComment("0x01001500", "EOL Comment Repeated", CommentType.EOL); + builder.createComment("0x01001600", "EOL Comment Repeated", CommentType.EOL); + builder.createComment("0x01001700", "Generic Comment Repeated", CommentType.EOL); + builder.createComment("0x01001800", "Generic Comment Repeated", CommentType.PRE); + builder.createComment("0x01001900", "Generic Comment Repeated", CommentType.POST); + builder.createComment("0x01002000", "Generic Comment Repeated", CommentType.PLATE); + builder.createComment("0x01002100", "Generic Comment Repeated", CommentType.REPEATABLE); return builder.getProgram(); } @@ -92,13 +90,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001000, "EOL Comment", CodeUnit.EOL_COMMENT); + assertCommentEquals(0x01001000, "EOL Comment", CommentType.EOL); respondToDialog("EOL Comment", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001000, "New Value", CodeUnit.EOL_COMMENT); + assertCommentEquals(0x01001000, "New Value", CommentType.EOL); } @Test @@ -106,13 +104,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001100, "Pre Comment", CodeUnit.PRE_COMMENT); + assertCommentEquals(0x01001100, "Pre Comment", CommentType.PRE); respondToDialog("Pre Comment", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001100, "New Value", CodeUnit.PRE_COMMENT); + assertCommentEquals(0x01001100, "New Value", CommentType.PRE); } @Test @@ -120,13 +118,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001200, "Post Comment", CodeUnit.POST_COMMENT); + assertCommentEquals(0x01001200, "Post Comment", CommentType.POST); respondToDialog("Post Comment", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001200, "New Value", CodeUnit.POST_COMMENT); + assertCommentEquals(0x01001200, "New Value", CommentType.POST); } @Test @@ -134,13 +132,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001300, "Plate Comment", CodeUnit.PLATE_COMMENT); + assertCommentEquals(0x01001300, "Plate Comment", CommentType.PLATE); respondToDialog("Plate Comment", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001300, "New Value", CodeUnit.PLATE_COMMENT); + assertCommentEquals(0x01001300, "New Value", CommentType.PLATE); } @Test @@ -148,13 +146,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001400, "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); + assertCommentEquals(0x01001400, "Repeatable Comment", CommentType.REPEATABLE); respondToDialog("Repeatable Comment", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001400, "New Value", CodeUnit.REPEATABLE_COMMENT); + assertCommentEquals(0x01001400, "New Value", CommentType.REPEATABLE); } @Test @@ -162,15 +160,15 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001500, "EOL Comment Repeated", CodeUnit.EOL_COMMENT); - assertCommentEquals(0x01001600, "EOL Comment Repeated", CodeUnit.EOL_COMMENT); + assertCommentEquals(0x01001500, "EOL Comment Repeated", CommentType.EOL); + assertCommentEquals(0x01001600, "EOL Comment Repeated", CommentType.EOL); respondToDialog("EOL Comment Repeated", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001500, "New Value", CodeUnit.EOL_COMMENT); - assertCommentEquals(0x01001600, "New Value", CodeUnit.EOL_COMMENT); + assertCommentEquals(0x01001500, "New Value", CommentType.EOL); + assertCommentEquals(0x01001600, "New Value", CommentType.EOL); } @Test @@ -178,21 +176,21 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001700, "Generic Comment Repeated", CodeUnit.EOL_COMMENT); - assertCommentEquals(0x01001800, "Generic Comment Repeated", CodeUnit.PRE_COMMENT); - assertCommentEquals(0x01001900, "Generic Comment Repeated", CodeUnit.POST_COMMENT); - assertCommentEquals(0x01002000, "Generic Comment Repeated", CodeUnit.PLATE_COMMENT); - assertCommentEquals(0x01002100, "Generic Comment Repeated", CodeUnit.REPEATABLE_COMMENT); + assertCommentEquals(0x01001700, "Generic Comment Repeated", CommentType.EOL); + assertCommentEquals(0x01001800, "Generic Comment Repeated", CommentType.PRE); + assertCommentEquals(0x01001900, "Generic Comment Repeated", CommentType.POST); + assertCommentEquals(0x01002000, "Generic Comment Repeated", CommentType.PLATE); + assertCommentEquals(0x01002100, "Generic Comment Repeated", CommentType.REPEATABLE); respondToDialog("Generic Comment Repeated", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001700, "New Value", CodeUnit.EOL_COMMENT); - assertCommentEquals(0x01001800, "New Value", CodeUnit.PRE_COMMENT); - assertCommentEquals(0x01001900, "New Value", CodeUnit.POST_COMMENT); - assertCommentEquals(0x01002000, "New Value", CodeUnit.PLATE_COMMENT); - assertCommentEquals(0x01002100, "New Value", CodeUnit.REPEATABLE_COMMENT); + assertCommentEquals(0x01001700, "New Value", CommentType.EOL); + assertCommentEquals(0x01001800, "New Value", CommentType.PRE); + assertCommentEquals(0x01001900, "New Value", CommentType.POST); + assertCommentEquals(0x01002000, "New Value", CommentType.PLATE); + assertCommentEquals(0x01002100, "New Value", CommentType.REPEATABLE); } @Test @@ -203,7 +201,7 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra respondToDialog("This Value Does Not Exist", FIND_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE); - assertCommentDoesNotExists("New Value"); + assertCommentDoesNotExist("New Value"); } @Test @@ -211,21 +209,21 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra ScriptTaskListener scriptID = env.runScript(script); assertNotNull(scriptID); - assertCommentEquals(0x01001000, "EOL Comment", CodeUnit.EOL_COMMENT); - assertCommentEquals(0x01001100, "Pre Comment", CodeUnit.PRE_COMMENT); - assertCommentEquals(0x01001200, "Post Comment", CodeUnit.POST_COMMENT); - assertCommentEquals(0x01001300, "Plate Comment", CodeUnit.PLATE_COMMENT); - assertCommentEquals(0x01001400, "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); + assertCommentEquals(0x01001000, "EOL Comment", CommentType.EOL); + assertCommentEquals(0x01001100, "Pre Comment", CommentType.PRE); + assertCommentEquals(0x01001200, "Post Comment", CommentType.POST); + assertCommentEquals(0x01001300, "Plate Comment", CommentType.PLATE); + assertCommentEquals(0x01001400, "Repeatable Comment", CommentType.REPEATABLE); respondToDialog("Comment", FIND_DIALOG_TITLE); respondToDialog("Test", REPLACE_DIALOG_TITLE); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); - assertCommentEquals(0x01001000, "EOL Test", CodeUnit.EOL_COMMENT); - assertCommentEquals(0x01001100, "Pre Test", CodeUnit.PRE_COMMENT); - assertCommentEquals(0x01001200, "Post Test", CodeUnit.POST_COMMENT); - assertCommentEquals(0x01001300, "Plate Test", CodeUnit.PLATE_COMMENT); - assertCommentEquals(0x01001400, "Repeatable Test", CodeUnit.REPEATABLE_COMMENT); + assertCommentEquals(0x01001000, "EOL Test", CommentType.EOL); + assertCommentEquals(0x01001100, "Pre Test", CommentType.PRE); + assertCommentEquals(0x01001200, "Post Test", CommentType.POST); + assertCommentEquals(0x01001300, "Plate Test", CommentType.PLATE); + assertCommentEquals(0x01001400, "Repeatable Test", CommentType.REPEATABLE); } private void respondToDialog(String response, String titleValue) { @@ -235,21 +233,22 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra pressButtonByText(askStringDialog, "OK"); } - private void assertCommentEquals(int commentAddress, String commentValue, int commentType) { + private void assertCommentEquals(int commentAddress, String commentValue, + CommentType commentType) { Address address = program.getMinAddress().getNewAddress(commentAddress); String existingComment = listing.getComment(commentType, address); assertEquals(commentValue, existingComment); } - private void assertCommentDoesNotExists(String comment) { + private void assertCommentDoesNotExist(String comment) { Memory memory = program.getMemory(); Iterator
addressIterator = listing.getCommentAddressIterator(memory, true); boolean commentExists = false; while (addressIterator.hasNext()) { Address address = addressIterator.next(); - for (int i : COMMENT_TYPES) { - String foundComment = listing.getComment(i, address); + for (CommentType type : CommentType.values()) { + String foundComment = listing.getComment(type, address); if (foundComment != null && foundComment.equals(comment)) { commentExists = true; } diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/ListingDisplaySearcherTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/ListingDisplaySearcherTest.java index a4f14968f4..14804b8c61 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/ListingDisplaySearcherTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/ListingDisplaySearcherTest.java @@ -100,7 +100,7 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT builder.disassemble("0x10029bd", 0xe, true); builder.createLabel("0x01001068", "CreateDCW"); - builder.createComment("0x01001068", "CreateDCW", CodeUnit.EOL_COMMENT); + builder.createComment("0x01001068", "CreateDCW", CommentType.EOL); builder.createLabel("0x010010b4", "CreateFileW"); builder.createLabel("0x010012bc", "CreateWindowExW"); @@ -119,8 +119,8 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT // dt.add(new BooleanDataType(), "likesCheese", null); // dt.add(new PointerDataType(dt), "next", null); - builder.createComment("0x01006642", "EOL comment", CodeUnit.EOL_COMMENT); - builder.createComment("0x01006648", "EOL comment", CodeUnit.EOL_COMMENT); + builder.createComment("0x01006642", "EOL comment", CommentType.EOL); + builder.createComment("0x01006648", "EOL comment", CommentType.EOL); return builder.getProgram(); } @@ -789,7 +789,7 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT } else if (location instanceof EolCommentFieldLocation) { EolCommentFieldLocation eLoc = (EolCommentFieldLocation) location; - assertEquals(CodeUnit.EOL_COMMENT, eLoc.getCommentType()); + assertEquals(CommentType.EOL, eLoc.getCommentType()); String[] comment = eLoc.getComment(); for (String element : comment) { if (element.indexOf(text) >= 0) { @@ -801,7 +801,7 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT } else if (location instanceof AutomaticCommentFieldLocation) { AutomaticCommentFieldLocation eLoc = (AutomaticCommentFieldLocation) location; - assertEquals(CodeUnit.EOL_COMMENT, eLoc.getCommentType()); + assertEquals(CommentType.EOL, eLoc.getCommentType()); String[] comment = eLoc.getComment(); for (String element : comment) { if (element.indexOf(text) >= 0) { diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java index 6379707375..ff8a790c76 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin1Test.java @@ -114,7 +114,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { builder.createMemory(".debug_data", Long.toHexString(0xF0001300), 0x1C); builder.createOverlayMemory("otherOverlay", "OTHER:0", 100); - builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CodeUnit.PRE_COMMENT); + builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CommentType.PRE); //create and disassemble a function builder.setBytes("0x0100415a", "55 8b ec 83 ec 0c 33 c0 c7 45 f8 01 00 00 00 21 45 fc 39 45 08 c7 45 f4 04" + @@ -167,7 +167,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { param, param); builder.createComment("otherOverlay:4", "This is a comment in the other overlay", - CodeUnit.EOL_COMMENT); + CommentType.EOL); return builder.getProgram(); } @@ -403,7 +403,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { ProgramLocation loc = cbPlugin.getCurrentLocation(); assertEquals(getAddr(0x0100416f), loc.getAddress()); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.EOL_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.EOL, ((CommentFieldLocation) loc).getCommentType()); JButton searchButton = (JButton) findButton(dialog.getComponent(), "Next"); pressButton(searchButton); @@ -412,7 +412,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { loc = cbPlugin.getCurrentLocation(); assertEquals(getAddr(0x01004178), loc.getAddress()); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.REPEATABLE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.REPEATABLE, ((CommentFieldLocation) loc).getCommentType()); pressButton(searchButton); waitForSearchTasks(dialog); @@ -422,7 +422,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { assertTrue(loc instanceof CommentFieldLocation); assertEquals("Search result not placed at the matching character position", 15, loc.getCharOffset()); - assertEquals(CodeUnit.PLATE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.PLATE, ((CommentFieldLocation) loc).getCommentType()); pressButton(searchButton); waitForSearchTasks(dialog); @@ -430,7 +430,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { loc = cbPlugin.getCurrentLocation(); assertEquals(getAddr(0x01004192), loc.getAddress()); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.POST_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.POST, ((CommentFieldLocation) loc).getCommentType()); pressButton(searchButton); waitForSearchTasks(dialog); @@ -443,7 +443,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest { loc = cbPlugin.getCurrentLocation(); assertEquals(getAddr(0x0100415a), loc.getAddress()); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.PRE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.PRE, ((CommentFieldLocation) loc).getCommentType()); } private void programLocationChange2(String buttonText) throws Exception { diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin2Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin2Test.java index d3b88ecc7c..ec2c6179d1 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin2Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin2Test.java @@ -83,7 +83,7 @@ public class SearchTextPlugin2Test extends AbstractGhidraHeadedIntegrationTest { builder.createMemory(".rsrc", Long.toHexString(0x100A000), 0x5400); builder.createMemory(".bound_import_table", Long.toHexString(0xF0000248), 0xA8); builder.createMemory(".debug_data", Long.toHexString(0xF0001300), 0x1C); - builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CodeUnit.PRE_COMMENT); + builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CommentType.PRE); //create and disassemble a function builder.setBytes("0x0100415a", diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin3Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin3Test.java index 6ee40156f0..f8d9386db0 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin3Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/SearchTextPlugin3Test.java @@ -92,7 +92,7 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { builder.createMemory(".rsrc", Long.toHexString(0x100A000), 0x5400); builder.createMemory(".bound_import_table", Long.toHexString(0xF0000248), 0xA8); builder.createMemory(".debug_data", Long.toHexString(0xF0001300), 0x1C); - builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CodeUnit.PRE_COMMENT); + builder.createComment("0x100415a", "scanf, fscanf, sscanf ...", CommentType.PRE); //create and disassemble a function builder.setBytes("0x0100415a", "55 8b ec 83 ec 0c 33 c0 c7 45 f8 01 00 00 00 21 45 fc 39 45 08 c7 45 f4 04" + @@ -218,7 +218,7 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { ProgramLocation loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.PLATE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.PLATE, ((CommentFieldLocation) loc).getCommentType()); assertEquals(cu.getMinAddress(), loc.getAddress()); triggerEnter(tf); @@ -226,7 +226,7 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.PRE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.PRE, ((CommentFieldLocation) loc).getCommentType()); triggerEnter(tf); waitForSearchTasks(dialog); @@ -246,14 +246,14 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.EOL_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.EOL, ((CommentFieldLocation) loc).getCommentType()); assertEquals(cu.getMinAddress(), loc.getAddress()); triggerEnter(tf); waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.POST_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.POST, ((CommentFieldLocation) loc).getCommentType()); assertEquals(cu.getMinAddress(), loc.getAddress()); } @@ -287,7 +287,7 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { ProgramLocation loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.PLATE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.PLATE, ((CommentFieldLocation) loc).getCommentType()); triggerEnter(searchButton); @@ -306,7 +306,7 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { waitForSearchTasks(dialog); loc = cbPlugin.getCurrentLocation(); assertTrue(loc instanceof CommentFieldLocation); - assertEquals(CodeUnit.PRE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.PRE, ((CommentFieldLocation) loc).getCommentType()); } @Test @@ -562,13 +562,11 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { assertTrue(loc instanceof FunctionSignatureFieldLocation); String signature = ((FunctionSignatureFieldLocation) loc).getSignature(); - Function function = listing.getFunctionAt(loc.getAddress()); ListingHighlightProvider highlightProvider = cbPlugin.getFormatManager().getFormatHighlightProvider(); FieldPanel fieldPanel = cbPlugin.getFieldPanel(); ListingField field = (ListingField) fieldPanel.getCurrentField(); - FieldFactory factory = field.getFieldFactory(); Highlight[] h = highlightProvider.createHighlights(signature, field, -1); int numberOfHighlights = h.length; @@ -596,7 +594,6 @@ public class SearchTextPlugin3Test extends AbstractGhidraHeadedIntegrationTest { assertTrue(loc instanceof OperandFieldLocation); field = (ListingField) fieldPanel.getCurrentField(); - factory = field.getFieldFactory(); h = highlightProvider.createHighlights(signature, field, -1); assertTrue("Did not update highlights for new search.", (numberOfHighlights != h.length)); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/quicksearch/ProgramDatabaseSearchIteratorTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/quicksearch/ProgramDatabaseSearchIteratorTest.java index 8fe5394672..b89293b52c 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/quicksearch/ProgramDatabaseSearchIteratorTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/plugin/core/searchtext/quicksearch/ProgramDatabaseSearchIteratorTest.java @@ -97,7 +97,7 @@ public class ProgramDatabaseSearchIteratorTest extends AbstractGhidraHeadedInteg p2.setComment("cause a hit! -- imm xxx"); Parameter p3 = new ParameterImpl(null, new DoubleDataType(), program); builder.createEmptyFunction("MyFunc", "0", 26, new WordDataType(), p1, p2, p3); - builder.createComment("0", "Blah Blah Blah -- imm", CodeUnit.PLATE_COMMENT); + builder.createComment("0", "Blah Blah Blah -- imm", CommentType.PLATE); ProgramManager pm = tool.getService(ProgramManager.class); pm.openProgram(program.getDomainFile()); @@ -128,22 +128,22 @@ public class ProgramDatabaseSearchIteratorTest extends AbstractGhidraHeadedInteg Pattern pattern = UserSearchUtils.createSearchPattern("XXZ*", false); ProgramLocation startLocation = new ProgramLocation(program, program.getMinAddress()); - CommentFieldSearcher searcher = new CommentFieldSearcher(program, startLocation, null, true, - pattern, CodeUnit.EOL_COMMENT); + CommentFieldSearcher searcher = + new CommentFieldSearcher(program, startLocation, null, true, pattern, CommentType.EOL); currentAddress = searcher.getNextSignificantAddress(null); assertNull(getNextMatch(searcher)); // add a comment with no match addEolComment(0x1005146L, "Test EOL comments..."); - searcher = new CommentFieldSearcher(program, startLocation, null, true, pattern, - CodeUnit.EOL_COMMENT); + searcher = + new CommentFieldSearcher(program, startLocation, null, true, pattern, CommentType.EOL); currentAddress = searcher.getNextSignificantAddress(null); assertNull(getNextMatch(searcher)); // add a comment that has one match addEolComment(0x1005d4bL, "Test something with eXXZabc"); - searcher = new CommentFieldSearcher(program, startLocation, null, true, pattern, - CodeUnit.EOL_COMMENT); + searcher = + new CommentFieldSearcher(program, startLocation, null, true, pattern, CommentType.EOL); currentAddress = searcher.getNextSignificantAddress(null); ProgramLocation loc = getNextMatch(searcher); assertNotNull(loc); @@ -151,8 +151,8 @@ public class ProgramDatabaseSearchIteratorTest extends AbstractGhidraHeadedInteg // add a comment with two matches for a total of 3 matches addEolComment(0x100595f, "Hit found: eXXZabc followed by XXZabc"); - searcher = new CommentFieldSearcher(program, startLocation, null, true, pattern, - CodeUnit.EOL_COMMENT); + searcher = + new CommentFieldSearcher(program, startLocation, null, true, pattern, CommentType.EOL); currentAddress = searcher.getNextSignificantAddress(null); loc = getNextMatch(searcher); @@ -176,8 +176,8 @@ public class ProgramDatabaseSearchIteratorTest extends AbstractGhidraHeadedInteg Pattern pattern = UserSearchUtils.createSearchPattern("*", false); ProgramLocation startLocation = new ProgramLocation(program, program.getMinAddress()); - CommentFieldSearcher searcher = new CommentFieldSearcher(program, startLocation, null, true, - pattern, CodeUnit.EOL_COMMENT); + CommentFieldSearcher searcher = + new CommentFieldSearcher(program, startLocation, null, true, pattern, CommentType.EOL); currentAddress = searcher.getNextSignificantAddress(null); int count = 0; Address[] addrs = @@ -198,8 +198,8 @@ public class ProgramDatabaseSearchIteratorTest extends AbstractGhidraHeadedInteg Pattern pattern = UserSearchUtils.createSearchPattern("ABC*123", false); ProgramLocation startLocation = new ProgramLocation(program, program.getMinAddress()); - CommentFieldSearcher searcher = new CommentFieldSearcher(program, startLocation, null, true, - pattern, CodeUnit.EOL_COMMENT); + CommentFieldSearcher searcher = + new CommentFieldSearcher(program, startLocation, null, true, pattern, CommentType.EOL); currentAddress = searcher.getNextSignificantAddress(null); ProgramLocation loc = getNextMatch(searcher); @@ -479,7 +479,7 @@ public class ProgramDatabaseSearchIteratorTest extends AbstractGhidraHeadedInteg loc = ts.search().programLocation(); assertTrue("Expected CommentFieldLocation, got " + loc.getClass() + " instead!", (loc instanceof CommentFieldLocation)); - assertEquals(CodeUnit.POST_COMMENT, ((CommentFieldLocation) loc).getCommentType()); + assertEquals(CommentType.POST, ((CommentFieldLocation) loc).getCommentType()); } diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/EolCommentFieldFactoryTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/EolCommentFieldFactoryTest.java index 7fa3798adf..0bd1e37717 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/EolCommentFieldFactoryTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/EolCommentFieldFactoryTest.java @@ -172,10 +172,10 @@ public class EolCommentFieldFactoryTest extends AbstractGhidraHeadedIntegrationT } private void setRepeatableComment(Address a, String comment) { - setComment(a, CodeUnit.REPEATABLE_COMMENT, comment); + setComment(a, CommentType.REPEATABLE, comment); } - private void setComment(Address a, int commentType, String comment) { + private void setComment(Address a, CommentType commentType, String comment) { CodeUnit cu = program.getListing().getCodeUnitAt(a); tx(program, () -> { cu.setComment(commentType, comment); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PlateFieldFactoryTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PlateFieldFactoryTest.java index 334657e03a..69d01f6de5 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PlateFieldFactoryTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PlateFieldFactoryTest.java @@ -96,7 +96,7 @@ public class PlateFieldFactoryTest extends AbstractGhidraHeadedIntegrationTest { builder.createFunction("1001300"); builder.createLabel("1001400", "bob"); - builder.createComment("1001400", "my comment", CodeUnit.PLATE_COMMENT); + builder.createComment("1001400", "my comment", CommentType.PLATE); builder.addBytesReturn("1001500"); builder.disassemble("1001500", 4); @@ -136,8 +136,7 @@ public class PlateFieldFactoryTest extends AbstractGhidraHeadedIntegrationTest { tx(program, () -> { CodeUnit cu = program.getListing().getCodeUnitAt(addr); - cu.setCommentAsArray(CodeUnit.PLATE_COMMENT, - new String[] { "this is", "a plate comment" }); + cu.setCommentAsArray(CommentType.PLATE, new String[] { "this is", "a plate comment" }); // create a reference to addr ReferenceManager rm = program.getReferenceManager(); rm.addMemoryReference(getAddr(0x010023ee), addr, RefType.DATA, SourceType.USER_DEFINED, @@ -172,11 +171,11 @@ public class PlateFieldFactoryTest extends AbstractGhidraHeadedIntegrationTest { tx(program, () -> { CodeUnit cu = program.getListing().getCodeUnitAt(addr); - cu.setCommentAsArray(CodeUnit.PLATE_COMMENT, new String[] { originalText }); + cu.setCommentAsArray(CommentType.PLATE, new String[] { originalText }); // create a reference to addr program.getReferenceManager() - .addMemoryReference(getAddr(0x010023ee), addr, - RefType.DATA, SourceType.USER_DEFINED, 0); + .addMemoryReference(getAddr(0x010023ee), addr, RefType.DATA, + SourceType.USER_DEFINED, 0); }); cb.updateNow(); @@ -437,8 +436,7 @@ public class PlateFieldFactoryTest extends AbstractGhidraHeadedIntegrationTest { CodeUnit cu = program.getListing().getCodeUnitAt(addr); tx(program, () -> { - cu.setComment(CommentType.PLATE, - "this is a comment\ngo to the address 0x010028de"); + cu.setComment(CommentType.PLATE, "this is a comment\ngo to the address 0x010028de"); }); assertTrue(cb.goToField(cu.getMinAddress(), PlateFieldFactory.FIELD_NAME, 2, 23)); click(cb, 2); @@ -459,10 +457,8 @@ public class PlateFieldFactoryTest extends AbstractGhidraHeadedIntegrationTest { CodeUnit cu = program.getListing().getCodeUnitAt(addr); tx(program, () -> { program.getSymbolTable() - .createLabel(addr, testName.getMethodName(), - SourceType.USER_DEFINED); - cu.setComment(CommentType.PLATE, - "this is a comment\ngo to the address 0x010028de"); + .createLabel(addr, testName.getMethodName(), SourceType.USER_DEFINED); + cu.setComment(CommentType.PLATE, "this is a comment\ngo to the address 0x010028de"); }); int nonCommentHeader = precedingBlankLines + 1; // +1 for the '***' line diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PostCommentFieldFactoryTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PostCommentFieldFactoryTest.java index 2ff8bd5581..d0a685590f 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PostCommentFieldFactoryTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/field/PostCommentFieldFactoryTest.java @@ -167,7 +167,6 @@ public class PostCommentFieldFactoryTest extends AbstractGhidraHeadedIntegration builder.createReturnInstruction("100e002"); builder.createEmptyFunction("call_dest_12", "0x100e020", 10, null); - return builder.getProgram(); } @@ -1008,8 +1007,7 @@ public class PostCommentFieldFactoryTest extends AbstractGhidraHeadedIntegration assertTrue(cb.goToField(addr("100d000"), PostCommentFieldFactory.FIELD_NAME, 0, 1)); ListingField tf = cb.getCurrentField(); //old way of overriding (With RefType.UNCONDITIONAL CALL) does not yield a post comment - assertEquals( - "-- CALLOTHER(pcodeop_three) Call Override: call_dest_10 (0100d020)", + assertEquals("-- CALLOTHER(pcodeop_three) Call Override: call_dest_10 (0100d020)", tf.getText()); } diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/listingpanel/ListingPanelTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/listingpanel/ListingPanelTest.java index a80131e957..f5437ae395 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/listingpanel/ListingPanelTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/app/util/viewer/listingpanel/ListingPanelTest.java @@ -247,7 +247,7 @@ public class ListingPanelTest extends AbstractGhidraHeadedIntegrationTest { String comment2 = "I want this sentence to wrap to the next line so that I can test wrapping."; String[] comments = new String[] { comment1, comment2 }; - inst.setCommentAsArray(CodeUnit.EOL_COMMENT, comments); + inst.setCommentAsArray(CommentType.EOL, comments); program.endTransaction(id, true); Options opt = tool.getOptions(GhidraOptions.CATEGORY_BROWSER_FIELDS); opt.setBoolean("EOL Comments Field.Enable Word Wrapping", true); @@ -284,7 +284,7 @@ public class ListingPanelTest extends AbstractGhidraHeadedIntegrationTest { String comment2 = "I want this sentence to wrap to the next line so that I can test wrapping."; String[] comments = new String[] { comment1, comment2 }; - inst.setCommentAsArray(CodeUnit.EOL_COMMENT, comments); + inst.setCommentAsArray(CommentType.EOL, comments); program.endTransaction(id, true); // Options opt = tool.getOptions(GhidraOptions.CATEGORY_BROWSER_FIELDS); // opt.putBoolean("test", "EOL Comments Field.Enable Word Wrapping", true); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/database/code/CodeUnitIteratorTest.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/database/code/CodeUnitIteratorTest.java index c72bbc4eaa..3f94214507 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/database/code/CodeUnitIteratorTest.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/database/code/CodeUnitIteratorTest.java @@ -783,8 +783,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testIteratorForComments() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, - false); + mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i + 10)); @@ -811,10 +810,8 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testIteratorForCommentType() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, - false); - mem.createInitializedBlock("test2", addr(5000), 100, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test2", addr(5000), 100, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i + 10)); @@ -829,8 +826,8 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { } endTransaction(); - CodeUnitIterator iter = ((ProgramDB) program).getCodeManager().getCommentCodeUnitIterator( - CodeUnit.PLATE_COMMENT, mem); + CodeUnitIterator iter = ((ProgramDB) program).getCodeManager() + .getCommentCodeUnitIterator(CommentType.PLATE, mem); int n = 0; Address expectedAddr = null; while (iter.hasNext()) { @@ -851,8 +848,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testIteratorForCommentsBackwards() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, - false); + mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, false); CodeUnit cu = listing.getCodeUnitAt(addr(90)); cu.setComment(CommentType.PLATE, "comment for plate " + addr(90)); @@ -892,8 +888,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetPropertyCodeUnitIterator() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, - false); + mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i + 10)); cu.setProperty("Numbers", i); @@ -915,8 +910,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetPropertyCuIteratorBackwards() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, - false); + mem.createInitializedBlock("test", addr(0), 100, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i)); cu.setProperty("Numbers", i); @@ -937,8 +931,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetPropertCUIteratorSet() throws Exception { startTransaction(); - mem.createInitializedBlock("bk1", addr(0), 200, (byte) 0, TaskMonitor.DUMMY, - false); + mem.createInitializedBlock("bk1", addr(0), 200, (byte) 0, TaskMonitor.DUMMY, false); // addresses 10-19 for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i + 10)); @@ -973,8 +966,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { public void testPropertyCommentIterator() throws Exception { startTransaction(); // mem.createUninitializedBlock("Test", addr(0), 200); - mem.createInitializedBlock("bk1", addr(0), 200, (byte) 0, TaskMonitor.DUMMY, - false); + mem.createInitializedBlock("bk1", addr(0), 200, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i + 10)); cu.setComment(CommentType.EOL, "This is an eol comment " + i); @@ -1196,8 +1188,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetDataBackwards() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 10; i++) { listing.createData(addr(i), DataType.DEFAULT, 1); @@ -1251,8 +1242,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCompositeData() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); Structure struct = new StructureDataType("struct_1", 100); Structure struct2 = new StructureDataType("struct_2", 0); @@ -1306,8 +1296,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCompositeDataStartingAt() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); Structure struct = new StructureDataType("struct_1", 100); Structure struct2 = new StructureDataType("struct_2", 0); @@ -1360,8 +1349,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCompositeDataInSet() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); Structure struct = new StructureDataType("struct_1", 100); Structure struct2 = new StructureDataType("struct_2", 0); @@ -1418,8 +1406,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { public void testGetDefinedDataIterator() throws Exception { startTransaction(); mem.removeBlock(mem.getBlock(addr(1000)), monitor); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 10; i++) { listing.createData(addr(i), new ByteDataType(), 1); @@ -1491,8 +1478,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { public void testGetDefinedDataAtIterator() throws Exception { startTransaction(); mem.removeBlock(mem.getBlock(addr(1000)), monitor); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 10; i++) { listing.createData(addr(i), DataType.DEFAULT, 1); @@ -1553,8 +1539,7 @@ public class CodeUnitIteratorTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetDefinedDataSetIterator() throws Exception { startTransaction(); - mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0), 1000, (byte) 0, TaskMonitor.DUMMY, false); for (int i = 0; i < 10; i++) { listing.createData(addr(i), new ByteDataType(), 0); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff1Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff1Test.java index 370c044add..beee79de7e 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff1Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff1Test.java @@ -179,14 +179,14 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); programBuilder1.setBytes("0x01002b45", "ee"); programBuilder1.setBytes("0x01002b49", "57"); programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); programBuilder2.setBytes("0x01002b45", "8b"); programBuilder2.setBytes("0x01002b49", "ee"); @@ -276,7 +276,7 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); programBuilder1.setBytes("0x01002b45", "ee"); programBuilder1.setBytes("0x01002b49", "57", true); programBuilder1.clearCodeUnits("0x01002cf5", "0x01002d6d", true); @@ -285,7 +285,7 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); programBuilder2.setBytes("0x01002b45", "8b"); programBuilder2.setBytes("0x01002b49", "ee", true); programBuilder2.clearCodeUnits("0x01002239", "0x0100248e", true); @@ -363,12 +363,11 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference1() throws Exception { // 0x1002040: p1 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder1.createComment("0x1002040", "My Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x1002040", "My Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder1.createComment("0x1002040", "My EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder1.createComment("0x1002040", "My Post Comment", CodeUnit.POST_COMMENT); - programBuilder1.createComment("0x1002040", "My Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002040", "My Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x1002040", "My Pre Comment", CommentType.PRE); + programBuilder1.createComment("0x1002040", "My EOL Comment", CommentType.EOL); + programBuilder1.createComment("0x1002040", "My Post Comment", CommentType.POST); + programBuilder1.createComment("0x1002040", "My Repeatable Comment", CommentType.REPEATABLE); checkCommentDifference(0x1002040); } @@ -376,12 +375,12 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference2() throws Exception { // 0x100204c: p2 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder2.createComment("0x100204c", "Other Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100204c", "Other Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x100204c", "Other EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100204c", "Other Post Comment", CodeUnit.POST_COMMENT); + programBuilder2.createComment("0x100204c", "Other Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100204c", "Other Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x100204c", "Other EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x100204c", "Other Post Comment", CommentType.POST); programBuilder2.createComment("0x100204c", "Other Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); checkCommentDifference(0x100204c); } @@ -389,7 +388,7 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference3() throws Exception { // 0x1002304: p1 has EOL comment. - programBuilder1.createComment("0x1002304", "My EOL Comment", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x1002304", "My EOL Comment", CommentType.EOL); checkCommentDifference(0x1002304); } @@ -397,7 +396,7 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference4() throws Exception { // 0x1002306: p1 has pre-comment. - programBuilder1.createComment("0x1002306", "My Pre Comment", CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x1002306", "My Pre Comment", CommentType.PRE); checkCommentDifference(0x1002306); } @@ -405,8 +404,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference5() throws Exception { // 0x100230b: p1 has plate and post comments. - programBuilder1.createComment("0x100230b", "My Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x100230b", "My Post Comment", CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100230b", "My Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x100230b", "My Post Comment", CommentType.POST); checkCommentDifference(0x100230b); } @@ -414,8 +413,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference6() throws Exception { // p2 plate comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100230d", "Other Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100230d", "Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100230d", "Other Plate Comment", CommentType.PLATE); checkCommentDifference(0x100230d); } @@ -423,8 +422,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference7() throws Exception { // p2 pre comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x100230d", "Other Pre Comment", CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x100230d", "Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x100230d", "Other Pre Comment", CommentType.PRE); checkCommentDifference(0x100230d); } @@ -432,8 +431,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference8() throws Exception { // p2 eol comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100230d", "Other EOL Comment", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x100230d", "EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x100230d", "Other EOL Comment", CommentType.EOL); checkCommentDifference(0x100230d); } @@ -441,8 +440,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference9() throws Exception { // p2 post comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Post Comment", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x100230d", "Other Post Comment", CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100230d", "Post Comment", CommentType.POST); + programBuilder2.createComment("0x100230d", "Other Post Comment", CommentType.POST); checkCommentDifference(0x100230d); } @@ -450,10 +449,9 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference10() throws Exception { // p2 repeatable comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x100230d", "Repeatable Comment", CommentType.REPEATABLE); programBuilder2.createComment("0x100230d", "Other Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); checkCommentDifference(0x100230d); } @@ -461,10 +459,9 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference11() throws Exception { // 0x1002336: Different Repeatable comments. - programBuilder1.createComment("0x1002336", "Once upon a time,", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002336", "Once upon a time,", CommentType.REPEATABLE); programBuilder2.createComment("0x1002336", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); checkCommentDifference(0x1002336); } @@ -473,8 +470,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { public void testGetCommentDifference12() throws Exception { // 0x1002346: P1 Repeatable comment contains P2 Repeatable comment. programBuilder1.createComment("0x1002346", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); - programBuilder2.createComment("0x1002346", "This is a sample", CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); + programBuilder2.createComment("0x1002346", "This is a sample", CommentType.REPEATABLE); checkCommentDifference(0x1002346); } @@ -482,9 +479,9 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference13() throws Exception { // 0x1002350: P1 Repeatable comment contained within P2 Repeatable comment. - programBuilder1.createComment("0x1002350", "This is a sample", CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002350", "This is a sample", CommentType.REPEATABLE); programBuilder2.createComment("0x1002350", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); checkCommentDifference(0x1002350); } @@ -492,9 +489,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference14() throws Exception { // 0x100238f: Different EOL comments. - programBuilder1.createComment("0x100238f", "Once upon a time,", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100238f", "This is a sample comment.", - CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x100238f", "Once upon a time,", CommentType.EOL); + programBuilder2.createComment("0x100238f", "This is a sample comment.", CommentType.EOL); checkCommentDifference(0x100238f); } @@ -502,9 +498,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference15() throws Exception { // 0x1002395: Different Pre comments. - programBuilder1.createComment("0x1002395", "Once upon a time,", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x1002395", "This is a sample comment.", - CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x1002395", "Once upon a time,", CommentType.PRE); + programBuilder2.createComment("0x1002395", "This is a sample comment.", CommentType.PRE); checkCommentDifference(0x1002395); } @@ -512,9 +507,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference16() throws Exception { // 0x100239d: Different Plate comments. - programBuilder1.createComment("0x100239d", "Once upon a time,", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100239d", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100239d", "Once upon a time,", CommentType.PLATE); + programBuilder2.createComment("0x100239d", "This is a sample comment.", CommentType.PLATE); checkCommentDifference(0x100239d); } @@ -522,9 +516,8 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference17() throws Exception { // 0x100239d: Different Post comments. - programBuilder1.createComment("0x100239d", "Once upon a time,", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x100239d", "This is a sample comment.", - CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100239d", "Once upon a time,", CommentType.POST); + programBuilder2.createComment("0x100239d", "This is a sample comment.", CommentType.POST); checkCommentDifference(0x100239d); } @@ -532,8 +525,7 @@ public class ProgramDiff1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testGetCommentDifference18() throws Exception { // 0x1002a91: p2 has a plate comment. - programBuilder2.createComment("0x1002a91", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder2.createComment("0x1002a91", "This is a sample comment.", CommentType.PLATE); checkCommentDifference(0x1002a91); } diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff4Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff4Test.java index 0462568bb3..c18d51fc8e 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff4Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramDiff4Test.java @@ -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. @@ -29,7 +29,7 @@ import ghidra.program.database.ProgramBuilder; import ghidra.program.model.address.*; import ghidra.program.model.data.*; import ghidra.program.model.lang.Register; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; import ghidra.program.model.symbol.*; import ghidra.test.ClassicSampleX86ProgramBuilder; @@ -76,6 +76,7 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { programBuilder1 = null; programBuilder2 = null; } + /** * Test that ProgramDiff can determine the blank format line user defined property * differences between Program1 and Program2. @@ -85,10 +86,10 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { // 0x100248c: p2 has format line indicating function exit. // 0x1002428: p1 and p2 both have a format line. programBuilder1.setIntProperty("0x1002428", "Space", 1); - + programBuilder2.setIntProperty("0x100248c", "Space", 1); programBuilder2.setIntProperty("0x1002428", "Space", 1); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x100248c), addr(0x100248e)); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.USER_DEFINED_DIFFS)); @@ -101,11 +102,11 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testCompareDifferentAddressSpaces() throws Exception { - + try { ProgramBuilder programBuilder3 = new ProgramBuilder("program3", ProgramBuilder._8051); Program p3 = programBuilder3.getProgram(); - + programDiff = new ProgramDiff(p1, p3); assertNull(programDiff); } @@ -119,13 +120,13 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testCompareDifferentMemory() throws Exception { - + programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); - + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); - + try { programDiff = new ProgramDiff(p1, p2); assertTrue("Memory in program 1 and program 2 should have been different.", @@ -142,13 +143,13 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testCompareSameAddressSpaces() throws Exception { - + programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); - + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); - + try { programDiff = new ProgramDiff(p1, p2); } @@ -163,7 +164,7 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testCompareSameMemory() throws Exception { - + try { programDiff = new ProgramDiff(p1, p2); assertTrue("Memory in program 1 and program 2 should have been the same.", @@ -176,276 +177,276 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testDataDifference1() throws Exception { - + // 0x01003ac8: same size and named struct with different components. - + Structure struct_a1 = new StructureDataType("struct_a", 0); struct_a1.add(new ByteDataType()); struct_a1.add(new DWordDataType()); programBuilder1.applyDataType("0x01003ac8", struct_a1, 1); - + //=========== - + Structure struct_a2 = new StructureDataType("struct_a", 0); struct_a2.add(new CharDataType()); struct_a2.add(new DWordDataType()); programBuilder2.applyDataType("0x01003ac8", struct_a2, 1); - + verifyDifference(0x01003ac8, 0x01003acc); } @Test public void testDataDifference10() throws Exception { - + // 0x01003b29: different type of pointers. - + programBuilder1.applyDataType("0x01003b29", new PointerDataType(new WordDataType()), 1); - + //=========== - + programBuilder2.applyDataType("0x01003b29", new PointerDataType(new ByteDataType()), 1); - + verifyDifference(0x01003b29, 0x01003b2c); } @Test public void testDataDifference11() throws Exception { - + // 0x01003b31: 5 bytes vs an array of 5 bytes. - + programBuilder1.applyDataType("0x01003b31", new WordDataType(), 1); programBuilder1.applyDataType("0x01003b31", new WordDataType(), 1); programBuilder1.applyDataType("0x01003b31", new WordDataType(), 1); programBuilder1.applyDataType("0x01003b31", new WordDataType(), 1); programBuilder1.applyDataType("0x01003b31", new WordDataType(), 1); - + //=========== - + programBuilder2.applyDataType("0x01003b31", new ArrayDataType(new ByteDataType(), 5, 1), 1); - + verifyDifference(0x01003b31, 0x01003b35); } @Test public void testDataDifference12() throws Exception { - + // 0x01003b3a: p2 has a double. - + //=========== - + programBuilder2.applyDataType("0x1003b3a", new DoubleDataType(), 1); - + verifyDifference(0x01003b3a, 0x01003b41); } @Test public void testDataDifference13() throws Exception { - + // 0x01003b45: p1 and p2 have the same nested structure. - + Structure inner = new StructureDataType("inner", 0); inner.add(new ByteDataType()); inner.add(new PointerDataType(new DWordDataType())); - + Structure outer = new StructureDataType("outer", 0); outer.add(new ByteDataType()); outer.add(inner); - + programBuilder1.applyDataType("0x01003b45", outer, 1); - + //=========== - + programBuilder2.applyDataType("0x01003b45", outer, 1); - + p1 = programBuilder1.getProgram(); p2 = programBuilder2.getProgram(); - + AddressSet as = new AddressSet(); as.addRange(addr(p1, 0x01003ac0), addr(p1, 0x01003bec)); programDiff = new ProgramDiff(p1, p2, as); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.CODE_UNIT_DIFFS)); AddressSet addrSet = new AddressSet(); - + AddressSetView diffAs = programDiff.getDifferences(programDiff.getFilter(), null); assertEquals(addrSet, diffAs); } @Test public void testDataDifference14() throws Exception { - + // 0x01003b5e - 0x01003b62: p1 has instructions and p2 has structure - + programBuilder1.setBytes("0x01003b5e", "75 12 39 75 08", true); - + //=========== - + programBuilder2.setBytes("0x01003b5e", "75 12 39 75 08", false); - + Structure struct_a2 = new StructureDataType("struct_a", 0); struct_a2.add(new CharDataType()); struct_a2.add(new DWordDataType()); programBuilder2.applyDataType("0x01003b5e", struct_a2, 1); - + verifyDifference(0x01003b5e, 0x01003b62); } @Test public void testDataDifference2() throws Exception { - + // 0x01003ad5: same structs except different pointer type component. - + Structure struct_b1 = new StructureDataType("struct_a", 0); struct_b1.add(new ByteDataType()); struct_b1.add(new PointerDataType(new DWordDataType())); programBuilder1.applyDataType("0x01003ad5", struct_b1, 1); - + //=========== - + Structure struct_b2 = new StructureDataType("struct_a", 0); struct_b2.add(new ByteDataType()); struct_b2.add(new PointerDataType(new CharDataType())); programBuilder2.applyDataType("0x01003ad5", struct_b2, 1); - + verifyDifference(0x01003ad5, 0x01003ad9); } @Test public void testDataDifference3() throws Exception { - + // 0x01003ae1: struct vs union - + Structure struct_c1 = new StructureDataType("struct_c", 0); struct_c1.add(new WordDataType()); struct_c1.add(new FloatDataType()); programBuilder1.applyDataType("0x01003ae1", struct_c1, 1); - + //=========== - + Union union_c2 = new UnionDataType("union_c"); union_c2.add(new ByteDataType()); union_c2.add(new PointerDataType(new DWordDataType())); union_c2.add(new DWordDataType()); programBuilder2.applyDataType("0x01003ae1", union_c2, 1); - + verifyDifference(0x01003ae1, 0x01003ae6); } @Test public void testDataDifference4() throws Exception { - + // 0x01003aec & 0x1003aed: same struct positioned 0ne byte address different. Structure struct_a1 = new StructureDataType("struct_a", 0); struct_a1.add(new ByteDataType()); struct_a1.add(new DWordDataType()); - + programBuilder1.applyDataType("0x01003aec", struct_a1, 1); - + //=========== - + programBuilder2.applyDataType("0x1003aed", struct_a1, 1); - + verifyDifference(0x01003aec, 0x01003af1); } @Test public void testDataDifference5() throws Exception { - + // 0x01003af7: same struct with different names. - + Structure struct_a1 = new StructureDataType("struct_a", 0); struct_a1.add(new ByteDataType()); struct_a1.add(new DWordDataType()); - + programBuilder1.applyDataType("0x01003af7", struct_a1, 1); - + //=========== - + Structure struct_altName_a1 = new StructureDataType("my_struct_a", 0); struct_altName_a1.add(new ByteDataType()); struct_altName_a1.add(new DWordDataType()); programBuilder2.applyDataType("0x1003af7", struct_altName_a1, 1); - + verifyDifference(0x01003af7, 0x01003afb); } @Test public void testDataDifference6() throws Exception { - + // 0x01003b02: same struct, different category - + Structure struct_a1 = new StructureDataType("struct_a", 0); struct_a1.add(new ByteDataType()); struct_a1.add(new DWordDataType()); programBuilder1.applyDataType("0x01003b02", struct_a1, 1); - + //=========== - + Structure struct_sub1_a1 = new StructureDataType(new CategoryPath("/sub1"), "struct_a", 0); struct_sub1_a1.add(new ByteDataType()); struct_sub1_a1.add(new DWordDataType()); programBuilder2.applyDataType("0x1003b02", struct_sub1_a1, 1); - + verifyDifference(0x01003b02, 0x01003b06); } @Test public void testDataDifference7() throws Exception { - + // 0x01003b0d: different data type with different size - + programBuilder1.applyDataType("0x01003b0d", new WordDataType(), 1); - + //=========== - + programBuilder2.applyDataType("0x1003b0d", new ByteDataType(), 1); - + verifyDifference(0x01003b0d, 0x01003b0e); } @Test public void testDataDifference8() throws Exception { - + // 0x01003b14: different data type, same size - + programBuilder1.applyDataType("0x01003b14", new CharDataType(), 1); - + //=========== - + programBuilder2.applyDataType("0x1003b14", new ByteDataType(), 1); - + verifyDifference(0x01003b14, 0x01003b14); } @Test public void testDataDifference9() throws Exception { - + // 0x01003b1c: different variable length data types, same size - + programBuilder1.applyDataType("0x01003b1c", new StringDataType(), 1); - + //=========== - + programBuilder2.applyDataType("0x1003b1c", new UnicodeDataType(), 1); - + verifyDifference(0x01003b1c, 0x01003b1d); } @Test public void testExtRefDiff1() throws Exception { // 0x1001028: p2 changed external ref to mem ref on operand 0. - + programBuilder1.applyDataType("0x01001028", new Pointer32DataType(), 1); programBuilder1.createExternalReference("0x01001028", "ADVAPI32.dll", "IsTextUnicode", 0); - + programBuilder2.applyDataType("0x01001028", new Pointer32DataType(), 1); programBuilder2.createMemoryReference("0x01001028", "0x01001000", RefType.INDIRECTION, SourceType.DEFAULT); - + programDiff = new ProgramDiff(p1, p2, new AddressSet(addr(p1, 0x01001000), addr(p1, 0x010017ff))); AddressSet as = new AddressSet(); as.addRange(addr(p1, 0x01001028), addr(p1, 0x0100102b)); - + programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); assertEquals(as, programDiff.getDifferences(programDiff.getFilter(), null)); } @@ -453,19 +454,19 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testExtRefDiff2() throws Exception { // 0x100102c: p1 changed external ref to mem ref on operand 0. - + programBuilder1.applyDataType("0x0100102c", new Pointer32DataType(), 1); programBuilder1.createMemoryReference("0x0100102c", "0x01001000", RefType.INDIRECTION, SourceType.DEFAULT); - + programBuilder2.applyDataType("0x0100102c", new Pointer32DataType(), 1); programBuilder2.createExternalReference("0x0100102c", "ADVAPI32.dll", "IsTextUnicode", 0); - + programDiff = new ProgramDiff(p1, p2, new AddressSet(addr(p1, 0x01001000), addr(p1, 0x010017ff))); AddressSet as = new AddressSet(); as.addRange(addr(p1, 0x0100102c), addr(p1, 0x0100102f)); - + programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); assertEquals(as, programDiff.getDifferences(programDiff.getFilter(), null)); } @@ -478,25 +479,25 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); - + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); - + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); + programDiff = new ProgramDiff(p1, p2); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); AddressSetView diffs; - + // before ignore it should detect diffs. diffs = programDiff.getDifferences(TaskMonitor.DUMMY); assertTrue(diffs.contains(addr(p1, 0x01006420))); assertTrue(diffs.contains(addr(p1, 0x010059a3))); - + // ignore is initially empty. assertEquals(new AddressSet(), programDiff.getIgnoreAddressSet()); - + // ignore returns what has been ignored. programDiff.ignore(new AddressSet(addr(p1, 0x01006420), addr(p1, 0x01006580))); programDiff.ignore(new AddressSet(addr(p1, 0x010059a3), addr(p1, 0x01005c6d))); @@ -504,12 +505,12 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { as.addRange(addr(p1, 0x01006420), addr(p1, 0x01006580)); as.addRange(addr(p1, 0x010059a3), addr(p1, 0x01005c6d)); assertEquals(as, programDiff.getIgnoreAddressSet()); - + // ignore set is used by the Diff. diffs = programDiff.getDifferences(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS), TaskMonitor.DUMMY); assertTrue(!diffs.contains(addr(p1, 0x01006420)) && !diffs.contains(addr(p1, 0x010059a3))); - + // ignore set can be cleared. programDiff.clearIgnoreAddressSet(); assertEquals(new AddressSet(), programDiff.getIgnoreAddressSet()); @@ -523,29 +524,29 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); - + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); - + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); + programDiff = new ProgramDiff(p1, p2); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); AddressSetView diffs; - + // before limiting it should detect diffs. diffs = programDiff.getDifferences(TaskMonitor.DUMMY); assertTrue(diffs.contains(addr(p1, 0x01006420))); assertTrue(diffs.contains(addr(p1, 0x010059a3))); - + // Program Diff only determines differences within the limited set. - programDiff.setLimitedAddressSet( - new AddressSet(addr(p1, 0x01002239), addr(p1, 0x0100248c))); + programDiff + .setLimitedAddressSet(new AddressSet(addr(p1, 0x01002239), addr(p1, 0x0100248c))); AddressSet as = new AddressSet(); as.addRange(addr(p1, 0x01002239), addr(p1, 0x0100248c)); assertEquals(as, programDiff.getLimitedAddressSet()); - + // ignore set is used by the Diff. diffs = programDiff.getDifferences(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS), TaskMonitor.DUMMY); @@ -559,13 +560,13 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testMemRefOpIndexDiff() throws Exception { // 0x1002d0f: p1 and p2 have mem refs on different op indices. - + programBuilder1.createMemoryReference("0x1002d0f", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 0); - + programBuilder2.createMemoryReference("0x1002d0f", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 1); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(); as.addRange(addr(0x1002d0f), addr(0x1002d10)); @@ -581,12 +582,12 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { public void testMemRefP1MnemonicDiff() throws Exception { // 0x1002cfc: p1 has mem ref on mnemonic and p2 doesn't. // 0x1002d03: p2 has mem ref on mnemonic and p1 doesn't. - + programBuilder1.createMemoryReference("0x1002cfc", "0x1006488", RefType.READ, SourceType.USER_DEFINED, -1); programBuilder2.createMemoryReference("0x1002d03", "0x1006488", RefType.READ, SourceType.USER_DEFINED, -1); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x1002cfc), addr(0x1002cfc)); as.add(addr(0x1002d03), addr(0x1002d03)); @@ -601,10 +602,10 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testMemRefP2OpDiff() throws Exception { // 0x1002d25: p2 has operand 1 mem ref and p1 doesn't. - + programBuilder2.createMemoryReference("0x1002d25", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 1); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x1002d25), addr(0x1002d26)); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -619,7 +620,7 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testMemRefPrimaryDiff() throws Exception { // 0x1002cfc: p1 and p2 have mem refs, but different ref is primary. - + programBuilder1.createMemoryReference("0x1002cfc", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 0); programBuilder1.createMemoryReference("0x1002cfc", "0x10064a0", RefType.READ, @@ -628,7 +629,7 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { SourceType.USER_DEFINED, 0); programBuilder2.createMemoryReference("0x1002cfc", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 0); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x1002cfc), addr(0x1002cfc)); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -643,12 +644,12 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testMemRefToAddrDiff() throws Exception { // 0x1002cfc: p1 and p2 have mem refs to different addresses. - + programBuilder1.createMemoryReference("0x1002cfc", "0x10064a0", RefType.READ, SourceType.USER_DEFINED, 0); programBuilder2.createMemoryReference("0x1002cfc", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 0); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x1002cfc), addr(0x1002cfc)); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -658,19 +659,17 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testNoCommentDifference() throws Exception { // 0x1002040: p1 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder1.createComment("0x1002040", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x1002040", "Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder1.createComment("0x1002040", "EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder1.createComment("0x1002040", "Post Comment", CodeUnit.POST_COMMENT); - programBuilder1.createComment("0x1002040", "Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); - programBuilder2.createComment("0x1002040", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x1002040", "Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x1002040", "EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x1002040", "Post Comment", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x1002040", "Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); - + programBuilder1.createComment("0x1002040", "Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x1002040", "Pre Comment", CommentType.PRE); + programBuilder1.createComment("0x1002040", "EOL Comment", CommentType.EOL); + programBuilder1.createComment("0x1002040", "Post Comment", CommentType.POST); + programBuilder1.createComment("0x1002040", "Repeatable Comment", CommentType.REPEATABLE); + programBuilder2.createComment("0x1002040", "Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x1002040", "Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x1002040", "EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x1002040", "Post Comment", CommentType.POST); + programBuilder2.createComment("0x1002040", "Repeatable Comment", CommentType.REPEATABLE); + checkNoCommentDifference(); } @@ -681,12 +680,12 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { @Test public void testOffsetRefDiff() throws Exception { // 0x1002cfc: p1 and p2 have mem refs, but p1 has offset. - + programBuilder1.createOffsetMemReference("0x1002cfc", "0x1006488", 2, RefType.READ, SourceType.USER_DEFINED, 0); programBuilder2.createMemoryReference("0x1002cfc", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 0); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x1002cfc), addr(0x1002cfc)); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -699,13 +698,13 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testOnlyInOne() throws Exception { - + programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); - + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); - + programDiff = new ProgramDiff(p1, p2); AddressSetView as = programDiff.getAddressesOnlyInOne(); AddressSet as1 = new AddressSet(); @@ -719,13 +718,13 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testOnlyInTwo() throws Exception { - + programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); - + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); - + programDiff = new ProgramDiff(p1, p2); AddressSetView as = programDiff.getAddressesOnlyInTwo(); AddressSet as1 = new AddressSet(); @@ -739,24 +738,24 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { */ @Test public void testPrimarySymbolDifferences() throws Exception { - + // 0x1002d1d: p1 has "Foo" & "Bar" symbols. "Foo" is primary. // p2 has "Foo" & "Bar" symbols. "Bar" is primary. - + int transactionID = p1.startTransaction("Test Transaction"); Namespace namespace = p1.getSymbolTable().getNamespace(addr(p1, 0x1002cf5)); String namespaceStr = namespace.getName(); programBuilder1.createLabel("1002d1d", "Foo", namespaceStr); programBuilder1.createLabel("1002d1d", "Bar", namespaceStr); p1.endTransaction(transactionID, true); - + transactionID = p2.startTransaction("Test Transaction"); namespace = p2.getSymbolTable().getNamespace(addr(p2, 0x1002cf5)); namespaceStr = namespace.getName(); programBuilder2.createLabel("1002d1d", "Bar", namespaceStr); programBuilder2.createLabel("1002d1d", "Foo", namespaceStr); p2.endTransaction(transactionID, true); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(addr(0x1002d1d), addr(0x1002d1d)); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.SYMBOL_DIFFS)); @@ -773,38 +772,38 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { // 0x100295a: p2 has reg ref to cx. // 0x1002cf5: p1 has reg ref to edi; p2 has reg ref to eax. // 0x10033f6: p1 & p2 both have reg ref to edi. - + Register esiReg1 = p1.getRegister("ESI"); Register ediReg1 = p1.getRegister("EDI"); - + int transactionID1 = p1.startTransaction("Test Transaction"); ReferenceManager refManager1 = p1.getReferenceManager(); refManager1.addRegisterReference(addr(p1, "0x10018a6"), 0, esiReg1, RefType.DATA, SourceType.USER_DEFINED); - + refManager1.addRegisterReference(addr(p1, "0x1002cf5"), 0, ediReg1, RefType.DATA, SourceType.USER_DEFINED); - + refManager1.addRegisterReference(addr(p1, "0x10033f6"), 0, ediReg1, RefType.DATA, SourceType.USER_DEFINED); p1.endTransaction(transactionID1, true); - + ReferenceManager referenceManager2 = p2.getReferenceManager(); Register cxReg2 = p2.getRegister("CX"); Register ediReg2 = p2.getRegister("EDI"); Register eaxReg2 = p2.getRegister("EAX"); - + int transactionID2 = p2.startTransaction("Test Transaction"); referenceManager2.addRegisterReference(addr(p2, "0x100295a"), 0, cxReg2, RefType.DATA, SourceType.USER_DEFINED); - + referenceManager2.addRegisterReference(addr(p2, "0x1002cf5"), 0, eaxReg2, RefType.DATA, SourceType.USER_DEFINED); - + referenceManager2.addRegisterReference(addr(p2, "0x10033f6"), 0, ediReg2, RefType.DATA, SourceType.USER_DEFINED); p2.endTransaction(transactionID2, true); - + programDiff = new ProgramDiff(p1, p2); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); AddressSet expectedDiffs = new AddressSet(); @@ -822,37 +821,37 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); - + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); + programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); - + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); + programDiff = new ProgramDiff(p1, p2); programDiff.setFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); AddressSetView diffs; - + // before restricting it should detect diffs. diffs = programDiff.getDifferences(TaskMonitor.DUMMY); assertTrue(diffs.contains(addr(p1, 0x01006420))); assertTrue(diffs.contains(addr(p1, 0x010059a3))); - + // restricted set is initially null. assertNull(programDiff.getRestrictedAddressSet()); - + // must be in restricted set to be returned. programDiff.setRestrictedAddressSet( new AddressSet(addr(p1, 0x01002239), addr(p1, 0x0100248c))); AddressSet as = new AddressSet(); as.addRange(addr(p1, 0x01002239), addr(p1, 0x0100248c)); assertEquals(as, programDiff.getRestrictedAddressSet()); - + // ignore set is used by the Diff. diffs = programDiff.getDifferences(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS), TaskMonitor.DUMMY); assertTrue(!diffs.contains(addr(p1, 0x01006420)) && !diffs.contains(addr(p1, 0x010059a3))); - + // restricted set can be cleared. programDiff.removeRestrictedAddressSet(); assertNull(programDiff.getRestrictedAddressSet()); @@ -868,23 +867,23 @@ public class ProgramDiff4Test extends AbstractProgramDiffTest { // 0x1006446: p2 stack ref on op 0. // 0x10064ce: p1 has stack ref on op 0; p2 stack ref on op 1. // 0x1006480: p1 has mem ref on op 0; p2 has stack ref on op 0. - + programBuilder1.createStackReference("0x1006443", RefType.READ, -0x18, SourceType.USER_DEFINED, 0); - + programBuilder2.createStackReference("0x1006446", RefType.READ, -0x4, SourceType.USER_DEFINED, 0); - + programBuilder1.createStackReference("0x10064ce", RefType.READ, -0x6c, SourceType.USER_DEFINED, 0); programBuilder2.createStackReference("0x10064ce", RefType.READ, -0x6c, SourceType.USER_DEFINED, 1); - + programBuilder1.createMemoryReference("0x1006480", "0x1006488", RefType.READ, SourceType.USER_DEFINED, 0); programBuilder2.createStackReference("0x1006480", RefType.READ, -0x6c, SourceType.USER_DEFINED, 0); - + programDiff = new ProgramDiff(p1, p2); AddressSet as = new AddressSet(); as.addRange(addr(0x1006443), addr(0x1006445)); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge1Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge1Test.java index 48b14c5a0a..46620fae87 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge1Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge1Test.java @@ -318,12 +318,12 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); programMerge = new ProgramMergeManager(p1, p2); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); @@ -335,8 +335,8 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { assertTrue(diffs.contains(addr(p1, 0x010059a3))); // Program Diff only determines differences within the limited set. - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01002239), addr(0x0100248c))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01002239), addr(0x0100248c))); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); AddressSet as = new AddressSet(); as.addRange(addr(0x01002239), addr(0x0100248c)); @@ -355,12 +355,12 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); programMerge = new ProgramMergeManager(p1, p2); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); @@ -396,12 +396,12 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); programMerge = new ProgramMergeManager(p1, p2); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.ALL_DIFFS)); @@ -438,85 +438,76 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testReplaceCommentDifferences() throws Exception { // 0x1002040: p1 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder1.createComment("0x1002040", "My Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x1002040", "My Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder1.createComment("0x1002040", "My EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder1.createComment("0x1002040", "My Post Comment", CodeUnit.POST_COMMENT); - programBuilder1.createComment("0x1002040", "My Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002040", "My Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x1002040", "My Pre Comment", CommentType.PRE); + programBuilder1.createComment("0x1002040", "My EOL Comment", CommentType.EOL); + programBuilder1.createComment("0x1002040", "My Post Comment", CommentType.POST); + programBuilder1.createComment("0x1002040", "My Repeatable Comment", CommentType.REPEATABLE); // 0x100204c: p2 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder2.createComment("0x100204c", "Other Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100204c", "Other Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x100204c", "Other EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100204c", "Other Post Comment", CodeUnit.POST_COMMENT); + programBuilder2.createComment("0x100204c", "Other Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100204c", "Other Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x100204c", "Other EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x100204c", "Other Post Comment", CommentType.POST); programBuilder2.createComment("0x100204c", "Other Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x1002304: p1 has EOL comment. - programBuilder1.createComment("0x1002304", "My EOL Comment", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x1002304", "My EOL Comment", CommentType.EOL); // 0x1002306: p1 has pre-comment. - programBuilder1.createComment("0x1002306", "My Pre Comment", CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x1002306", "My Pre Comment", CommentType.PRE); // 0x100230b: p1 has plate and post comments. - programBuilder1.createComment("0x100230b", "My Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x100230b", "My Post Comment", CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100230b", "My Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x100230b", "My Post Comment", CommentType.POST); // 0x100230d: p2 plate comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100230d", "Other Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100230d", "Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100230d", "Other Plate Comment", CommentType.PLATE); // 0x100230d: p2 pre comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x100230d", "Other Pre Comment", CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x100230d", "Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x100230d", "Other Pre Comment", CommentType.PRE); // 0x100230d: p2 eol comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100230d", "Other EOL Comment", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x100230d", "EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x100230d", "Other EOL Comment", CommentType.EOL); // 0x100230d: p2 post comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Post Comment", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x100230d", "Other Post Comment", CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100230d", "Post Comment", CommentType.POST); + programBuilder2.createComment("0x100230d", "Other Post Comment", CommentType.POST); // 0x100230d: p2 repeatable comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x100230d", "Repeatable Comment", CommentType.REPEATABLE); programBuilder2.createComment("0x100230d", "Other Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x1002336: Different Repeatable comments. - programBuilder1.createComment("0x1002336", "Once upon a time,", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002336", "Once upon a time,", CommentType.REPEATABLE); programBuilder2.createComment("0x1002336", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x1002346: P1 Repeatable comment contains P2 Repeatable comment. programBuilder1.createComment("0x1002346", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); - programBuilder2.createComment("0x1002346", "This is a sample", CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); + programBuilder2.createComment("0x1002346", "This is a sample", CommentType.REPEATABLE); // 0x1002350: P1 Repeatable comment contained within P2 Repeatable comment. - programBuilder1.createComment("0x1002350", "This is a sample", CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002350", "This is a sample", CommentType.REPEATABLE); programBuilder2.createComment("0x1002350", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x100238f: Different EOL comments. - programBuilder1.createComment("0x100238f", "Once upon a time,", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100238f", "This is a sample comment.", - CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x100238f", "Once upon a time,", CommentType.EOL); + programBuilder2.createComment("0x100238f", "This is a sample comment.", CommentType.EOL); // 0x1002395: Different Pre comments. - programBuilder1.createComment("0x1002395", "Once upon a time,", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x1002395", "This is a sample comment.", - CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x1002395", "Once upon a time,", CommentType.PRE); + programBuilder2.createComment("0x1002395", "This is a sample comment.", CommentType.PRE); // 0x100239d: Different Plate comments. - programBuilder1.createComment("0x100239d", "Once upon a time,", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100239d", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100239d", "Once upon a time,", CommentType.PLATE); + programBuilder2.createComment("0x100239d", "This is a sample comment.", CommentType.PLATE); // 0x100239d: Different Post comments. - programBuilder1.createComment("0x100239d", "Once upon a time,", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x100239d", "This is a sample comment.", - CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100239d", "Once upon a time,", CommentType.POST); + programBuilder2.createComment("0x100239d", "This is a sample comment.", CommentType.POST); // 0x1002a91: p2 has a plate comment. - programBuilder2.createComment("0x1002a91", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder2.createComment("0x1002a91", "This is a sample comment.", CommentType.PLATE); // 0x10030d2: p1 has plate comment. - programBuilder1.createComment("0x10030d2", "Once upon a time,", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x10030d2", "Once upon a time,", CommentType.PLATE); // 0x10030d8: p2 has plate comment. - programBuilder2.createComment("0x10030d8", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder2.createComment("0x10030d8", "This is a sample comment.", CommentType.PLATE); // 0x100355f: p1 has plate comment. - programBuilder1.createComment("0x100355f", "Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100355f", "Plate Comment", CommentType.PLATE); // 0x100415a: p1 and p2 have same plate comments. - programBuilder1.createComment("0x100415a", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100415a", "Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100415a", "Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100415a", "Plate Comment", CommentType.PLATE); programMerge = new ProgramMergeManager(p1, p2); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.COMMENT_DIFFS)); @@ -633,85 +624,76 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { @Test public void testMergeCommentDifferences() throws Exception { // 0x1002040: p1 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder1.createComment("0x1002040", "My Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x1002040", "My Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder1.createComment("0x1002040", "My EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder1.createComment("0x1002040", "My Post Comment", CodeUnit.POST_COMMENT); - programBuilder1.createComment("0x1002040", "My Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002040", "My Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x1002040", "My Pre Comment", CommentType.PRE); + programBuilder1.createComment("0x1002040", "My EOL Comment", CommentType.EOL); + programBuilder1.createComment("0x1002040", "My Post Comment", CommentType.POST); + programBuilder1.createComment("0x1002040", "My Repeatable Comment", CommentType.REPEATABLE); // 0x100204c: p2 has Plate, Pre, EOL, Post, & Repeatable comment. - programBuilder2.createComment("0x100204c", "Other Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100204c", "Other Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x100204c", "Other EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100204c", "Other Post Comment", CodeUnit.POST_COMMENT); + programBuilder2.createComment("0x100204c", "Other Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100204c", "Other Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x100204c", "Other EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x100204c", "Other Post Comment", CommentType.POST); programBuilder2.createComment("0x100204c", "Other Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x1002304: p1 has EOL comment. - programBuilder1.createComment("0x1002304", "My EOL Comment", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x1002304", "My EOL Comment", CommentType.EOL); // 0x1002306: p1 has pre-comment. - programBuilder1.createComment("0x1002306", "My Pre Comment", CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x1002306", "My Pre Comment", CommentType.PRE); // 0x100230b: p1 has plate and post comments. - programBuilder1.createComment("0x100230b", "My Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder1.createComment("0x100230b", "My Post Comment", CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100230b", "My Plate Comment", CommentType.PLATE); + programBuilder1.createComment("0x100230b", "My Post Comment", CommentType.POST); // 0x100230d: p2 plate comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100230d", "Other Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100230d", "Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100230d", "Other Plate Comment", CommentType.PLATE); // 0x100230d: p2 pre comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Pre Comment", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x100230d", "Other Pre Comment", CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x100230d", "Pre Comment", CommentType.PRE); + programBuilder2.createComment("0x100230d", "Other Pre Comment", CommentType.PRE); // 0x100230d: p2 eol comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "EOL Comment", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100230d", "Other EOL Comment", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x100230d", "EOL Comment", CommentType.EOL); + programBuilder2.createComment("0x100230d", "Other EOL Comment", CommentType.EOL); // 0x100230d: p2 post comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Post Comment", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x100230d", "Other Post Comment", CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100230d", "Post Comment", CommentType.POST); + programBuilder2.createComment("0x100230d", "Other Post Comment", CommentType.POST); // 0x100230d: p2 repeatable comments contain the p1 comment string. - programBuilder1.createComment("0x100230d", "Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x100230d", "Repeatable Comment", CommentType.REPEATABLE); programBuilder2.createComment("0x100230d", "Other Repeatable Comment", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x1002336: Different Repeatable comments. - programBuilder1.createComment("0x1002336", "Once upon a time,", - CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002336", "Once upon a time,", CommentType.REPEATABLE); programBuilder2.createComment("0x1002336", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x1002346: P1 Repeatable comment contains P2 Repeatable comment. programBuilder1.createComment("0x1002346", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); - programBuilder2.createComment("0x1002346", "This is a sample", CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); + programBuilder2.createComment("0x1002346", "This is a sample", CommentType.REPEATABLE); // 0x1002350: P1 Repeatable comment contained within P2 Repeatable comment. - programBuilder1.createComment("0x1002350", "This is a sample", CodeUnit.REPEATABLE_COMMENT); + programBuilder1.createComment("0x1002350", "This is a sample", CommentType.REPEATABLE); programBuilder2.createComment("0x1002350", "This is a sample comment.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); // 0x100238f: Different EOL comments. - programBuilder1.createComment("0x100238f", "Once upon a time,", CodeUnit.EOL_COMMENT); - programBuilder2.createComment("0x100238f", "This is a sample comment.", - CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x100238f", "Once upon a time,", CommentType.EOL); + programBuilder2.createComment("0x100238f", "This is a sample comment.", CommentType.EOL); // 0x1002395: Different Pre comments. - programBuilder1.createComment("0x1002395", "Once upon a time,", CodeUnit.PRE_COMMENT); - programBuilder2.createComment("0x1002395", "This is a sample comment.", - CodeUnit.PRE_COMMENT); + programBuilder1.createComment("0x1002395", "Once upon a time,", CommentType.PRE); + programBuilder2.createComment("0x1002395", "This is a sample comment.", CommentType.PRE); // 0x100239d: Different Plate comments. - programBuilder1.createComment("0x100239d", "Once upon a time,", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100239d", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100239d", "Once upon a time,", CommentType.PLATE); + programBuilder2.createComment("0x100239d", "This is a sample comment.", CommentType.PLATE); // 0x100239d: Different Post comments. - programBuilder1.createComment("0x100239d", "Once upon a time,", CodeUnit.POST_COMMENT); - programBuilder2.createComment("0x100239d", "This is a sample comment.", - CodeUnit.POST_COMMENT); + programBuilder1.createComment("0x100239d", "Once upon a time,", CommentType.POST); + programBuilder2.createComment("0x100239d", "This is a sample comment.", CommentType.POST); // 0x1002a91: p2 has a plate comment. - programBuilder2.createComment("0x1002a91", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder2.createComment("0x1002a91", "This is a sample comment.", CommentType.PLATE); // 0x10030d2: p1 has plate comment. - programBuilder1.createComment("0x10030d2", "Once upon a time,", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x10030d2", "Once upon a time,", CommentType.PLATE); // 0x10030d8: p2 has plate comment. - programBuilder2.createComment("0x10030d8", "This is a sample comment.", - CodeUnit.PLATE_COMMENT); + programBuilder2.createComment("0x10030d8", "This is a sample comment.", CommentType.PLATE); // 0x100355f: p1 has plate comment. - programBuilder1.createComment("0x100355f", "Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100355f", "Plate Comment", CommentType.PLATE); // 0x100415a: p1 and p2 have same plate comments. - programBuilder1.createComment("0x100415a", "Plate Comment", CodeUnit.PLATE_COMMENT); - programBuilder2.createComment("0x100415a", "Plate Comment", CodeUnit.PLATE_COMMENT); + programBuilder1.createComment("0x100415a", "Plate Comment", CommentType.PLATE); + programBuilder2.createComment("0x100415a", "Plate Comment", CommentType.PLATE); programMerge = new ProgramMergeManager(p1, p2); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.COMMENT_DIFFS)); @@ -842,8 +824,8 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.applyDataType("0x0100102c", new Pointer32DataType(), 1); programBuilder2.createExternalReference("0x0100102c", "ADVAPI32.dll", "IsTextUnicode", 0); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01001000), addr(0x010017ff))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01001000), addr(0x010017ff))); AddressSet as = new AddressSet(addr(0x0100102c), addr(0x0100102f)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -864,8 +846,8 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.applyDataType("0x01001034", new Pointer32DataType(), 1); programBuilder2.createExternalReference("0x01001034", "myGDI32.dll", "SomePlace", 0); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01001000), addr(0x010017ff))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01001000), addr(0x010017ff))); AddressSet as = new AddressSet(addr(0x01001034), addr(0x01001037)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -886,8 +868,8 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.applyDataType("0x01001038", new Pointer32DataType(), 1); programBuilder2.createExternalReference("0x01001038", "GDI32.dll", "ABC12345", 0); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01001000), addr(0x010017ff))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01001000), addr(0x010017ff))); AddressSet as = new AddressSet(addr(0x01001038), addr(0x0100103b)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -908,8 +890,8 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.applyDataType("0x0100103c", new Pointer32DataType(), 1); programBuilder2.createExternalReference("0x0100103c", "GDI32.dll", "XYZ", "0x77f4abcd", 0); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01001000), addr(0x010017ff))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01001000), addr(0x010017ff))); AddressSet as = new AddressSet(addr(0x0100103c), addr(0x0100103f)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -929,8 +911,8 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.applyDataType("0x01001044", new Pointer32DataType(), 1); programBuilder2.createExternalReference("0x01001044", "GDI32.dll", "MNM", 0); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01001000), addr(0x010017ff))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01001000), addr(0x010017ff))); AddressSet as = new AddressSet(addr(0x01001044), addr(0x01001047)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -1699,8 +1681,7 @@ public class ProgramMerge1Test extends AbstractGhidraHeadedIntegrationTest { SymbolTable symtab2 = p2.getSymbolTable(); symtab2.createLabel(addr(0x1002969), "ONE", SourceType.USER_DEFINED); AddressSet limitedAddrSet = new AddressSet(addr(0x1002950), addr(0x100299b)); - programMerge = - new ProgramMergeManager(p1, p2, limitedAddrSet); + programMerge = new ProgramMergeManager(p1, p2, limitedAddrSet); AddressSet as = new AddressSet(addr(0x100295d)); AddressSet as2 = new AddressSet(addr(0x1002969)); diff --git a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge3Test.java b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge3Test.java index 6e3c239311..0a5148df1c 100644 --- a/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge3Test.java +++ b/Ghidra/Features/Base/src/test.slow/java/ghidra/program/util/ProgramMerge3Test.java @@ -148,8 +148,8 @@ public class ProgramMerge3Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createBookmark("0x1002323", BookmarkType.INFO, "stuff", "My bookmark"); programBuilder2.createBookmark("0x1002323", BookmarkType.INFO, "stuff", "My bookmark"); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x1002306), addr(0x100232f))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x1002306), addr(0x100232f))); AddressSet as = new AddressSet(addr(0x100230b), addr(0x100231c)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.BOOKMARK_DIFFS)); programMerge.setMergeFilter( @@ -245,7 +245,7 @@ public class ProgramMerge3Test extends AbstractGhidraHeadedIntegrationTest { programBuilder1.createMemory("d1", "0x100", 0x100, null, (byte) 0xAC); programBuilder1.createMemory("d2", "0x200", 0x100); programBuilder1.createLabel("0x01006420", "Function1"); - programBuilder1.createComment("0x010059a3", "Here we are.", CodeUnit.EOL_COMMENT); + programBuilder1.createComment("0x010059a3", "Here we are.", CommentType.EOL); programBuilder1.setBytes("0x01002b45", "ee"); programBuilder1.setBytes("0x01002b49", "57", true); programBuilder1.clearCodeUnits("0x01002cf5", "0x01002d6d", true); @@ -254,7 +254,7 @@ public class ProgramMerge3Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.createMemory("d1", "0x100", 0x100, null, (byte) 0xAF); programBuilder2.createMemory("d4", "0x400", 0x100); programBuilder2.createLabel("0x01006420", "Function2"); - programBuilder2.createComment("0x010059a3", "There you have it.", CodeUnit.EOL_COMMENT); + programBuilder2.createComment("0x010059a3", "There you have it.", CommentType.EOL); programBuilder2.setBytes("0x01002b45", "8b"); programBuilder2.setBytes("0x01002b49", "ee", true); programBuilder2.clearCodeUnits("0x01002239", "0x0100248e", true); @@ -747,8 +747,8 @@ public class ProgramMerge3Test extends AbstractGhidraHeadedIntegrationTest { programBuilder2.createMemoryReference("0x01001028", "0x01001000", RefType.INDIRECTION, SourceType.DEFAULT); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x01001000), addr(0x010017ff))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x01001000), addr(0x010017ff))); AddressSet as = new AddressSet(addr(0x01001028), addr(0x0100102b)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.REFERENCE_DIFFS)); @@ -769,8 +769,8 @@ public class ProgramMerge3Test extends AbstractGhidraHeadedIntegrationTest { function2.setBody(new AddressSet(addr(0x100299e), addr(0x1002a89))); p2.endTransaction(transactionID, true); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x0100299e), addr(0x01002a90))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x0100299e), addr(0x01002a90))); AddressSet as = new AddressSet(addr(0x0100299e), addr(0x0100299e)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.FUNCTION_DIFFS)); programMerge.setMergeFilter( @@ -971,8 +971,8 @@ public class ProgramMerge3Test extends AbstractGhidraHeadedIntegrationTest { p2.getFunctionManager().removeFunction(addr(0x10030d2)); p2.endTransaction(transactionID, true); - programMerge = new ProgramMergeManager(p1, p2, - new AddressSet(addr(0x10030d2), addr(0x10030d7))); + programMerge = + new ProgramMergeManager(p1, p2, new AddressSet(addr(0x10030d2), addr(0x10030d7))); AddressSet as = new AddressSet(addr(0x10030d2), addr(0x10030d2)); programMerge.setDiffFilter(new ProgramDiffFilter(ProgramDiffFilter.FUNCTION_DIFFS)); programMerge.setMergeFilter( diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/SampleLocationGenerator.java b/Ghidra/Features/Base/src/test/java/ghidra/app/SampleLocationGenerator.java index 92ecfc900e..3f857e645a 100644 --- a/Ghidra/Features/Base/src/test/java/ghidra/app/SampleLocationGenerator.java +++ b/Ghidra/Features/Base/src/test/java/ghidra/app/SampleLocationGenerator.java @@ -120,22 +120,22 @@ public class SampleLocationGenerator implements GhidraLocationGenerator { Address a = addr(0x100101c); CodeUnit cu = program.getListing().getCodeUnitAt(a); String[] comment = cu.getCommentAsArray(CommentType.PRE); - locs[0] = new CommentFieldLocation(program, a, null, comment, CodeUnit.PRE_COMMENT, 0, 5); + locs[0] = new CommentFieldLocation(program, a, null, comment, CommentType.PRE, 0, 5); a = addr(0x10030e4); cu = program.getListing().getCodeUnitAt(a); comment = cu.getCommentAsArray(CommentType.PRE); - locs[1] = new CommentFieldLocation(program, a, null, comment, CodeUnit.PRE_COMMENT, 0, 5); + locs[1] = new CommentFieldLocation(program, a, null, comment, CommentType.PRE, 0, 5); a = addr(0x100352f); cu = program.getListing().getCodeUnitAt(a); comment = cu.getCommentAsArray(CommentType.EOL); - locs[2] = new CommentFieldLocation(program, a, null, comment, CodeUnit.EOL_COMMENT, 0, 5); + locs[2] = new CommentFieldLocation(program, a, null, comment, CommentType.EOL, 0, 5); a = addr(0x10030e4); cu = program.getListing().getCodeUnitAt(a); comment = cu.getCommentAsArray(CommentType.EOL); - locs[3] = new CommentFieldLocation(program, a, null, comment, CodeUnit.EOL_COMMENT, 1, 5); + locs[3] = new CommentFieldLocation(program, a, null, comment, CommentType.EOL, 1, 5); a = addr(0x10075ff); cu = program.getListing().getCodeUnitAt(a); @@ -169,12 +169,12 @@ public class SampleLocationGenerator implements GhidraLocationGenerator { Address a = addr(0x100101c); CodeUnit cu = program.getListing().getCodeUnitAt(a); String[] comment = cu.getCommentAsArray(CommentType.PRE); - locs[0] = new CommentFieldLocation(program, a, null, comment, CodeUnit.PRE_COMMENT, 0, 5); + locs[0] = new CommentFieldLocation(program, a, null, comment, CommentType.PRE, 0, 5); a = addr(0x10030e4); cu = program.getListing().getCodeUnitAt(a); comment = cu.getCommentAsArray(CommentType.PRE); - locs[1] = new CommentFieldLocation(program, a, null, comment, CodeUnit.PRE_COMMENT, 0, 5); + locs[1] = new CommentFieldLocation(program, a, null, comment, CommentType.PRE, 0, 5); return locs; } @@ -185,12 +185,12 @@ public class SampleLocationGenerator implements GhidraLocationGenerator { Address a = addr(0x100352f); CodeUnit cu = program.getListing().getCodeUnitAt(a); String[] comment = cu.getCommentAsArray(CommentType.EOL); - locs[0] = new CommentFieldLocation(program, a, null, comment, CodeUnit.EOL_COMMENT, 0, 5); + locs[0] = new CommentFieldLocation(program, a, null, comment, CommentType.EOL, 0, 5); a = addr(0x10030e4); cu = program.getListing().getCodeUnitAt(a); comment = cu.getCommentAsArray(CommentType.EOL); - locs[1] = new CommentFieldLocation(program, a, null, comment, CodeUnit.EOL_COMMENT, 1, 5); + locs[1] = new CommentFieldLocation(program, a, null, comment, CommentType.EOL, 1, 5); return locs; } @@ -535,8 +535,7 @@ public class SampleLocationGenerator implements GhidraLocationGenerator { @Override public ProgramLocation[] getLocationsWithLocalLabels() { ProgramLocation[] locs = new ProgramLocation[2]; - locs[0] = - new LabelFieldLocation(program, addr(0x1002d1f), "MyLocal"); + locs[0] = new LabelFieldLocation(program, addr(0x1002d1f), "MyLocal"); locs[1] = new LabelFieldLocation(program, addr(0x1002d2b), "AnotherLocal"); return locs; } diff --git a/Ghidra/Features/Base/src/test/java/ghidra/features/base/replace/ListingCommentsSearchAndReplaceTest.java b/Ghidra/Features/Base/src/test/java/ghidra/features/base/replace/ListingCommentsSearchAndReplaceTest.java index 14cd4a6082..150afbeb7f 100644 --- a/Ghidra/Features/Base/src/test/java/ghidra/features/base/replace/ListingCommentsSearchAndReplaceTest.java +++ b/Ghidra/Features/Base/src/test/java/ghidra/features/base/replace/ListingCommentsSearchAndReplaceTest.java @@ -158,7 +158,7 @@ public class ListingCommentsSearchAndReplaceTest extends AbstractSearchAndReplac assertEquals("Not Applied", item.getStatusMessage()); assertEquals("Update", item.getActionName()); assertEquals("Code Comment", item.getItemType()); - assertEquals(new CommentFieldLocation(program, addr(10), null, null, PRE.ordinal(), 0, 0), + assertEquals(new CommentFieldLocation(program, addr(10), null, null, PRE, 0, 0), item.getProgramLocation()); assertEquals("PRE xxx abcxxxdef", item.getCurrent()); diff --git a/Ghidra/Features/Base/src/test/java/ghidra/program/database/MergeProgramGenerator_DiffTestPrograms.java b/Ghidra/Features/Base/src/test/java/ghidra/program/database/MergeProgramGenerator_DiffTestPrograms.java index a41b6f5d91..dd7ffedf18 100644 --- a/Ghidra/Features/Base/src/test/java/ghidra/program/database/MergeProgramGenerator_DiffTestPrograms.java +++ b/Ghidra/Features/Base/src/test/java/ghidra/program/database/MergeProgramGenerator_DiffTestPrograms.java @@ -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. @@ -91,27 +91,27 @@ class MergeProgramGenerator_DiffTestPrograms implements MergeProgramGenerator { //@formatter:on // comments - builder.createComment("1002304", "EOL comment", CodeUnit.EOL_COMMENT); - builder.createComment("1002306", "\"Pre Comment\"", CodeUnit.PRE_COMMENT); - builder.createComment("100230c", "Post comment", CodeUnit.POST_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.PRE_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.EOL_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.POST_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.REPEATABLE_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.PLATE_COMMENT); + builder.createComment("1002304", "EOL comment", CommentType.EOL); + builder.createComment("1002306", "\"Pre Comment\"", CommentType.PRE); + builder.createComment("100230c", "Post comment", CommentType.POST); + builder.createComment("100230d", "simple comment", CommentType.PRE); + builder.createComment("100230d", "simple comment", CommentType.EOL); + builder.createComment("100230d", "simple comment", CommentType.POST); + builder.createComment("100230d", "simple comment", CommentType.REPEATABLE); + builder.createComment("100230d", "simple comment", CommentType.PLATE); builder.createComment("1002312", "\"My comment that the other comment is in.\"", - CodeUnit.PRE_COMMENT); + CommentType.PRE); builder.createComment("1002312", "My comment that the other comment is in.", - CodeUnit.EOL_COMMENT); + CommentType.EOL); builder.createComment("1002312", "My comment that the other comment is in.", - CodeUnit.POST_COMMENT); + CommentType.POST); - builder.createComment("1002040", "Pre in P1.", CodeUnit.PRE_COMMENT); - builder.createComment("1002040", "EOL in P1.", CodeUnit.EOL_COMMENT); - builder.createComment("1002040", "Post in P1.", CodeUnit.POST_COMMENT); - builder.createComment("1002040", "Plate in P1.", CodeUnit.PLATE_COMMENT); - builder.createComment("1002040", "Repeatable in P1.", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002040", "Pre in P1.", CommentType.PRE); + builder.createComment("1002040", "EOL in P1.", CommentType.EOL); + builder.createComment("1002040", "Post in P1.", CommentType.POST); + builder.createComment("1002040", "Plate in P1.", CommentType.PLATE); + builder.createComment("1002040", "Repeatable in P1.", CommentType.REPEATABLE); // data types builder.addCategory(new CategoryPath("/cat1")); diff --git a/Ghidra/Features/Base/src/test/java/ghidra/program/database/code/CodeManagerTest.java b/Ghidra/Features/Base/src/test/java/ghidra/program/database/code/CodeManagerTest.java index 66d27f443a..df3ae3db89 100644 --- a/Ghidra/Features/Base/src/test/java/ghidra/program/database/code/CodeManagerTest.java +++ b/Ghidra/Features/Base/src/test/java/ghidra/program/database/code/CodeManagerTest.java @@ -673,8 +673,7 @@ public class CodeManagerTest extends AbstractGenericTest { @Test public void testGetDataContaining() throws Exception { - mem.createInitializedBlock("test", addr(0x0), 100, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0x0), 100, (byte) 0, TaskMonitor.DUMMY, false); StringDataType s = new StringDataType(); listing.createData(addr(0x0), s, 10); @@ -716,8 +715,7 @@ public class CodeManagerTest extends AbstractGenericTest { @Test public void testGetDataBefore() throws Exception { - mem.createInitializedBlock("test", addr(0x0), 200, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0x0), 200, (byte) 0, TaskMonitor.DUMMY, false); StringDataType s = new StringDataType(); listing.createData(addr(0x0), s, 10); @@ -738,8 +736,7 @@ public class CodeManagerTest extends AbstractGenericTest { @Test public void testGetDataBefore2() throws Exception { - mem.createInitializedBlock("test", addr(0x0), 200, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("test", addr(0x0), 200, (byte) 0, TaskMonitor.DUMMY, false); StringDataType s = new StringDataType(); listing.createData(addr(0x0), s, 0x10); @@ -825,8 +822,7 @@ public class CodeManagerTest extends AbstractGenericTest { @Test public void testGetUndefinedDataAfter() throws Exception { - mem.createInitializedBlock("bk1", addr(0x0), 0x200, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("bk1", addr(0x0), 0x200, (byte) 0, TaskMonitor.DUMMY, false); parseStatic(addr(0x1100), addr(0x1500)); Instruction inst = listing.getInstructionContaining(addr(0x1500)); @@ -857,8 +853,7 @@ public class CodeManagerTest extends AbstractGenericTest { @Test public void testGetFirstUndefinedData() throws Exception { - mem.createInitializedBlock("bk1", addr(0x0), 0x200, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("bk1", addr(0x0), 0x200, (byte) 0, TaskMonitor.DUMMY, false); parseStatic(addr(0x1100), addr(0x1500)); Instruction inst = listing.getInstructionContaining(addr(0x1500)); @@ -874,8 +869,7 @@ public class CodeManagerTest extends AbstractGenericTest { assertEquals(expectedAddr, data.getMinAddress()); data = listing.getFirstUndefinedData( - new AddressSet(expectedAddr.add(1), expectedAddr.add(500)), - TaskMonitor.DUMMY); + new AddressSet(expectedAddr.add(1), expectedAddr.add(500)), TaskMonitor.DUMMY); assertNotNull(data); assertEquals(expectedAddr.addNoWrap(1), data.getMinAddress()); @@ -909,8 +903,7 @@ public class CodeManagerTest extends AbstractGenericTest { @Test public void testClearProperties() throws Exception { - mem.createInitializedBlock("bk1", addr(0x0), 0x200, (byte) 0, - TaskMonitor.DUMMY, false); + mem.createInitializedBlock("bk1", addr(0x0), 0x200, (byte) 0, TaskMonitor.DUMMY, false); // addresses 10-19 for (int i = 0; i < 20; i++) { CodeUnit cu = listing.getCodeUnitAt(addr(i + 10)); @@ -983,7 +976,7 @@ public class CodeManagerTest extends AbstractGenericTest { cu.setComment(CommentType.EOL, "This is a changed comment 3"); CodeManager cm = ((ProgramDB) program).getCodeManager(); - CommentHistory[] history = cm.getCommentHistory(addr(0x1000), CodeUnit.EOL_COMMENT); + CommentHistory[] history = cm.getCommentHistory(addr(0x1000), CommentType.EOL); assertEquals(3, history.length); assertEquals("This is a changed comment 3", history[0].getComments()); assertEquals("This is a changed comment 2", history[1].getComments()); diff --git a/Ghidra/Features/CodeCompare/src/main/java/ghidra/features/codecompare/correlator/DebugUtils.java b/Ghidra/Features/CodeCompare/src/main/java/ghidra/features/codecompare/correlator/DebugUtils.java index 7e6c667a59..b2091f1d5a 100755 --- a/Ghidra/Features/CodeCompare/src/main/java/ghidra/features/codecompare/correlator/DebugUtils.java +++ b/Ghidra/Features/CodeCompare/src/main/java/ghidra/features/codecompare/correlator/DebugUtils.java @@ -153,8 +153,8 @@ class DebugUtils { program.getIntRangeMap(PropertyBasedBackgroundColorModel.COLOR_PROPERTY_NAME); if (map == null && create) { try { - map = program.createIntRangeMap( - PropertyBasedBackgroundColorModel.COLOR_PROPERTY_NAME); + map = program + .createIntRangeMap(PropertyBasedBackgroundColorModel.COLOR_PROPERTY_NAME); } catch (DuplicateNameException e) { // can't happen since we just checked for it! diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java index 788af46ce9..d43fa7e46e 100644 --- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java +++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java @@ -574,19 +574,19 @@ public class DecompileCallback { * @throws IOException for errors in the underlying stream */ private void encodeCommentsType(Encoder encoder, AddressSetView addrset, Address addr, - int commenttype) throws IOException { + CommentType commenttype) throws IOException { String typename; switch (commenttype) { - case CodeUnit.EOL_COMMENT: + case EOL: typename = "user1"; break; - case CodeUnit.PRE_COMMENT: + case PRE: typename = "user2"; break; - case CodeUnit.POST_COMMENT: + case POST: typename = "user3"; break; - case CodeUnit.PLATE_COMMENT: + case PLATE: typename = "header"; break; default: @@ -598,7 +598,7 @@ public class DecompileCallback { Address commaddr = iter.next(); String text = listing.getComment(commenttype, commaddr); if (text != null) { - if (commenttype == CodeUnit.PLATE_COMMENT) { + if (commenttype == CommentType.PLATE) { // Plate comments on the function entry // address are considered part of the header if (commaddr.equals(addr)) { @@ -626,16 +626,16 @@ public class DecompileCallback { encodeHeaderComment(encoder, func); } if ((flags & 1) != 0) { - encodeCommentsType(encoder, addrset, addr, CodeUnit.EOL_COMMENT); + encodeCommentsType(encoder, addrset, addr, CommentType.EOL); } if ((flags & 2) != 0) { - encodeCommentsType(encoder, addrset, addr, CodeUnit.PRE_COMMENT); + encodeCommentsType(encoder, addrset, addr, CommentType.PRE); } if ((flags & 4) != 0) { - encodeCommentsType(encoder, addrset, addr, CodeUnit.POST_COMMENT); + encodeCommentsType(encoder, addrset, addr, CommentType.POST); } if ((flags & 8) != 0) { - encodeCommentsType(encoder, addrset, addr, CodeUnit.PLATE_COMMENT); + encodeCommentsType(encoder, addrset, addr, CommentType.PLATE); } encoder.closeElement(ELEM_COMMENTDB); } diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/comments/DecompilerCommentsActionFactory.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/comments/DecompilerCommentsActionFactory.java index 341655df3e..ec109bb477 100644 --- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/comments/DecompilerCommentsActionFactory.java +++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/plugin/core/comments/DecompilerCommentsActionFactory.java @@ -26,120 +26,116 @@ import ghidra.app.plugin.core.decompile.DecompilerActionContext; import ghidra.app.util.HelpTopics; import ghidra.program.model.address.Address; import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.util.*; import ghidra.util.HelpLocation; public class DecompilerCommentsActionFactory extends CommentsActionFactory { - @Override - protected DockingAction doGetEditCommentsAction(CommentsDialog dialog, - String name) { - return new DecompilerEditCommentsAction(dialog, name); - } + @Override + protected DockingAction doGetEditCommentsAction(CommentsDialog dialog, String name) { + return new DecompilerEditCommentsAction(dialog, name); + } - @Override - protected DockingAction doGetSetCommentsAction(CommentsDialog dialog, - String name, String actionName, int commentType) { - return new DecompilerSetCommentsAction(dialog, name, actionName, commentType); - } + @Override + protected DockingAction doGetSetCommentsAction(CommentsDialog dialog, String name, + String actionName, CommentType commentType) { + return new DecompilerSetCommentsAction(dialog, name, actionName, commentType); + } - @Override - protected boolean doIsCommentSupported(ProgramLocation loc) { - if (loc == null || loc.getAddress() == null) { - return false; - } - return ((loc instanceof CodeUnitLocation) - || (loc instanceof DecompilerLocation) || ((loc instanceof FunctionLocation) && !(loc instanceof VariableLocation))); - } + @Override + protected boolean doIsCommentSupported(ProgramLocation loc) { + if (loc == null || loc.getAddress() == null) { + return false; + } + return ((loc instanceof CodeUnitLocation) || (loc instanceof DecompilerLocation) || + ((loc instanceof FunctionLocation) && !(loc instanceof VariableLocation))); + } - private static class DecompilerSetCommentsAction extends DockingAction { - private final CommentsDialog dialog; - private final int commentType; + private static class DecompilerSetCommentsAction extends DockingAction { + private final CommentsDialog dialog; + private final CommentType commentType; // may be null for Generic Comment - DecompilerSetCommentsAction(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")); + DecompilerSetCommentsAction(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(HelpTopics.DECOMPILER, "ActionComments")); - } + } - protected int getEditCommentType(ActionContext context) { - return commentType; - } + 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) - || (context instanceof DecompilerActionContext); - } + @Override + public boolean isValidContext(ActionContext context) { + return (context instanceof ListingActionContext) || + (context instanceof DecompilerActionContext); + } - 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) { - // only allow decompiler to have PRE, PLATE, and Generic Comment actions - if ((actionContext instanceof DecompilerActionContext) - && commentType != CodeUnit.PRE_COMMENT - && commentType != CodeUnit.PLATE_COMMENT - && commentType != CodeUnit.NO_COMMENT) { - return null; - } + protected ProgramLocation getLocationForContext(ActionContext actionContext) { + // only allow decompiler to have PRE, PLATE, and Generic Comment actions + if ((actionContext instanceof DecompilerActionContext) && + commentType != CommentType.PRE && commentType != CommentType.PLATE && + commentType != null) { + return null; + } - if ( !(actionContext instanceof ProgramLocationActionContext) ) { - return null; - } - - ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext; - return context.getLocation(); - } - } + if (!(actionContext instanceof ProgramLocationActionContext)) { + return null; + } - private static class DecompilerEditCommentsAction extends - DecompilerSetCommentsAction { - // Edit Comments Action info - private final static String[] EDIT_MENUPATH = new String[] { - "Comments", "Set..." }; + ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext; + return context.getLocation(); + } + } - DecompilerEditCommentsAction(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)); - } + private static class DecompilerEditCommentsAction extends DecompilerSetCommentsAction { + // Edit Comments Action info + private final static String[] EDIT_MENUPATH = new String[] { "Comments", "Set..." }; - @Override - protected int getEditCommentType(ActionContext context) { - if (context instanceof DecompilerActionContext) { - DecompilerActionContext decompContext = (DecompilerActionContext) context; - Address addr = decompContext.getAddress(); - if (addr.equals(decompContext.getFunctionEntryPoint())) { - return CodeUnit.PLATE_COMMENT; - } - return CodeUnit.PRE_COMMENT; - } - CodeUnit cu = getCodeUnit(context); - return CommentTypeUtils.getCommentType(cu, getLocationForContext(context), CodeUnit.NO_COMMENT); - } - } + DecompilerEditCommentsAction(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 CommentType getEditCommentType(ActionContext context) { + if (context instanceof DecompilerActionContext) { + DecompilerActionContext decompContext = (DecompilerActionContext) context; + Address addr = decompContext.getAddress(); + if (addr.equals(decompContext.getFunctionEntryPoint())) { + return CommentType.PLATE; + } + return CommentType.PRE; + } + CodeUnit cu = getCodeUnit(context); + return CommentTypeUtils.getCommentType(cu, getLocationForContext(context), null); + } + } } diff --git a/Ghidra/Features/FileFormats/ghidra_scripts/MergeTwoProgramsScript.java b/Ghidra/Features/FileFormats/ghidra_scripts/MergeTwoProgramsScript.java index 38031b800b..7053239ab6 100644 --- a/Ghidra/Features/FileFormats/ghidra_scripts/MergeTwoProgramsScript.java +++ b/Ghidra/Features/FileFormats/ghidra_scripts/MergeTwoProgramsScript.java @@ -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. @@ -154,8 +154,6 @@ public class MergeTwoProgramsScript extends GhidraScript { private void mergeComments(Program currProgram, Program otherProgram) throws Exception { monitor.setMessage("Merging comments..."); - int[] commentTypes = { CodeUnit.EOL_COMMENT, CodeUnit.PRE_COMMENT, CodeUnit.POST_COMMENT, - CodeUnit.PLATE_COMMENT, CodeUnit.REPEATABLE_COMMENT, }; Listing currentListing = currProgram.getListing(); Listing otherListing = otherProgram.getListing(); CodeUnitIterator otherCodeUnits = otherListing.getCodeUnits(true); @@ -164,7 +162,7 @@ public class MergeTwoProgramsScript extends GhidraScript { break; } CodeUnit otherCodeUnit = otherCodeUnits.next(); - for (int commentType : commentTypes) { + for (CommentType commentType : CommentType.values()) { if (monitor.isCancelled()) { break; } diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java index 0fd68975a9..f8c989871e 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/app/util/opinion/DexLoader.java @@ -139,11 +139,9 @@ public class DexLoader extends AbstractProgramWrapperLoader { protected void createMethods(Program program, DexHeader header, ClassDefItem item, List methods, TaskMonitor monitor, MessageLog log) throws Exception { - for (int i = 0; i < methods.size(); ++i) { + for (EncodedMethod encodedMethod : methods) { monitor.checkCancelled(); - EncodedMethod encodedMethod = methods.get(i); - CodeItem codeItem = encodedMethod.getCodeItem(); Address methodIndexAddress = @@ -165,8 +163,7 @@ public class DexLoader extends AbstractProgramWrapperLoader { } protected void markupMethodLookup(Program program, DexHeader header, TaskMonitor monitor, - MessageLog log) - throws Exception { + MessageLog log) throws Exception { monitor.setMessage("DEX: processing methods"); monitor.setMaximum(header.getMethodIdsSize()); @@ -198,9 +195,8 @@ public class DexLoader extends AbstractProgramWrapperLoader { DexUtil.createNameSpaceFromMangledClassName(program, className); if (classNameSpace != null) { Address externalAddress = DexUtil.toLookupAddress(program, methodIndex); - Symbol methodSymbol = - createMethodSymbol(program, externalAddress, methodName, classNameSpace, - log); + Symbol methodSymbol = createMethodSymbol(program, externalAddress, methodName, + classNameSpace, log); if (methodSymbol != null) { String externalName = methodSymbol.getName(true); program.getReferenceManager() diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/analyzers/FileFormatAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/analyzers/FileFormatAnalyzer.java index 4b8ade2c64..329a893b04 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/analyzers/FileFormatAnalyzer.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/analyzers/FileFormatAnalyzer.java @@ -74,8 +74,8 @@ public abstract class FileFormatAnalyzer implements Analyzer { } @Override - public boolean removed(Program program, AddressSetView set, TaskMonitor monitor, - MessageLog log) throws CancelledException { + public boolean removed(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) + throws CancelledException { return false; } @@ -151,7 +151,7 @@ public abstract class FileFormatAnalyzer implements Analyzer { } protected ProgramFragment createFragment(Program program, String fragmentName, Address start, - Address end) throws DuplicateNameException, NotFoundException { + Address end) throws DuplicateNameException, NotFoundException { ProgramModule module = program.getListing().getDefaultRootModule(); ProgramFragment fragment = getFragment(module, fragmentName); if (fragment == null) { @@ -187,7 +187,8 @@ public abstract class FileFormatAnalyzer implements Analyzer { return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset); } - protected Data createData(Program program, Address address, DataType datatype) throws CodeUnitInsertionException { + protected Data createData(Program program, Address address, DataType datatype) + throws CodeUnitInsertionException { if (datatype instanceof StringDataType) { CreateStringCmd cmd = new CreateStringCmd(address); if (!cmd.applyTo(program)) { diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.java index 358d19d19e..c8d374e73d 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/art/ArtImageSections.java @@ -202,9 +202,8 @@ public abstract class ArtImageSections { Address address = program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset()); - for (int i = 0; i < fieldList.size(); ++i) { + for (ArtField field : fieldList) { monitor.checkCancelled(); - ArtField field = fieldList.get(i); DataType dataType = field.toDataType(); program.getListing().createData(address, dataType); @@ -221,9 +220,8 @@ public abstract class ArtImageSections { if (section.getSize() > 0) { Address address = program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset()); - for (int i = 0; i < fieldGroupList.size(); ++i) { + for (ArtFieldGroup fieldGroup : fieldGroupList) { monitor.checkCancelled(); - ArtFieldGroup fieldGroup = fieldGroupList.get(i); DataType dataType = fieldGroup.toDataType(); program.getListing().createData(address, dataType); if (fieldGroup.getFieldCount() > 0) { @@ -253,10 +251,9 @@ public abstract class ArtImageSections { if (section.getSize() > 0) { Address address = program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset()); - for (int i = 0; i < methodList.size(); ++i) { + for (ArtMethod method : methodList) { monitor.checkCancelled(); - ArtMethod method = methodList.get(i); DataType dataType = method.toDataType(); program.getListing().createData(address, dataType); String comment = @@ -272,10 +269,9 @@ public abstract class ArtImageSections { if (section.getSize() > 0) { Address address = program.getMinAddress().getNewAddress(header.getImageBegin() + section.getOffset()); - for (int i = 0; i < methodGroupList.size(); ++i) { + for (ArtMethodGroup methodGroup : methodGroupList) { monitor.checkCancelled(); - ArtMethodGroup methodGroup = methodGroupList.get(i); DataType dataType = methodGroup.toDataType(); program.getListing().createData(address, dataType); if (methodGroup.getMethodCount() > 0) { diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.java index 79c4cbd199..b09e7001aa 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPK_Partition.java @@ -97,7 +97,8 @@ public abstract class FBPK_Partition implements StructConverter { * @param log the message log * @throws Exception if any exception occurs during markup */ - public void markup(Program program, Address address, TaskMonitor monitor, MessageLog log) throws Exception { + public void markup(Program program, Address address, TaskMonitor monitor, MessageLog log) + throws Exception { FlatProgramAPI api = new FlatProgramAPI(program); DataType partitionDataType = toDataType(); diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.java index c1690fc514..7daffc8bc3 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/fbpk/FBPT.java @@ -31,7 +31,8 @@ public abstract class FBPT implements StructConverter { public abstract List getEntries(); - public void processFBPT(Program program, Address address, TaskMonitor monitor, MessageLog log) throws Exception { + public void processFBPT(Program program, Address address, TaskMonitor monitor, MessageLog log) + throws Exception { FlatProgramAPI api = new FlatProgramAPI(program); DataType fbptDataType = toDataType(); @@ -48,7 +49,8 @@ public abstract class FBPT implements StructConverter { processFbPtEntries(program, address, monitor, log); } - private void processFbPtEntries(Program program, Address address, TaskMonitor monitor, MessageLog log) throws Exception { + private void processFbPtEntries(Program program, Address address, TaskMonitor monitor, + MessageLog log) throws Exception { int i = 0; FlatProgramAPI api = new FlatProgramAPI(program); for (FBPT_Entry entry : getEntries()) { diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/oatdexfile/OatDexFile_S_T.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/oatdexfile/OatDexFile_S_T.java index fac19bfe64..b8eefcc3a2 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/oatdexfile/OatDexFile_S_T.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/oat/oatdexfile/OatDexFile_S_T.java @@ -59,8 +59,7 @@ public class OatDexFile_S_T extends OatDexFile { private long _offset; private DexHeader dexHeader; - public OatDexFile_S_T(BinaryReader reader, OatBundle bundle) - throws IOException { + public OatDexFile_S_T(BinaryReader reader, OatBundle bundle) throws IOException { _offset = reader.getPointerIndex(); diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.java index b9113e1271..2b688ea10a 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/android/vdex/VdexHeaderAnalyzer.java @@ -81,7 +81,7 @@ public class VdexHeaderAnalyzer extends FileFormatAnalyzer { address = address.add(vdexHeaderDataType.getLength()); if (!vdexHeader.isDexHeaderEmbeddedInDataType()) { - for (int i = 0; i < vdexHeader.getDexHeaderList().size(); ++i) { + for (DexHeader dexHeader : vdexHeader.getDexHeaderList()) { monitor.checkCancelled(); program.getListing() @@ -89,7 +89,6 @@ public class VdexHeaderAnalyzer extends FileFormatAnalyzer { createData(program, address, new DWordDataType()); address = address.add(4); - DexHeader dexHeader = vdexHeader.getDexHeaderList().get(i); DataType dexHeaderDataType = dexHeader.toDataType(); createData(program, address, dexHeaderDataType); diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java index f0672aad42..d700946dc7 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/Ext4Analyzer.java @@ -29,7 +29,7 @@ import ghidra.util.exception.DuplicateNameException; import ghidra.util.task.TaskMonitor; public class Ext4Analyzer extends FileFormatAnalyzer { - + private int blockSize; @Override @@ -53,18 +53,19 @@ public class Ext4Analyzer extends FileFormatAnalyzer { MemoryByteProvider.createDefaultAddressSpaceByteProvider(program, false); BinaryReader reader = new BinaryReader(provider, true); int start = getSuperBlockStart(reader); - if( start == -1 ) { + if (start == -1) { return false; } - + reader.setPointerIndex(start + 0x38); short magic = -1; try { magic = reader.readNextShort(); - } catch (IOException e ) { + } + catch (IOException e) { // ignore } - if( magic != (short)0xef53 ) { + if (magic != (short) 0xef53) { return false; } return true; @@ -76,8 +77,8 @@ public class Ext4Analyzer extends FileFormatAnalyzer { } @Override - public boolean analyze(Program program, AddressSetView set, - TaskMonitor monitor, MessageLog log) throws Exception { + public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) + throws Exception { ByteProvider provider = MemoryByteProvider.createDefaultAddressSpaceByteProvider(program, false); BinaryReader reader = new BinaryReader(provider, true); @@ -86,67 +87,74 @@ public class Ext4Analyzer extends FileFormatAnalyzer { reader.setPointerIndex(start); Ext4SuperBlock superBlock = new Ext4SuperBlock(reader); createData(program, toAddr(program, start), superBlock.toDataType()); - - boolean is64Bit = (superBlock.getS_desc_size() > 32) && ((superBlock.getS_feature_incompat() & 0x80) > 0); - long numBytes = program.getMaxAddress().getOffset() - program.getMinAddress().getOffset() + 1; - int groupSize = calculateGroupSize( superBlock ); - int numGroups = (int)numBytes / groupSize; - if( numBytes % groupSize != 0) { + boolean is64Bit = + (superBlock.getS_desc_size() > 32) && ((superBlock.getS_feature_incompat() & 0x80) > 0); + long numBytes = + program.getMaxAddress().getOffset() - program.getMinAddress().getOffset() + 1; + int groupSize = calculateGroupSize(superBlock); + int numGroups = (int) numBytes / groupSize; + if (numBytes % groupSize != 0) { numGroups++; } - + long groupDescOffset = groupStart + blockSize; Address groupDescAddress = toAddr(program, groupDescOffset); reader.setPointerIndex(groupDescOffset); Ext4GroupDescriptor groupDescriptors[] = new Ext4GroupDescriptor[numGroups]; monitor.setMessage("Creating group descriptors..."); monitor.setMaximum(numGroups); - for( int i = 0; i < numGroups; i++ ) { + for (int i = 0; i < numGroups; i++) { monitor.checkCancelled(); groupDescriptors[i] = new Ext4GroupDescriptor(reader, is64Bit); DataType groupDescDataType = groupDescriptors[i].toDataType(); createData(program, groupDescAddress, groupDescDataType); - groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); + groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); monitor.incrementProgress(1); } - + boolean isSparseSuper = (superBlock.getS_feature_ro_compat() & 1) != 0; - createSuperBlockCopies(program, reader, groupSize, numGroups, is64Bit, isSparseSuper, monitor); - + createSuperBlockCopies(program, reader, groupSize, numGroups, is64Bit, isSparseSuper, + monitor); + createInodeTables(program, reader, superBlock, groupDescriptors, is64Bit, monitor); - + // test(program, reader); return true; } - + private void createInodeTables(Program program, BinaryReader reader, Ext4SuperBlock superBlock, - Ext4GroupDescriptor[] groupDescriptors, boolean is64Bit, TaskMonitor monitor) throws DuplicateNameException, Exception { - + Ext4GroupDescriptor[] groupDescriptors, boolean is64Bit, TaskMonitor monitor) + throws DuplicateNameException, Exception { + int inodeCount = superBlock.getS_inodes_count(); Ext4Inode inodes[] = new Ext4Inode[inodeCount]; - for( int i = 0; i < groupDescriptors.length; i++ ) { + for (int i = 0; i < groupDescriptors.length; i++) { monitor.checkCancelled(); long inodeTableBlockOffset = groupDescriptors[i].getBg_inode_table_lo() & 0xffffffffL; - if( is64Bit ) { - inodeTableBlockOffset = (((long) groupDescriptors[i].getBg_inode_table_hi()) << 32) | inodeTableBlockOffset; + if (is64Bit) { + inodeTableBlockOffset = + (((long) groupDescriptors[i].getBg_inode_table_hi()) << 32) | + inodeTableBlockOffset; } long offset = inodeTableBlockOffset * blockSize; reader.setPointerIndex(offset); Address address = null; try { address = toAddr(program, offset); - } catch (Exception e ) { + } + catch (Exception e) { throw new IOException("offset " + offset + " not in program."); } - + int inodesPerGroup = superBlock.getS_inodes_per_group(); - monitor.setMessage("Creating inode table " + i + " of " + (groupDescriptors.length - 1) + "..."); + monitor.setMessage( + "Creating inode table " + i + " of " + (groupDescriptors.length - 1) + "..."); monitor.setMaximum(inodesPerGroup); monitor.setProgress(0); - for( int j = 0; j < inodesPerGroup; j++ ) { - if( i == 0 && j == 0) { + for (int j = 0; j < inodesPerGroup; j++) { + if (i == 0 && j == 0) { //inode 0 does not exist continue; } @@ -163,37 +171,39 @@ public class Ext4Analyzer extends FileFormatAnalyzer { inodes[inodesPerGroup * i + j] = inode; } } - processInodes( program, reader, superBlock, inodes, monitor); + processInodes(program, reader, superBlock, inodes, monitor); } - private void processInodes(Program program, BinaryReader reader, - Ext4SuperBlock superBlock, Ext4Inode[] inodes, TaskMonitor monitor) throws Exception { + private void processInodes(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4Inode[] inodes, TaskMonitor monitor) throws Exception { //first 0xa inodes are reserved (0 doesn't exist) - for( int i = 0x1; i < inodes.length; i++ ) { + for (int i = 0x1; i < inodes.length; i++) { monitor.checkCancelled(); Ext4Inode inode = inodes[i]; short mode = inode.getI_mode(); - if( (mode & Ext4Constants.S_IFDIR) != 0 ) { + if ((mode & Ext4Constants.S_IFDIR) != 0) { processDirectory(program, reader, superBlock, inode, monitor); - } else if( (mode & Ext4Constants.S_IFREG) != 0 ) { + } + else if ((mode & Ext4Constants.S_IFREG) != 0) { processFile(program, reader, superBlock, inode, monitor); - } + } } } - private void processFile(Program program, BinaryReader reader, - Ext4SuperBlock superBlock, Ext4Inode inode, TaskMonitor monitor) { + private void processFile(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4Inode inode, TaskMonitor monitor) { // TODO? } - private void processDirectory(Program program, BinaryReader reader, - Ext4SuperBlock superBlock, Ext4Inode inode, TaskMonitor monitor) throws Exception { - if( (inode.getI_flags() & Ext4Constants.EXT4_INDEX_FL) != 0 ) { + private void processDirectory(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4Inode inode, TaskMonitor monitor) throws Exception { + if ((inode.getI_flags() & Ext4Constants.EXT4_INDEX_FL) != 0) { processHashTreeDirectory(program, reader, superBlock, inode, monitor); } - boolean isDirEntry2 = (superBlock.getS_feature_incompat() & Ext4Constants.INCOMPAT_FILETYPE) != 0; + boolean isDirEntry2 = + (superBlock.getS_feature_incompat() & Ext4Constants.INCOMPAT_FILETYPE) != 0; // if uses extents - if( (inode.getI_flags() & Ext4Constants.EXT4_EXTENTS_FL) != 0 ) { + if ((inode.getI_flags() & Ext4Constants.EXT4_EXTENTS_FL) != 0) { // Ext4IBlock i_block = inode.getI_block(); // Ext4ExtentHeader header = i_block.getHeader(); // if( header.getEh_depth() == 0 ) { @@ -216,7 +226,7 @@ public class Ext4Analyzer extends FileFormatAnalyzer { // // } } - + } private void processHashTreeDirectory(Program program, BinaryReader reader, @@ -224,13 +234,14 @@ public class Ext4Analyzer extends FileFormatAnalyzer { // TODO? } - private void createSuperBlockCopies(Program program, BinaryReader reader, - int groupSize, int numGroups, boolean is64Bit, boolean isSparseSuper, TaskMonitor monitor) throws DuplicateNameException, IOException, Exception { + private void createSuperBlockCopies(Program program, BinaryReader reader, int groupSize, + int numGroups, boolean is64Bit, boolean isSparseSuper, TaskMonitor monitor) + throws DuplicateNameException, IOException, Exception { monitor.setMessage("Creating super block and group descriptor copies..."); monitor.setMaximum(numGroups); - for( int i = 1; i < numGroups; i++ ) { + for (int i = 1; i < numGroups; i++) { monitor.checkCancelled(); - if( isSparseSuper && (!isXpowerOfY(i, 3) && !isXpowerOfY(i, 5) && !isXpowerOfY(i, 7)) ) { + if (isSparseSuper && (!isXpowerOfY(i, 3) && !isXpowerOfY(i, 5) && !isXpowerOfY(i, 7))) { continue; } int offset = groupSize * i; @@ -238,27 +249,26 @@ public class Ext4Analyzer extends FileFormatAnalyzer { reader.setPointerIndex(offset); Ext4SuperBlock superBlock = new Ext4SuperBlock(reader); createData(program, address, superBlock.toDataType()); - - + long groupDescOffset = offset + blockSize; Address groupDescAddress = toAddr(program, groupDescOffset); reader.setPointerIndex(groupDescOffset); - for( int j = 0; j < numGroups; j++ ) { + for (int j = 0; j < numGroups; j++) { Ext4GroupDescriptor groupDesc = new Ext4GroupDescriptor(reader, is64Bit); DataType groupDescDataType = groupDesc.toDataType(); createData(program, groupDescAddress, groupDescDataType); - groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); + groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); } monitor.incrementProgress(1); } - + } - - private boolean isXpowerOfY( int x, int y ) { - if( x == 0 ) { + + private boolean isXpowerOfY(int x, int y) { + if (x == 0) { return false; } - while( x % y == 0 ) { + while (x % y == 0) { x = x / y; } return x == 1; @@ -276,23 +286,25 @@ public class Ext4Analyzer extends FileFormatAnalyzer { int padding = -1; int padStart = 0; boolean isPadding = false; - while( padStart < 1024 ) { - if( !isPadding ) { - padStart = (int)reader.getPointerIndex(); + while (padStart < 1024) { + if (!isPadding) { + padStart = (int) reader.getPointerIndex(); } padding = reader.readNextInt(); - if( padding == 0 ) { - if( isPadding ) { + if (padding == 0) { + if (isPadding) { return padStart + 0x400; } isPadding = true; - } else { + } + else { isPadding = false; } } - } catch (Exception e) { + } + catch (Exception e) { } return -1; } - + } diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java index 4fa4c90bfa..1beed26cb5 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ext4/NewExt4Analyzer.java @@ -34,46 +34,46 @@ import ghidra.util.exception.DuplicateNameException; import ghidra.util.task.TaskMonitor; public class NewExt4Analyzer extends FileFormatAnalyzer { - + private int blockSize; private Program program2; private Program program3; @Override - public String getName( ) { + public String getName() { return "Ext4 Analyzer NEW"; } @Override - public boolean getDefaultEnablement( Program program ) { + public boolean getDefaultEnablement(Program program) { return true; } @Override - public String getDescription( ) { + public String getDescription() { return "Annotates Ext4 file systems. " + - "For EXT4 files >2GB, split into 2 programs. Analysis will markup both. "+ - "Simply name the programs ABC and ABC_0x70000000 and ABC_0xF0000000"; + "For EXT4 files >2GB, split into 2 programs. Analysis will markup both. " + + "Simply name the programs ABC and ABC_0x70000000 and ABC_0xF0000000"; } @Override - public boolean canAnalyze( Program program ) { + public boolean canAnalyze(Program program) { ByteProvider provider = MemoryByteProvider.createDefaultAddressSpaceByteProvider(program, false); - BinaryReader reader = new BinaryReader( provider, true ); - int start = getSuperBlockStart( reader ); - if ( start == -1 ) { + BinaryReader reader = new BinaryReader(provider, true); + int start = getSuperBlockStart(reader); + if (start == -1) { return false; } - reader.setPointerIndex( start + 0x38 ); + reader.setPointerIndex(start + 0x38); int magic = -1; try { - magic = reader.readNextShort( ) & 0xffff; + magic = reader.readNextShort() & 0xffff; } - catch ( IOException e ) { + catch (IOException e) { // ignore } return magic == Ext4Constants.SUPER_BLOCK_MAGIC; @@ -85,85 +85,91 @@ public class NewExt4Analyzer extends FileFormatAnalyzer { } @Override - public boolean analyze( Program program, AddressSetView set, TaskMonitor monitor, MessageLog log ) throws Exception { + public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) + throws Exception { - program2 = findOtherProgram( program, "0x70000000" ); + program2 = findOtherProgram(program, "0x70000000"); int transactionId2 = -1; - if ( program2 != null ) { - transactionId2 = program2.startTransaction( getName( ) ); + if (program2 != null) { + transactionId2 = program2.startTransaction(getName()); } - program3 = findOtherProgram( program, "0xE0000000" ); + program3 = findOtherProgram(program, "0xE0000000"); int transactionId3 = -1; - if ( program3 != null ) { - transactionId3 = program3.startTransaction( getName( ) ); + if (program3 != null) { + transactionId3 = program3.startTransaction(getName()); } - try { - ByteProvider provider = new MultiProgramMemoryByteProvider( program, program2, program3 ); - BinaryReader reader = new BinaryReader( provider, true ); - int start = getSuperBlockStart( reader ); + try { + ByteProvider provider = new MultiProgramMemoryByteProvider(program, program2, program3); + BinaryReader reader = new BinaryReader(provider, true); + int start = getSuperBlockStart(reader); int groupStart = 0; - reader.setPointerIndex( start ); - Ext4SuperBlock superBlock = new Ext4SuperBlock( reader ); - Address superBlockAddress = toAddr( program, start ); - createData( program, superBlockAddress, superBlock.toDataType( ) ); - + reader.setPointerIndex(start); + Ext4SuperBlock superBlock = new Ext4SuperBlock(reader); + Address superBlockAddress = toAddr(program, start); + createData(program, superBlockAddress, superBlock.toDataType()); - boolean is64Bit = ( superBlock.getS_desc_size( ) > 32 ) && ( ( superBlock.getS_feature_incompat( ) & 0x80 ) > 0 ); + boolean is64Bit = (superBlock.getS_desc_size() > 32) && + ((superBlock.getS_feature_incompat() & 0x80) > 0); - long numBytes = program.getMaxAddress( ).getOffset( ) - program.getMinAddress( ).getOffset( ) + 1; - if ( program2 != null ) { - numBytes = program2.getMaxAddress( ).getOffset( ) - program.getMinAddress( ).getOffset( ) + 1; + long numBytes = + program.getMaxAddress().getOffset() - program.getMinAddress().getOffset() + 1; + if (program2 != null) { + numBytes = + program2.getMaxAddress().getOffset() - program.getMinAddress().getOffset() + 1; } - if ( program3 != null ) { - numBytes = program3.getMaxAddress( ).getOffset( ) - program.getMinAddress( ).getOffset( ) + 1; + if (program3 != null) { + numBytes = + program3.getMaxAddress().getOffset() - program.getMinAddress().getOffset() + 1; } - int groupSize = calculateGroupSize( superBlock ); - int numGroups = ( int ) ( numBytes / groupSize ); - if ( numBytes % groupSize != 0 ) { + int groupSize = calculateGroupSize(superBlock); + int numGroups = (int) (numBytes / groupSize); + if (numBytes % groupSize != 0) { numGroups++; } - setPlateComment( program, superBlockAddress, "SuperBlock (main) \n" + - "Group Size In Bytes: 0x" + Integer.toHexString( groupSize ) + "\n" + - "Number of Groups: 0x" + Integer.toHexString( numGroups ) ); + setPlateComment(program, superBlockAddress, + "SuperBlock (main) \n" + "Group Size In Bytes: 0x" + + Integer.toHexString(groupSize) + "\n" + "Number of Groups: 0x" + + Integer.toHexString(numGroups)); long groupDescOffset = groupStart + blockSize; - Address groupDescAddress = toAddr( program, groupDescOffset ); - reader.setPointerIndex( groupDescOffset ); - Ext4GroupDescriptor groupDescriptors[] = new Ext4GroupDescriptor [ numGroups ]; - monitor.setMessage( "Creating group descriptors..." ); - monitor.setMaximum( numGroups ); - for ( int i = 0; i < numGroups; i++ ) { - monitor.checkCancelled( ); - groupDescriptors[ i ] = new Ext4GroupDescriptor( reader, is64Bit ); - DataType groupDescDataType = groupDescriptors[ i ].toDataType( ); - createData( program, groupDescAddress, groupDescDataType ); - setPlateComment( program, groupDescAddress, "group descriptor: " + i ); + Address groupDescAddress = toAddr(program, groupDescOffset); + reader.setPointerIndex(groupDescOffset); + Ext4GroupDescriptor groupDescriptors[] = new Ext4GroupDescriptor[numGroups]; + monitor.setMessage("Creating group descriptors..."); + monitor.setMaximum(numGroups); + for (int i = 0; i < numGroups; i++) { + monitor.checkCancelled(); + groupDescriptors[i] = new Ext4GroupDescriptor(reader, is64Bit); + DataType groupDescDataType = groupDescriptors[i].toDataType(); + createData(program, groupDescAddress, groupDescDataType); + setPlateComment(program, groupDescAddress, "group descriptor: " + i); - groupDescAddress = groupDescAddress.add( groupDescDataType.getLength( ) ); - monitor.incrementProgress( 1 ); + groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); + monitor.incrementProgress(1); } - boolean isSparseSuper = ( superBlock.getS_feature_ro_compat( ) & 1 ) != 0; - createSuperBlockCopies( program, reader, groupSize, numGroups, is64Bit, isSparseSuper, monitor ); + boolean isSparseSuper = (superBlock.getS_feature_ro_compat() & 1) != 0; + createSuperBlockCopies(program, reader, groupSize, numGroups, is64Bit, isSparseSuper, + monitor); - createInodeTables( program, reader, superBlock, groupDescriptors, is64Bit, monitor ); - - // test(program, reader); + createInodeTables(program, reader, superBlock, groupDescriptors, is64Bit, monitor); + + // test(program, reader); } - catch ( Exception e ) { + catch (Exception e) { throw e; } finally { - if ( program2 != null ) { - program2.endTransaction( transactionId2, true ); + if (program2 != null) { + program2.endTransaction(transactionId2, true); program2 = null; } - if ( program3 != null ) { - program3.endTransaction( transactionId3, true ); + if (program3 != null) { + program3.endTransaction(transactionId3, true); program3 = null; } } @@ -175,13 +181,14 @@ public class NewExt4Analyzer extends FileFormatAnalyzer { * This method allows for EXT4 files larger than 2GB to be imported as 2 (or 3) separate programs. * Then if both programs are opened (and have the same base name), then both will be analyzed. */ - private Program findOtherProgram( Program program, String suffix ) { - AutoAnalysisManager manager = AutoAnalysisManager.getAnalysisManager( program ); - ProgramManager programManager = manager.getAnalysisTool( ).getService( ProgramManager.class ); - Program [] openPrograms = programManager.getAllOpenPrograms( ); - for ( Program otherProgram : openPrograms ) { - if ( program != otherProgram ) { - if ( otherProgram.getName( ).startsWith( program.getName( ) ) && otherProgram.getName( ).endsWith( suffix ) ) { + private Program findOtherProgram(Program program, String suffix) { + AutoAnalysisManager manager = AutoAnalysisManager.getAnalysisManager(program); + ProgramManager programManager = manager.getAnalysisTool().getService(ProgramManager.class); + Program[] openPrograms = programManager.getAllOpenPrograms(); + for (Program otherProgram : openPrograms) { + if (program != otherProgram) { + if (otherProgram.getName().startsWith(program.getName()) && + otherProgram.getName().endsWith(suffix)) { return otherProgram; } } @@ -190,69 +197,72 @@ public class NewExt4Analyzer extends FileFormatAnalyzer { } @Override - protected Data createData( Program program, Address address, DataType datatype ) throws CodeUnitInsertionException { - if ( program.getMemory( ).contains( address ) ) { - return super.createData( program, address, datatype ); + protected Data createData(Program program, Address address, DataType datatype) + throws CodeUnitInsertionException { + if (program.getMemory().contains(address)) { + return super.createData(program, address, datatype); } - if ( program2 != null && program2.getMemory( ).contains( address ) ) { - return super.createData( program2, address, datatype ); + if (program2 != null && program2.getMemory().contains(address)) { + return super.createData(program2, address, datatype); } - throw new CodeUnitInsertionException( "Cannot create data, neither program contains that address." ); + throw new CodeUnitInsertionException( + "Cannot create data, neither program contains that address."); } @Override - protected boolean setPlateComment( Program program, Address address, String comment ) { + protected boolean setPlateComment(Program program, Address address, String comment) { SetCommentCmd cmd = new SetCommentCmd(address, CommentType.PLATE, comment); - if ( program.getMemory( ).contains( address ) ) { - return cmd.applyTo( program ); + if (program.getMemory().contains(address)) { + return cmd.applyTo(program); } - if ( program2 != null && program2.getMemory( ).contains( address ) ) { - return cmd.applyTo( program2 ); + if (program2 != null && program2.getMemory().contains(address)) { + return cmd.applyTo(program2); } - throw new RuntimeException( "Cannot set plate comment, neither program contains that address." ); + throw new RuntimeException( + "Cannot set plate comment, neither program contains that address."); } - private void createInodeTables( Program program, - BinaryReader reader, - Ext4SuperBlock superBlock, - Ext4GroupDescriptor [] groupDescriptors, - boolean is64Bit, - TaskMonitor monitor ) throws DuplicateNameException, Exception { - - int inodeCount = superBlock.getS_inodes_count( ); - Ext4Inode [] inodes = new Ext4Inode [ inodeCount ]; + private void createInodeTables(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4GroupDescriptor[] groupDescriptors, boolean is64Bit, TaskMonitor monitor) + throws DuplicateNameException, Exception { + + int inodeCount = superBlock.getS_inodes_count(); + Ext4Inode[] inodes = new Ext4Inode[inodeCount]; int inodeIndex = 0; - for ( int i = 0; i < groupDescriptors.length; i++ ) { - monitor.checkCancelled( ); - long inodeTableBlockOffset = groupDescriptors[ i ].getBg_inode_table_lo( ) & 0xffffffffL; - if ( is64Bit ) { - inodeTableBlockOffset = ( ((long) groupDescriptors[ i ].getBg_inode_table_hi( )) << 32 ) | inodeTableBlockOffset; + for (int i = 0; i < groupDescriptors.length; i++) { + monitor.checkCancelled(); + long inodeTableBlockOffset = groupDescriptors[i].getBg_inode_table_lo() & 0xffffffffL; + if (is64Bit) { + inodeTableBlockOffset = + (((long) groupDescriptors[i].getBg_inode_table_hi()) << 32) | + inodeTableBlockOffset; } long offset = inodeTableBlockOffset * blockSize; - reader.setPointerIndex( offset ); + reader.setPointerIndex(offset); Address address = null; try { - address = toAddr( program, offset ); + address = toAddr(program, offset); } - catch ( Exception e ) { - throw new IOException( "offset " + offset + " not in program." ); + catch (Exception e) { + throw new IOException("offset " + offset + " not in program."); } - int inodesPerGroup = superBlock.getS_inodes_per_group( ); - monitor.setMessage( "Creating inode table " + i + " of " + ( groupDescriptors.length - 1 ) + "..." ); - monitor.setMaximum( inodesPerGroup ); - monitor.setProgress( 0 ); - for ( int j = 0; j < inodesPerGroup; j++ ) { - monitor.checkCancelled( ); + int inodesPerGroup = superBlock.getS_inodes_per_group(); + monitor.setMessage( + "Creating inode table " + i + " of " + (groupDescriptors.length - 1) + "..."); + monitor.setMaximum(inodesPerGroup); + monitor.setProgress(0); + for (int j = 0; j < inodesPerGroup; j++) { + monitor.checkCancelled(); - Ext4Inode inode = new Ext4Inode( reader ); - DataType dataType = inode.toDataType( ); - createData( program, address, dataType ); + Ext4Inode inode = new Ext4Inode(reader); + DataType dataType = inode.toDataType(); + createData(program, address, dataType); - String comment = "Inode: 0x" + Integer.toHexString( inodeIndex + 1 ) + "\n"; - comment += "Group Descriptor ID: 0x" + Integer.toHexString( i ) + "\n"; - comment += "Inode Offset Into Group: 0x" + Integer.toHexString( j ) + "\n"; + String comment = "Inode: 0x" + Integer.toHexString(inodeIndex + 1) + "\n"; + comment += "Group Descriptor ID: 0x" + Integer.toHexString(i) + "\n"; + comment += "Inode Offset Into Group: 0x" + Integer.toHexString(j) + "\n"; // Ext4IBlock iBlock = inode.getI_block( ); // if ( iBlock != null ) { @@ -263,157 +273,143 @@ public class NewExt4Analyzer extends FileFormatAnalyzer { // } // } - setPlateComment( program, address, comment ); - createLabel( program, address, "INODE_" + "0x" + Integer.toHexString( inodeIndex + 1 ) ); - address = address.add( superBlock.getS_inode_size( ) ); - reader.setPointerIndex( address.getOffset( ) ); - monitor.incrementProgress( 1 ); - inodes[ inodeIndex++ ] = inode; //inodes[ inodesPerGroup * i + j ] = inode; + setPlateComment(program, address, comment); + createLabel(program, address, + "INODE_" + "0x" + Integer.toHexString(inodeIndex + 1)); + address = address.add(superBlock.getS_inode_size()); + reader.setPointerIndex(address.getOffset()); + monitor.incrementProgress(1); + inodes[inodeIndex++] = inode; //inodes[ inodesPerGroup * i + j ] = inode; } } - processInodes( program, reader, superBlock, inodes, monitor ); + processInodes(program, reader, superBlock, inodes, monitor); } - private void createLabel( Program program, Address address, String labelName ) throws Exception { - if ( program.getMemory( ).contains( address ) ) { - program.getSymbolTable( ).createLabel( address, labelName, SourceType.ANALYSIS ); + private void createLabel(Program program, Address address, String labelName) throws Exception { + if (program.getMemory().contains(address)) { + program.getSymbolTable().createLabel(address, labelName, SourceType.ANALYSIS); return; } - if ( program2 != null && program2.getMemory( ).contains( address ) ) { - program2.getSymbolTable( ).createLabel( address, labelName, SourceType.ANALYSIS ); + if (program2 != null && program2.getMemory().contains(address)) { + program2.getSymbolTable().createLabel(address, labelName, SourceType.ANALYSIS); return; } - throw new RuntimeException( "Cannot create label, neither program contains that address." ); + throw new RuntimeException("Cannot create label, neither program contains that address."); } - private void processInodes(Program program, BinaryReader reader, - Ext4SuperBlock superBlock, Ext4Inode[] inodes, TaskMonitor monitor) throws Exception { + private void processInodes(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4Inode[] inodes, TaskMonitor monitor) throws Exception { //first 0xa inodes are reserved (0 doesn't exist) - for ( int i = 0x1; i < inodes.length; i++ ) { - monitor.checkCancelled( ); - Ext4Inode inode = inodes[ i ]; - + for (int i = 0x1; i < inodes.length; i++) { + monitor.checkCancelled(); + Ext4Inode inode = inodes[i]; + short mode = inode.getI_mode(); - if ( ( mode & Ext4Constants.S_IFDIR ) != 0 ) { - processDirectory(program, reader, superBlock, inode, monitor ); + if ((mode & Ext4Constants.S_IFDIR) != 0) { + processDirectory(program, reader, superBlock, inode, monitor); + } + else if ((mode & Ext4Constants.S_IFREG) != 0) { + processFile(program, reader, superBlock, inode, monitor); } - else if ( (mode & Ext4Constants.S_IFREG ) != 0 ) { - processFile( program, reader, superBlock, inode, monitor ); - } } } - private void processFile(Program program, - BinaryReader reader, - Ext4SuperBlock superBlock, - Ext4Inode inode, - TaskMonitor monitor ) { + private void processFile(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4Inode inode, TaskMonitor monitor) { // TODO? } - private void processDirectory( Program program, - BinaryReader reader, - Ext4SuperBlock superBlock, - Ext4Inode inode, - TaskMonitor monitor ) throws Exception { + private void processDirectory(Program program, BinaryReader reader, Ext4SuperBlock superBlock, + Ext4Inode inode, TaskMonitor monitor) throws Exception { - if ( (inode.getI_flags() & Ext4Constants.EXT4_INDEX_FL) != 0 ) { - processHashTreeDirectory( program, reader, superBlock, inode, monitor ); + if ((inode.getI_flags() & Ext4Constants.EXT4_INDEX_FL) != 0) { + processHashTreeDirectory(program, reader, superBlock, inode, monitor); } - boolean isDirEntry2 = (superBlock.getS_feature_incompat() & Ext4Constants.INCOMPAT_FILETYPE) != 0; + boolean isDirEntry2 = + (superBlock.getS_feature_incompat() & Ext4Constants.INCOMPAT_FILETYPE) != 0; // if uses extents - if ( (inode.getI_flags() & Ext4Constants.EXT4_EXTENTS_FL) != 0 ) { + if ((inode.getI_flags() & Ext4Constants.EXT4_EXTENTS_FL) != 0) { // Ext4IBlock i_block = inode.getI_block(); // processIBlock( program, reader, isDirEntry2, i_block, monitor ); } } - private void processIBlock( Program program, - BinaryReader reader, - boolean isDirEntry2, - Ext4IBlock i_block, - TaskMonitor monitor ) throws Exception { + private void processIBlock(Program program, BinaryReader reader, boolean isDirEntry2, + Ext4IBlock i_block, TaskMonitor monitor) throws Exception { Ext4ExtentHeader header = i_block.getHeader(); - if ( header.getEh_depth() == 0 ) {//leaf node.... + if (header.getEh_depth() == 0) {//leaf node.... short numEntries = header.getEh_entries(); List entries = i_block.getExtentEntries(); - for ( int i = 0; i < numEntries; i++ ) { - Ext4Extent extent = entries.get( i ); + for (int i = 0; i < numEntries; i++) { + Ext4Extent extent = entries.get(i); long offset = extent.getExtentStartBlockNumber() * blockSize; reader.setPointerIndex(offset); - Address address = toAddr( program, offset ); - if ( isDirEntry2 ) { - while ( ( reader.getPointerIndex( ) - offset ) < ( extent.getEe_len( ) * blockSize ) ) { + Address address = toAddr(program, offset); + if (isDirEntry2) { + while ((reader.getPointerIndex() - offset) < (extent.getEe_len() * blockSize)) { Ext4DirEntry2 dirEnt2 = Ext4DirEntry2.read(reader); - DataType dataType = dirEnt2.toDataType( ); - createData( program, address, dataType ); - String comment = "Name: " + dirEnt2.getName( ) + "\n"; - if ( dirEnt2.getFile_type( ) == Ext4Constants.FILE_TYPE_REGULAR_FILE ) { + DataType dataType = dirEnt2.toDataType(); + createData(program, address, dataType); + String comment = "Name: " + dirEnt2.getName() + "\n"; + if (dirEnt2.getFile_type() == Ext4Constants.FILE_TYPE_REGULAR_FILE) { comment += "Type: REGULAR FILE" + "\n"; } - else if ( dirEnt2.getFile_type( ) == Ext4Constants.FILE_TYPE_DIRECTORY ) { + else if (dirEnt2.getFile_type() == Ext4Constants.FILE_TYPE_DIRECTORY) { comment += "Type: DIRECTORY" + "\n"; } - comment += "Type: INODE_0x" + Integer.toHexString( dirEnt2.getInode( ) ); + comment += "Type: INODE_0x" + Integer.toHexString(dirEnt2.getInode()); //TODO: add link to iNode using {@program program_name.exe@symbol_name} //TODO: add parent path to comment - setPlateComment( program, address, comment ); - address = address.add( dataType.getLength( ) ); + setPlateComment(program, address, comment); + address = address.add(dataType.getLength()); } } else { - throw new RuntimeException( "TODO: support old style dir entry" ); + throw new RuntimeException("TODO: support old style dir entry"); } } } else {//interior node.... - short numEntries = header.getEh_entries( ); + short numEntries = header.getEh_entries(); List entries = i_block.getIndexEntries(); - for ( int i = 0; i < numEntries; i++ ) { - monitor.checkCancelled( ); + for (int i = 0; i < numEntries; i++) { + monitor.checkCancelled(); - Ext4ExtentIdx extentIndex = entries.get( i ); + Ext4ExtentIdx extentIndex = entries.get(i); long lo = extentIndex.getEi_leaf_lo(); long hi = extentIndex.getEi_leaf_hi(); - long physicalBlockOfNextLevel = ( hi << 32 ) | lo; + long physicalBlockOfNextLevel = (hi << 32) | lo; long offset = physicalBlockOfNextLevel * blockSize; - Address address = toAddr( program, offset ); - setPlateComment( program, address, "TODO Ext4ExtentIdx / ext4_fsblk_t ???" ); + Address address = toAddr(program, offset); + setPlateComment(program, address, "TODO Ext4ExtentIdx / ext4_fsblk_t ???"); - reader.setPointerIndex( offset ); + reader.setPointerIndex(offset); - Ext4IBlock iBlock = new Ext4IBlock( reader, true ); - DataType dataType = iBlock.toDataType( ); - createData( program, address, dataType ); + Ext4IBlock iBlock = new Ext4IBlock(reader, true); + DataType dataType = iBlock.toDataType(); + createData(program, address, dataType); - processIBlock( program, reader, isDirEntry2, iBlock, monitor ); + processIBlock(program, reader, isDirEntry2, iBlock, monitor); } } } - private void processHashTreeDirectory( Program program, - BinaryReader reader, - Ext4SuperBlock superBlock, - Ext4Inode inode, - TaskMonitor monitor ) { + private void processHashTreeDirectory(Program program, BinaryReader reader, + Ext4SuperBlock superBlock, Ext4Inode inode, TaskMonitor monitor) { // TODO? } - private void createSuperBlockCopies(Program program, - BinaryReader reader, - int groupSize, - int numGroups, - boolean is64Bit, - boolean isSparseSuper, - TaskMonitor monitor ) throws Exception { - monitor.setMessage( "Creating super block and group descriptor copies..." ); + private void createSuperBlockCopies(Program program, BinaryReader reader, int groupSize, + int numGroups, boolean is64Bit, boolean isSparseSuper, TaskMonitor monitor) + throws Exception { + monitor.setMessage("Creating super block and group descriptor copies..."); monitor.setMaximum(numGroups); - for ( int i = 1; i < numGroups; i++ ) { + for (int i = 1; i < numGroups; i++) { monitor.checkCancelled(); - if( isSparseSuper && (!isXpowerOfY(i, 3) && !isXpowerOfY(i, 5) && !isXpowerOfY(i, 7)) ) { + if (isSparseSuper && (!isXpowerOfY(i, 3) && !isXpowerOfY(i, 5) && !isXpowerOfY(i, 7))) { continue; } int offset = groupSize * i; @@ -421,53 +417,54 @@ public class NewExt4Analyzer extends FileFormatAnalyzer { reader.setPointerIndex(offset); Ext4SuperBlock superBlock = new Ext4SuperBlock(reader); createData(program, address, superBlock.toDataType()); - setPlateComment( program, address, "SuperBlock Copy 0x" + Integer.toHexString( i ) ); + setPlateComment(program, address, "SuperBlock Copy 0x" + Integer.toHexString(i)); - long groupDescOffset = ( offset & 0xffffffffL ) + blockSize; + long groupDescOffset = (offset & 0xffffffffL) + blockSize; Address groupDescAddress = toAddr(program, groupDescOffset); reader.setPointerIndex(groupDescOffset); - for ( int j = 0; j < numGroups; j++ ) { + for (int j = 0; j < numGroups; j++) { Ext4GroupDescriptor groupDesc = new Ext4GroupDescriptor(reader, is64Bit); DataType groupDescDataType = groupDesc.toDataType(); createData(program, groupDescAddress, groupDescDataType); - setPlateComment( program, groupDescAddress, "SuperBlock Copy 0x" + Integer.toHexString( i ) + " Group 0x" + Integer.toHexString( j ) ); + setPlateComment(program, groupDescAddress, "SuperBlock Copy 0x" + + Integer.toHexString(i) + " Group 0x" + Integer.toHexString(j)); - groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); + groupDescAddress = groupDescAddress.add(groupDescDataType.getLength()); } monitor.incrementProgress(1); } } - - private boolean isXpowerOfY( int x, int y ) { - if ( x == 0 ) { + + private boolean isXpowerOfY(int x, int y) { + if (x == 0) { return false; } - while ( x % y == 0 ) { + while (x % y == 0) { x = x / y; } return x == 1; } - private int calculateGroupSize( Ext4SuperBlock superBlock ) { - int logBlockSize = superBlock.getS_log_block_size( ); - blockSize = ( int ) Math.pow( 2, 10 + logBlockSize ); - int groupSize = blockSize * superBlock.getS_blocks_per_group( ); + private int calculateGroupSize(Ext4SuperBlock superBlock) { + int logBlockSize = superBlock.getS_log_block_size(); + blockSize = (int) Math.pow(2, 10 + logBlockSize); + int groupSize = blockSize * superBlock.getS_blocks_per_group(); return groupSize; } - private int getSuperBlockStart( BinaryReader reader ) { + private int getSuperBlockStart(BinaryReader reader) { try { int padding = -1; int padStart = 0; boolean isPadding = false; - while ( padStart < 1024 ) { - if ( !isPadding ) { - padStart = ( int ) reader.getPointerIndex( ); + while (padStart < 1024) { + if (!isPadding) { + padStart = (int) reader.getPointerIndex(); } - padding = reader.readNextInt( ); - if ( padding == 0 ) { - if ( isPadding ) { + padding = reader.readNextInt(); + if (padding == 0) { + if (isPadding) { return padStart + 0x400; } isPadding = true; @@ -477,7 +474,7 @@ public class NewExt4Analyzer extends FileFormatAnalyzer { } } } - catch ( Exception e ) { + catch (Exception e) { } return -1; } diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/CFStringAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/CFStringAnalyzer.java index a0ba231e59..8e28506c20 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/CFStringAnalyzer.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/CFStringAnalyzer.java @@ -107,13 +107,13 @@ public class CFStringAnalyzer extends AbstractAnalyzer { .setComment(currentAddress, CommentType.REPEATABLE, "\"" + comment + "\",00"); - if (program.getSymbolTable().getGlobalSymbol(symbolString, - currentAddress) != null) { + if (program.getSymbolTable() + .getGlobalSymbol(symbolString, currentAddress) != null) { continue; } - Symbol mine = program.getSymbolTable().createLabel(currentAddress, symbolString, - SourceType.ANALYSIS); + Symbol mine = program.getSymbolTable() + .createLabel(currentAddress, symbolString, SourceType.ANALYSIS); mine.setPrimary(); } catch (CodeUnitInsertionException e) { diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/TestAnalyzer.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/TestAnalyzer.java index 8de29979ca..cdbc70d4b9 100644 --- a/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/TestAnalyzer.java +++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/macosx/analyzers/TestAnalyzer.java @@ -66,7 +66,7 @@ public class TestAnalyzer extends AbstractAnalyzer { program.getListing() .setComment(currentAddress, CommentType.PLATE, - "Address = " + currentAddress.toString()); + "Address = " + currentAddress.toString()); currentAddress = currentAddress.add(data.getLength()); } diff --git a/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/EHDataTypeUtilities.java b/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/EHDataTypeUtilities.java index c894305904..b4d69d50b6 100644 --- a/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/EHDataTypeUtilities.java +++ b/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/EHDataTypeUtilities.java @@ -276,7 +276,6 @@ public class EHDataTypeUtilities { // Make sure we have underscores in name dataTypeName = SymbolUtilities.replaceInvalidChars(dataTypeName, true); - SymbolTable symbolTable = program.getSymbolTable(); SymbolIterator symbols = symbolTable.getSymbolsAsIterator(address); for (Symbol symbol : symbols) { diff --git a/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/rtti/CreateVfTableBackgroundCmd.java b/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/rtti/CreateVfTableBackgroundCmd.java index 562ddef7fb..f45a80ce46 100644 --- a/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/rtti/CreateVfTableBackgroundCmd.java +++ b/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/cmd/data/rtti/CreateVfTableBackgroundCmd.java @@ -120,8 +120,7 @@ public class CreateVfTableBackgroundCmd extends AbstractCreateDataBackgroundCmd< String prefixString = ((demangledTypeDescriptor != null) ? (demangledTypeDescriptor + Namespace.DELIMITER) : ""); - data.setComment(CommentType.EOL, - "terminator for " + prefixString + VF_TABLE_LABEL); + data.setComment(CommentType.EOL, "terminator for " + prefixString + VF_TABLE_LABEL); return true; } return false; @@ -172,20 +171,22 @@ public class CreateVfTableBackgroundCmd extends AbstractCreateDataBackgroundCmd< if (rtti0Model == null) { return true; } - + // Label boolean shouldCreateComment = true; if (applyOptions.shouldCreateLabel()) { - shouldCreateComment = RttiUtil.createSymbolFromDemangledType(program, vfTableAddress, rtti0Model, - VF_TABLE_LABEL); + shouldCreateComment = RttiUtil.createSymbolFromDemangledType(program, vfTableAddress, + rtti0Model, VF_TABLE_LABEL); } // Plate Comment if (shouldCreateComment) { // comment created if a label was created, or createLabel option off - EHDataTypeUtilities.createPlateCommentIfNeeded(program, RttiUtil.CONST_PREFIX + - RttiUtil.getDescriptorTypeNamespace(rtti0Model) + Namespace.DELIMITER, - VF_TABLE_LABEL, null, vfTableAddress, applyOptions); + EHDataTypeUtilities + .createPlateCommentIfNeeded(program, + RttiUtil.CONST_PREFIX + RttiUtil.getDescriptorTypeNamespace(rtti0Model) + + Namespace.DELIMITER, + VF_TABLE_LABEL, null, vfTableAddress, applyOptions); } // Create functions that are referred to by the vf table. @@ -215,23 +216,23 @@ public class CreateVfTableBackgroundCmd extends AbstractCreateDataBackgroundCmd< if (rtti0Model == null) { return true; } - + monitor.checkCancelled(); // Label boolean shouldCreateComment = true; if (applyOptions.shouldCreateLabel()) { - shouldCreateComment = RttiUtil.createSymbolFromDemangledType(program, metaAddress, rtti0Model, - VF_TABLE_LABEL + NAME_SEPARATOR + META_LABEL + "_ptr"); + shouldCreateComment = RttiUtil.createSymbolFromDemangledType(program, metaAddress, + rtti0Model, VF_TABLE_LABEL + NAME_SEPARATOR + META_LABEL + "_ptr"); } // Plate Comment if (shouldCreateComment) { // comment created if a label was created, or createLabel option off EHDataTypeUtilities.createPlateCommentIfNeeded( - program, META_LABEL + " pointer for " + - RttiUtil.getDescriptorTypeNamespace(rtti0Model) + Namespace.DELIMITER, - VF_TABLE_LABEL, null, metaAddress, applyOptions); + program, META_LABEL + " pointer for " + + RttiUtil.getDescriptorTypeNamespace(rtti0Model) + Namespace.DELIMITER, + VF_TABLE_LABEL, null, metaAddress, applyOptions); } return true; diff --git a/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/plugin/prototype/MicrosoftCodeAnalyzerPlugin/PropagateExternalParametersAnalyzer.java b/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/plugin/prototype/MicrosoftCodeAnalyzerPlugin/PropagateExternalParametersAnalyzer.java index 7163f1ecf2..15bea6f042 100644 --- a/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/plugin/prototype/MicrosoftCodeAnalyzerPlugin/PropagateExternalParametersAnalyzer.java +++ b/Ghidra/Features/MicrosoftCodeAnalyzer/src/main/java/ghidra/app/plugin/prototype/MicrosoftCodeAnalyzerPlugin/PropagateExternalParametersAnalyzer.java @@ -267,8 +267,7 @@ public class PropagateExternalParametersAnalyzer extends AbstractAnalyzer { // use the 'results' to propagate param info to the local variables, data, and params of // the calling function Msg.trace(this, "Processing propagation results - count: " + results.size()); - for (int i = 0; i < results.size(); i++) { - PushedParamInfo paramInfo = results.get(i); + for (PushedParamInfo paramInfo : results) { Address paramAddress = paramInfo.getAddress(); Instruction instruction = listing.getInstructionAt(paramAddress); diff --git a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockCommentsManager.java b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockCommentsManager.java index dad5bf1f20..c1cef7ba93 100644 --- a/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockCommentsManager.java +++ b/Ghidra/Features/PDB/src/main/java/ghidra/app/util/pdb/pdbapplicator/BlockCommentsManager.java @@ -120,9 +120,8 @@ public class BlockCommentsManager { CommentType.PRE); } for (Map.Entry entry : blockPostComments.entrySet()) { - CodeUnit codeUnit = program.getListing() - .getCodeUnitContaining( - entry.getKey().add(addressDelta)); + CodeUnit codeUnit = + program.getListing().getCodeUnitContaining(entry.getKey().add(addressDelta)); if (codeUnit == null) { Msg.warn(this, "PDB error: null Code unit"); } diff --git a/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffApplyMergeTest.java b/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffApplyMergeTest.java index ca257033c4..659f1f3573 100644 --- a/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffApplyMergeTest.java +++ b/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffApplyMergeTest.java @@ -173,13 +173,8 @@ public class DiffApplyMergeTest extends DiffApplyTestAdapter { setDiffSelection(as); apply(); - // Check the results. We should have both tags now in the target program - // (Program 1), so check the number of tags and make sure the names are - // correct. - Iterator iter = f1.getTags().iterator(); List tagNames = new ArrayList<>(); - while (iter.hasNext()) { - FunctionTag tag = iter.next(); + for (FunctionTag tag : f1.getTags()) { tagNames.add(tag.getName()); } assertEquals(tagNames.size(), 2); diff --git a/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffTestAdapter.java b/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffTestAdapter.java index d6ac84ce36..7c482ca6c4 100644 --- a/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffTestAdapter.java +++ b/Ghidra/Features/ProgramDiff/src/test.slow/java/ghidra/app/plugin/core/diff/DiffTestAdapter.java @@ -164,49 +164,49 @@ public class DiffTestAdapter extends AbstractGhidraHeadedIntegrationTest { builder.createExternalReference("0x01001034", "yourLib.dll", "GetStuff", "0x77f42caa", 0); // comments - builder.createComment("1002040", "Plate in P1.", CodeUnit.PLATE_COMMENT); - builder.createComment("1002040", "Pre in P1.", CodeUnit.PRE_COMMENT); - builder.createComment("1002040", "EOL in P1.", CodeUnit.EOL_COMMENT); - builder.createComment("1002040", "Repeatable in P1.", CodeUnit.REPEATABLE_COMMENT); - builder.createComment("1002040", "Post in P1.", CodeUnit.POST_COMMENT); + builder.createComment("1002040", "Plate in P1.", CommentType.PLATE); + builder.createComment("1002040", "Pre in P1.", CommentType.PRE); + builder.createComment("1002040", "EOL in P1.", CommentType.EOL); + builder.createComment("1002040", "Repeatable in P1.", CommentType.REPEATABLE); + builder.createComment("1002040", "Post in P1.", CommentType.POST); - builder.createComment("1002304", "EOL comment", CodeUnit.EOL_COMMENT); - builder.createComment("1002306", "\"Pre Comment\"", CodeUnit.PRE_COMMENT); - builder.createComment("100230b", "Plate Comment", CodeUnit.PRE_COMMENT); - builder.createComment("100230b", "Post Comment", CodeUnit.PRE_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.PRE_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.EOL_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.POST_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.REPEATABLE_COMMENT); - builder.createComment("100230d", "simple comment", CodeUnit.PLATE_COMMENT); + builder.createComment("1002304", "EOL comment", CommentType.EOL); + builder.createComment("1002306", "\"Pre Comment\"", CommentType.PRE); + builder.createComment("100230b", "Plate Comment", CommentType.PRE); + builder.createComment("100230b", "Post Comment", CommentType.PRE); + builder.createComment("100230d", "simple comment", CommentType.PRE); + builder.createComment("100230d", "simple comment", CommentType.EOL); + builder.createComment("100230d", "simple comment", CommentType.POST); + builder.createComment("100230d", "simple comment", CommentType.REPEATABLE); + builder.createComment("100230d", "simple comment", CommentType.PLATE); builder.createComment("1002312", "\"My comment that the other comment is in.\"", - CodeUnit.PRE_COMMENT); + CommentType.PRE); builder.createComment("1002312", "My comment that the other comment is in.", - CodeUnit.EOL_COMMENT); + CommentType.EOL); builder.createComment("1002312", "My comment that the other comment is in.", - CodeUnit.POST_COMMENT); + CommentType.POST); builder.createComment("1002312", "My comment that the other comment is in.", - CodeUnit.PLATE_COMMENT); + CommentType.PLATE); - builder.createComment("1002336", "ONE: Repeatable comment.", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002336", "ONE: Repeatable comment.", CommentType.REPEATABLE); - builder.createComment("1002346", "Easy as pie.", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002346", "Easy as pie.", CommentType.REPEATABLE); - builder.createComment("1002350", "Once upon a", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002350", "Once upon a", CommentType.REPEATABLE); - builder.createComment("100238f", "EOL: Program1", CodeUnit.EOL_COMMENT); + builder.createComment("100238f", "EOL: Program1", CommentType.EOL); - builder.createComment("1002395", "Pre: Program1", CodeUnit.PRE_COMMENT); + builder.createComment("1002395", "Pre: Program1", CommentType.PRE); -// builder.createComment("100239d", "Plate: Program1", CodeUnit.PLATE_COMMENT); - builder.createComment("100239d", "Post: Program1", CodeUnit.POST_COMMENT); +// builder.createComment("100239d", "Plate: Program1", CommentType.PLATE); + builder.createComment("100239d", "Post: Program1", CommentType.POST); - builder.createComment("10030d2", "FUNCTION", CodeUnit.PLATE_COMMENT); + builder.createComment("10030d2", "FUNCTION", CommentType.PLATE); - builder.createComment("100355f", "This is a function.", CodeUnit.PLATE_COMMENT); + builder.createComment("100355f", "This is a function.", CommentType.PLATE); - builder.createComment("100415a", "This is my function", CodeUnit.PLATE_COMMENT); + builder.createComment("100415a", "This is my function", CommentType.PLATE); // functions DataType dt = new ByteDataType(); @@ -333,54 +333,50 @@ public class DiffTestAdapter extends AbstractGhidraHeadedIntegrationTest { // comments builder.createComment("100204c", "My multi-line plate\ncomment for program2.", - CodeUnit.PLATE_COMMENT); + CommentType.PLATE); builder.createComment("100204c", "My multi-line pre\ncomment for program2.", - CodeUnit.PRE_COMMENT); + CommentType.PRE); builder.createComment("100204c", "My multi-line EOL\ncomment for program2.", - CodeUnit.EOL_COMMENT); + CommentType.EOL); builder.createComment("100204c", "My multi-line repeatable\ncomment for program2.", - CodeUnit.REPEATABLE_COMMENT); + CommentType.REPEATABLE); builder.createComment("100204c", "My multi-line post\ncomment for program2.", - CodeUnit.POST_COMMENT); + CommentType.POST); + builder.createComment("100230d", "This is a simple comment for example.", CommentType.PRE); + builder.createComment("100230d", "This is a simple comment for example.", CommentType.EOL); + builder.createComment("100230d", "This is a simple comment for example.", CommentType.POST); builder.createComment("100230d", "This is a simple comment for example.", - CodeUnit.PRE_COMMENT); + CommentType.REPEATABLE); builder.createComment("100230d", "This is a simple comment for example.", - CodeUnit.EOL_COMMENT); - builder.createComment("100230d", "This is a simple comment for example.", - CodeUnit.POST_COMMENT); - builder.createComment("100230d", "This is a simple comment for example.", - CodeUnit.REPEATABLE_COMMENT); - builder.createComment("100230d", "This is a simple comment for example.", - CodeUnit.PLATE_COMMENT); + CommentType.PLATE); - builder.createComment("1002312", "My comment", CodeUnit.PRE_COMMENT); - builder.createComment("1002312", "My comment", CodeUnit.EOL_COMMENT); - builder.createComment("1002312", "My comment", CodeUnit.POST_COMMENT); - builder.createComment("1002312", "My comment", CodeUnit.PLATE_COMMENT); + builder.createComment("1002312", "My comment", CommentType.PRE); + builder.createComment("1002312", "My comment", CommentType.EOL); + builder.createComment("1002312", "My comment", CommentType.POST); + builder.createComment("1002312", "My comment", CommentType.PLATE); - builder.createComment("1002329", "Before the code unit", CodeUnit.PRE_COMMENT); - builder.createComment("1002329", "End of the line.", CodeUnit.EOL_COMMENT); - builder.createComment("1002329", "After the code unit", CodeUnit.POST_COMMENT); - builder.createComment("1002329", "PLATE", CodeUnit.PLATE_COMMENT); + builder.createComment("1002329", "Before the code unit", CommentType.PRE); + builder.createComment("1002329", "End of the line.", CommentType.EOL); + builder.createComment("1002329", "After the code unit", CommentType.POST); + builder.createComment("1002329", "PLATE", CommentType.PLATE); - builder.createComment("1002336", "TWO: Repeatable comment.", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002336", "TWO: Repeatable comment.", CommentType.REPEATABLE); - builder.createComment("1002346", "Easy", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002346", "Easy", CommentType.REPEATABLE); - builder.createComment("1002350", "Once upon a time...", CodeUnit.REPEATABLE_COMMENT); + builder.createComment("1002350", "Once upon a time...", CommentType.REPEATABLE); - builder.createComment("100238f", "EOL: Program2", CodeUnit.EOL_COMMENT); + builder.createComment("100238f", "EOL: Program2", CommentType.EOL); - builder.createComment("1002395", "Pre: Program2", CodeUnit.PRE_COMMENT); + builder.createComment("1002395", "Pre: Program2", CommentType.PRE); -// builder.createComment("100239d", "Plate: Program2", CodeUnit.PLATE_COMMENT); - builder.createComment("100239d", "Post: Program2", CodeUnit.POST_COMMENT); +// builder.createComment("100239d", "Plate: Program2", CommentType.PLATE); + builder.createComment("100239d", "Post: Program2", CommentType.POST); - builder.createComment("1002a91", "FUNCTION", CodeUnit.PLATE_COMMENT); + builder.createComment("1002a91", "FUNCTION", CommentType.PLATE); - builder.createComment("100415a", "This is my function for testing diff", - CodeUnit.PLATE_COMMENT); + builder.createComment("100415a", "This is my function for testing diff", CommentType.PLATE); // functions DataType dt = new ByteDataType(); diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtComment.java b/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtComment.java index 4235be079a..beb5070043 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtComment.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtComment.java @@ -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,15 +16,17 @@ package sarif.export.dd; import ghidra.program.model.data.ISF.IsfObject; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Data; +import sarif.managers.CommentsSarifMgr; public class ExtComment implements IsfObject { - int commentType; + String commentType; String comment; - public ExtComment(Data data, int type) { - commentType = type; + public ExtComment(Data data, CommentType type) { + commentType = CommentsSarifMgr.getCommentTypeString(type); comment = data.getComment(type); } diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtCommentSet.java b/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtCommentSet.java index 37cb7d93a5..ec58861f49 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtCommentSet.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/ExtCommentSet.java @@ -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. @@ -15,15 +15,12 @@ */ package sarif.export.dd; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import ghidra.program.model.data.ISF.IsfObject; import ghidra.program.model.data.ISF.IsfSetting; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Data; -import sarif.managers.CommentsSarifMgr; public class ExtCommentSet implements IsfObject { @@ -49,8 +46,7 @@ public class ExtCommentSet implements IsfObject { } private void exportComments(Data data) { - for (int i = 0; i < CommentsSarifMgr.COMMENT_TYPES.length; i++) { - int type = CommentsSarifMgr.COMMENT_TYPES[i]; + for (CommentType type : CommentType.values()) { String cval = data.getComment(type); if (cval != null) { if (comment == null) { diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/SarifDataWriter.java b/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/SarifDataWriter.java index ca076105a1..1a592b6144 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/SarifDataWriter.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/export/dd/SarifDataWriter.java @@ -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. @@ -28,7 +28,7 @@ import sarif.export.SarifObject; import sarif.managers.DefinedDataSarifMgr; public class SarifDataWriter extends AbstractExtWriter { - + private List definedData = new ArrayList<>(); public SarifDataWriter(List target, Writer baseWriter) throws IOException { @@ -42,14 +42,15 @@ public class SarifDataWriter extends AbstractExtWriter { root.add("definedData", objects); } - private void genData(TaskMonitor monitor) throws CancelledException, IOException{ + private void genData(TaskMonitor monitor) throws CancelledException { monitor.initialize(definedData.size()); for (Data d : definedData) { ExtData isf = new ExtData(d); - SarifObject sarif = new SarifObject("DefinedData", DefinedDataSarifMgr.KEY, getTree(isf), d.getMinAddress(), d.getMaxAddress()); + SarifObject sarif = new SarifObject("DefinedData", DefinedDataSarifMgr.KEY, + getTree(isf), d.getMinAddress(), d.getMaxAddress()); objects.add(getTree(sarif)); monitor.increment(); } } - + } diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/export/extlib/SarifClassesNamespaceWriter.java b/Ghidra/Features/Sarif/src/main/java/sarif/export/extlib/SarifClassesNamespaceWriter.java index 003c868de4..b52171ebff 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/export/extlib/SarifClassesNamespaceWriter.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/export/extlib/SarifClassesNamespaceWriter.java @@ -17,19 +17,12 @@ package sarif.export.extlib; import java.io.IOException; import java.io.Writer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import java.util.*; import com.google.gson.JsonArray; import ghidra.program.model.listing.GhidraClass; -import ghidra.program.model.symbol.ExternalLocation; -import ghidra.program.model.symbol.ExternalManager; -import ghidra.program.model.symbol.SourceType; -import ghidra.program.model.symbol.Symbol; -import ghidra.program.model.symbol.SymbolIterator; -import ghidra.program.model.symbol.SymbolTable; +import ghidra.program.model.symbol.*; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; import sarif.export.AbstractExtWriter; @@ -42,8 +35,8 @@ public class SarifClassesNamespaceWriter extends AbstractExtWriter { private ExternalManager externalManager; private SymbolTable symbolTable; - public SarifClassesNamespaceWriter(ExternalManager externalManager, SymbolTable symbolTable, List request, Writer baseWriter) - throws IOException { + public SarifClassesNamespaceWriter(ExternalManager externalManager, SymbolTable symbolTable, + List request, Writer baseWriter) throws IOException { super(baseWriter); this.externalManager = externalManager; this.symbolTable = symbolTable; @@ -56,7 +49,7 @@ public class SarifClassesNamespaceWriter extends AbstractExtWriter { root.add("definedData", objects); } - private void genClasses(TaskMonitor monitor) throws CancelledException, IOException { + private void genClasses(TaskMonitor monitor) throws CancelledException { monitor.initialize(classes.size()); Iterator classNamespaces = symbolTable.getClassNamespaces(); while (classNamespaces.hasNext()) { @@ -73,18 +66,19 @@ public class SarifClassesNamespaceWriter extends AbstractExtWriter { path = ""; } ExtLibrary lib = new ExtLibrary(clsName, path, SourceType.DEFAULT); - SarifObject sarif = new SarifObject(ExternalLibSarifMgr.SUBKEY0, ExternalLibSarifMgr.KEY, getTree(lib), null); + SarifObject sarif = new SarifObject(ExternalLibSarifMgr.SUBKEY0, ExternalLibSarifMgr.KEY, + getTree(lib), null); objects.add(getTree(sarif)); - - SymbolIterator symbols = symbolTable.getSymbols(cls); + if (cls.isExternal()) { + SymbolIterator symbols = symbolTable.getSymbols(cls); while (symbols.hasNext()) { Symbol sym = symbols.next(); ExternalLocation loc = externalManager.getExternalLocation(sym); if (loc != null) { ExtLibraryLocation obj = new ExtLibraryLocation(loc); - SarifObject sarif2 = new SarifObject(ExternalLibSarifMgr.SUBKEY1, ExternalLibSarifMgr.KEY, getTree(obj), - loc.getAddress(), loc.getAddress()); + SarifObject sarif2 = new SarifObject(ExternalLibSarifMgr.SUBKEY1, + ExternalLibSarifMgr.KEY, getTree(obj), loc.getAddress(), loc.getAddress()); objects.add(getTree(sarif2)); } } diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/managers/CommentsSarifMgr.java b/Ghidra/Features/Sarif/src/main/java/sarif/managers/CommentsSarifMgr.java index b1979beae9..bf98c2ad72 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/managers/CommentsSarifMgr.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/managers/CommentsSarifMgr.java @@ -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,23 +16,14 @@ package sarif.managers; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import com.google.gson.JsonArray; import generic.stl.Pair; -import ghidra.app.util.CommentTypes; import ghidra.app.util.importer.MessageLog; -import ghidra.program.model.address.Address; -import ghidra.program.model.address.AddressFormatException; -import ghidra.program.model.address.AddressIterator; -import ghidra.program.model.address.AddressSetView; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.CodeUnitIterator; -import ghidra.program.model.listing.Instruction; -import ghidra.program.model.listing.Program; +import ghidra.program.model.address.*; +import ghidra.program.model.listing.*; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskLauncher; import ghidra.util.task.TaskMonitor; @@ -48,34 +39,38 @@ public class CommentsSarifMgr extends SarifMgr { public static String KEY = "COMMENTS"; public static String SUBKEY = "Comment"; - public static int[] COMMENT_TYPES; - public static String[] COMMENT_TAGS; - - public static String[] COMMENT_TAGS2 = { "end-of-line", "pre", "post", "plate", "repeatable" }; + static String[] commentTags; + static Map commentTypeMap; static { - COMMENT_TYPES = CommentTypes.getTypes(); - COMMENT_TAGS = new String[COMMENT_TYPES.length]; - for (int i = 0; i < COMMENT_TAGS.length; i++) { + CommentType[] commentTypes = CommentType.values(); + commentTags = new String[commentTypes.length]; + commentTypeMap = new HashMap<>(); - switch (COMMENT_TYPES[i]) { - case CodeUnit.PRE_COMMENT: - COMMENT_TAGS[i] = "pre"; - break; - case CodeUnit.POST_COMMENT: - COMMENT_TAGS[i] = "post"; - break; - case CodeUnit.EOL_COMMENT: - COMMENT_TAGS[i] = "end-of-line"; - break; - case CodeUnit.PLATE_COMMENT: - COMMENT_TAGS[i] = "plate"; - break; - case CodeUnit.REPEATABLE_COMMENT: - COMMENT_TAGS[i] = "repeatable"; - break; + for (CommentType type : commentTypes) { + String tag; + switch (type) { + case PRE: + tag = "pre"; + break; + case POST: + tag = "post"; + break; + case EOL: + tag = "end-of-line"; + break; + case PLATE: + tag = "plate"; + break; + case REPEATABLE: + tag = "repeatable"; + break; + default: + throw new RuntimeException("Missing comment type support: " + type.name()); } + commentTags[type.ordinal()] = tag; + commentTypeMap.put(tag, type); } } @@ -88,8 +83,8 @@ public class CommentsSarifMgr extends SarifMgr { //////////////////////////// @Override - public boolean read(Map result, SarifProgramOptions options, TaskMonitor monitor) - throws AddressFormatException, CancelledException { + public boolean read(Map result, SarifProgramOptions options, + TaskMonitor monitor) throws AddressFormatException, CancelledException { processComment(result); return true; } @@ -100,8 +95,8 @@ public class CommentsSarifMgr extends SarifMgr { String typeStr = (String) result.get("kind"); String comment = (String) result.get("value"); boolean standard = (boolean) result.get("standard"); - int commentType = getCommentType(typeStr); - if (commentType < 0) { + CommentType commentType = getCommentType(typeStr); + if (commentType == null) { log.appendMsg("Unknown comment type: " + typeStr); return; } @@ -113,32 +108,35 @@ public class CommentsSarifMgr extends SarifMgr { String currCmt = cu.getComment(commentType); if (currCmt == null || currCmt.length() == 0) { cu.setComment(commentType, comment); - } else if (currCmt.indexOf(comment) < 0) { + } + else if (currCmt.indexOf(comment) < 0) { log.appendMsg("Merged " + typeStr + " comment at " + addr); cu.setComment(commentType, currCmt + "\n" + comment); } } - } else { + } + else { String currCmt = listing.getComment(commentType, addr); if (currCmt == null || currCmt.length() == 0) { listing.setComment(addr, commentType, comment); - } else if (currCmt.indexOf(comment) < 0) { + } + else if (currCmt.indexOf(comment) < 0) { log.appendMsg("Merged " + typeStr + " comment at " + addr); listing.setComment(addr, commentType, currCmt + "\n" + comment); } } - } catch (Exception e) { + } + catch (Exception e) { log.appendException(e); } } - private int getCommentType(String typeStr) { - for (int i = 0; i < COMMENT_TAGS.length; i++) { - if (COMMENT_TAGS[i].equals(typeStr)) { - return COMMENT_TYPES[i]; - } - } - return -1; // unknown comment + public static CommentType getCommentType(String typeTagStr) { + return commentTypeMap.get(typeTagStr); + } + + public static String getCommentTypeString(CommentType type) { + return commentTags[type.ordinal()]; } ///////////////////////////// @@ -152,8 +150,10 @@ public class CommentsSarifMgr extends SarifMgr { * @param set address set that is either the entire program or a selection * @param monitor monitor that can be canceled should be written * @throws IOException + * @throws CancelledException */ - void write(JsonArray results, AddressSetView set, TaskMonitor monitor) throws IOException, CancelledException { + void write(JsonArray results, AddressSetView set, TaskMonitor monitor) + throws IOException, CancelledException { monitor.setMessage("Writing COMMENTS ..."); if (set == null) { @@ -166,10 +166,11 @@ public class CommentsSarifMgr extends SarifMgr { while (iter.hasNext()) { monitor.checkCancelled(); CodeUnit cu = iter.next(); - for (int i = 0; i < COMMENT_TYPES.length; i++) { - String[] comments = cu.getCommentAsArray(COMMENT_TYPES[i]); + for (CommentType type : CommentType.values()) { + String[] comments = cu.getCommentAsArray(type); + String typeStr = getCommentTypeString(type); for (String c : comments) { - Pair pair = new Pair<>(COMMENT_TAGS[i], c); + Pair pair = new Pair<>(typeStr, c); request0.add(new Pair>(cu, pair)); } } @@ -178,15 +179,15 @@ public class CommentsSarifMgr extends SarifMgr { writeAsSARIF0(request0, results); List>> request1 = new ArrayList<>(); - for (int i = 0; i < COMMENT_TAGS2.length; i++) { - AddressIterator aiter = listing.getCommentAddressIterator(i, set, true); + for (CommentType type : CommentType.values()) { + AddressIterator aiter = listing.getCommentAddressIterator(type, set, true); while (aiter.hasNext()) { monitor.checkCancelled(); Address a = aiter.next(); CodeUnit cu = listing.getCodeUnitContaining(a); if (cu instanceof Instruction && !a.equals(cu.getMinAddress())) { - String c = listing.getComment(i, a); - Pair pair = new Pair<>(COMMENT_TAGS2[i], c); + String c = listing.getComment(type, a); + Pair pair = new Pair<>(getCommentTypeString(type), c); request1.add(new Pair>(a, pair)); } } @@ -196,14 +197,14 @@ public class CommentsSarifMgr extends SarifMgr { } - public static void writeAsSARIF0(List>> request, JsonArray results) - throws IOException { + public static void writeAsSARIF0(List>> request, + JsonArray results) throws IOException { SarifCommentWriter writer = new SarifCommentWriter(request, null); new TaskLauncher(new SarifWriterTask(SUBKEY, writer, results), null); } - public static void writeAsSARIF1(List>> request, JsonArray results) - throws IOException { + public static void writeAsSARIF1(List>> request, + JsonArray results) throws IOException { SarifCommentWriter writer = new SarifCommentWriter(null, request); new TaskLauncher(new SarifWriterTask(SUBKEY, writer, results), null); } diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/managers/DefinedDataSarifMgr.java b/Ghidra/Features/Sarif/src/main/java/sarif/managers/DefinedDataSarifMgr.java index 9052d8e427..8d2cfeb3f1 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/managers/DefinedDataSarifMgr.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/managers/DefinedDataSarifMgr.java @@ -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,28 +16,15 @@ package sarif.managers; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import com.google.gson.JsonArray; import ghidra.app.util.importer.MessageLog; import ghidra.docking.settings.Settings; -import ghidra.program.model.address.Address; -import ghidra.program.model.address.AddressOverflowException; -import ghidra.program.model.address.AddressSet; -import ghidra.program.model.address.AddressSetView; -import ghidra.program.model.data.CategoryPath; -import ghidra.program.model.data.DataType; -import ghidra.program.model.data.DataTypeInstance; -import ghidra.program.model.data.DataTypeManager; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.CodeUnitIterator; -import ghidra.program.model.listing.Data; -import ghidra.program.model.listing.DataIterator; -import ghidra.program.model.listing.Listing; -import ghidra.program.model.listing.Program; +import ghidra.program.model.address.*; +import ghidra.program.model.data.*; +import ghidra.program.model.listing.*; import ghidra.program.model.mem.DumbMemBufferImpl; import ghidra.program.model.util.CodeUnitInsertionException; import ghidra.util.exception.CancelledException; @@ -62,8 +49,8 @@ public class DefinedDataSarifMgr extends SarifMgr { @SuppressWarnings("unchecked") @Override - public boolean read(Map result, SarifProgramOptions options, TaskMonitor monitor) - throws CancelledException { + public boolean read(Map result, SarifProgramOptions options, + TaskMonitor monitor) throws CancelledException { Listing listing = program.getListing(); DataTypeManager dataManager = program.getDataTypeManager(); @@ -80,7 +67,8 @@ public class DefinedDataSarifMgr extends SarifMgr { String dataTypeName = (String) result.get("typeName"); String typeLocation = (String) result.get("typeLocation"); - CategoryPath path = typeLocation != null ? new CategoryPath(typeLocation) : CategoryPath.ROOT; + CategoryPath path = + typeLocation != null ? new CategoryPath(typeLocation) : CategoryPath.ROOT; DataType dt = dtParser.parseDataType(dataTypeName, path, size); if (dt == null) { @@ -90,7 +78,8 @@ public class DefinedDataSarifMgr extends SarifMgr { } } if (dt == null) { - log.appendMsg("Defined root: unknown datatype: " + dataTypeName + " in category: " + path); + log.appendMsg( + "Defined root: unknown datatype: " + dataTypeName + " in category: " + path); return false; } @@ -104,17 +93,20 @@ public class DefinedDataSarifMgr extends SarifMgr { Map comments = (Map) result.get("nested"); processComment(comments, data); - } catch (CodeUnitInsertionException e) { + } + catch (CodeUnitInsertionException e) { Data d = listing.getDefinedDataAt(addr); if (d == null || !d.getDataType().isEquivalent(dt)) { log.appendMsg(e.getMessage()); } - } catch (Exception e) { + } + catch (Exception e) { log.appendException(e); } - } catch (AddressOverflowException e1) { + } + catch (AddressOverflowException e1) { log.appendException(e1); - } + } return true; } @@ -147,10 +139,13 @@ public class DefinedDataSarifMgr extends SarifMgr { if (localComments != null) { for (Map lmap : localComments) { String comment = (String) lmap.get("comment"); - int type = (int) (double) lmap.get("commentType"); - String existing = data.getComment(type); - if (existing == null || !existing.equals(comment)) { - data.setComment(type, comment); + String typeStr = (String) lmap.get("commentType"); + CommentType type = CommentsSarifMgr.getCommentType(typeStr); + if (type != null) { + String existing = data.getComment(type); + if (existing == null || !existing.equals(comment)) { + data.setComment(type, comment); + } } } } @@ -166,7 +161,8 @@ public class DefinedDataSarifMgr extends SarifMgr { } } } - Map> embedded = (Map>) c.get("embedded"); + Map> embedded = + (Map>) c.get("embedded"); if (embedded != null) { for (String index : embedded.keySet()) { Data component = data.getComponent(Integer.parseInt(index)); @@ -182,14 +178,16 @@ public class DefinedDataSarifMgr extends SarifMgr { if (dti != null) { boolean doClear = false; Address maxAddr = addr.add(dti.getLength() - 1); - CodeUnitIterator codeUnits = listing.getCodeUnitIterator(CodeUnit.DEFINED_DATA_PROPERTY, new AddressSet(addr, maxAddr), true); + CodeUnitIterator codeUnits = listing.getCodeUnitIterator(CodeUnit.DEFINED_DATA_PROPERTY, + new AddressSet(addr, maxAddr), true); while (codeUnits.hasNext()) { CodeUnit cu = codeUnits.next(); if (cu instanceof Data) { if (((Data) cu).isDefined()) { doClear = true; } - } else { + } + else { return; // don't clear instructions } } @@ -203,7 +201,8 @@ public class DefinedDataSarifMgr extends SarifMgr { // SARIF WRITE CURRENT DTD // ///////////////////////////// - void write(JsonArray results, AddressSetView addrset, TaskMonitor monitor) throws IOException, CancelledException { + void write(JsonArray results, AddressSetView addrset, TaskMonitor monitor) + throws IOException, CancelledException { monitor.setMessage("Writing DATA ..."); List request = new ArrayList<>(); @@ -216,7 +215,8 @@ public class DefinedDataSarifMgr extends SarifMgr { writeAsSARIF(program, request, results); } - public static void writeAsSARIF(Program program, List request, JsonArray results) throws IOException { + public static void writeAsSARIF(Program program, List request, JsonArray results) + throws IOException { SarifDataWriter writer = new SarifDataWriter(request, null); new TaskLauncher(new SarifWriterTask("DefinedData", writer, results), null); } diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/managers/FunctionsSarifMgr.java b/Ghidra/Features/Sarif/src/main/java/sarif/managers/FunctionsSarifMgr.java index 104b53479b..d1002947f5 100644 --- a/Ghidra/Features/Sarif/src/main/java/sarif/managers/FunctionsSarifMgr.java +++ b/Ghidra/Features/Sarif/src/main/java/sarif/managers/FunctionsSarifMgr.java @@ -50,8 +50,8 @@ public class FunctionsSarifMgr extends SarifMgr { public final static String LIB_BOOKMARK_CATEGORY = "Library Identification"; public final static String FID_BOOKMARK_CATEGORY = "Function ID Analyzer"; - public static final Set LIBRARY_BOOKMARK_CATEGORY_STRINGS = Set.of(LIB_BOOKMARK_CATEGORY, - FID_BOOKMARK_CATEGORY); + public static final Set LIBRARY_BOOKMARK_CATEGORY_STRINGS = + Set.of(LIB_BOOKMARK_CATEGORY, FID_BOOKMARK_CATEGORY); private DtParser dtParser; private Library externalNamespace; @@ -65,8 +65,8 @@ public class FunctionsSarifMgr extends SarifMgr { //////////////////////////// @Override - protected void readResults(List> list, SarifProgramOptions options, TaskMonitor monitor) - throws AddressFormatException, CancelledException { + protected void readResults(List> list, SarifProgramOptions options, + TaskMonitor monitor) throws AddressFormatException, CancelledException { if (list != null) { monitor.setMessage("Processing " + key + "..."); monitor.setMaximum(list.size() * 2); @@ -83,7 +83,8 @@ public class FunctionsSarifMgr extends SarifMgr { monitor.increment(); } monitor.incrementProgress(); - } else { + } + else { monitor.setMessage("Skipping over " + key + " ..."); } } @@ -104,7 +105,7 @@ public class FunctionsSarifMgr extends SarifMgr { * * * @param result the parser - * @param overwriteConflicts true to overwrite any conflicts + * @param options * @param monitor the task monitor * @throws AddressFormatException if any address is not parsable * @throws CancelledException if the operation is cancelled through the @@ -112,8 +113,8 @@ public class FunctionsSarifMgr extends SarifMgr { */ @SuppressWarnings("unchecked") @Override - public boolean read(Map result, SarifProgramOptions options, TaskMonitor monitor) - throws AddressFormatException, CancelledException { + public boolean read(Map result, SarifProgramOptions options, + TaskMonitor monitor) throws AddressFormatException, CancelledException { DataTypeManager dataManager = listing.getDataTypeManager(); BuiltInDataTypeManager builtInMgr = BuiltInDataTypeManager.getDataTypeManager(); @@ -122,10 +123,10 @@ public class FunctionsSarifMgr extends SarifMgr { dtParser = new DtParser(dataManager); try { - String key = (String) result.get("Message"); + String msgKey = (String) result.get("Message"); boolean isThunk = (boolean) result.get("isThunk"); boolean process = (firstPass && !isThunk) || (!firstPass && isThunk); - if (!key.equals("Function") || !process) { + if (!msgKey.equals("Function") || !process) { return true; } @@ -139,17 +140,20 @@ public class FunctionsSarifMgr extends SarifMgr { for (Symbol symbol : symbols) { SourceType srcType = symbol.getSource(); if (!srcType.equals(SourceType.DEFAULT)) { - program.getSymbolTable().createLabel(entryPoint, symbol.getName(true), srcType); + program.getSymbolTable() + .createLabel(entryPoint, symbol.getName(true), srcType); } } String source = (String) result.get("sourceType"); - SourceType sourceType = source.equals("DEFAULT") ? SourceType.IMPORTED : getSourceType(source); + SourceType sourceType = + source.equals("DEFAULT") ? SourceType.IMPORTED : getSourceType(source); String typeInfoComment = setProperties(result, func, entryPoint); // Process stack List stackParams = new ArrayList<>(); - List> regVars = (List>) result.get("regVars"); + List> regVars = + (List>) result.get("regVars"); for (Map var : regVars) { readRegisterVars(var, func, stackParams); } @@ -174,16 +178,16 @@ public class FunctionsSarifMgr extends SarifMgr { plist = formalParams; } - if (plist != null) { - updateFunction(func, retImpl, plist, sourceType); - } + updateFunction(func, retImpl, plist, sourceType); postProcess(result, func, stack); - } catch (Exception e) { + } + catch (Exception e) { log.appendException(e); } - } finally { + } + finally { builtInMgr.close(); } return true; @@ -196,21 +200,22 @@ public class FunctionsSarifMgr extends SarifMgr { } Address entryPoint = parseAddress(factory, entryPointStr); if (entryPoint == null) { - throw new AddressFormatException("Incompatible Function Entry Point Address: " + entryPointStr); + throw new AddressFormatException( + "Incompatible Function Entry Point Address: " + entryPointStr); } return entryPoint; } private Function createFunction(Map result, boolean isThunk, Address entryPoint) - throws InvalidInputException, OverlappingFunctionException, DuplicateNameException, - AddressOverflowException { + throws InvalidInputException, OverlappingFunctionException, AddressOverflowException { AddressSet body = new AddressSet(entryPoint, entryPoint); getLocations(result, body); Function func = program.getFunctionManager().getFunctionAt(entryPoint); if (func == null) { String source = (String) result.get("sourceType"); SourceType sourceType = getSourceType(source); - func = program.getFunctionManager().createFunction(null, null, entryPoint, body, sourceType); + func = program.getFunctionManager() + .createFunction(null, null, entryPoint, body, sourceType); } String name = (String) result.get("name"); @@ -221,25 +226,29 @@ public class FunctionsSarifMgr extends SarifMgr { return func; } - private Library getExternalNamespace(Program program, MessageLog log) { + private Library getExternalNamespace() { if (externalNamespace == null) { int txId = program.startTransaction("SARIF FunctionMgr"); try { SymbolTable symbolTable = program.getSymbolTable(); Symbol extLib = symbolTable.getLibrarySymbol(""); if (extLib == null) { - externalNamespace = symbolTable.createExternalLibrary(Library.UNKNOWN, SourceType.IMPORTED); + externalNamespace = + symbolTable.createExternalLibrary(Library.UNKNOWN, SourceType.IMPORTED); } - } catch (Exception e) { + } + catch (Exception e) { log.appendException(e); - } finally { + } + finally { program.endTransaction(txId, true); } } return externalNamespace; } - private void setName(Address entryPoint, Function func, String name, Map result) { + private void setName(Address entryPoint, Function func, String name, + Map result) { SymbolPath path = new SymbolPath(name); if (name != null) { String nss = (String) result.get("namespace"); @@ -262,22 +271,25 @@ public class FunctionsSarifMgr extends SarifMgr { if (parent != null && !parent.getName().equals(ns.getName())) { Boolean isClass = (Boolean) result.get("namespaceIsClass"); String source = (String) result.get("sourceType"); - SourceType sourceType = source.equals("DEFAULT") ? SourceType.IMPORTED : getSourceType(source); - ns = walkNamespace(program.getGlobalNamespace(), parent.getPath() + "::", entryPoint, - sourceType, isClass); + SourceType sourceType = + source.equals("DEFAULT") ? SourceType.IMPORTED : getSourceType(source); + ns = walkNamespace(program.getGlobalNamespace(), parent.getPath() + "::", + entryPoint, sourceType, isClass); symbol.setNameAndNamespace(name, ns, getSourceType("DEFAULT")); return; } } if (path.getName().contains(Library.UNKNOWN)) { - ns = getExternalNamespace(program, log); + ns = getExternalNamespace(); } if (ns.getParentNamespace() == null) { symbol.setName(name, getSourceType("DEFAULT")); - } else { + } + else { symbol.setNameAndNamespace(name, ns.getParentNamespace(), getSourceType("DEFAULT")); // symbol.getSource()); } - } catch (Exception e) { + } + catch (Exception e) { // name may already be set if symbols were loaded... } } @@ -325,13 +337,19 @@ public class FunctionsSarifMgr extends SarifMgr { for (Variable variable : plist) { arr[i++] = variable; } - FunctionUpdateType type = func.hasCustomVariableStorage() ? FunctionUpdateType.CUSTOM_STORAGE - : FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS; - func.updateFunction(func.getCallingConventionName(), retImpl, type, true, SourceType.IMPORTED, arr); - } catch (DuplicateNameException e) { - log.appendMsg("Could not set name of a parameter in function: " + funcDesc(func) + ": " + e.getMessage()); - } catch (InvalidInputException iie) { - log.appendMsg("Bad parameter definition in function: " + funcDesc(func) + ": " + iie.getMessage()); + FunctionUpdateType type = + func.hasCustomVariableStorage() ? FunctionUpdateType.CUSTOM_STORAGE + : FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS; + func.updateFunction(func.getCallingConventionName(), retImpl, type, true, + SourceType.IMPORTED, arr); + } + catch (DuplicateNameException e) { + log.appendMsg("Could not set name of a parameter in function: " + funcDesc(func) + + ": " + e.getMessage()); + } + catch (InvalidInputException iie) { + log.appendMsg("Bad parameter definition in function: " + funcDesc(func) + ": " + + iie.getMessage()); } } @@ -347,14 +365,15 @@ public class FunctionsSarifMgr extends SarifMgr { if (purgeSize != null) { if (purgeValid == null) { func.setStackPurgeSize((int) (double) purgeSize); - } else { - func.setStackPurgeSize(purgeValid ? (int) (double) purgeSize : Function.UNKNOWN_STACK_DEPTH_CHANGE); + } + else { + func.setStackPurgeSize( + purgeValid ? (int) (double) purgeSize : Function.UNKNOWN_STACK_DEPTH_CHANGE); } } } - private void createThunk(Map result, Function func) - throws InvalidInputException, DuplicateNameException { + private void createThunk(Map result, Function func) { String thunkStr = (String) result.get("thunkAddress"); if (thunkStr == null) { throw new RuntimeException("No thunk address provided."); @@ -367,12 +386,14 @@ public class FunctionsSarifMgr extends SarifMgr { thunkFn = (Function) symbol.getObject(); func.setThunkedFunction(thunkFn); } - } else { + } + else { thunkFn = program.getFunctionManager().getFunctionAt(thunk); if (thunkFn == null) { CreateFunctionCmd cmd = new CreateFunctionCmd(thunk); if (!cmd.applyTo(program)) { - Msg.error(this, "Failed to create function at " + thunk + ": " + cmd.getStatusMsg()); + Msg.error(this, + "Failed to create function at " + thunk + ": " + cmd.getStatusMsg()); } thunkFn = cmd.getFunction(); } @@ -380,14 +401,17 @@ public class FunctionsSarifMgr extends SarifMgr { } } - private void addLocalVar(Function function, Variable v, SourceType sourceType, boolean overwriteConflicts) throws InvalidInputException { - VariableUtilities.checkVariableConflict(function, v, v.getVariableStorage(), overwriteConflicts); + private void addLocalVar(Function function, Variable v, SourceType sourceType, + boolean overwriteConflicts) throws InvalidInputException { + VariableUtilities.checkVariableConflict(function, v, v.getVariableStorage(), + overwriteConflicts); try { function.addLocalVariable(v, sourceType); - } catch (DuplicateNameException e) { - log.appendMsg("Could not add local variable to function " + funcDesc(function) + ": " + v.getName() + ": " - + e.getMessage()); + } + catch (DuplicateNameException e) { + log.appendMsg("Could not add local variable to function " + funcDesc(function) + ": " + + v.getName() + ": " + e.getMessage()); } } @@ -406,7 +430,8 @@ public class FunctionsSarifMgr extends SarifMgr { } @SuppressWarnings("unchecked") - private void readStackFrame(Map result, Function func, List stackParams, SourceType sourceType) { + private void readStackFrame(Map result, Function func, + List stackParams, SourceType sourceType) { if (func == null) { return; } @@ -435,7 +460,8 @@ public class FunctionsSarifMgr extends SarifMgr { } @SuppressWarnings("unchecked") - private void readVariable(Map result, Function function, List stackParams, SourceType sourceType) { + private void readVariable(Map result, Function function, + List stackParams, SourceType sourceType) { int offset = (int) (double) result.get("offset"); int size = (int) (double) result.get("size"); @@ -464,19 +490,22 @@ public class FunctionsSarifMgr extends SarifMgr { if (isParameter) { var = new ParameterImpl(name, dt, offset, program); stackParams.add(var); - } else { + } + else { var = new LocalVariableImpl(name, dt, offset, program); addLocalVar(function, var, sourceType, true); } String regularComment = (String) result.get("comment"); var.setComment(regularComment); - } catch (InvalidInputException e) { + } + catch (InvalidInputException e) { log.appendException(e); } } @SuppressWarnings("unchecked") - private DataType readParameter(Map result, Function function, List formalParams) { + private DataType readParameter(Map result, Function function, + List formalParams) { String name = (String) result.get("name"); // int ordinal = (int) (double) result.get("ordinal"); @@ -514,7 +543,8 @@ public class FunctionsSarifMgr extends SarifMgr { formalParams.add(var); } return dt; - } catch (InvalidInputException e) { + } + catch (InvalidInputException e) { log.appendException(e); return null; } @@ -536,7 +566,8 @@ public class FunctionsSarifMgr extends SarifMgr { try { List rnames = (List) result.get("registers"); if (rnames != null) { - List vnodes = convertRegisterListToVarnodeStorage(rnames, dt.getLength(), offset); + List vnodes = + convertRegisterListToVarnodeStorage(rnames, dt.getLength(), offset); VariableStorage returnStorage = new VariableStorage(program, vnodes); return new ReturnParameterImpl(dt, returnStorage, true, program); } @@ -545,7 +576,8 @@ public class FunctionsSarifMgr extends SarifMgr { return new ReturnParameterImpl(dt, offset, program); } return new ReturnParameterImpl(dt, program); - } catch (InvalidInputException e) { + } + catch (InvalidInputException e) { log.appendException(e); return null; } @@ -567,7 +599,8 @@ public class FunctionsSarifMgr extends SarifMgr { } @SuppressWarnings("unchecked") - private void readRegisterVars(Map result, Function function, List stackParams) { + private void readRegisterVars(Map result, Function function, + List stackParams) { try { ProgramContext context = program.getProgramContext(); String name = (String) result.get("name"); @@ -580,7 +613,8 @@ public class FunctionsSarifMgr extends SarifMgr { Map type = (Map) result.get("type"); DataType dt = findDataType(type); if (dt != null && dt.getLength() > register.getMinimumByteSize()) { - log.appendMsg("Data type [" + result.get("type") + "] too large for register [" + registerName + "]"); + log.appendMsg("Data type [" + result.get("type") + "] too large for register [" + + registerName + "]"); dt = null; } @@ -589,15 +623,17 @@ public class FunctionsSarifMgr extends SarifMgr { registerParam.setComment(comment); stackParams.add(registerParam); - } catch (InvalidInputException e) { + } + catch (InvalidInputException e) { log.appendException(e); - } catch (IllegalArgumentException e) { + } + catch (IllegalArgumentException e) { log.appendException(e); } } - public List convertRegisterListToVarnodeStorage(List registNames, int dataTypeSize, - int stackOffset) { + public List convertRegisterListToVarnodeStorage(List registNames, + int dataTypeSize, int stackOffset) { List results = new ArrayList<>(); ProgramContext context = program.getProgramContext(); for (String rname : registNames) { @@ -612,7 +648,8 @@ public class FunctionsSarifMgr extends SarifMgr { dataTypeSize -= bytesUsed; } if (dataTypeSize != 0 && stackOffset >= 0) { - results.add(new Varnode(program.getAddressFactory().getStackSpace().getAddress(stackOffset), dataTypeSize)); + results.add(new Varnode( + program.getAddressFactory().getStackSpace().getAddress(stackOffset), dataTypeSize)); } return results; } @@ -621,7 +658,8 @@ public class FunctionsSarifMgr extends SarifMgr { // SARIF WRITE CURRENT DTD // ///////////////////////////// - void write(JsonArray results, AddressSetView addrs, TaskMonitor monitor) throws IOException, CancelledException { + void write(JsonArray results, AddressSetView addrs, TaskMonitor monitor) + throws IOException, CancelledException { monitor.setMessage("Writing FUNCTIONS ..."); List request = new ArrayList<>(); @@ -633,8 +671,10 @@ public class FunctionsSarifMgr extends SarifMgr { writeAsSARIF(program, request, results); } - public static void writeAsSARIF(Program program, List request, JsonArray results) throws IOException { - SarifFunctionWriter writer = new SarifFunctionWriter(program.getFunctionManager(), request, null); + public static void writeAsSARIF(Program program, List request, JsonArray results) + throws IOException { + SarifFunctionWriter writer = + new SarifFunctionWriter(program.getFunctionManager(), request, null); new TaskLauncher(new SarifWriterTask("Functions", writer, results), null); } diff --git a/Ghidra/Features/Sarif/src/test/java/sarif/CommentSarifTest.java b/Ghidra/Features/Sarif/src/test/java/sarif/CommentSarifTest.java index d5de234133..5dd384f87b 100644 --- a/Ghidra/Features/Sarif/src/test/java/sarif/CommentSarifTest.java +++ b/Ghidra/Features/Sarif/src/test/java/sarif/CommentSarifTest.java @@ -15,12 +15,15 @@ */ package sarif; +import static org.junit.Assert.*; + import org.junit.Test; +import ghidra.app.cmd.disassemble.DisassembleCommand; +import ghidra.program.model.address.AddressSet; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.data.*; -import ghidra.program.model.listing.CommentType; -import ghidra.program.model.listing.Listing; +import ghidra.program.model.listing.*; import ghidra.program.util.ProgramDiff; public class CommentSarifTest extends AbstractSarifTest { @@ -41,9 +44,9 @@ public class CommentSarifTest extends AbstractSarifTest { listing.setComment(entry.add(5), CommentType.REPEATABLE, "My Repeatable comment"); ProgramDiff programDiff = readWriteCompare(); - + AddressSetView differences = programDiff.getDifferences(monitor); - assert(differences.isEmpty()); + assert (differences.isEmpty()); } @Test @@ -63,9 +66,27 @@ public class CommentSarifTest extends AbstractSarifTest { listing.setComment(entry.add(4), CommentType.PLATE, "My Plate comment"); ProgramDiff programDiff = readWriteCompare(); - + AddressSetView differences = programDiff.getDifferences(monitor); - assert(differences.isEmpty()); + assert (differences.isEmpty()); + } + + @Test + public void testCommentsInInstr() throws Exception { + block.putBytes(entry, asm, 0, asm.length); + + Listing listing = program.getListing(); + + DisassembleCommand cmd = new DisassembleCommand(entry, new AddressSet(entry, entry), false); + assertTrue(cmd.applyTo(program)); + Instruction instr = listing.getInstructionAt(entry); + assertNotNull(instr); + listing.setComment(entry, CommentType.EOL, "My EOL comment"); + + ProgramDiff programDiff = readWriteCompare(); + + AddressSetView differences = programDiff.getDifferences(monitor); + assert (differences.isEmpty()); } @Test @@ -80,8 +101,8 @@ public class CommentSarifTest extends AbstractSarifTest { listing.createData(entry, struct); ProgramDiff programDiff = readWriteCompare(); - + AddressSetView differences = programDiff.getDifferences(monitor); - assert(!differences.isEmpty()); + assert (!differences.isEmpty()); } } diff --git a/Ghidra/Features/Sarif/src/test/java/sarif/DefinedDataSarifTest.java b/Ghidra/Features/Sarif/src/test/java/sarif/DefinedDataSarifTest.java index fed2798f47..541817525a 100644 --- a/Ghidra/Features/Sarif/src/test/java/sarif/DefinedDataSarifTest.java +++ b/Ghidra/Features/Sarif/src/test/java/sarif/DefinedDataSarifTest.java @@ -15,11 +15,16 @@ */ package sarif; +import static org.junit.Assert.*; + import org.junit.Test; +import ghidra.docking.settings.FormatSettingsDefinition; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.data.ProgramBasedDataTypeManager; import ghidra.program.model.data.Structure; +import ghidra.program.model.listing.CommentType; +import ghidra.program.model.listing.Data; import ghidra.program.util.ProgramDiff; public class DefinedDataSarifTest extends AbstractSarifTest { @@ -34,7 +39,15 @@ public class DefinedDataSarifTest extends AbstractSarifTest { Structure sdt = DataTypesSarifTest.createComplexStructureDataType(dtm); Structure struct = (Structure) dtm.resolve(sdt, null); - program.getListing().createData(addr(0x100), struct); + Data d = program.getListing().createData(addr(0x100), struct); + Data component = d.getComponent(new int[] { 1, 2 }); + assertNotNull(component); + + // Set EOL comment on nested component + component.setComment(CommentType.EOL, "My EOL comment"); + + // Set instance settings on nested component + FormatSettingsDefinition.DEF.setChoice(component, FormatSettingsDefinition.DECIMAL); ProgramDiff programDiff = readWriteCompare(); diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/CommentMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/CommentMarkupType.java index c71c0e9692..7722289b6e 100644 --- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/CommentMarkupType.java +++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/CommentMarkupType.java @@ -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,12 +38,12 @@ import ghidra.util.task.TaskMonitor; public abstract class CommentMarkupType extends VTMarkupType { - protected abstract int getCodeUnitCommentType(); - public CommentMarkupType(String name) { super(name); } + protected abstract CommentType getCodeUnitCommentType(); + protected abstract ProgramLocation getLocation(VTAssociation association, Address address, boolean isSource); @@ -105,7 +105,7 @@ public abstract class CommentMarkupType extends VTMarkupType { } private String getSourceComment(VTAssociation association, Address sourceAddress) { - int commentType = getCodeUnitCommentType(); + CommentType commentType = getCodeUnitCommentType(); Listing sourceListing = getSourceListing(association); return sourceListing.getComment(commentType, sourceAddress); } @@ -131,7 +131,7 @@ public abstract class CommentMarkupType extends VTMarkupType { throw new VersionTrackingApplyException("No value applied"); } String originalDestinationComment = originalDestinationValue.getString(); - int commentType = getCodeUnitCommentType(); + CommentType commentType = getCodeUnitCommentType(); Listing destinationListing = getDestinationListing(markupItem.getAssociation()); String comment = destinationListing.getComment(commentType, destinationAddress); if (!StringUtils.equals(originalDestinationComment, comment)) { @@ -179,7 +179,7 @@ public abstract class CommentMarkupType extends VTMarkupType { comment = StringUtilities.mergeStrings(destinationComment, sourceComment); } - int commentType = getCodeUnitCommentType(); + CommentType commentType = getCodeUnitCommentType(); Listing destinationListing = getDestinationListing(markupItem.getAssociation()); destinationListing.setComment(destinationAddress, commentType, comment); return true; @@ -187,7 +187,7 @@ public abstract class CommentMarkupType extends VTMarkupType { private String getDestinationComment(VTAssociation association, Address destinationAddress) { if (destinationAddress != null && destinationAddress != Address.NO_ADDRESS) { - int commentType = getCodeUnitCommentType(); + CommentType commentType = getCodeUnitCommentType(); Listing destinationListing = getDestinationListing(association); return destinationListing.getComment(commentType, destinationAddress); } diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/EolCommentMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/EolCommentMarkupType.java index def9781e7a..81ee8fc077 100644 --- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/EolCommentMarkupType.java +++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/EolCommentMarkupType.java @@ -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,8 +22,7 @@ import ghidra.feature.vt.gui.util.VTMatchApplyChoices.CommentChoices; import ghidra.framework.options.Options; import ghidra.framework.options.ToolOptions; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.Program; +import ghidra.program.model.listing.*; import ghidra.program.util.EolCommentFieldLocation; import ghidra.program.util.ProgramLocation; @@ -44,8 +43,8 @@ public class EolCommentMarkupType extends CommentMarkupType { } @Override - protected int getCodeUnitCommentType() { - return CodeUnit.EOL_COMMENT; + protected CommentType getCodeUnitCommentType() { + return CommentType.EOL; } @Override @@ -92,8 +91,8 @@ public class EolCommentMarkupType extends CommentMarkupType { CommentChoices.APPEND_TO_EXISTING); break; case ADD_AS_PRIMARY: - throw new IllegalArgumentException(getDisplayName() + - " markup items cannot perform an Add As Primary action."); + throw new IllegalArgumentException( + getDisplayName() + " markup items cannot perform an Add As Primary action."); case REPLACE_DEFAULT_ONLY: throw new IllegalArgumentException(getDisplayName() + " markup items cannot perform a Replace Default Only action."); diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PlateCommentMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PlateCommentMarkupType.java index 38d731892a..caf8bbdd2f 100644 --- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PlateCommentMarkupType.java +++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PlateCommentMarkupType.java @@ -24,7 +24,7 @@ import ghidra.feature.vt.gui.util.VTOptionDefines; import ghidra.framework.options.Options; import ghidra.framework.options.ToolOptions; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; import ghidra.program.util.PlateFieldLocation; import ghidra.program.util.ProgramLocation; @@ -46,8 +46,8 @@ public class PlateCommentMarkupType extends CommentMarkupType { } @Override - protected int getCodeUnitCommentType() { - return CodeUnit.PLATE_COMMENT; + protected CommentType getCodeUnitCommentType() { + return CommentType.PLATE; } @Override diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PostCommentMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PostCommentMarkupType.java index 24e674086c..5dbb480c77 100644 --- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PostCommentMarkupType.java +++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PostCommentMarkupType.java @@ -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. @@ -17,12 +17,13 @@ package ghidra.feature.vt.api.markuptype; import ghidra.feature.vt.api.main.VTAssociation; import ghidra.feature.vt.api.main.VTMarkupItemApplyActionType; -import ghidra.feature.vt.gui.util.*; +import ghidra.feature.vt.gui.util.VTMatchApplyChoices; import ghidra.feature.vt.gui.util.VTMatchApplyChoices.CommentChoices; +import ghidra.feature.vt.gui.util.VTOptionDefines; import ghidra.framework.options.Options; import ghidra.framework.options.ToolOptions; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; import ghidra.program.util.PostCommentFieldLocation; import ghidra.program.util.ProgramLocation; @@ -44,8 +45,8 @@ public class PostCommentMarkupType extends CommentMarkupType { } @Override - protected int getCodeUnitCommentType() { - return CodeUnit.POST_COMMENT; + protected CommentType getCodeUnitCommentType() { + return CommentType.POST; } @Override @@ -91,8 +92,8 @@ public class PostCommentMarkupType extends CommentMarkupType { options.setEnum(VTOptionDefines.POST_COMMENT, CommentChoices.APPEND_TO_EXISTING); break; case ADD_AS_PRIMARY: - throw new IllegalArgumentException(getDisplayName() + - " markup items cannot perform an Add As Primary action."); + throw new IllegalArgumentException( + getDisplayName() + " markup items cannot perform an Add As Primary action."); case REPLACE_DEFAULT_ONLY: throw new IllegalArgumentException(getDisplayName() + " markup items cannot perform a Replace Default Only action."); diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PreCommentMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PreCommentMarkupType.java index 68132727d2..eb8b5aede4 100644 --- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PreCommentMarkupType.java +++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/PreCommentMarkupType.java @@ -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. @@ -17,12 +17,13 @@ package ghidra.feature.vt.api.markuptype; import ghidra.feature.vt.api.main.VTAssociation; import ghidra.feature.vt.api.main.VTMarkupItemApplyActionType; -import ghidra.feature.vt.gui.util.*; +import ghidra.feature.vt.gui.util.VTMatchApplyChoices; import ghidra.feature.vt.gui.util.VTMatchApplyChoices.CommentChoices; +import ghidra.feature.vt.gui.util.VTOptionDefines; import ghidra.framework.options.Options; import ghidra.framework.options.ToolOptions; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; import ghidra.program.util.CommentFieldLocation; import ghidra.program.util.ProgramLocation; @@ -44,8 +45,8 @@ public class PreCommentMarkupType extends CommentMarkupType { } @Override - protected int getCodeUnitCommentType() { - return CodeUnit.PRE_COMMENT; + protected CommentType getCodeUnitCommentType() { + return CommentType.PRE; } @Override @@ -57,7 +58,7 @@ public class PreCommentMarkupType extends CommentMarkupType { Program program = isSource ? getSourceProgram(association) : getDestinationProgram(association); - return new CommentFieldLocation(program, address, null, null, CodeUnit.PRE_COMMENT, 0, 0); + return new CommentFieldLocation(program, address, null, null, CommentType.PRE, 0, 0); } @Override @@ -91,8 +92,8 @@ public class PreCommentMarkupType extends CommentMarkupType { options.setEnum(VTOptionDefines.PRE_COMMENT, CommentChoices.APPEND_TO_EXISTING); break; case ADD_AS_PRIMARY: - throw new IllegalArgumentException(getDisplayName() + - " markup items cannot perform an Add As Primary action."); + throw new IllegalArgumentException( + getDisplayName() + " markup items cannot perform an Add As Primary action."); case REPLACE_DEFAULT_ONLY: throw new IllegalArgumentException(getDisplayName() + " markup items cannot perform a Replace Default Only action."); diff --git a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/RepeatableCommentMarkupType.java b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/RepeatableCommentMarkupType.java index c6475e135e..27be23b467 100644 --- a/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/RepeatableCommentMarkupType.java +++ b/Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/markuptype/RepeatableCommentMarkupType.java @@ -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. @@ -17,12 +17,13 @@ package ghidra.feature.vt.api.markuptype; import ghidra.feature.vt.api.main.VTAssociation; import ghidra.feature.vt.api.main.VTMarkupItemApplyActionType; -import ghidra.feature.vt.gui.util.*; +import ghidra.feature.vt.gui.util.VTMatchApplyChoices; import ghidra.feature.vt.gui.util.VTMatchApplyChoices.CommentChoices; +import ghidra.feature.vt.gui.util.VTOptionDefines; import ghidra.framework.options.Options; import ghidra.framework.options.ToolOptions; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; import ghidra.program.util.FunctionRepeatableCommentFieldLocation; import ghidra.program.util.ProgramLocation; @@ -44,8 +45,8 @@ public class RepeatableCommentMarkupType extends CommentMarkupType { } @Override - protected int getCodeUnitCommentType() { - return CodeUnit.REPEATABLE_COMMENT; + protected CommentType getCodeUnitCommentType() { + return CommentType.REPEATABLE; } @Override @@ -92,8 +93,8 @@ public class RepeatableCommentMarkupType extends CommentMarkupType { CommentChoices.APPEND_TO_EXISTING); break; case ADD_AS_PRIMARY: - throw new IllegalArgumentException(getDisplayName() + - " markup items cannot perform an Add As Primary action."); + throw new IllegalArgumentException( + getDisplayName() + " markup items cannot perform an Add As Primary action."); case REPLACE_DEFAULT_ONLY: throw new IllegalArgumentException(getDisplayName() + " markup items cannot perform a Replace Default Only action."); diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTAutoVersionTrackingTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTAutoVersionTrackingTest.java index 98917c81a5..6102c1a337 100644 --- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTAutoVersionTrackingTest.java +++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTAutoVersionTrackingTest.java @@ -224,7 +224,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run auto VT which would normally accept the match we blocked ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); @@ -276,10 +276,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Now test that the correct matches were created based on the duplicate functions we created @@ -326,10 +326,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Now test that the correct matches were created based on the duplicate functions we created @@ -366,10 +366,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Test to make sure that they weren't matched by something else first so we can @@ -439,10 +439,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Test to make sure that they weren't matched by something else first so we can @@ -597,10 +597,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Test to make sure that they weren't matched by something else first so we can @@ -655,10 +655,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run Auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Check that the match we are interested in got accepted @@ -715,10 +715,10 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // run Auto VT ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 1.0); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); - + runAutoVTCommand(vtOptions); // Check that the match we are interested in got accepted @@ -783,7 +783,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // Now run the AutoVT command with lower confidence thresholds to allow the match we want to // test in as a match ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 0.5); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 1.0); @@ -850,14 +850,13 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // Score .999999 and confidence 10.0 (log10 confidence 2.0) and up ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 0.999999999); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); vtOptions.setBoolean(VTOptionDefines.CREATE_IMPLIED_MATCHES_OPTION, true); vtOptions.setBoolean(VTOptionDefines.APPLY_IMPLIED_MATCHES_OPTION, true); vtOptions.setInt(VTOptionDefines.MIN_VOTES_OPTION, 3); vtOptions.setInt(VTOptionDefines.MAX_CONFLICTS_OPTION, 0); - runAutoVTCommand(vtOptions); @@ -878,7 +877,6 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe VTAssociation association = match.getAssociation(); int numConflicts = association.getRelatedAssociations().size() - 1; - // if not min vote count or has conflicts - make sure not accepted match if (association.getVoteCount() < 3 || numConflicts > 0) { assertEquals(VTAssociationStatus.AVAILABLE, matchStatus); @@ -904,11 +902,11 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe // Score .999999 and confidence 10.0 (log10 confidence 2.0) and up ToolOptions vtOptions = getVTToolOptions(tool); - + vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_SCORE_OPTION, 0.999999999); vtOptions.setDouble(VTOptionDefines.REF_CORRELATOR_MIN_CONF_OPTION, 10.0); vtOptions.setBoolean(VTOptionDefines.CREATE_IMPLIED_MATCHES_OPTION, false); - + runAutoVTCommand(vtOptions); assertTrue(session.getImpliedMatchSet().getMatchCount() == 0); @@ -1149,8 +1147,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe private void runAutoVTCommand(ToolOptions options) { - AutoVersionTrackingTask task = - new AutoVersionTrackingTask(session, options); + AutoVersionTrackingTask task = new AutoVersionTrackingTask(session, options); TaskLauncher.launch(task); waitForSession(); } @@ -1162,9 +1159,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe private VTMatchSet getVTMatchSet(VTSession vtSession, String correlatorName) { List matchSets = vtSession.getMatchSets(); - Iterator iterator = matchSets.iterator(); - while (iterator.hasNext()) { - VTMatchSet matches = iterator.next(); + for (VTMatchSet matches : matchSets) { if (matches.getProgramCorrelatorInfo().getName().equals(correlatorName)) { return matches; } @@ -1178,9 +1173,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe VTMatchSet matches = getVTMatchSet(vtSession, correlatorName); Msg.info(this, score + " " + confidence); - Iterator it = matches.getMatches().iterator(); - while (it.hasNext()) { - VTMatch match = it.next(); + for (VTMatch match : matches.getMatches()) { VTAssociationStatus status = match.getAssociation().getStatus(); if (status.equals(VTAssociationStatus.ACCEPTED)) { Msg.info(this, @@ -1201,9 +1194,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe VTMatchSet matches = getVTMatchSet(vtSession, correlatorName); int count = 0; - Iterator it = matches.getMatches().iterator(); - while (it.hasNext()) { - VTMatch match = it.next(); + for (VTMatch match : matches.getMatches()) { VTAssociationStatus status = match.getAssociation().getStatus(); if (status.equals(VTAssociationStatus.ACCEPTED)) { count++; @@ -1217,9 +1208,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe VTMatchSet matches = getVTMatchSet(vtSession, correlatorName); - Iterator it = matches.getMatches().iterator(); - while (it.hasNext()) { - VTMatch match = it.next(); + for (VTMatch match : matches.getMatches()) { if (match.getSourceAddress().equals(sourceAddress) && match.getDestinationAddress().equals(destinationAddress)) { return match.getAssociation().getStatus(); @@ -1231,9 +1220,7 @@ public class VTAutoVersionTrackingTest extends AbstractGhidraHeadedIntegrationTe private VTMatch getMatch(VTMatchSet matches, Address sourceAddress, Address destinationAddress) { - Iterator it = matches.getMatches().iterator(); - while (it.hasNext()) { - VTMatch match = it.next(); + for (VTMatch match : matches.getMatches()) { if (match.getSourceAddress().equals(sourceAddress) && match.getDestinationAddress().equals(destinationAddress)) { return match; diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyTest.java index c1082d9d0d..bbfbb1284f 100644 --- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyTest.java +++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/VTMatchApplyTest.java @@ -177,39 +177,39 @@ public class VTMatchApplyTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testApplyMatchEOLComments_Ignore() throws Exception { - doTestApplyCommentMatch_Ignore(CodeUnit.EOL_COMMENT, VTOptionDefines.END_OF_LINE_COMMENT, + doTestApplyCommentMatch_Ignore(CommentType.EOL, VTOptionDefines.END_OF_LINE_COMMENT, CommentChoices.EXCLUDE); } @Test public void testApplyMatchPreComments_Ignore() throws Exception { - doTestApplyCommentMatch_Ignore(CodeUnit.PRE_COMMENT, VTOptionDefines.PRE_COMMENT, + doTestApplyCommentMatch_Ignore(CommentType.PRE, VTOptionDefines.PRE_COMMENT, CommentChoices.EXCLUDE); } @Test public void testApplyMatchPostComments_Ignore() throws Exception { - doTestApplyCommentMatch_Ignore(CodeUnit.POST_COMMENT, VTOptionDefines.POST_COMMENT, + doTestApplyCommentMatch_Ignore(CommentType.POST, VTOptionDefines.POST_COMMENT, CommentChoices.EXCLUDE); } @Test public void testApplyMatchPlateComments_Ignore() throws Exception { - doTestApplyCommentMatch_Ignore(CodeUnit.PLATE_COMMENT, VTOptionDefines.PLATE_COMMENT, + doTestApplyCommentMatch_Ignore(CommentType.PLATE, VTOptionDefines.PLATE_COMMENT, CommentChoices.EXCLUDE); } @Test public void testApplyMatchRepeatableComments_Ignore() throws Exception { - doTestApplyCommentMatch_Ignore(CodeUnit.REPEATABLE_COMMENT, - VTOptionDefines.REPEATABLE_COMMENT, CommentChoices.EXCLUDE); + doTestApplyCommentMatch_Ignore(CommentType.REPEATABLE, VTOptionDefines.REPEATABLE_COMMENT, + CommentChoices.EXCLUDE); } - private void doTestApplyCommentMatch_Ignore(int codeUnitCommentType, + private void doTestApplyCommentMatch_Ignore(CommentType codeUnitCommentType, String vtCommentOptionDefine, CommentChoices commentChoice) throws Exception { String sourceComment = "Hi mom replace"; Address sourceAddress = addr("0x01002cf5", sourceProgram); @@ -249,39 +249,39 @@ public class VTMatchApplyTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testApplyMatchEOLComments_Append() throws Exception { - doTestApplyCommentMatch_Append(CodeUnit.EOL_COMMENT, VTOptionDefines.END_OF_LINE_COMMENT, + doTestApplyCommentMatch_Append(CommentType.EOL, VTOptionDefines.END_OF_LINE_COMMENT, CommentChoices.APPEND_TO_EXISTING); } @Test public void testApplyMatchPreComments_Append() throws Exception { - doTestApplyCommentMatch_Append(CodeUnit.PRE_COMMENT, VTOptionDefines.PRE_COMMENT, + doTestApplyCommentMatch_Append(CommentType.PRE, VTOptionDefines.PRE_COMMENT, CommentChoices.APPEND_TO_EXISTING); } @Test public void testApplyMatchPostComments_Append() throws Exception { - doTestApplyCommentMatch_Append(CodeUnit.POST_COMMENT, VTOptionDefines.POST_COMMENT, + doTestApplyCommentMatch_Append(CommentType.POST, VTOptionDefines.POST_COMMENT, CommentChoices.APPEND_TO_EXISTING); } @Test public void testApplyMatchPlateComments_Append() throws Exception { - doTestApplyCommentMatch_Append(CodeUnit.PLATE_COMMENT, VTOptionDefines.PLATE_COMMENT, + doTestApplyCommentMatch_Append(CommentType.PLATE, VTOptionDefines.PLATE_COMMENT, CommentChoices.APPEND_TO_EXISTING); } @Test public void testApplyMatchRepeatableComments_Append() throws Exception { - doTestApplyCommentMatch_Append(CodeUnit.REPEATABLE_COMMENT, - VTOptionDefines.REPEATABLE_COMMENT, CommentChoices.APPEND_TO_EXISTING); + doTestApplyCommentMatch_Append(CommentType.REPEATABLE, VTOptionDefines.REPEATABLE_COMMENT, + CommentChoices.APPEND_TO_EXISTING); } - private void doTestApplyCommentMatch_Append(int codeUnitCommentType, + private void doTestApplyCommentMatch_Append(CommentType codeUnitCommentType, String vtCommentOptionDefine, CommentChoices commentChoice) throws Exception { String sourceComment = "Hi mom replace"; String destinationComment = "Hi dad replace"; @@ -326,39 +326,39 @@ public class VTMatchApplyTest extends AbstractGhidraHeadedIntegrationTest { @Test public void testApplyMatchEOLComments_Overwrite() throws Exception { - doTestApplyCommentMatch_Overwrite(CodeUnit.EOL_COMMENT, VTOptionDefines.END_OF_LINE_COMMENT, + doTestApplyCommentMatch_Overwrite(CommentType.EOL, VTOptionDefines.END_OF_LINE_COMMENT, CommentChoices.OVERWRITE_EXISTING); } @Test public void testApplyMatchPreComments_Overwrite() throws Exception { - doTestApplyCommentMatch_Overwrite(CodeUnit.PRE_COMMENT, VTOptionDefines.PRE_COMMENT, + doTestApplyCommentMatch_Overwrite(CommentType.PRE, VTOptionDefines.PRE_COMMENT, CommentChoices.OVERWRITE_EXISTING); } @Test public void testApplyMatchPostComments_Overwrite() throws Exception { - doTestApplyCommentMatch_Overwrite(CodeUnit.POST_COMMENT, VTOptionDefines.POST_COMMENT, + doTestApplyCommentMatch_Overwrite(CommentType.POST, VTOptionDefines.POST_COMMENT, CommentChoices.OVERWRITE_EXISTING); } @Test public void testApplyMatchPlateComments_Overwrite() throws Exception { - doTestApplyCommentMatch_Overwrite(CodeUnit.PLATE_COMMENT, VTOptionDefines.PLATE_COMMENT, + doTestApplyCommentMatch_Overwrite(CommentType.PLATE, VTOptionDefines.PLATE_COMMENT, CommentChoices.OVERWRITE_EXISTING); } @Test public void testApplyMatchRepeatableComments_Overwrite() throws Exception { - doTestApplyCommentMatch_Overwrite(CodeUnit.REPEATABLE_COMMENT, + doTestApplyCommentMatch_Overwrite(CommentType.REPEATABLE, VTOptionDefines.REPEATABLE_COMMENT, CommentChoices.OVERWRITE_EXISTING); } - private void doTestApplyCommentMatch_Overwrite(int codeUnitCommentType, + private void doTestApplyCommentMatch_Overwrite(CommentType codeUnitCommentType, String vtCommentOptionDefine, CommentChoices commentChoice) throws Exception { String sourceComment = "Hi mom replace"; String destinationComment = "Hi dad replace"; @@ -1062,8 +1062,8 @@ public class VTMatchApplyTest extends AbstractGhidraHeadedIntegrationTest { String sourceComment = "Hi mom replace"; String destinationComment = "Hi dad replace"; Address commentAddress = addr("0x01002d06", sourceProgram); - setComment(sourceProgram, commentAddress, CodeUnit.EOL_COMMENT, sourceComment); - setComment(destinationProgram, commentAddress, CodeUnit.EOL_COMMENT, destinationComment); + setComment(sourceProgram, commentAddress, CommentType.EOL, sourceComment); + setComment(destinationProgram, commentAddress, CommentType.EOL, destinationComment); MatchInfo matchInfo = controller.getMatchInfo(match); Collection markupItems = matchInfo.getAppliableMarkupItems(TaskMonitor.DUMMY); @@ -2069,7 +2069,7 @@ public class VTMatchApplyTest extends AbstractGhidraHeadedIntegrationTest { } } - private void setComment(Program program, Address address, int codeUnitCommentType, + private void setComment(Program program, Address address, CommentType codeUnitCommentType, String comment) { Listing listing = program.getListing(); diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/correlator/address/AddressCorrelationTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/correlator/address/AddressCorrelationTest.java index 1efc6c840a..5a44785551 100644 --- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/correlator/address/AddressCorrelationTest.java +++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/correlator/address/AddressCorrelationTest.java @@ -88,7 +88,7 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest // Test a function match created by the Exact Bytes Match correlator. createSession(TEST_SOURCE_PROGRAM_NAME, TEST_DESTINATION_PROGRAM_NAME); vtTestEnv.showTool(); - addComment(CodeUnit.EOL_COMMENT, "0x0041222b", "Exact bytes comment."); + addComment(CommentType.EOL, "0x0041222b", "Exact bytes comment."); runCorrelator(new ExactMatchBytesProgramCorrelatorFactory()); selectMatch("0x00412210", "0x004121f0"); @@ -103,7 +103,7 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest // Test a function match created by the Exact Mnemonics Match correlator. createSession(TEST_SOURCE_PROGRAM_NAME, TEST_DESTINATION_PROGRAM_NAME); vtTestEnv.showTool(); - addComment(CodeUnit.PRE_COMMENT, "0x00412988", "Exact mnemonics comment."); + addComment(CommentType.PRE, "0x00412988", "Exact mnemonics comment."); runCorrelator(new ExactMatchMnemonicsProgramCorrelatorFactory()); selectMatch("0x00412950", "0x00412930"); @@ -118,7 +118,7 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest // Test a function match created by the Exact Instructions Match correlator. createSession(TEST_SOURCE_PROGRAM_NAME, TEST_DESTINATION_PROGRAM_NAME); vtTestEnv.showTool(); - addComment(CodeUnit.POST_COMMENT, "0x004129a2", "Exact instructions comment."); + addComment(CommentType.POST, "0x004129a2", "Exact instructions comment."); runCorrelator(new ExactMatchInstructionsProgramCorrelatorFactory()); selectMatch("0x00412950", "0x00412930"); @@ -134,8 +134,8 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest // two programs are for the same language and processor. createSession(TEST_SOURCE_PROGRAM_NAME, TEST_DESTINATION_PROGRAM_NAME); vtTestEnv.showTool(); - addComment(CodeUnit.EOL_COMMENT, "0x004126dd", "Similar name eol comment."); - addComment(CodeUnit.PRE_COMMENT, "0x004126d7", "Similar name pre comment."); + addComment(CommentType.EOL, "0x004126dd", "Similar name eol comment."); + addComment(CommentType.PRE, "0x004126d7", "Similar name pre comment."); runCorrelator(new SimilarSymbolNameProgramCorrelatorFactory()); selectMatch("0x00412690", "0x00412720"); @@ -158,8 +158,7 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest vtTestEnv.showTool(); // add source comment - addComment(CodeUnit.PLATE_COMMENT, "0x00401003", - "Similar name plate comment not at entry."); + addComment(CommentType.PLATE, "0x00401003", "Similar name plate comment not at entry."); // create correlation run runCorrelator(new SimilarSymbolNameProgramCorrelatorFactory()); @@ -187,7 +186,7 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest Program p2 = buildProgram3("language3"); createSession(p1, p2); vtTestEnv.showTool(); - addComment(CodeUnit.EOL_COMMENT, "0x00401003", "Similar name eol comment."); + addComment(CommentType.EOL, "0x00401003", "Similar name eol comment."); runCorrelator(new SimilarSymbolNameProgramCorrelatorFactory()); selectMatch("0x00401000", "0x00402000"); @@ -208,8 +207,8 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest Program p2 = buildProgram2("language2"); createSession(p1, p2); vtTestEnv.showTool(); - addComment(CodeUnit.PLATE_COMMENT, "0x00401000", "First plate comment."); - addComment(CodeUnit.PLATE_COMMENT, "0x00401003", "Second plate comment."); + addComment(CommentType.PLATE, "0x00401000", "First plate comment."); + addComment(CommentType.PLATE, "0x00401003", "Second plate comment."); runCorrelator(new SimilarSymbolNameProgramCorrelatorFactory()); selectMatch("0x00401000", "0x00402000"); @@ -237,8 +236,8 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest Program p2 = buildProgram3("language3"); createSession(p1, p2); vtTestEnv.showTool(); - addComment(CodeUnit.PLATE_COMMENT, "0x00401000", "First plate comment."); - addComment(CodeUnit.PLATE_COMMENT, "0x00401003", "Second plate comment."); + addComment(CommentType.PLATE, "0x00401000", "First plate comment."); + addComment(CommentType.PLATE, "0x00401003", "Second plate comment."); runCorrelator(new SimilarSymbolNameProgramCorrelatorFactory()); selectMatch("0x00401000", "0x00402000"); @@ -443,7 +442,7 @@ public class AddressCorrelationTest extends AbstractGhidraHeadedIntegrationTest * @param sourceAddressString the source address of the markup * @param comment the comment to be added at the source address */ - private void addComment(int commentType, String sourceAddressString, String comment) { + private void addComment(CommentType commentType, String sourceAddressString, String comment) { Address srcAddress = addr(sourceAddressString, sourceProgram); int txID = sourceProgram.startTransaction("Add Comment"); boolean commit = false; diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ApplyMultipleMarkupItemsTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ApplyMultipleMarkupItemsTest.java index a8a34792d6..56fd3b612e 100644 --- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ApplyMultipleMarkupItemsTest.java +++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ApplyMultipleMarkupItemsTest.java @@ -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. @@ -15,8 +15,8 @@ */ package ghidra.feature.vt.api.markupitem; -import static ghidra.feature.vt.db.VTTestUtils.addr; -import static org.junit.Assert.assertTrue; +import static ghidra.feature.vt.db.VTTestUtils.*; +import static org.junit.Assert.*; import java.util.List; @@ -29,7 +29,7 @@ import ghidra.feature.vt.api.main.VTMatch; import ghidra.feature.vt.api.markuptype.EolCommentMarkupType; import ghidra.feature.vt.api.util.VTOptions; import ghidra.feature.vt.gui.task.ApplyMarkupItemTask; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.util.task.TaskMonitor; public class ApplyMultipleMarkupItemsTest extends AbstractVTMarkupItemTest { @@ -38,8 +38,8 @@ public class ApplyMultipleMarkupItemsTest extends AbstractVTMarkupItemTest { @Before public void setUp() throws Exception { super.setUp(); - sourceBuilder.createComment("1002248", "Comment 1", CodeUnit.EOL_COMMENT); - sourceBuilder.createComment("100224b", "Comment 2", CodeUnit.EOL_COMMENT); + sourceBuilder.createComment("1002248", "Comment 1", CommentType.EOL); + sourceBuilder.createComment("100224b", "Comment 2", CommentType.EOL); sourceProgram = sourceBuilder.getProgram(); } diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/CommentMarkupItemTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/CommentMarkupItemTest.java index 5c30806c8c..4b047203fe 100644 --- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/CommentMarkupItemTest.java +++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/CommentMarkupItemTest.java @@ -39,8 +39,8 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { super(); } -@Test - public void testFindAndApplyMarkupItem_Merge_WithNonNullDestinationValue() throws Exception { + @Test + public void testFindAndApplyMarkupItem_Merge_WithNonNullDestinationValue() throws Exception { String sourceComment = "Hi mom merge"; String destinationComment = "Hi dad merge"; String appliedComment = destinationComment + '\n' + sourceComment; @@ -50,15 +50,14 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { setComment(sourceProgram, sourceComment, commentAddress); setComment(destinationProgram, destinationComment, commentAddress); - CommentValidator validator = - new CommentValidator("0x01002cf5", "0x01002cf5", commentAddress, sourceComment, - destinationComment, appliedComment, CodeUnit.EOL_COMMENT, - CommentChoices.APPEND_TO_EXISTING); + CommentValidator validator = new CommentValidator("0x01002cf5", "0x01002cf5", + commentAddress, sourceComment, destinationComment, appliedComment, CommentType.EOL, + CommentChoices.APPEND_TO_EXISTING); doTestFindAndApplyMarkupItem(validator); } -@Test - public void testFindAndApplyMarkupItem_Merge_WithNullDestinationValue() throws Exception { + @Test + public void testFindAndApplyMarkupItem_Merge_WithNullDestinationValue() throws Exception { String sourceComment = "Hi mom merge"; String destinationComment = null; String appliedComment = sourceComment; @@ -68,15 +67,14 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { setComment(sourceProgram, sourceComment, commentAddress); setComment(destinationProgram, destinationComment, commentAddress); - CommentValidator validator = - new CommentValidator("0x01002cf5", "0x01002cf5", commentAddress, sourceComment, - destinationComment, appliedComment, CodeUnit.EOL_COMMENT, - CommentChoices.APPEND_TO_EXISTING); + CommentValidator validator = new CommentValidator("0x01002cf5", "0x01002cf5", + commentAddress, sourceComment, destinationComment, appliedComment, CommentType.EOL, + CommentChoices.APPEND_TO_EXISTING); doTestFindAndApplyMarkupItem(validator); } -@Test - public void testFindAndApplyMarkupItem_Replace_WithNonNullDestinationValue() throws Exception { + @Test + public void testFindAndApplyMarkupItem_Replace_WithNonNullDestinationValue() throws Exception { String sourceComment = "Hi mom merge"; String destinationComment = "Hi dad merge"; String appliedComment = sourceComment; @@ -86,15 +84,14 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { setComment(sourceProgram, sourceComment, commentAddress); setComment(destinationProgram, destinationComment, commentAddress); - CommentValidator validator = - new CommentValidator("0x01002cf5", "0x01002cf5", commentAddress, sourceComment, - destinationComment, appliedComment, CodeUnit.EOL_COMMENT, - CommentChoices.OVERWRITE_EXISTING); + CommentValidator validator = new CommentValidator("0x01002cf5", "0x01002cf5", + commentAddress, sourceComment, destinationComment, appliedComment, CommentType.EOL, + CommentChoices.OVERWRITE_EXISTING); doTestFindAndApplyMarkupItem(validator); } -@Test - public void testFindAndApplyMarkupItem_Replace_WithNullDestinationValue() throws Exception { + @Test + public void testFindAndApplyMarkupItem_Replace_WithNullDestinationValue() throws Exception { String sourceComment = "Hi mom merge"; String destinationComment = null; String appliedComment = sourceComment; @@ -104,15 +101,14 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { setComment(sourceProgram, sourceComment, commentAddress); setComment(destinationProgram, destinationComment, commentAddress); - CommentValidator validator = - new CommentValidator("0x01002cf5", "0x01002cf5", commentAddress, sourceComment, - destinationComment, appliedComment, CodeUnit.EOL_COMMENT, - CommentChoices.OVERWRITE_EXISTING); + CommentValidator validator = new CommentValidator("0x01002cf5", "0x01002cf5", + commentAddress, sourceComment, destinationComment, appliedComment, CommentType.EOL, + CommentChoices.OVERWRITE_EXISTING); doTestFindAndApplyMarkupItem(validator); } -@Test - public void testFindAndApplyMarkupItem_IgnoreAction() throws Exception { + @Test + public void testFindAndApplyMarkupItem_IgnoreAction() throws Exception { String sourceComment = "Hi mom merge"; String destinationComment = null; String appliedComment = destinationComment; // the comment is not applied @@ -124,7 +120,7 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { CommentValidator validator = new CommentValidator("0x01002cf5", "0x01002cf5", commentAddress, sourceComment, - destinationComment, appliedComment, CodeUnit.EOL_COMMENT, CommentChoices.EXCLUDE); + destinationComment, appliedComment, CommentType.EOL, CommentChoices.EXCLUDE); doTestFindAndApplyMarkupItem(validator); } @@ -156,12 +152,12 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { private final String sourceComment; private final String destinationComment; private final String appliedComment; - private final int commentType; + private final CommentType commentType; private CommentChoices commentChoice; CommentValidator(String sourceFunctionAddress, String destinationFunctionAddress, Address commentAddress, String sourceComment, String destinationComment, - String appliedComment, int commentType, CommentChoices commentChoice) { + String appliedComment, CommentType commentType, CommentChoices commentChoice) { this.commentChoice = commentChoice; this.sourceFunctionAddress = addr(sourceFunctionAddress, sourceProgram); this.destinationFunctionAddress = addr(destinationFunctionAddress, destinationProgram); @@ -242,15 +238,15 @@ public class CommentMarkupItemTest extends AbstractVTMarkupItemTest { private String getOptionName() { switch (commentType) { - case CodeUnit.EOL_COMMENT: + case EOL: return VTOptionDefines.END_OF_LINE_COMMENT; - case CodeUnit.PLATE_COMMENT: + case PLATE: return VTOptionDefines.PLATE_COMMENT; - case CodeUnit.POST_COMMENT: + case POST: return VTOptionDefines.POST_COMMENT; - case CodeUnit.PRE_COMMENT: + case PRE: return VTOptionDefines.PRE_COMMENT; - case CodeUnit.REPEATABLE_COMMENT: + case REPEATABLE: return VTOptionDefines.REPEATABLE_COMMENT; default: return null; diff --git a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ForceApplyOfExcludedMarkupTest.java b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ForceApplyOfExcludedMarkupTest.java index 6653e6d624..2b9f4742a0 100644 --- a/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ForceApplyOfExcludedMarkupTest.java +++ b/Ghidra/Features/VersionTracking/src/test.slow/java/ghidra/feature/vt/api/markupitem/ForceApplyOfExcludedMarkupTest.java @@ -164,8 +164,8 @@ public class ForceApplyOfExcludedMarkupTest extends AbstractFunctionSignatureMar @Test public void testForceApplyForExcludedPlateComment() throws Exception { - genericTestForceApplyForExcludedComment(PlateCommentMarkupType.class, - CommentType.PLATE, PLATE_COMMENT); + genericTestForceApplyForExcludedComment(PlateCommentMarkupType.class, CommentType.PLATE, + PLATE_COMMENT); } @Test @@ -230,7 +230,7 @@ public class ForceApplyOfExcludedMarkupTest extends AbstractFunctionSignatureMar //---------------------------- - protected void checkComments(final CommentType commentType, final Address sourceAddr, + protected void checkComments(CommentType commentType, final Address sourceAddr, final String expectedSourceComment, final Address destinationAddr, final String expectedDestinationComment) { @@ -299,27 +299,27 @@ public class ForceApplyOfExcludedMarkupTest extends AbstractFunctionSignatureMar matchInfo.getAppliableMarkupItems(TaskMonitor.DUMMY); for (VTMarkupItem vtMarkupItem : appliableMarkupItems) { switch (commentType) { - case CommentType.PLATE: + case PLATE: if (vtMarkupItem.getMarkupType() instanceof PlateCommentMarkupType) { return vtMarkupItem; } continue; - case CommentType.PRE: + case PRE: if (vtMarkupItem.getMarkupType() instanceof PreCommentMarkupType) { return vtMarkupItem; } continue; - case CommentType.EOL: + case EOL: if (vtMarkupItem.getMarkupType() instanceof EolCommentMarkupType) { return vtMarkupItem; } continue; - case CommentType.REPEATABLE: + case REPEATABLE: if (vtMarkupItem.getMarkupType() instanceof RepeatableCommentMarkupType) { return vtMarkupItem; } continue; - case CommentType.POST: + case POST: if (vtMarkupItem.getMarkupType() instanceof PostCommentMarkupType) { return vtMarkupItem; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoCodeUnit.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoCodeUnit.java index d465c7aebc..629201badc 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoCodeUnit.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoCodeUnit.java @@ -20,8 +20,7 @@ import java.util.*; import ghidra.program.model.address.*; import ghidra.program.model.lang.Register; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.Program; +import ghidra.program.model.listing.*; import ghidra.program.model.mem.*; import ghidra.program.model.symbol.*; import ghidra.util.*; @@ -43,7 +42,7 @@ abstract class PseudoCodeUnit implements CodeUnit { protected final static Reference[] emptyMemRefs = new Reference[0]; - protected Map comments = new HashMap(); + protected Map comments = new HashMap(); protected ReferenceManager refMgr; @@ -88,8 +87,7 @@ abstract class PseudoCodeUnit implements CodeUnit { * @param memBuffer the memory buffer where bytes can be obtained for this code unit. * @throws AddressOverflowException if code unit length causes wrap within space */ - PseudoCodeUnit(Address addr, int length, MemBuffer memBuffer) - throws AddressOverflowException { + PseudoCodeUnit(Address addr, int length, MemBuffer memBuffer) throws AddressOverflowException { this(addr, length, length, memBuffer); } @@ -124,8 +122,8 @@ abstract class PseudoCodeUnit implements CodeUnit { isValid = true; } catch (MemoryAccessException e) { - throw new RuntimeException("Not enough bytes in memory buffer to create code unit: " + - e.getMessage()); + throw new RuntimeException( + "Not enough bytes in memory buffer to create code unit: " + e.getMessage()); } } @@ -479,7 +477,7 @@ abstract class PseudoCodeUnit implements CodeUnit { } /** - * Get the code unit after this code unit. + * {@return the code unit after this code unit.} * * @throws ConcurrentModificationException * if this object is no longer valid. @@ -491,10 +489,9 @@ abstract class PseudoCodeUnit implements CodeUnit { } /** - * Get the code unit before this code unit. + * {@return the code unit before this code unit.} * - * @throws ConcurrentModificationException - * if this object is no longer valid. + * @throws ConcurrentModificationException if this object is no longer valid. */ public CodeUnit getPreviousCodeUnit() { if (program == null) @@ -503,7 +500,7 @@ abstract class PseudoCodeUnit implements CodeUnit { } @Override - public String getComment(int commentType) { + public String getComment(CommentType commentType) { return comments.get(commentType); //throw new UnsupportedOperationException(); } @@ -521,7 +518,7 @@ abstract class PseudoCodeUnit implements CodeUnit { * if this object is no longer valid. */ @Override - public String[] getCommentAsArray(int commentType) { + public String[] getCommentAsArray(CommentType commentType) { String comment = comments.get(commentType); if (comment == null) return new String[0]; @@ -544,7 +541,7 @@ abstract class PseudoCodeUnit implements CodeUnit { * if this object is no longer valid. */ @Override - public void setCommentAsArray(int commentType, String comment[]) { + public void setCommentAsArray(CommentType commentType, String comment[]) { setComment(commentType, comment[0]); //throw new UnsupportedOperationException(); } @@ -562,34 +559,9 @@ abstract class PseudoCodeUnit implements CodeUnit { * if this object is no longer valid. */ @Override - public void setComment(int commentType, String comment) { + public void setComment(CommentType commentType, String comment) { comments.put(commentType, comment); -// String oldValue = comments.get(commentType); comments.put(commentType, comment); -// int changeType; -// switch (commentType) { -// case CodeUnit.EOL_COMMENT: -// changeType = ChangeManager.DOCR_EOL_COMMENT_CHANGED; -// break; -// case CodeUnit.PLATE_COMMENT: -// changeType = ChangeManager.DOCR_PLATE_COMMENT_CHANGED; -// break; -// case CodeUnit.POST_COMMENT: -// changeType = ChangeManager.DOCR_POST_COMMENT_CHANGED; -// break; -// case CodeUnit.PRE_COMMENT: -// changeType = ChangeManager.DOCR_PRE_COMMENT_CHANGED; -// break; -// case CodeUnit.REPEATABLE_COMMENT: -// changeType = ChangeManager.DOCR_REPEATABLE_COMMENT_CHANGED; -// break; -// default: -// changeType = ChangeManager.DOCR_EOL_COMMENT_CHANGED; -// break; -// } -// -// program.setObjChanged(changeType, getMinAddress(), this, oldValue, comment); - //throw new UnsupportedOperationException(); } /** @@ -768,8 +740,8 @@ abstract class PseudoCodeUnit implements CodeUnit { ArrayList list = new ArrayList(); for (int i = 0; i < getNumOperands(); i++) { Reference[] refs = getOperandReferences(i); - for (int j = 0; j < refs.length; j++) { - list.add(refs[j]); + for (Reference ref : refs) { + list.add(ref); } } return list.toArray(emptyMemRefs); diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoDataComponent.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoDataComponent.java index 09186fa3b8..826d92ac43 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoDataComponent.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/app/util/PseudoDataComponent.java @@ -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. @@ -40,10 +40,9 @@ class PseudoDataComponent extends PseudoData { private int[] path; PseudoDataComponent(Program program, Address address, PseudoData parent, - DataTypeComponent component, MemBuffer memBuffer) - throws AddressOverflowException { - super(program, address, component.getDataType(), new WrappedMemBuffer(memBuffer, - component.getOffset())); + DataTypeComponent component, MemBuffer memBuffer) throws AddressOverflowException { + super(program, address, component.getDataType(), + new WrappedMemBuffer(memBuffer, component.getOffset())); this.indexInParent = component.getOrdinal(); this.parent = parent; this.component = component; @@ -170,9 +169,9 @@ class PseudoDataComponent extends PseudoData { } @Override - public synchronized String getComment(int commentType) { + public synchronized String getComment(CommentType commentType) { String cmt = super.getComment(commentType); - if (cmt == null && commentType == CodeUnit.EOL_COMMENT && component != null) { + if (cmt == null && commentType == CommentType.EOL && component != null) { cmt = component.getComment(); } return cmt; diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/ListingDB.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/ListingDB.java index eea1f70a14..27d9a25ab7 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/ListingDB.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/ListingDB.java @@ -480,18 +480,19 @@ class ListingDB implements Listing { } @Override - public CommentHistory[] getCommentHistory(Address addr, int commentType) { + public CommentHistory[] getCommentHistory(Address addr, CommentType commentType) { return codeMgr.getCommentHistory(addr, commentType); } @Override - public CodeUnitIterator getCommentCodeUnitIterator(int commentType, AddressSetView addrSet) { + public CodeUnitIterator getCommentCodeUnitIterator(CommentType commentType, + AddressSetView addrSet) { return codeMgr.getCommentCodeUnitIterator(commentType, addrSet); } @Override - public AddressIterator getCommentAddressIterator(int commentType, AddressSetView addrSet, - boolean forward) { + public AddressIterator getCommentAddressIterator(CommentType commentType, + AddressSetView addrSet, boolean forward) { return codeMgr.getCommentAddressIterator(commentType, addrSet, forward); } @@ -506,7 +507,7 @@ class ListingDB implements Listing { } @Override - public String getComment(int commentType, Address address) { + public String getComment(CommentType commentType, Address address) { return codeMgr.getComment(commentType, address); } @@ -516,7 +517,7 @@ class ListingDB implements Listing { } @Override - public void setComment(Address address, int commentType, String comment) { + public void setComment(Address address, CommentType commentType, String comment) { codeMgr.setComment(address, commentType, comment); } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeManager.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeManager.java index eb0dcbee04..1055d9d138 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeManager.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeManager.java @@ -138,8 +138,6 @@ public class CodeManager implements ErrorHandler, ManagerDB { throws CancelledException, IOException { try { - ReferenceManager refMgr = program.getReferenceManager(); - LongPropertyMapDB oldFallFroms = new LongPropertyMapDB(dbHandle, OpenMode.UPGRADE, this, null, addrMap, "FallFroms", monitor); @@ -940,7 +938,7 @@ public class CodeManager implements ErrorHandler, ManagerDB { * * @return the property map object associated to the property name */ - public PropertyMap getPropertyMap(String propertyName) { + public PropertyMap getPropertyMap(String propertyName) { return propertyMapMgr.getPropertyMap(propertyName); } @@ -1144,7 +1142,7 @@ public class CodeManager implements ErrorHandler, ManagerDB { } else { // Possibly a user-defined property. - PropertyMapDB pm = (PropertyMapDB) propertyMapMgr.getPropertyMap(property); + PropertyMapDB pm = (PropertyMapDB) propertyMapMgr.getPropertyMap(property); if (pm != null) { try { AddressKeyIterator iter = pm.getAddressKeyIterator(start, end, forward); @@ -1215,7 +1213,7 @@ public class CodeManager implements ErrorHandler, ManagerDB { } } // Possibly a user-defined property. - PropertyMapDB pm = (PropertyMapDB) propertyMapMgr.getPropertyMap(property); + PropertyMapDB pm = (PropertyMapDB) propertyMapMgr.getPropertyMap(property); if (pm != null) { try { AddressKeyIterator iter = pm.getAddressKeyIterator(addrSetView, forward); @@ -1234,7 +1232,8 @@ public class CodeManager implements ErrorHandler, ManagerDB { * @param set address set (null for all defined memory) * @return code unit iterator */ - public CodeUnitIterator getCommentCodeUnitIterator(int commentType, AddressSetView set) { + public CodeUnitIterator getCommentCodeUnitIterator(CommentType commentType, + AddressSetView set) { CodeUnitIterator it = getCodeUnitIterator(CodeUnit.COMMENT_PROPERTY, set, true); return new CommentTypeFilterIterator(it, commentType); } @@ -1260,7 +1259,7 @@ public class CodeManager implements ErrorHandler, ManagerDB { * @param forward true to iterate in the direction of increasing addresses. * @return address iterator */ - public AddressIterator getCommentAddressIterator(int commentType, AddressSetView set, + public AddressIterator getCommentAddressIterator(CommentType commentType, AddressSetView set, boolean forward) { if (set != null && set.isEmpty()) { return AddressIterator.EMPTY_ITERATOR; @@ -3280,19 +3279,18 @@ public class CodeManager implements ErrorHandler, ManagerDB { /** * Get the comment for the given type at the specified address. * - * @param commentType either EOL_COMMENT, PRE_COMMENT, POST_COMMENT, PLATE_COMMENT, or - * REPEATABLE_COMMENT + * @param commentType {@link CommentType comment type} * @param address the address of the comment. * @return the comment string of the appropriate type or null if no comment of that type exists * for this code unit * @throws IllegalArgumentException if type is not one of the types of comments supported */ - public String getComment(int commentType, Address address) { + public String getComment(CommentType commentType, Address address) { try { long addr = addrMap.getKey(address, false); DBRecord commentRec = getCommentAdapter().getRecord(addr); if (commentRec != null) { - return commentRec.getString(commentType); + return commentRec.getString(commentType.ordinal()); } } catch (IOException e) { @@ -3334,7 +3332,7 @@ public class CodeManager implements ErrorHandler, ManagerDB { * @param comment comment to set at the address * @throws IllegalArgumentException if type is not one of the types of comments supported */ - public void setComment(Address address, int commentType, String comment) { + public void setComment(Address address, CommentType commentType, String comment) { CodeUnit cu = getCodeUnitAt(address); if (cu != null) { cu.setComment(commentType, comment); @@ -3343,18 +3341,19 @@ public class CodeManager implements ErrorHandler, ManagerDB { lock.acquire(); try { long addr = addrMap.getKey(address, true); + DBRecord commentRec = getCommentAdapter().getRecord(addr); if (commentRec == null) { if (comment == null) { return; } - commentRec = getCommentAdapter().createRecord(addr, commentType, comment); + commentRec = getCommentAdapter().createRecord(addr, commentType.ordinal(), comment); sendNotification(address, commentType, null, comment); return; } - String oldValue = commentRec.getString(commentType); - commentRec.setString(commentType, comment); + String oldValue = commentRec.getString(commentType.ordinal()); + commentRec.setString(commentType.ordinal(), comment); sendNotification(address, commentType, oldValue, comment); for (int i = 0; i < CommentsDBAdapter.COMMENT_COL_COUNT; i++) { @@ -3373,12 +3372,13 @@ public class CodeManager implements ErrorHandler, ManagerDB { } } - void sendNotification(Address address, int commentType, String oldValue, String newValue) { + void sendNotification(Address address, CommentType commentType, String oldValue, + String newValue) { createCommentHistoryRecord(address, commentType, oldValue, newValue); program.setChanged(new CommentChangeRecord(commentType, address, oldValue, newValue)); } - void createCommentHistoryRecord(Address address, int commentType, String oldComment, + void createCommentHistoryRecord(Address address, CommentType commentType, String oldComment, String newComment) { if (oldComment == null) { oldComment = ""; @@ -3393,8 +3393,8 @@ public class CodeManager implements ErrorHandler, ManagerDB { long addr = addrMap.getKey(address, true); try { for (StringDiff diff : diffs) { - historyAdapter.createRecord(addr, (byte) commentType, diff.start, diff.end, - diff.text, date); + historyAdapter.createRecord(addr, (byte) commentType.ordinal(), diff.start, + diff.end, diff.text, date); } } catch (IOException e) { @@ -3409,7 +3409,7 @@ public class CodeManager implements ErrorHandler, ManagerDB { * @param commentType comment type * @return zero length array if no history exists */ - public CommentHistory[] getCommentHistory(Address addr, int commentType) { + public CommentHistory[] getCommentHistory(Address addr, CommentType commentType) { lock.acquire(); try { @@ -3454,12 +3454,13 @@ public class CodeManager implements ErrorHandler, ManagerDB { } // note: you must have the lock when calling this method - private List getHistoryRecords(Address addr, int commentType) throws IOException { + private List getHistoryRecords(Address addr, CommentType commentType) + throws IOException { RecordIterator it = historyAdapter.getRecordsByAddress(addr); List list = new ArrayList<>(); while (it.hasNext()) { DBRecord rec = it.next(); - if (rec.getByteValue(CommentHistoryAdapter.HISTORY_TYPE_COL) == commentType) { + if (rec.getByteValue(CommentHistoryAdapter.HISTORY_TYPE_COL) == commentType.ordinal()) { list.add(rec); } } @@ -3480,10 +3481,10 @@ public class CodeManager implements ErrorHandler, ManagerDB { return records.subList(0, records.size()); } - private String getComment(Address addr, int commentType) throws IOException { + private String getComment(Address addr, CommentType commentType) throws IOException { DBRecord record = commentAdapter.getRecord(addrMap.getKey(addr, false)); if (record != null) { - return record.getString(commentType); + return record.getString(commentType.ordinal()); } return ""; } @@ -3523,16 +3524,16 @@ public class CodeManager implements ErrorHandler, ManagerDB { RecordIterator iter = commentAdapter.getRecords(start, end, true); while (iter.hasNext()) { DBRecord rec = iter.next(); - addCommentHistoryRecord(rec, CodeUnit.PRE_COMMENT); - addCommentHistoryRecord(rec, CodeUnit.POST_COMMENT); - addCommentHistoryRecord(rec, CodeUnit.EOL_COMMENT); - addCommentHistoryRecord(rec, CodeUnit.PLATE_COMMENT); - addCommentHistoryRecord(rec, CodeUnit.REPEATABLE_COMMENT); + addCommentHistoryRecord(rec, CommentType.PRE); + addCommentHistoryRecord(rec, CommentType.POST); + addCommentHistoryRecord(rec, CommentType.EOL); + addCommentHistoryRecord(rec, CommentType.PLATE); + addCommentHistoryRecord(rec, CommentType.REPEATABLE); } } - private void addCommentHistoryRecord(DBRecord commentRec, int commentType) { - String comment = commentRec.getString(commentType); + private void addCommentHistoryRecord(DBRecord commentRec, CommentType commentType) { + String comment = commentRec.getString(commentType.ordinal()); if (comment != null) { createCommentHistoryRecord(addrMap.decodeAddress(commentRec.getKey()), commentType, comment, ""); diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeUnitDB.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeUnitDB.java index 18c62d4d68..aae9a3fa82 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeUnitDB.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CodeUnitDB.java @@ -190,7 +190,10 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC } @Override - public String getComment(int commentType) { + public String getComment(CommentType commentType) { + if (commentType == null) { + return null; + } lock.acquire(); try { checkIsValid(); @@ -200,7 +203,7 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC if (commentRec == null) { return null; } - return commentRec.getString(commentType); + return commentRec.getString(commentType.ordinal()); } finally { lock.release(); @@ -208,7 +211,7 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC } @Override - public String[] getCommentAsArray(int commentType) { + public String[] getCommentAsArray(CommentType commentType) { String comment = getComment(commentType); return StringUtilities.toLines(comment); } @@ -247,11 +250,7 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC SymbolTable st = codeMgr.getSymbolTable(); Symbol symbol = st.getPrimarySymbol(address); if (symbol != null) { - try { - return symbol.getName(); - } - catch (ConcurrentModificationException e) { - } + return symbol.getName(); } return null; } @@ -293,12 +292,8 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC PropertyMapManager upm = codeMgr.getPropertyMapManager(); ObjectPropertyMap pm = upm.getObjectPropertyMap(name); if (pm != null) { - try { - validate(lock); - return pm.get(address); - } - catch (ConcurrentModificationException e) { - } + validate(lock); + return pm.get(address); } return null; } @@ -344,12 +339,8 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC PropertyMapManager upm = codeMgr.getPropertyMapManager(); StringPropertyMap pm = upm.getStringPropertyMap(name); if (pm != null) { - try { - validate(lock); - return pm.getString(address); - } - catch (ConcurrentModificationException e) { - } + validate(lock); + return pm.getString(address); } return null; } @@ -366,12 +357,8 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC PropertyMapManager upm = codeMgr.getPropertyMapManager(); VoidPropertyMap pm = upm.getVoidPropertyMap(name); if (pm != null) { - try { - validate(lock); - return pm.hasProperty(address); - } - catch (ConcurrentModificationException e) { - } + validate(lock); + return pm.hasProperty(address); } return false; } @@ -381,12 +368,8 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC PropertyMapManager upm = codeMgr.getPropertyMapManager(); PropertyMap pm = upm.getPropertyMap(name); if (pm != null) { - try { - validate(lock); - return pm.hasProperty(address); - } - catch (ConcurrentModificationException e) { - } + validate(lock); + return pm.hasProperty(address); } return false; } @@ -433,12 +416,13 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC pm.remove(address); } catch (ConcurrentModificationException e) { + // ignore } } } @Override - public void setComment(int commentType, String comment) { + public void setComment(CommentType commentType, String comment) { lock.acquire(); try { checkDeleted(); @@ -451,8 +435,8 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC return; } try { - commentRec = - codeMgr.getCommentAdapter().createRecord(addr, commentType, comment); + commentRec = codeMgr.getCommentAdapter() + .createRecord(addr, commentType.ordinal(), comment); } catch (IOException e) { codeMgr.dbError(e); @@ -461,8 +445,8 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC return; } - String oldValue = commentRec.getString(commentType); - commentRec.setString(commentType, comment); + String oldValue = commentRec.getString(commentType.ordinal()); + commentRec.setString(commentType.ordinal(), comment); codeMgr.sendNotification(address, commentType, oldValue, comment); for (int i = 0; i < CommentsDBAdapter.COMMENT_COL_COUNT; i++) { @@ -485,7 +469,7 @@ abstract class CodeUnitDB extends DatabaseObject implements CodeUnit, ProcessorC } @Override - public void setCommentAsArray(int commentType, String[] comment) { + public void setCommentAsArray(CommentType commentType, String[] comment) { setComment(commentType, StringUtils.join(comment, '\n')); } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterAddressIterator.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterAddressIterator.java index e219dcf44c..98fff2deb9 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterAddressIterator.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterAddressIterator.java @@ -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. @@ -15,12 +15,11 @@ */ package ghidra.program.database.code; +import java.util.Iterator; + import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressIterator; -import ghidra.program.model.listing.Listing; -import ghidra.program.model.listing.Program; - -import java.util.Iterator; +import ghidra.program.model.listing.*; /** * Filters the given address iterator to only return addresses that have a comment of the given type @@ -28,7 +27,7 @@ import java.util.Iterator; public class CommentTypeFilterAddressIterator implements AddressIterator { private AddressIterator it; private Listing listing; - private int commentType; + private CommentType commentType; private Address nextAddr; /** @@ -36,7 +35,8 @@ public class CommentTypeFilterAddressIterator implements AddressIterator { * @param it an address iterator whose items are tested for the comment type. * @param commentType the type of comment to search for. */ - public CommentTypeFilterAddressIterator(Program program, AddressIterator it, int commentType) { + public CommentTypeFilterAddressIterator(Program program, AddressIterator it, + CommentType commentType) { this.listing = program.getListing(); this.it = it; this.commentType = commentType; diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterIterator.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterIterator.java index 35d2b44f80..7a5521cd15 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterIterator.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentTypeFilterIterator.java @@ -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. @@ -16,17 +15,16 @@ */ package ghidra.program.database.code; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.CodeUnitIterator; - import java.util.Iterator; +import ghidra.program.model.listing.*; + /** * Filters the given codeUnit iterator to only return codeUnits that have a comment of the given type */ public class CommentTypeFilterIterator implements CodeUnitIterator { private CodeUnitIterator it; - private int commentType; + private CommentType commentType; private CodeUnit nextCu; /** @@ -34,7 +32,7 @@ public class CommentTypeFilterIterator implements CodeUnitIterator { * @param it a codeunit iterator whose items are tested for the comment type. * @param commentType the type of comment to search for. */ - public CommentTypeFilterIterator(CodeUnitIterator it, int commentType) { + public CommentTypeFilterIterator(CodeUnitIterator it, CommentType commentType) { this.it = it; this.commentType = commentType; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapter.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapter.java index 3a4b3631e2..b9f07f2348 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapter.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapter.java @@ -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.program.database.map.AddressKeyIterator; import ghidra.program.database.map.AddressMap; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressSetView; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.util.exception.CancelledException; import ghidra.util.exception.VersionException; import ghidra.util.task.TaskMonitor; @@ -39,11 +39,16 @@ abstract class CommentsDBAdapter { static final Schema COMMENTS_SCHEMA; - static final int PRE_COMMENT_COL = CodeUnit.PRE_COMMENT; - static final int POST_COMMENT_COL = CodeUnit.POST_COMMENT; - static final int EOL_COMMENT_COL = CodeUnit.EOL_COMMENT; - static final int PLATE_COMMENT_COL = CodeUnit.PLATE_COMMENT; - static final int REPEATABLE_COMMENT_COL = CodeUnit.REPEATABLE_COMMENT; + // + // IMPORTANT: It is very important that the defined table columns and their sequence + // do not change and must match the ordinal ordering of CommentType enum values. + // + + static final int EOL_COMMENT_COL = CommentType.EOL.ordinal(); + static final int PRE_COMMENT_COL = CommentType.PRE.ordinal(); + static final int POST_COMMENT_COL = CommentType.POST.ordinal(); + static final int PLATE_COMMENT_COL = CommentType.PLATE.ordinal(); + static final int REPEATABLE_COMMENT_COL = CommentType.REPEATABLE.ordinal(); static final int COMMENT_COL_COUNT = 5; @@ -51,9 +56,9 @@ abstract class CommentsDBAdapter { static { NAMES = new String[5]; + NAMES[EOL_COMMENT_COL] = "EOL"; NAMES[PRE_COMMENT_COL] = "Pre"; NAMES[POST_COMMENT_COL] = "Post"; - NAMES[EOL_COMMENT_COL] = "EOL"; NAMES[PLATE_COMMENT_COL] = "Plate"; NAMES[REPEATABLE_COMMENT_COL] = "Repeatable"; @@ -62,17 +67,6 @@ abstract class CommentsDBAdapter { StringField.INSTANCE, StringField.INSTANCE, StringField.INSTANCE }, NAMES); } -// /** comment type for end of line */ -// static final int EOL_COMMENT = 0; -// /** comment type that goes before a code unit */ -// static final int PRE_COMMENT = 1; -// /** comment type that follows after a code unit */ -// static final int POST_COMMENT = 2; -// /** plate comment type */ -// static final int PLATE_COMMENT = 3; -// /** repeatable comment type */ -// static final int REPEATABLE_COMMENT = 4; - static CommentsDBAdapter getAdapter(DBHandle dbHandle, OpenMode openMode, AddressMap addrMap, TaskMonitor monitor) throws VersionException, CancelledException, IOException { @@ -105,6 +99,7 @@ abstract class CommentsDBAdapter { return new CommentsDBAdapterV1(handle, addrMap.getOldAddressMap(), false); } catch (VersionException e) { + // ignore } return new CommentsDBAdapterV0(handle, addrMap); diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapterV0.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapterV0.java index e29f37dd5a..f6d031e948 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapterV0.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/CommentsDBAdapterV0.java @@ -21,7 +21,6 @@ import db.*; import ghidra.program.database.map.*; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressSetView; -import ghidra.program.model.listing.CodeUnit; import ghidra.util.exception.CancelledException; import ghidra.util.exception.VersionException; import ghidra.util.task.TaskMonitor; @@ -32,27 +31,19 @@ import ghidra.util.task.TaskMonitor; class CommentsDBAdapterV0 extends CommentsDBAdapter { /** column for end of line comment */ - private static final int EOL_COMMENT_COLUMN = 0; + private static final int V0_EOL_COMMENT_COLUMN = 0; /** comment type that goes before a code unit */ - private static final int PRE_COMMENT_COLUMN = 1; + private static final int V0_PRE_COMMENT_COLUMN = 1; /** comment type that follows after a code unit */ - private static final int POST_COMMENT_COLUMN = 2; + private static final int V0_POST_COMMENT_COLUMN = 2; /** Property name for plate comment type */ - private static final int PLATE_COMMENT_COLUMN = 3; - /** The number of comment fields in this version. */ - /** Version 0 comment column names. */ - private static final String[] V0_NAMES = new String[4]; - static { - V0_NAMES[EOL_COMMENT_COLUMN] = "EOL"; - V0_NAMES[PRE_COMMENT_COLUMN] = "Pre"; - V0_NAMES[POST_COMMENT_COLUMN] = "Post"; - V0_NAMES[PLATE_COMMENT_COLUMN] = "Plate"; - } + private static final int V0_PLATE_COMMENT_COLUMN = 3; + /** Version 0 comment table schema. */ // private static final Schema V0_SCHEMA = new Schema(0, "Address", // new Class[] {StringField.class, StringField.class, // StringField.class, StringField.class}, -// V0_NAMES); +// "EOL", "Pre", "Post", "Plate"); /** the comment table. */ private Table commentTable; private AddressMap addrMap; @@ -62,8 +53,8 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { * */ @SuppressWarnings("unused") - public CommentsDBAdapterV0(DBHandle handle, AddressMap addrMap) throws IOException, - VersionException { + public CommentsDBAdapterV0(DBHandle handle, AddressMap addrMap) + throws IOException, VersionException { this.addrMap = addrMap.getOldAddressMap(); commentTable = handle.getTable(COMMENTS_TABLE_NAME); @@ -75,49 +66,31 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { } } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#getRecord(long) - */ @Override public DBRecord getRecord(long addr) throws IOException { - return adaptRecord(commentTable.getRecord(addr)); + return v0ConvertRecord(commentTable.getRecord(addr)); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#createRecord(long, int, java.lang.String) - */ @Override public DBRecord createRecord(long addr, int commentCol, String comment) throws IOException { - return null; + throw new UnsupportedOperationException(); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#deleteRecord(long) - */ @Override public boolean deleteRecord(long addr) throws IOException { - return false; + throw new UnsupportedOperationException(); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#deleteRecords(long, long) - */ @Override public boolean deleteRecords(Address start, Address end) throws IOException { - return false; + throw new UnsupportedOperationException(); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#updateRecord(ghidra.framework.store.db.DBRecord) - */ @Override public void updateRecord(DBRecord commentRec) throws IOException { + throw new UnsupportedOperationException(); } - /** - * - * @see ghidra.program.database.code.CommentsDBAdapter#getKeys(long, long, boolean) - */ @Override public AddressKeyIterator getKeys(Address start, Address end, boolean atStart) throws IOException { @@ -127,9 +100,6 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { return new AddressKeyIterator(commentTable, addrMap, start, end, end, false); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#getKeys(ghidra.program.model.address.AddressSetView, boolean) - */ @Override public AddressKeyIterator getKeys(AddressSetView set, boolean forward) throws IOException { if (forward) { @@ -138,9 +108,6 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { return new AddressKeyIterator(commentTable, addrMap, set, set.getMaxAddress(), false); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#getRecords(Address, Address, boolean) - */ @Override public RecordIterator getRecords(Address start, Address end, boolean atStart) throws IOException { @@ -154,41 +121,27 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { return new RecordIteratorAdapter(it); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#getRecords(Address) - */ @Override public RecordIterator getRecords(Address addr) throws IOException { - return new RecordIteratorAdapter(new AddressKeyRecordIterator(commentTable, addrMap, addr, - true)); + return new RecordIteratorAdapter( + new AddressKeyRecordIterator(commentTable, addrMap, addr, true)); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#getRecords() - */ @Override public RecordIterator getRecords() throws IOException { return new RecordIteratorAdapter(new AddressKeyRecordIterator(commentTable, addrMap)); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#putRecord(db.DBRecord) - */ @Override public void putRecord(DBRecord record) throws IOException { + throw new UnsupportedOperationException(); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#getRecordCount() - */ @Override public int getRecordCount() throws IOException { return commentTable.getRecordCount(); } - /** - * @see ghidra.program.database.code.CommentsDBAdapter#moveAddressRange(ghidra.program.model.address.Address, ghidra.program.model.address.Address, long, ghidra.util.task.TaskMonitor) - */ @Override void moveAddressRange(Address fromAddr, Address toAddr, long length, TaskMonitor monitor) throws CancelledException, IOException { @@ -200,29 +153,29 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { * @param recV0 the record matching the version 0 schema. * @return a current comment record. */ - private DBRecord adaptRecord(DBRecord recV0) { + private DBRecord v0ConvertRecord(DBRecord recV0) { if (recV0 == null) return null; DBRecord record = COMMENTS_SCHEMA.createRecord(recV0.getKey()); - String comment = recV0.getString(EOL_COMMENT_COLUMN); + String comment = recV0.getString(V0_EOL_COMMENT_COLUMN); if (comment != null) { - record.setString(CodeUnit.EOL_COMMENT, comment); + record.setString(EOL_COMMENT_COL, comment); } - comment = recV0.getString(PRE_COMMENT_COLUMN); + comment = recV0.getString(V0_PRE_COMMENT_COLUMN); if (comment != null) { - record.setString(CodeUnit.PRE_COMMENT, comment); + record.setString(PRE_COMMENT_COL, comment); } - comment = recV0.getString(POST_COMMENT_COLUMN); + comment = recV0.getString(V0_POST_COMMENT_COLUMN); if (comment != null) { - record.setString(CodeUnit.POST_COMMENT, comment); + record.setString(POST_COMMENT_COL, comment); } - comment = recV0.getString(PLATE_COMMENT_COLUMN); + comment = recV0.getString(V0_PLATE_COMMENT_COLUMN); if (comment != null) { - record.setString(CodeUnit.PLATE_COMMENT, comment); + record.setString(PLATE_COMMENT_COL, comment); } return record; @@ -235,46 +188,31 @@ class CommentsDBAdapterV0 extends CommentsDBAdapter { this.it = it; } - /** - * @see ghidra.framework.store.db.RecordIterator#delete() - */ @Override public boolean delete() throws IOException { - return false; + throw new UnsupportedOperationException(); } - /** - * @see ghidra.framework.store.db.RecordIterator#hasNext() - */ @Override public boolean hasNext() throws IOException { return it.hasNext(); } - /** - * @see ghidra.framework.store.db.RecordIterator#hasPrevious() - */ @Override public boolean hasPrevious() throws IOException { return it.hasPrevious(); } - /** - * @see ghidra.framework.store.db.RecordIterator#next() - */ @Override public DBRecord next() throws IOException { DBRecord rec = it.next(); - return adaptRecord(rec); + return v0ConvertRecord(rec); } - /** - * @see ghidra.framework.store.db.RecordIterator#previous() - */ @Override public DBRecord previous() throws IOException { DBRecord rec = it.previous(); - return adaptRecord(rec); + return v0ConvertRecord(rec); } } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataComponent.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataComponent.java index b59d447030..62dd15dc14 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataComponent.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataComponent.java @@ -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. @@ -20,8 +20,7 @@ import ghidra.docking.settings.Settings; import ghidra.program.database.DBObjectCache; import ghidra.program.model.address.Address; import ghidra.program.model.data.*; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.Data; +import ghidra.program.model.listing.*; import ghidra.program.model.mem.MemoryAccessException; /** @@ -234,11 +233,11 @@ class DataComponent extends DataDB { } @Override - public int getBytes(byte[] b, int offset) { + public int getBytes(byte[] b, int off) { lock.acquire(); try { checkIsValid(); - return parent.getBytes(b, this.offset + offset); + return parent.getBytes(b, this.offset + off); } finally { lock.release(); @@ -274,9 +273,9 @@ class DataComponent extends DataDB { } @Override - public String getComment(int commentType) { + public String getComment(CommentType commentType) { String cmt = super.getComment(commentType); - if (cmt == null && commentType == CodeUnit.EOL_COMMENT && component != null) { + if (cmt == null && commentType == CommentType.EOL && component != null) { cmt = component.getComment(); } return cmt; diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataDB.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataDB.java index 5e02659908..f0e9f78cf8 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataDB.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/code/DataDB.java @@ -25,6 +25,7 @@ import ghidra.program.database.data.ProgramDataTypeManager; import ghidra.program.database.map.AddressMap; import ghidra.program.model.address.*; import ghidra.program.model.data.*; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Data; import ghidra.program.model.mem.Memory; import ghidra.program.model.mem.MemoryBlock; @@ -459,7 +460,7 @@ class DataDB extends CodeUnitDB implements Data { } @Override - public String getComment(int commentType) { + public String getComment(CommentType commentType) { Data child = getComponentContaining(0); if (child != null) { // avoid caching issue by maintaining comment at lowest point in data path @@ -469,7 +470,7 @@ class DataDB extends CodeUnitDB implements Data { } @Override - public void setComment(int commentType, String comment) { + public void setComment(CommentType commentType, String comment) { Data child = getComponentContaining(0); if (child != null) { // avoid caching issue by maintaining comment at lowest point in data path diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/function/FunctionDB.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/function/FunctionDB.java index 740bb7d1cb..20a428a911 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/function/FunctionDB.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/function/FunctionDB.java @@ -262,7 +262,7 @@ public class FunctionDB extends DatabaseObject implements Function { manager.lock.acquire(); try { checkIsValid(); - return manager.getCodeManager().getComment(CodeUnit.PLATE_COMMENT, getEntryPoint()); + return manager.getCodeManager().getComment(CommentType.PLATE, getEntryPoint()); } finally { manager.lock.release(); @@ -280,7 +280,7 @@ public class FunctionDB extends DatabaseObject implements Function { try { startUpdate(); checkDeleted(); - manager.getCodeManager().setComment(getEntryPoint(), CodeUnit.PLATE_COMMENT, comment); + manager.getCodeManager().setComment(getEntryPoint(), CommentType.PLATE, comment); } finally { endUpdate(); @@ -293,8 +293,7 @@ public class FunctionDB extends DatabaseObject implements Function { manager.lock.acquire(); try { checkIsValid(); - return manager.getCodeManager() - .getComment(CodeUnit.REPEATABLE_COMMENT, getEntryPoint()); + return manager.getCodeManager().getComment(CommentType.REPEATABLE, getEntryPoint()); } finally { manager.lock.release(); @@ -311,8 +310,7 @@ public class FunctionDB extends DatabaseObject implements Function { manager.lock.acquire(); try { checkDeleted(); - manager.getCodeManager() - .setComment(getEntryPoint(), CodeUnit.REPEATABLE_COMMENT, comment); + manager.getCodeManager().setComment(getEntryPoint(), CommentType.REPEATABLE, comment); } finally { manager.lock.release(); diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/oldfunction/OldFunctionDataDB.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/oldfunction/OldFunctionDataDB.java index 6104959ca7..347c985f48 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/oldfunction/OldFunctionDataDB.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/oldfunction/OldFunctionDataDB.java @@ -16,7 +16,8 @@ package ghidra.program.database.oldfunction; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.List; import db.DBRecord; import db.Field; @@ -47,8 +48,8 @@ class OldFunctionDataDB { private OldStackFrameDB frame; private List regParams; - OldFunctionDataDB(OldFunctionManager functionManager, AddressMap addrMap, DBRecord functionRecord, - AddressSetView body) { + OldFunctionDataDB(OldFunctionManager functionManager, AddressMap addrMap, + DBRecord functionRecord, AddressSetView body) { this.functionManager = functionManager; this.addrMap = addrMap; @@ -83,7 +84,6 @@ class OldFunctionDataDB { */ public synchronized String getComment() { CodeUnit cu = program.getCodeManager().getCodeUnitContaining(entryPoint); - return cu.getComment(CommentType.PLATE); } @@ -254,17 +254,15 @@ class OldFunctionDataDB { Parameter[] parms = new Parameter[regParams.size() + frame.getParameterCount()]; int ordinal = 0; - Iterator iter = regParams.iterator(); - while (iter.hasNext()) { - Parameter rp = iter.next(); + for (Parameter rp : regParams) { parms[ordinal++] = rp; } try { Variable[] stackParams = frame.getParameters(); - for (int i = 0; i < stackParams.length; i++) { - parms[ordinal++] = new OldFunctionParameter(stackParams[i].getName(), ordinal, - stackParams[i].getDataType(), stackParams[i].getVariableStorage(), program, + for (Variable stackParam : stackParams) { + parms[ordinal++] = new OldFunctionParameter(stackParam.getName(), ordinal, + stackParam.getDataType(), stackParam.getVariableStorage(), program, SourceType.USER_DEFINED); } } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CodeUnit.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CodeUnit.java index 214c5118b8..cb95478a4b 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CodeUnit.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CodeUnit.java @@ -38,38 +38,36 @@ public interface CodeUnit extends MemBuffer, PropertySet { */ public final static int MNEMONIC = -1; - public static final int NO_COMMENT = -1; - /** * comment type for end of line * @deprecated use {@link CommentType#EOL} */ - @Deprecated - public static final int EOL_COMMENT = 0; + @Deprecated(forRemoval = true, since = "11.4") + public static final int EOL_COMMENT = 0; // CommentType.EOL.ordinal(); /** * comment type that goes before a code unit * @deprecated use {@link CommentType#PRE} */ - @Deprecated - public static final int PRE_COMMENT = 1; + @Deprecated(forRemoval = true, since = "11.4") + public static final int PRE_COMMENT = 1; // CommentType.PRE.ordinal(); /** * comment type that follows after a code unit * @deprecated use {@link CommentType#POST} */ - @Deprecated - public static final int POST_COMMENT = 2; + @Deprecated(forRemoval = true, since = "11.4") + public static final int POST_COMMENT = 2; // CommentType.POST.ordinal(); /** * Property name for plate comment type * @deprecated use {@link CommentType#POST} */ - @Deprecated - public static final int PLATE_COMMENT = 3; + @Deprecated(forRemoval = true, since = "11.4") + public static final int PLATE_COMMENT = 3; // CommentType.PLATE.ordinal(); /** * Property name for repeatable comment type * @deprecated use {@link CommentType#REPEATABLE} */ - @Deprecated - public static final int REPEATABLE_COMMENT = 4; + @Deprecated(forRemoval = true, since = "11.4") + public static final int REPEATABLE_COMMENT = 4; // CommentType.REPEATABLE.ordinal(); /** * Any comment property. @@ -99,42 +97,36 @@ public interface CodeUnit extends MemBuffer, PropertySet { public String getAddressString(boolean showBlockName, boolean pad); /** - * Get the label for this code unit. - * @return the label for this code unit. + * {@return the label for this code unit.} */ public String getLabel(); /** - * Get the Symbols for this code unit. - * @return the Symbols for this code unit. + * {@return the Symbols for this code unit.} * @throws ConcurrentModificationException if this object is no * longer valid. */ public Symbol[] getSymbols(); /** - * Get the Primary Symbol for this code unit. - * @return the Primary Symbol for this code unit. + * {@return the Primary Symbol for this code unit.} * @throws ConcurrentModificationException if this object is no * longer valid. */ public Symbol getPrimarySymbol(); /** - * Get the starting address for this code unit. - * @return the starting address for this code unit. + * {@return the starting address for this code unit.} */ public Address getMinAddress(); /** - * Get the ending address for this code unit. - * @return the ending address for this code unit. + * {@return the ending address for this code unit.} */ public Address getMaxAddress(); /** - * Get the mnemonic for this code unit, e.g., MOV, JMP - * @return the mnemonic for this code unit, e.g., MOV, JMP + * {@return the mnemonic for this code unit, e.g., MOV, JMP} */ public String getMnemonicString(); @@ -149,19 +141,19 @@ public interface CodeUnit extends MemBuffer, PropertySet { * three types of comments supported * @deprecated use {@link #getComment(CommentType)} instead */ - @Deprecated - public String getComment(int commentType); + @Deprecated(forRemoval = true, since = "11.4") + public default String getComment(int commentType) { + return getComment(CommentType.valueOf(commentType)); + } /** * Get the comment for the given type * - * @param type which type of comment to retrieve + * @param type {@link CommentType comment type} * @return the comment string of the appropriate type or null if no comment of * that type exists for this code unit */ - public default String getComment(CommentType type) { - return getComment(type.ordinal()); - } + public String getComment(CommentType type); /** * Get the comment for the given type and parse it into an array of strings @@ -176,21 +168,21 @@ public interface CodeUnit extends MemBuffer, PropertySet { * three types of comments supported * @deprecated use {@link #getCommentAsArray(CommentType)} instead */ - @Deprecated - public String[] getCommentAsArray(int commentType); + @Deprecated(forRemoval = true, since = "11.4") + public default String[] getCommentAsArray(int commentType) { + return getCommentAsArray(CommentType.valueOf(commentType)); + } /** * Get the comment for the given type and parse it into an array of strings * such that each line is its own string. * - * @param type the comment type to retrieve + * @param type {@link CommentType comment type} * @return an array of strings where each item in the array is a line of text * in the comment. If there is no comment of the requested type, an empty array * is returned. */ - public default String[] getCommentAsArray(CommentType type) { - return getCommentAsArray(type.ordinal()); - } + public String[] getCommentAsArray(CommentType type); /** * Set the comment for the given comment type. Passing null clears the comment @@ -204,17 +196,17 @@ public interface CodeUnit extends MemBuffer, PropertySet { * @deprecated use {@link #setComment(CommentType, String)} instead */ @Deprecated - public void setComment(int commentType, String comment); + public default void setComment(int commentType, String comment) { + setComment(CommentType.valueOf(commentType), comment); + } /** * Set the comment for the given comment type. Passing null clears the comment * - * @param type of comment to set + * @param type {@link CommentType comment type} * @param comment comment for code unit; null clears the comment */ - public default void setComment(CommentType type, String comment) { - setComment(type.ordinal(), comment); - } + public void setComment(CommentType type, String comment); /** * Set the comment (with each line in its own string) for the given comment type @@ -225,12 +217,20 @@ public interface CodeUnit extends MemBuffer, PropertySet { * @throws IllegalArgumentException if type is not one of the * three types of comments supported */ - public void setCommentAsArray(int commentType, String[] comment); - - public default void setCommentAsArray(CommentType type, String[] comment) { - setCommentAsArray(type.ordinal(), comment); + public default void setCommentAsArray(int commentType, String[] comment) { + setCommentAsArray(CommentType.valueOf(commentType), comment); } + /** + * Set the comment (with each line in its own string) for the given comment type + * + * @param type {@link CommentType comment type} + * @param comment an array of strings where each string is a single line of the comment. + * @throws IllegalArgumentException if type is not one of the + * three types of comments supported + */ + public void setCommentAsArray(CommentType type, String[] comment); + /** * Get length of this code unit. * NOTE: If an {@link Instruction#isLengthOverridden() instruction length-override} is @@ -260,9 +260,8 @@ public interface CodeUnit extends MemBuffer, PropertySet { public void getBytesInCodeUnit(byte[] buffer, int bufferOffset) throws MemoryAccessException; /** - * Returns true if address is contained in the range of this codeUnit + * {@return true if address is contained in the range of this codeUnit} * @param testAddr the address to test. - * @return true if address is contained in the range of this codeUnit */ public boolean contains(Address testAddr); @@ -298,16 +297,14 @@ public interface CodeUnit extends MemBuffer, PropertySet { public Reference[] getMnemonicReferences(); /** - * Get the references for the operand index. + * {@return the references for the operand index.} * @param index operand index (0 is the first operand) - * @return the references for the operand index. */ public Reference[] getOperandReferences(int index); /** - * Get the primary reference for the operand index. + * {@return the primary reference for the operand index.} * @param index operand index (0 is the first operand) - * @return the primary reference for the operand index. */ public Reference getPrimaryReference(int index); @@ -336,14 +333,12 @@ public interface CodeUnit extends MemBuffer, PropertySet { public Reference[] getReferencesFrom(); /** - * Get an iterator over all references TO this code unit. - * @return an iterator over all references TO this code unit. + * {@return an iterator over all references TO this code unit.} */ public ReferenceIterator getReferenceIteratorTo(); /** - * Returns the program that generated this CodeUnit. - * @return the program that generated this CodeUnit. + * {@return the program that generated this CodeUnit.} */ public Program getProgram(); @@ -356,8 +351,7 @@ public interface CodeUnit extends MemBuffer, PropertySet { /** * Remove external reference (if any) at the given opIndex - * opIndex the index of the operand from which to remove any external reference. - * @param opIndex the op index + * @param opIndex the index of the operand from which to remove any external reference. */ public void removeExternalReference(int opIndex); @@ -403,8 +397,7 @@ public interface CodeUnit extends MemBuffer, PropertySet { RefType refType); /** - * Get the number of operands for this code unit. - * @return the number of operands for this code unit. + * {@return the number of operands for this code unit.} */ public int getNumOperands(); diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentHistory.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentHistory.java index 817e1be6be..3fd66eca47 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentHistory.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentHistory.java @@ -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,7 +27,7 @@ import ghidra.program.model.address.Address; public class CommentHistory { private Address addr; - private int commentType; + private CommentType commentType; private Date modificationDate; private String userName; private String comments; @@ -40,7 +40,7 @@ public class CommentHistory { * @param comments the list of comments. * @param modificationDate the date the comment was changed. */ - public CommentHistory(Address addr, int commentType, String userName, String comments, + public CommentHistory(Address addr, CommentType commentType, String userName, String comments, Date modificationDate) { this.addr = addr; this.commentType = commentType; @@ -77,7 +77,7 @@ public class CommentHistory { * Get the comment type * @return the comment type */ - public int getCommentType() { + public CommentType getCommentType() { return commentType; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentType.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentType.java index befb6a7a21..74111ff024 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentType.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/CommentType.java @@ -19,10 +19,38 @@ package ghidra.program.model.listing; * Types of comments that be placed at an address or on a {@link CodeUnit} */ public enum CommentType { + + // + // IMPORTANT: The ordinals of the defined comment types must be preserved since + // these values are used for comment storage. Any new comment types must be added + // to the bottom of the list. + // EOL, // comments that appear at the end of the line PRE, // comments that appear before the code unit POST, // comments that appear after the code unit PLATE, // comments that appear before the code unit with a decorated border REPEATABLE // comments that appear at locations that refer to the address // where this comment is defined + ; + + /** + * Get the comment type which corresponds to the specified ordinal value. + *

+ * NOTE: This method is intended for conversion of old legacy commentType integer + * values to the enum type. + * + * @param commentType comment type value + * @return comment type enum which corresponds to specified ordinal + * @throws IllegalArgumentException if invalid comment type ordinal specified + * + */ + public static CommentType valueOf(int commentType) throws IllegalArgumentException { + try { + return CommentType.values()[commentType]; + } + catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException("Invalid comment type: " + commentType, e); + } + } + } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/DataStub.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/DataStub.java index 2bcff01401..b009ca2c81 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/DataStub.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/DataStub.java @@ -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. @@ -130,22 +130,22 @@ public class DataStub implements Data { } @Override - public String getComment(int commentType) { + public String getComment(CommentType commentType) { throw new UnsupportedOperationException(); } @Override - public String[] getCommentAsArray(int commentType) { + public String[] getCommentAsArray(CommentType commentType) { throw new UnsupportedOperationException(); } @Override - public void setComment(int commentType, String comment) { + public void setComment(CommentType commentType, String comment) { throw new UnsupportedOperationException(); } @Override - public void setCommentAsArray(int commentType, String[] comment) { + public void setCommentAsArray(CommentType commentType, String[] comment) { throw new UnsupportedOperationException(); } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/InstructionStub.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/InstructionStub.java index 7961ec2852..616fdadac4 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/InstructionStub.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/InstructionStub.java @@ -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. @@ -127,22 +127,22 @@ public class InstructionStub implements Instruction { } @Override - public String getComment(int commentType) { + public String getComment(CommentType commentType) { throw new UnsupportedOperationException(); } @Override - public String[] getCommentAsArray(int commentType) { + public String[] getCommentAsArray(CommentType commentType) { throw new UnsupportedOperationException(); } @Override - public void setComment(int commentType, String comment) { + public void setComment(CommentType commentType, String comment) { throw new UnsupportedOperationException(); } @Override - public void setCommentAsArray(int commentType, String[] comment) { + public void setCommentAsArray(CommentType commentType, String[] comment) { throw new UnsupportedOperationException(); } @@ -207,7 +207,8 @@ public class InstructionStub implements Instruction { } @Override - public void addOperandReference(int index, Address refAddr, RefType type, SourceType sourceType) { + public void addOperandReference(int index, Address refAddr, RefType type, + SourceType sourceType) { throw new UnsupportedOperationException(); } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/Listing.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/Listing.java index d27f51785f..294db1a4da 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/Listing.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/Listing.java @@ -141,8 +141,13 @@ public interface Listing { * @param addrSet address set * @return a CodeUnitIterator that returns all code units from the indicated * address set that have the specified comment type defined + * @deprecated use {@link #getCommentCodeUnitIterator(CommentType, AddressSetView)} */ - public CodeUnitIterator getCommentCodeUnitIterator(int commentType, AddressSetView addrSet); + @Deprecated(forRemoval = true, since = "11.4") + public default CodeUnitIterator getCommentCodeUnitIterator(int commentType, + AddressSetView addrSet) { + return getCommentCodeUnitIterator(CommentType.valueOf(commentType), addrSet); + } /** * Get a forward code unit iterator over code units that have the specified @@ -153,10 +158,7 @@ public interface Listing { * @return a CodeUnitIterator that returns all code units from the indicated * address set that have the specified comment type defined */ - public default CodeUnitIterator getCommentCodeUnitIterator(CommentType type, - AddressSetView addrSet) { - return getCommentCodeUnitIterator(type.ordinal(), addrSet); - } + public CodeUnitIterator getCommentCodeUnitIterator(CommentType type, AddressSetView addrSet); /** * Get a forward iterator over addresses that have the specified comment @@ -170,9 +172,11 @@ public interface Listing { * address set that have the specified comment type defined * @deprecated use {@link #getCommentAddressIterator(CommentType, AddressSetView, boolean)} */ - @Deprecated - public AddressIterator getCommentAddressIterator(int commentType, AddressSetView addrSet, - boolean forward); + @Deprecated(forRemoval = true, since = "11.4") + public default AddressIterator getCommentAddressIterator(int commentType, + AddressSetView addrSet, boolean forward) { + return getCommentAddressIterator(CommentType.valueOf(commentType), addrSet, forward); + } /** * Get a forward iterator over addresses that have the specified comment @@ -185,10 +189,8 @@ public interface Listing { * @return an AddressIterator that returns all addresses from the indicated * address set that have the specified comment type defined */ - public default AddressIterator getCommentAddressIterator(CommentType type, - AddressSetView addrSet, boolean forward) { - return getCommentAddressIterator(type.ordinal(), addrSet, forward); - } + public AddressIterator getCommentAddressIterator(CommentType type, AddressSetView addrSet, + boolean forward); /** * Get a forward iterator over addresses that have any type of comment. @@ -213,15 +215,10 @@ public interface Listing { * comments supported * @deprecated use {@link #getComment(CommentType, Address)} */ - @Deprecated - public String getComment(int commentType, Address address); - - /** - * Get all the comments at the given address. - * @param address the address get comments - * @return a CodeUnitComments object that has all the comments at the address. - */ - public CodeUnitComments getAllComments(Address address); + @Deprecated(forRemoval = true, since = "11.4") + public default String getComment(int commentType, Address address) { + return getComment(CommentType.valueOf(commentType), address); + } /** * Get the comment for the given type at the specified address. @@ -231,9 +228,14 @@ public interface Listing { * @return the comment string of the appropriate type or null if no comment * of that type exists for this code unit */ - public default String getComment(CommentType type, Address address) { - return getComment(type.ordinal(), address); - } + public String getComment(CommentType type, Address address); + + /** + * Get all the comments at the given address. + * @param address the address get comments + * @return a CodeUnitComments object that has all the comments at the address. + */ + public CodeUnitComments getAllComments(Address address); /** * Set the comment for the given comment type at the specified address. @@ -246,8 +248,10 @@ public interface Listing { * comments supported * @deprecated use {@link #setComment(Address, CommentType, String)} */ - @Deprecated - public void setComment(Address address, int commentType, String comment); + @Deprecated(forRemoval = true, since = "11.4") + public default void setComment(Address address, int commentType, String comment) { + setComment(address, CommentType.valueOf(commentType), comment); + } /** * Set the comment for the given comment type at the specified address. @@ -258,9 +262,7 @@ public interface Listing { * @throws IllegalArgumentException if type is not one of the types of * comments supported */ - public default void setComment(Address address, CommentType type, String comment) { - setComment(address, type.ordinal(), comment); - } + public void setComment(Address address, CommentType type, String comment); /** * get a CodeUnit iterator that will iterate over the entire address space. @@ -655,7 +657,7 @@ public interface Listing { * @param propertyName the property name * @return PropertyMap the propertyMap object. */ - public PropertyMap getPropertyMap(String propertyName); + public PropertyMap getPropertyMap(String propertyName); /** * Creates a new Instruction object at the given address. The specified @@ -1048,8 +1050,21 @@ public interface Listing { * @param addr address for comments * @param commentType comment type defined in CodeUnit * @return array of comment history records + * @deprecated use {@link #getCommentHistory(Address, CommentType)} */ - public CommentHistory[] getCommentHistory(Address addr, int commentType); + @Deprecated(forRemoval = true, since = "11.4") + public default CommentHistory[] getCommentHistory(Address addr, int commentType) { + return getCommentHistory(addr, CommentType.valueOf(commentType)); + } + + /** + * Get the comment history for comments at the given address. + * + * @param addr address for comments + * @param type {@link CommentType comment type} + * @return array of comment history records + */ + public CommentHistory[] getCommentHistory(Address addr, CommentType type); /** * Returns the number of addresses where at least one comment type has been applied. diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/StubListing.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/StubListing.java index 20cc01e52c..fa9ced7e64 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/StubListing.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/StubListing.java @@ -75,13 +75,14 @@ public class StubListing implements Listing { } @Override - public CodeUnitIterator getCommentCodeUnitIterator(int commentType, AddressSetView addrSet) { + public CodeUnitIterator getCommentCodeUnitIterator(CommentType commentType, + AddressSetView addrSet) { throw new UnsupportedOperationException(); } @Override - public AddressIterator getCommentAddressIterator(int commentType, AddressSetView addrSet, - boolean forward) { + public AddressIterator getCommentAddressIterator(CommentType commentType, + AddressSetView addrSet, boolean forward) { throw new UnsupportedOperationException(); } @@ -96,7 +97,7 @@ public class StubListing implements Listing { } @Override - public String getComment(int commentType, Address address) { + public String getComment(CommentType commentType, Address address) { throw new UnsupportedOperationException(); } @@ -106,7 +107,7 @@ public class StubListing implements Listing { } @Override - public void setComment(Address address, int commentType, String comment) { + public void setComment(Address address, CommentType commentType, String comment) { throw new UnsupportedOperationException(); } @@ -481,7 +482,7 @@ public class StubListing implements Listing { } @Override - public CommentHistory[] getCommentHistory(Address addr, int commentType) { + public CommentHistory[] getCommentHistory(Address addr, CommentType commentType) { throw new UnsupportedOperationException(); } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/AutomaticCommentFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/AutomaticCommentFieldLocation.java index 7b1fd60085..1cc7f84b27 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/AutomaticCommentFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/AutomaticCommentFieldLocation.java @@ -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. @@ -17,8 +17,7 @@ package ghidra.program.util; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; -import ghidra.program.model.listing.Program; +import ghidra.program.model.listing.*; /** * The AutomaticCommentFieldLocation class contains specific location information @@ -41,7 +40,7 @@ public class AutomaticCommentFieldLocation extends CommentFieldLocation { */ public AutomaticCommentFieldLocation(Program program, Address addr, int[] componentPath, String[] comment, int row, int charOffset, int currentCommentRow) { - super(program, addr, componentPath, comment, CodeUnit.EOL_COMMENT, row, charOffset); + super(program, addr, componentPath, comment, CommentType.EOL, row, charOffset); this.currentCommentRow = currentCommentRow; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/BlockStartLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/BlockStartLocation.java index 55a7c3ce94..a3135f8f1d 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/BlockStartLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/BlockStartLocation.java @@ -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. @@ -42,7 +42,7 @@ public class BlockStartLocation extends CommentFieldLocation { public BlockStartLocation(Program program, Address addr, int[] componentPath, int row, int charOffset, String[] comment, int commentRow) { - super(program, addr, componentPath, comment, CodeUnit.NO_COMMENT, row, charOffset); + super(program, addr, componentPath, comment, null, row, charOffset); } /** diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentChangeRecord.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentChangeRecord.java index 97cda3909f..630929dcf4 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentChangeRecord.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentChangeRecord.java @@ -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. @@ -17,6 +17,7 @@ package ghidra.program.util; import ghidra.program.model.address.Address; import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; /** * Change record for comment changes @@ -24,16 +25,17 @@ import ghidra.program.model.listing.CodeUnit; public class CommentChangeRecord extends ProgramChangeRecord { // types defined in CodeUnit - private int commentType; + private CommentType commentType; /** * Constructor - * @param commentType the type of comment (as defined in {@link CodeUnit}) + * @param commentType {@link CommentType comment type} * @param address the address of the comment change * @param oldValue the old comment (may be null for a new comment) * @param newValue the new comment (may be null if the comment was deleted) */ - public CommentChangeRecord(int commentType, Address address, String oldValue, String newValue) { + public CommentChangeRecord(CommentType commentType, Address address, String oldValue, + String newValue) { super(ProgramEvent.COMMENT_CHANGED, address, address, null, oldValue, newValue); this.commentType = commentType; } @@ -42,7 +44,7 @@ public class CommentChangeRecord extends ProgramChangeRecord { * Returns the comment type as defined in {@link CodeUnit}. * @return the comment type */ - public int getCommentType() { + public CommentType getCommentType() { return commentType; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentFieldLocation.java index d3165392fe..cf6a9a622f 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentFieldLocation.java @@ -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. @@ -21,7 +21,7 @@ import java.util.Arrays; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; /** @@ -31,7 +31,7 @@ import ghidra.program.model.listing.Program; public class CommentFieldLocation extends CodeUnitLocation { protected String[] comment; - protected int type; + protected CommentType type; /** * Construct a new CommentFieldLocation. @@ -41,16 +41,14 @@ public class CommentFieldLocation extends CodeUnitLocation { * @param componentPath if not null, it is the array of indexes that point * to a specific data type inside of another data type * @param comment The array of strings that make up the comment - * @param type The type of this comment. - * Can be either CodeUnit.PRE_COMMENT, CodeUnit.POST_COMMENT, - * CodeUnit.PLATE_COMMENT, CodeUnit.EOL_COMMENT, or CodeUnit.REPEATABLE_COMMENT. + * @param type The type of this comment (null for no-comment type) * @param row The index of the string that contains the exact location. * @param charOffset The position within the string that specifies the exact location. * @exception IllegalArgumentException * Thrown if type is not one of the comment values given in CodeUnit */ public CommentFieldLocation(Program program, Address addr, int[] componentPath, - String[] comment, int type, int row, int charOffset) { + String[] comment, CommentType type, int row, int charOffset) { super(program, addr, componentPath, row, 0, charOffset); this.comment = comment; @@ -68,19 +66,6 @@ public class CommentFieldLocation extends CodeUnitLocation { public CommentFieldLocation() { } - /** - * Checks that the type is a valid comment type. - * @throws IllegalArgumentException if this doesn't have a valid comment type. - */ - protected void validateType() { - if (type != CodeUnit.PRE_COMMENT && type != CodeUnit.POST_COMMENT && - type != CodeUnit.EOL_COMMENT && type != CodeUnit.REPEATABLE_COMMENT && - type != CodeUnit.PLATE_COMMENT && type != CodeUnit.NO_COMMENT) { - throw new IllegalArgumentException( - "The comment type was " + type + ", but it must be from 0 to 4"); - } - } - /** * Returns the array of strings that make up the comment. * @return the comment @@ -90,11 +75,9 @@ public class CommentFieldLocation extends CodeUnitLocation { } /** - * Returns the comment type. The type is either CodeUnit.EOL_COMMENT, CodeUnit.POST_COMMENT, - * CodeUnit.PLATE_COMMENT, CodeUnit.PRE_COMMENT, or CodeUnit.REPEATABLE_COMMENT. - * @return the comment type + * {@return the comment type or null if no-comment.} */ - public int getCommentType() { + public CommentType getCommentType() { return type; } @@ -103,7 +86,8 @@ public class CommentFieldLocation extends CodeUnitLocation { */ @Override public String toString() { - return super.toString() + ", Comment Type = " + type; + String str = type != null ? type.name() : "NO-COMMENT"; + return super.toString() + ", Comment Type = " + str; } @Override @@ -111,7 +95,9 @@ public class CommentFieldLocation extends CodeUnitLocation { final int prime = 31; int result = super.hashCode(); result = prime * result + Arrays.hashCode(comment); - result = prime * result + type; + if (type != null) { + result = prime * result + type.hashCode(); + } return result; } @@ -140,14 +126,14 @@ public class CommentFieldLocation extends CodeUnitLocation { public void saveState(SaveState obj) { super.saveState(obj); obj.putStrings("_COMMENT", comment); - obj.putInt("_TYPE", type); + obj.putInt("_TYPE", type != null ? type.ordinal() : -1); } @Override public void restoreState(Program p, SaveState obj) { super.restoreState(p, obj); - comment = obj.getStrings("_COMMENT", new String[0]); - type = obj.getInt("_TYPE", 0); + int commentType = obj.getInt("_TYPE", CommentType.EOL.ordinal()); + type = commentType < 0 ? null : CommentType.valueOf(commentType); } } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentTypeUtils.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentTypeUtils.java index c45214a63b..4bfd08484c 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentTypeUtils.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/CommentTypeUtils.java @@ -28,32 +28,33 @@ public class CommentTypeUtils { * @param defaultCommentType * @return comment type */ - public static int getCommentType(CodeUnit cu, ProgramLocation loc, int defaultCommentType) { + public static CommentType getCommentType(CodeUnit cu, ProgramLocation loc, + CommentType defaultCommentType) { if (loc instanceof CommentFieldLocation) { CommentFieldLocation cfLoc = (CommentFieldLocation) loc; return cfLoc.getCommentType(); } else if (loc instanceof PlateFieldLocation) { - return CodeUnit.PLATE_COMMENT; + return CommentType.PLATE; } else if (loc instanceof FunctionRepeatableCommentFieldLocation) { - return CodeUnit.REPEATABLE_COMMENT; + return CommentType.REPEATABLE; } else if (cu != null) { if (cu.getComment(CommentType.PRE) != null) { - return CodeUnit.PRE_COMMENT; + return CommentType.PRE; } if (cu.getComment(CommentType.POST) != null) { - return CodeUnit.POST_COMMENT; + return CommentType.POST; } if (cu.getComment(CommentType.EOL) != null) { - return CodeUnit.EOL_COMMENT; + return CommentType.EOL; } if (cu.getComment(CommentType.PLATE) != null) { - return CodeUnit.PLATE_COMMENT; + return CommentType.PLATE; } if (cu.getComment(CommentType.REPEATABLE) != null) { - return CodeUnit.REPEATABLE_COMMENT; + return CommentType.REPEATABLE; } } return defaultCommentType; diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/EolCommentFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/EolCommentFieldLocation.java index 2aa42370ce..20707678be 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/EolCommentFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/EolCommentFieldLocation.java @@ -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. @@ -17,7 +17,7 @@ package ghidra.program.util; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; /** @@ -41,7 +41,7 @@ public class EolCommentFieldLocation extends CommentFieldLocation { */ public EolCommentFieldLocation(Program program, Address addr, int[] componentPath, String[] comment, int displayableCommentRow, int charOffset, int currentCommentRow) { - super(program, addr, componentPath, comment, CodeUnit.EOL_COMMENT, displayableCommentRow, + super(program, addr, componentPath, comment, CommentType.EOL, displayableCommentRow, charOffset); this.currentCommentRow = currentCommentRow; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/MemoryBlockStartFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/MemoryBlockStartFieldLocation.java index 08f48338f5..0665d8d588 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/MemoryBlockStartFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/MemoryBlockStartFieldLocation.java @@ -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.program.util; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.Program; /** @@ -38,10 +37,9 @@ public class MemoryBlockStartFieldLocation extends CommentFieldLocation { * @param comment the location comment * @param commentRow the comment row */ - public MemoryBlockStartFieldLocation(Program program, Address addr, int[] componentPath, int row, - int charOffset, String[] comment, int commentRow) { - - super(program, addr, componentPath, comment, CodeUnit.NO_COMMENT, row, charOffset); + public MemoryBlockStartFieldLocation(Program program, Address addr, int[] componentPath, + int row, int charOffset, String[] comment, int commentRow) { + super(program, addr, componentPath, comment, null, row, charOffset); } /** diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PlateFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PlateFieldLocation.java index c3ebe11370..e813405524 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PlateFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PlateFieldLocation.java @@ -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 @@ package ghidra.program.util; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; /** @@ -48,8 +48,7 @@ public class PlateFieldLocation extends CommentFieldLocation { */ public PlateFieldLocation(Program program, Address addr, int[] componentPath, int row, int charOffset, String[] comment, int commentRow) { - - super(program, addr, componentPath, comment, CodeUnit.PLATE_COMMENT, row, charOffset); + super(program, addr, componentPath, comment, CommentType.PLATE, row, charOffset); this.commentRow = commentRow; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PostCommentFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PostCommentFieldLocation.java index 7a8fddc007..daef275215 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PostCommentFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/PostCommentFieldLocation.java @@ -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,7 +16,7 @@ package ghidra.program.util; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; /** @@ -37,7 +37,7 @@ public class PostCommentFieldLocation extends CommentFieldLocation { */ public PostCommentFieldLocation(Program program, Address addr, int[] componentPath, String[] comment, int displayableCommentRow, int charOffset) { - super(program, addr, componentPath, comment, CodeUnit.POST_COMMENT, displayableCommentRow, + super(program, addr, componentPath, comment, CommentType.POST, displayableCommentRow, charOffset); } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RefRepeatCommentFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RefRepeatCommentFieldLocation.java index de70c45df8..5b8b91f1b8 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RefRepeatCommentFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RefRepeatCommentFieldLocation.java @@ -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. @@ -17,7 +17,7 @@ package ghidra.program.util; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; /** @@ -45,7 +45,7 @@ public class RefRepeatCommentFieldLocation extends CommentFieldLocation { public RefRepeatCommentFieldLocation(Program program, Address addr, int[] componentPath, String[] comment, int row, int charOffset, int currentCommentRow, Address refRepeatAddress) { - super(program, addr, componentPath, comment, CodeUnit.EOL_COMMENT, row, charOffset); + super(program, addr, componentPath, comment, CommentType.EOL, row, charOffset); this.currentCommentRow = currentCommentRow; this.refRepeatAddress = refRepeatAddress; } diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RepeatableCommentFieldLocation.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RepeatableCommentFieldLocation.java index 80193494f6..e1947826d8 100644 --- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RepeatableCommentFieldLocation.java +++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/util/RepeatableCommentFieldLocation.java @@ -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. @@ -17,7 +17,7 @@ package ghidra.program.util; import ghidra.framework.options.SaveState; import ghidra.program.model.address.Address; -import ghidra.program.model.listing.CodeUnit; +import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.Program; /** @@ -41,7 +41,7 @@ public class RepeatableCommentFieldLocation extends CommentFieldLocation { */ public RepeatableCommentFieldLocation(Program program, Address addr, int[] componentPath, String[] comment, int row, int charOffset, int currentCommentRow) { - super(program, addr, componentPath, comment, CodeUnit.REPEATABLE_COMMENT, row, charOffset); + super(program, addr, componentPath, comment, CommentType.REPEATABLE, row, charOffset); this.currentCommentRow = currentCommentRow; } diff --git a/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/FunctionComparisonScreenShots.java b/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/FunctionComparisonScreenShots.java index ff0d11b103..aa84613578 100644 --- a/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/FunctionComparisonScreenShots.java +++ b/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/FunctionComparisonScreenShots.java @@ -99,8 +99,7 @@ public class FunctionComparisonScreenShots extends GhidraScreenShotGenerator { plugin.createComparison(f1, f2); FunctionComparisonProvider provider = waitForComponentProvider(FunctionComparisonProvider.class); - FunctionComparisonPanel functionComparisonPanel = - provider.getComponent(); + FunctionComparisonPanel functionComparisonPanel = provider.getComponent(); runSwing(() -> { functionComparisonPanel.setCurrentTabbedComponent("Listing View"); ListingCodeComparisonPanel dualListing = diff --git a/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/RepositoryScreenShots.java b/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/RepositoryScreenShots.java index ec5593f76b..a86727d2b4 100644 --- a/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/RepositoryScreenShots.java +++ b/Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/RepositoryScreenShots.java @@ -363,8 +363,7 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { ProgramContext pc = program.getProgramContext(); Register regDR0 = pc.getRegister(regNameDR0); - setRegValue(pc, addr(program, "004010a0"), addr(program, "004010a3"), regDR0, - 0x5L); + setRegValue(pc, addr(program, "004010a0"), addr(program, "004010a3"), regDR0, 0x5L); } @Override @@ -1512,8 +1511,8 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { ReferenceManager refMgr = program.getReferenceManager(); ProgramContext pc = program.getProgramContext(); Register regESI = pc.getRegister("ESI"); - refMgr.addRegisterReference(addr(program, "0x004018e4"), 0, regESI, - RefType.READ, SourceType.USER_DEFINED); + refMgr.addRegisterReference(addr(program, "0x004018e4"), 0, regESI, RefType.READ, + SourceType.USER_DEFINED); } @Override @@ -1596,15 +1595,14 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { @Override public void modifyLatest(ProgramDB program) throws Exception { ReferenceManager refMgr = program.getReferenceManager(); - refMgr.addMemoryReference(addr(program, "0x004017db"), - addr(program, "0x00401953"), RefType.READ, SourceType.USER_DEFINED, 1); - refMgr.addMemoryReference(addr(program, "0x004017db"), - addr(program, "0x0040cbc8"), RefType.DATA, SourceType.USER_DEFINED, 1); - refMgr.addMemoryReference(addr(program, "0x004017db"), - addr(program, "0x004018bc"), RefType.READ_IND, SourceType.USER_DEFINED, 1); - refMgr.addExternalReference(addr(program, "0x00401810"), "USER32.DLL", - "getMessage", addr(program, "0x1001a11"), SourceType.USER_DEFINED, 0, - RefType.DATA); + refMgr.addMemoryReference(addr(program, "0x004017db"), addr(program, "0x00401953"), + RefType.READ, SourceType.USER_DEFINED, 1); + refMgr.addMemoryReference(addr(program, "0x004017db"), addr(program, "0x0040cbc8"), + RefType.DATA, SourceType.USER_DEFINED, 1); + refMgr.addMemoryReference(addr(program, "0x004017db"), addr(program, "0x004018bc"), + RefType.READ_IND, SourceType.USER_DEFINED, 1); + refMgr.addExternalReference(addr(program, "0x00401810"), "USER32.DLL", "getMessage", + addr(program, "0x1001a11"), SourceType.USER_DEFINED, 0, RefType.DATA); } @Override @@ -1612,14 +1610,12 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { ReferenceManager refMgr = program.getReferenceManager(); refMgr.addExternalReference(addr(program, "0x004017db"), "USER32.DLL", "printf", addr(program, "0x01234567"), SourceType.USER_DEFINED, 1, RefType.DATA); - refMgr.addMemoryReference(addr(program, "0x00401810"), - addr(program, "0x00000010"), RefType.CONDITIONAL_JUMP, - SourceType.USER_DEFINED, 0); - refMgr.addMemoryReference(addr(program, "0x00401810"), - addr(program, "0x100190b"), RefType.DATA, SourceType.USER_DEFINED, 0); - refMgr.addMemoryReference(addr(program, "0x00401810"), - addr(program, "0x100191f"), RefType.CONDITIONAL_JUMP, - SourceType.USER_DEFINED, 0); + refMgr.addMemoryReference(addr(program, "0x00401810"), addr(program, "0x00000010"), + RefType.CONDITIONAL_JUMP, SourceType.USER_DEFINED, 0); + refMgr.addMemoryReference(addr(program, "0x00401810"), addr(program, "0x100190b"), + RefType.DATA, SourceType.USER_DEFINED, 0); + refMgr.addMemoryReference(addr(program, "0x00401810"), addr(program, "0x100191f"), + RefType.CONDITIONAL_JUMP, SourceType.USER_DEFINED, 0); } }); @@ -1782,9 +1778,8 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { Listing listing = program.getListing(); CodeUnit cu; cu = listing.getCodeUnitAt(addr(program, "0x0040156c")); - cu.setComment(CommentType.PRE, - "Changed this to a multiple line comment.\n" + - "It was necessary for demonstration purposes."); + cu.setComment(CommentType.PRE, "Changed this to a multiple line comment.\n" + + "It was necessary for demonstration purposes."); } }); @@ -1935,7 +1930,7 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { SourceArchive sourceArchive = dtm.getSourceArchive(myTestArchive.getDataTypeManager().getUniversalID()); sourceArchive.setName("TestArchiveOne"); - + assertNotNull(sourceArchive); assertEquals("TestArchiveOne", sourceArchive.getName()); } @@ -1947,7 +1942,7 @@ public class RepositoryScreenShots extends AbstractListingMergeManagerTest { SourceArchive sourceArchive = dtm.getSourceArchive(myTestArchive.getDataTypeManager().getUniversalID()); sourceArchive.setName("TestArchiveTwo"); - + assertNotNull(sourceArchive); assertEquals("TestArchiveTwo", sourceArchive.getName()); } diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/clipboard/ClipboardPluginTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/clipboard/ClipboardPluginTest.java index 9bebcd716f..f0ec84502a 100644 --- a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/clipboard/ClipboardPluginTest.java +++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/clipboard/ClipboardPluginTest.java @@ -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. @@ -149,7 +149,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { builder.createComment("0x0100415a", "\n;|||||||||||||||||||| FUNCTION ||||||||||||||||||||||||||||||||||||||||||||||||||\n ", - CodeUnit.PLATE_COMMENT); + CommentType.PLATE); builder.setBytes("0x0100418c", "ff 15 08 10 00 01"); builder.disassemble("0x0100418c", 6); @@ -633,7 +633,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { // 3) // 0100415a PreCommentFieldLocation CommentFieldLocation commentFieldLocation = new CommentFieldLocation(program, - addr("0100415a"), null, new String[] { "" }, CodeUnit.PRE_COMMENT, 5, 10); + addr("0100415a"), null, new String[] { "" }, CommentType.PRE, 5, 10); codeBrowserPlugin.goTo(plateFieldLocation); @@ -1008,8 +1008,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { Rectangle bounds = bc.getBounds(); clickMouse(bc, 1, bounds.x + 20, bounds.y + 20, 1, 0); - ProgramSelection selection = - new ProgramSelection(program.getAddressFactory(), addr("1001050"), addr("1001052")); + ProgramSelection selection = new ProgramSelection(addr("1001050"), addr("1001052")); tool.firePluginEvent(new ProgramSelectionPluginEvent("Test", selection, program)); waitForBusyTool(tool); @@ -1034,8 +1033,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { bounds = bc.getBounds(); clickMouse(bc, 1, bounds.x + 20, bounds.y + 20, 1, 0); - selection = - new ProgramSelection(program.getAddressFactory(), addr("1001050"), addr("1001052")); + selection = new ProgramSelection(addr("1001050"), addr("1001052")); tool.firePluginEvent(new ProgramSelectionPluginEvent("Test", selection, program)); waitForBusyTool(tool); @@ -1058,8 +1056,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { bounds = bc.getBounds(); clickMouse(bc, 1, bounds.x + 20, bounds.y + 20, 1, 0); - selection = - new ProgramSelection(program.getAddressFactory(), addr("1001050"), addr("1001052")); + selection = new ProgramSelection(addr("1001050"), addr("1001052")); tool.firePluginEvent(new ProgramSelectionPluginEvent("Test", selection, program)); waitForBusyTool(tool); @@ -1100,8 +1097,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { Rectangle bounds = bc.getBounds(); clickMouse(bc, 1, bounds.x + 20, bounds.y + 20, 1, 0); - ProgramSelection selection = - new ProgramSelection(program.getAddressFactory(), addr("1001051"), addr("1001070")); + ProgramSelection selection = new ProgramSelection(addr("1001051"), addr("1001070")); tool.firePluginEvent(new ProgramSelectionPluginEvent("Test", selection, program)); waitForBusyTool(tool); @@ -1127,8 +1123,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { bounds = bc.getBounds(); clickMouse(bc, 1, bounds.x + 20, bounds.y + 20, 1, 0); - selection = - new ProgramSelection(program.getAddressFactory(), addr("1001051"), addr("1001070")); + selection = new ProgramSelection(addr("1001051"), addr("1001070")); tool.firePluginEvent(new ProgramSelectionPluginEvent("Test", selection, program)); waitForBusyTool(tool); @@ -1151,8 +1146,7 @@ public class ClipboardPluginTest extends AbstractGhidraHeadedIntegrationTest { bounds = bc.getBounds(); clickMouse(bc, 1, bounds.x + 20, bounds.y + 20, 1, 0); - selection = - new ProgramSelection(program.getAddressFactory(), addr("1001051"), addr("1001070")); + selection = new ProgramSelection(addr("1001051"), addr("1001070")); tool.firePluginEvent(new ProgramSelectionPluginEvent("Test", selection, program)); waitForBusyTool(tool); diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.java index 1dfc91d8b6..4d7754d6ae 100644 --- a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.java +++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.java @@ -221,8 +221,7 @@ public class VersionControlAction2Test extends AbstractVersionControlActionTest waitForTasks(); ProgramDB program = (ProgramDB) ((DomainFileNode) node).getDomainFile() - .getDomainObject(this, - true, false, TaskMonitor.DUMMY); + .getDomainObject(this, true, false, TaskMonitor.DUMMY); int transactionID = program.startTransaction("test"); try { SymbolTable symTable = program.getSymbolTable(); @@ -254,7 +253,7 @@ public class VersionControlAction2Test extends AbstractVersionControlActionTest assertTrue(!df.isCheckedOut()); } - + @Test public void testCheckInWhileOpen() throws Exception { GTreeNode node = getNode(PROGRAM_A); @@ -267,15 +266,15 @@ public class VersionControlAction2Test extends AbstractVersionControlActionTest waitForTasks(); ProgramDB program = (ProgramDB) ((DomainFileNode) node).getDomainFile() - .getDomainObject(this, - true, false, TaskMonitor.DUMMY); + .getDomainObject(this, true, false, TaskMonitor.DUMMY); int transactionID = program.startTransaction("test"); try { // Ensure that buffer memory cache has been completely consumed // Max BufferMgr cache size is 256*16KByte=4MByte AddressSpace space = program.getAddressFactory().getDefaultAddressSpace(); - program.getMemory().createInitializedBlock("BigBlock", space.getAddress(0x80000000L), - 4*1024*1024, (byte)0xff, TaskMonitor.DUMMY, false); + program.getMemory() + .createInitializedBlock("BigBlock", space.getAddress(0x80000000L), + 4 * 1024 * 1024, (byte) 0xff, TaskMonitor.DUMMY, false); } finally { program.endTransaction(transactionID, true);