Merge remote-tracking branch 'origin/GP-5742_ghidra1_CommentTypeCleanup--SQUASHED' into Ghidra_11.4

This commit is contained in:
ghidra1 2025-06-06 18:00:36 -04:00
commit e03fb9af76
211 changed files with 4627 additions and 4860 deletions

View file

@ -26,7 +26,7 @@ import ghidra.app.services.DebuggerTraceManagerService;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.data.PointerDataType; import ghidra.program.model.data.PointerDataType;
import ghidra.program.model.lang.*; import ghidra.program.model.lang.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Instruction; import ghidra.program.model.listing.Instruction;
import ghidra.program.model.symbol.SourceType; import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.util.CodeUnitInsertionException; import ghidra.program.model.util.CodeUnitInsertionException;
@ -236,8 +236,7 @@ public class PopulateDemoTrace extends GhidraScript {
return; return;
} }
TraceCodeSpace code = TraceCodeSpace code = thread.getTrace().getCodeManager().getCodeRegisterSpace(thread, true);
thread.getTrace().getCodeManager().getCodeRegisterSpace(thread, true);
code.definedUnits().clear(Lifespan.nowOn(tick), reg, TaskMonitor.DUMMY); code.definedUnits().clear(Lifespan.nowOn(tick), reg, TaskMonitor.DUMMY);
code.definedData().create(Lifespan.nowOn(tick), reg, PointerDataType.dataType); code.definedData().create(Lifespan.nowOn(tick), reg, PointerDataType.dataType);
} }
@ -344,20 +343,16 @@ public class PopulateDemoTrace extends GhidraScript {
*/ */
mainLabel = trace.getSymbolManager() mainLabel = trace.getSymbolManager()
.labels() .labels()
.create(snap, null, addr(0x00400000), .create(snap, null, addr(0x00400000), "main", global, SourceType.USER_DEFINED);
"main", global, SourceType.USER_DEFINED);
cloneLabel = trace.getSymbolManager() cloneLabel = trace.getSymbolManager()
.labels() .labels()
.create(snap, null, addr(0x00400060), .create(snap, null, addr(0x00400060), "clone", global, SourceType.USER_DEFINED);
"clone", global, SourceType.USER_DEFINED);
childLabel = trace.getSymbolManager() childLabel = trace.getSymbolManager()
.labels() .labels()
.create(snap, null, addr(0x00400034), .create(snap, null, addr(0x00400034), "child", global, SourceType.USER_DEFINED);
"child", global, SourceType.USER_DEFINED);
exitLabel = trace.getSymbolManager() exitLabel = trace.getSymbolManager()
.labels() .labels()
.create(snap, null, addr(0x00400061), .create(snap, null, addr(0x00400061), "exit", global, SourceType.USER_DEFINED);
"exit", global, SourceType.USER_DEFINED);
/** /**
* Note the use of getProgramView as a means of using components intended for Program * Note the use of getProgramView as a means of using components intended for Program
@ -409,8 +404,7 @@ public class PopulateDemoTrace extends GhidraScript {
trace.getCodeManager() trace.getCodeManager()
.codeUnits() .codeUnits()
.getAt(0, cloneLabel.getAddress()) .getAt(0, cloneLabel.getAddress())
.setComment( .setComment(CommentType.EOL, "Pretend this is a syscall");
CodeUnit.EOL_COMMENT, "Pretend this is a syscall");
/** /**
* Stub out "exit" * Stub out "exit"
@ -419,8 +413,7 @@ public class PopulateDemoTrace extends GhidraScript {
trace.getCodeManager() trace.getCodeManager()
.codeUnits() .codeUnits()
.getAt(0, exitLabel.getAddress()) .getAt(0, exitLabel.getAddress())
.setComment( .setComment(CommentType.EOL, "Pretend this is a syscall");
CodeUnit.EOL_COMMENT, "Pretend this is a syscall");
/** /**
* "Launch" the program by initializing RIP and RSP of the main thread * "Launch" the program by initializing RIP and RSP of the main thread
@ -504,10 +497,10 @@ public class PopulateDemoTrace extends GhidraScript {
regs2.putBytes(snap, reg("RSP"), regs2.putBytes(snap, reg("RSP"),
buf.clear().putLong(STACK2_BOTTOM + stack2offset).flip()); buf.clear().putLong(STACK2_BOTTOM + stack2offset).flip());
regs2.putBytes(snap, reg("RAX"), buf.clear().putLong(1).flip()); regs2.putBytes(snap, reg("RAX"), buf.clear().putLong(1).flip());
memory.putBytes(snap, addr(STACK2_BOTTOM + stack2offset), buf.clear() memory.putBytes(snap, addr(STACK2_BOTTOM + stack2offset),
.putLong( buf.clear()
mainInstructions.get(pc2 = pc1).getAddress().getOffset()) .putLong(mainInstructions.get(pc2 = pc1).getAddress().getOffset())
.flip()); .flip());
placeRegUnits(snap, thread1); placeRegUnits(snap, thread1);
placeRegUnits(snap, thread2); placeRegUnits(snap, thread2);

View file

@ -309,12 +309,11 @@ public class DebuggerCopyPlan {
long off = addr.subtract(fromRange.getMinAddress()); long off = addr.subtract(fromRange.getMinAddress());
Address dest = intoAddress.add(off); Address dest = intoAddress.add(off);
// Ugly, but there's not MAX/MIN_COMMENT_TYPE // Ugly, but there's not MAX/MIN_COMMENT_TYPE
for (int i = CodeUnit.EOL_COMMENT; i <= CodeUnit.REPEATABLE_COMMENT; i++) { for (CommentType type : CommentType.values()) {
String comment = fromListing.getComment(i, addr); String comment = fromListing.getComment(type, addr);
if (comment == null) { if (comment != null) {
continue; intoListing.setComment(dest, type, comment);
} }
intoListing.setComment(dest, i, comment);
} }
} }
} }

View file

@ -144,16 +144,14 @@ public class AnalysisUnwoundFrame<T> extends AbstractUnwoundFrame<T> {
info.mapSavedRegisters(base, registerMap); info.mapSavedRegisters(base, registerMap);
Address pcVal = info.computeNextPc(base, state, codeSpace, pc); Address pcVal = info.computeNextPc(base, state, codeSpace, pc);
Address spVal = info.computeNextSp(base); Address spVal = info.computeNextSp(base);
return unwinder.unwind(coordinates, level + 1, pcVal, spVal, state, registerMap, return unwinder.unwind(coordinates, level + 1, pcVal, spVal, state, registerMap, monitor);
monitor);
} }
@Override @Override
protected Address applyBase(long offset) { protected Address applyBase(long offset) {
if (base == null) { if (base == null) {
throw new UnwindException( throw new UnwindException("Cannot compute stack address for offset %d.\nFrame error: %s"
"Cannot compute stack address for offset %d.\nFrame error: %s".formatted(offset, .formatted(offset, info.error().getMessage()),
info.error().getMessage()),
info.error()); info.error());
} }
return base.add(offset); return base.add(offset);
@ -191,8 +189,7 @@ public class AnalysisUnwoundFrame<T> extends AbstractUnwoundFrame<T> {
@Override @Override
public String getDescription() { public String getDescription() {
return String.format("%s %s pc=%s sp=%s base=%s", return String.format("%s %s pc=%s sp=%s base=%s", level, info.function(),
level, info.function(),
pcVal == null ? null : pcVal.toString(false), pcVal == null ? null : pcVal.toString(false),
spVal == null ? null : spVal.toString(false), spVal == null ? null : spVal.toString(false),
base == null ? null : base.toString(false)); base == null ? null : base.toString(false));
@ -353,7 +350,7 @@ public class AnalysisUnwoundFrame<T> extends AbstractUnwoundFrame<T> {
TraceData frame = trace.getCodeManager() TraceData frame = trace.getCodeManager()
.definedData() .definedData()
.create(span, spPlusParams, platform, structure); .create(span, spPlusParams, platform, structure);
frame.setComment(CodeUnit.PRE_COMMENT, getDescription()); frame.setComment(CommentType.PRE, getDescription());
TraceReferenceManager refs = trace.getReferenceManager(); TraceReferenceManager refs = trace.getReferenceManager();
refs.clearReferencesFrom(span, frame.getRange()); refs.clearReferencesFrom(span, frame.getRange());
refs.clearReferencesTo(span, frame.getRange()); refs.clearReferencesTo(span, frame.getRange());

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -95,7 +95,7 @@ public class ListingUnwoundFrame extends AbstractUnwoundFrame<WatchValue> {
*/ */
private static Integer getLevel(TraceData data) { private static Integer getLevel(TraceData data) {
// TODO: Should this go into a property instead? // TODO: Should this go into a property instead?
String comment = data.getComment(CodeUnit.PRE_COMMENT); String comment = data.getComment(CommentType.PRE);
if (comment == null) { if (comment == null) {
return null; return null;
} }
@ -213,7 +213,7 @@ public class ListingUnwoundFrame extends AbstractUnwoundFrame<WatchValue> {
@Override @Override
public String getDescription() { public String getDescription() {
return frame.getComment(CodeUnit.PRE_COMMENT); return frame.getComment(CommentType.PRE);
} }
@Override @Override

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -76,8 +76,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
r.nextBytes(src); r.nextBytes(src);
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
memory.putBytes(0, tb.addr(0x55550000), ByteBuffer.wrap(src)); memory.putBytes(0, tb.addr(0x55550000), ByteBuffer.wrap(src));
} }
@ -108,8 +108,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
memory.putBytes(0, tb.addr(0x55550000), ByteBuffer.allocate(4096)); memory.putBytes(0, tb.addr(0x55550000), ByteBuffer.allocate(4096));
memory.setState(0, tb.addr(0x55551000), TraceMemoryState.ERROR); memory.setState(0, tb.addr(0x55551000), TraceMemoryState.ERROR);
} }
@ -126,11 +126,9 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
IntRangeMap map = IntRangeMap map =
program.getIntRangeMap(PropertyBasedBackgroundColorModel.COLOR_PROPERTY_NAME); program.getIntRangeMap(PropertyBasedBackgroundColorModel.COLOR_PROPERTY_NAME);
AddressSet staleSet = AddressSet staleSet = map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_STALE.getRGB());
map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_STALE.getRGB());
assertEquals(tb.set(tb.range(stSpace, 0x00401001, 0x0040ffff)), staleSet); assertEquals(tb.set(tb.range(stSpace, 0x00401001, 0x0040ffff)), staleSet);
AddressSet errorSet = AddressSet errorSet = map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_ERROR.getRGB());
map.getAddressSet(DebuggerResources.COLOR_BACKGROUND_ERROR.getRGB());
assertEquals(tb.set(tb.range(stSpace, 0x00401000, 0x00401000)), errorSet); assertEquals(tb.set(tb.range(stSpace, 0x00401000, 0x00401000)), errorSet);
} }
@ -186,10 +184,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, trng, TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); memory.createRegion(".text", 0, trng, TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
InstructionIterator iit = asm.assemble(tb.addr(0x55550000), InstructionIterator iit =
"imm r0, #123", asm.assemble(tb.addr(0x55550000), "imm r0, #123", "imm r1, #234", "add r0, r1");
"imm r1, #234",
"add r0, r1");
assertTrue(iit.hasNext()); assertTrue(iit.hasNext());
} }
@ -234,10 +230,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, trng, TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); memory.createRegion(".text", 0, trng, TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE);
InstructionIterator iit = asm.assemble(tb.addr(0x55550000), InstructionIterator iit =
"MOV RAX, 1234", asm.assemble(tb.addr(0x55550000), "MOV RAX, 1234", "MOV RCX, 2345", "ADD RAX, RCX");
"MOV RCX, 2345",
"ADD RAX, RCX");
assertTrue(iit.hasNext()); assertTrue(iit.hasNext());
} }
@ -299,8 +293,7 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
"ADD EAX, ECX"); "ADD EAX, ECX");
checkCtx = iit.next(); checkCtx = iit.next();
*/ */
memory.putBytes(0, tb.addr(0x55550000), tb.buf( memory.putBytes(0, tb.addr(0x55550000), tb.buf(0xb8, 0xd2, 0x04, 0x00, 0x00, // MOV EAX,1234
0xb8, 0xd2, 0x04, 0x00, 0x00, // MOV EAX,1234
0xb9, 0x29, 0x09, 0x00, 0x00, // MOV ECX,2345 0xb9, 0x29, 0x09, 0x00, 0x00, // MOV ECX,2345
0x01, 0xc8 // ADD EAX,ECX 0x01, 0xc8 // ADD EAX,ECX
)); ));
@ -487,8 +480,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
DBTraceNamespaceSymbol global = tb.trace.getSymbolManager().getGlobalNamespace(); DBTraceNamespaceSymbol global = tb.trace.getSymbolManager().getGlobalNamespace();
DBTraceLabelSymbolView labels = tb.trace.getSymbolManager().labels(); DBTraceLabelSymbolView labels = tb.trace.getSymbolManager().labels();
@ -558,8 +551,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
DBTraceBreakpointManager breakpoints = tb.trace.getBreakpointManager(); DBTraceBreakpointManager breakpoints = tb.trace.getBreakpointManager();
breakpoints.placeBreakpoint("[1]", 0, tb.addr(0x55550123), List.of(), breakpoints.placeBreakpoint("[1]", 0, tb.addr(0x55550123), List.of(),
@ -571,8 +564,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
Address paddr = tb.addr(stSpace, 0x55550000); Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) { try (Transaction tx = program.openTransaction("Init")) {
program.getMemory() program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000, .createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
(byte) 0, TaskMonitor.DUMMY, false); false);
// Set up a collision. This is normal with relocations // Set up a collision. This is normal with relocations
program.getBookmarkManager() program.getBookmarkManager()
.setBookmark(tb.addr(stSpace, 0x55550123), "BreakpointDisabled", "SW_EXECUTE;1", .setBookmark(tb.addr(stSpace, 0x55550123), "BreakpointDisabled", "SW_EXECUTE;1",
@ -611,8 +604,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
BookmarkManager bookmarks = view.getBookmarkManager(); BookmarkManager bookmarks = view.getBookmarkManager();
bookmarks.defineType("TestType", DebuggerResources.ICON_DEBUGGER, Palette.BLUE, 1); bookmarks.defineType("TestType", DebuggerResources.ICON_DEBUGGER, Palette.BLUE, 1);
@ -622,8 +615,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
Address paddr = tb.addr(stSpace, 0x55550000); Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) { try (Transaction tx = program.openTransaction("Init")) {
program.getMemory() program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000, .createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
(byte) 0, TaskMonitor.DUMMY, false); false);
AllCopiers.BOOKMARKS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr, AllCopiers.BOOKMARKS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr,
TaskMonitor.DUMMY); TaskMonitor.DUMMY);
@ -659,27 +652,27 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
memory.createRegion(".data", 0, tb.range(0x55560000, 0x5556ffff), memory.createRegion(".data", 0, tb.range(0x55560000, 0x5556ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.WRITE); TraceMemoryFlag.WRITE);
ReferenceManager references = view.getReferenceManager(); ReferenceManager references = view.getReferenceManager();
references.addMemoryReference(tb.addr(0x55550123), references.addMemoryReference(tb.addr(0x55550123), tb.addr(0x55550321),
tb.addr(0x55550321), RefType.COMPUTED_CALL, SourceType.USER_DEFINED, -1); RefType.COMPUTED_CALL, SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55550123), references.addMemoryReference(tb.addr(0x55550123), tb.addr(0x55560321), RefType.READ,
tb.addr(0x55560321), RefType.READ, SourceType.USER_DEFINED, -1); SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55560123), references.addMemoryReference(tb.addr(0x55560123), tb.addr(0x55550321), RefType.PARAM,
tb.addr(0x55550321), RefType.PARAM, SourceType.USER_DEFINED, -1); SourceType.USER_DEFINED, -1);
references.addMemoryReference(tb.addr(0x55560123), references.addMemoryReference(tb.addr(0x55560123), tb.addr(0x55560321), RefType.DATA,
tb.addr(0x55560321), RefType.DATA, SourceType.USER_DEFINED, -1); SourceType.USER_DEFINED, -1);
} }
Address paddr = tb.addr(stSpace, 0x55550000); Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) { try (Transaction tx = program.openTransaction("Init")) {
program.getMemory() program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000, .createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
(byte) 0, TaskMonitor.DUMMY, false); false);
AllCopiers.REFERENCES.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr, AllCopiers.REFERENCES.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr,
TaskMonitor.DUMMY); TaskMonitor.DUMMY);
@ -710,19 +703,19 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
try (Transaction tx = tb.startTransaction()) { try (Transaction tx = tb.startTransaction()) {
DBTraceMemoryManager memory = tb.trace.getMemoryManager(); DBTraceMemoryManager memory = tb.trace.getMemoryManager();
memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), memory.createRegion(".text", 0, tb.range(0x55550000, 0x5555ffff), TraceMemoryFlag.READ,
TraceMemoryFlag.READ, TraceMemoryFlag.EXECUTE); TraceMemoryFlag.EXECUTE);
Listing listing = view.getListing(); Listing listing = view.getListing();
listing.setComment(tb.addr(0x55550123), CodeUnit.EOL_COMMENT, "Test EOL Comment"); listing.setComment(tb.addr(0x55550123), CommentType.EOL, "Test EOL Comment");
listing.setComment(tb.addr(0x55550321), CodeUnit.PLATE_COMMENT, "Test Plate Comment"); listing.setComment(tb.addr(0x55550321), CommentType.PLATE, "Test Plate Comment");
} }
Address paddr = tb.addr(stSpace, 0x55550000); Address paddr = tb.addr(stSpace, 0x55550000);
try (Transaction tx = program.openTransaction("Init")) { try (Transaction tx = program.openTransaction("Init")) {
program.getMemory() program.getMemory()
.createInitializedBlock(".text", paddr, 0x10000, .createInitializedBlock(".text", paddr, 0x10000, (byte) 0, TaskMonitor.DUMMY,
(byte) 0, TaskMonitor.DUMMY, false); false);
AllCopiers.COMMENTS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr, AllCopiers.COMMENTS.copy(view, tb.range(0x55550000, 0x5555ffff), program, paddr,
TaskMonitor.DUMMY); TaskMonitor.DUMMY);
@ -735,8 +728,8 @@ public class DebuggerCopyPlanTest extends AbstractGhidraHeadedDebuggerTest {
assertEquals(Set.of(tb.addr(stSpace, 0x55550123), tb.addr(stSpace, 0x55550321)), addresses); assertEquals(Set.of(tb.addr(stSpace, 0x55550123), tb.addr(stSpace, 0x55550321)), addresses);
assertEquals("Test EOL Comment", assertEquals("Test EOL Comment",
listing.getComment(CodeUnit.EOL_COMMENT, tb.addr(stSpace, 0x55550123))); listing.getComment(CommentType.EOL, tb.addr(stSpace, 0x55550123)));
assertEquals("Test Plate Comment", assertEquals("Test Plate Comment",
listing.getComment(CodeUnit.PLATE_COMMENT, tb.addr(stSpace, 0x55550321))); listing.getComment(CommentType.PLATE, tb.addr(stSpace, 0x55550321)));
} }
} }

View file

@ -15,7 +15,7 @@
*/ */
package ghidra.trace.database.listing; package ghidra.trace.database.listing;
import static ghidra.lifecycle.Unfinished.TODO; import static ghidra.lifecycle.Unfinished.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.*; import java.util.*;
@ -27,6 +27,7 @@ import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRangeImpl; import ghidra.program.model.address.AddressRangeImpl;
import ghidra.program.model.lang.Register; import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.mem.*; import ghidra.program.model.mem.*;
import ghidra.program.model.symbol.*; import ghidra.program.model.symbol.*;
import ghidra.trace.database.DBTrace; import ghidra.trace.database.DBTrace;
@ -128,9 +129,8 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override @Override
default <T> T getProperty(String name, Class<T> valueClass) { default <T> T getProperty(String name, Class<T> valueClass) {
try (LockHold hold = LockHold.lock(getTrace().getReadWriteLock().readLock())) { try (LockHold hold = LockHold.lock(getTrace().getReadWriteLock().readLock())) {
TracePropertyMap<? extends T> map = TracePropertyMap<? extends T> map = getTrace().getInternalAddressPropertyManager()
getTrace().getInternalAddressPropertyManager() .getPropertyMapExtends(name, valueClass);
.getPropertyMapExtends(name, valueClass);
if (map == null) { if (map == null) {
return null; return null;
} }
@ -250,17 +250,16 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
} }
@Override @Override
default void setComment(int commentType, String comment) { default void setComment(CommentType commentType, String comment) {
if (getThread() != null) { if (getThread() != null) {
TODO(); // TODO: Comments in register space TODO(); // TODO: Comments in register space
} }
getTrace().getCommentAdapter() getTrace().getCommentAdapter()
.setComment(getLifespan(), getAddress(), commentType, .setComment(getLifespan(), getAddress(), commentType, comment);
comment);
} }
@Override @Override
default String getComment(int commentType) { default String getComment(CommentType commentType) {
if (getThread() != null) { if (getThread() != null) {
// TODO: Comments in register space // TODO: Comments in register space
return null; return null;
@ -269,12 +268,12 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
} }
@Override @Override
default void setCommentAsArray(int commentType, String[] comment) { default void setCommentAsArray(CommentType commentType, String[] comment) {
setComment(commentType, DBTraceCommentAdapter.commentFromArray(comment)); setComment(commentType, DBTraceCommentAdapter.commentFromArray(comment));
} }
@Override @Override
default String[] getCommentAsArray(int commentType) { default String[] getCommentAsArray(CommentType commentType) {
return DBTraceCommentAdapter.arrayFromComment(getComment(commentType)); return DBTraceCommentAdapter.arrayFromComment(getComment(commentType));
} }
@ -297,16 +296,15 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override @Override
default void addMnemonicReference(Address refAddr, RefType refType, SourceType sourceType) { default void addMnemonicReference(Address refAddr, RefType refType, SourceType sourceType) {
getTrace().getReferenceManager() getTrace().getReferenceManager()
.addMemoryReference(getLifespan(), getAddress(), refAddr, .addMemoryReference(getLifespan(), getAddress(), refAddr, refType, sourceType,
refType, sourceType, MNEMONIC); MNEMONIC);
} }
@Override @Override
default void addOperandReference(int index, Address refAddr, RefType type, default void addOperandReference(int index, Address refAddr, RefType type,
SourceType sourceType) { SourceType sourceType) {
getTrace().getReferenceManager() getTrace().getReferenceManager()
.addMemoryReference(getLifespan(), getAddress(), refAddr, .addMemoryReference(getLifespan(), getAddress(), refAddr, type, sourceType, index);
type, sourceType, index);
} }
@Override @Override
@ -319,16 +317,16 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
default void setStackReference(int opIndex, int offset, SourceType sourceType, default void setStackReference(int opIndex, int offset, SourceType sourceType,
RefType refType) { RefType refType) {
getTrace().getReferenceManager() getTrace().getReferenceManager()
.addStackReference(getLifespan(), getAddress(), offset, .addStackReference(getLifespan(), getAddress(), offset, refType, sourceType,
refType, sourceType, opIndex); opIndex);
} }
@Override @Override
default void setRegisterReference(int opIndex, Register reg, SourceType sourceType, default void setRegisterReference(int opIndex, Register reg, SourceType sourceType,
RefType refType) { RefType refType) {
getTrace().getReferenceManager() getTrace().getReferenceManager()
.addRegisterReference(getLifespan(), getAddress(), reg, .addRegisterReference(getLifespan(), getAddress(), reg, refType, sourceType,
refType, sourceType, opIndex); opIndex);
} }
@Override @Override
@ -346,8 +344,7 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override @Override
default DBTraceReference getPrimaryReference(int index) { default DBTraceReference getPrimaryReference(int index) {
return getTrace().getReferenceManager() return getTrace().getReferenceManager()
.getPrimaryReferenceFrom(getStartSnap(), getAddress(), .getPrimaryReferenceFrom(getStartSnap(), getAddress(), index);
index);
} }
@Override @Override
@ -359,10 +356,9 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override @Override
default ReferenceIterator getReferenceIteratorTo() { default ReferenceIterator getReferenceIteratorTo() {
return new ReferenceIteratorAdapter( return new ReferenceIteratorAdapter(getTrace().getReferenceManager()
getTrace().getReferenceManager() .getReferencesTo(getStartSnap(), getAddress())
.getReferencesTo(getStartSnap(), getAddress()) .iterator());
.iterator());
} }
@Override @Override
@ -377,9 +373,8 @@ public interface DBTraceCodeUnitAdapter extends TraceCodeUnit, MemBufferMixin {
@Override @Override
default void removeOperandReference(int index, Address refAddr) { default void removeOperandReference(int index, Address refAddr) {
TraceReference ref = TraceReference ref = getTrace().getReferenceManager()
getTrace().getReferenceManager() .getReference(getStartSnap(), getAddress(), refAddr, index);
.getReference(getStartSnap(), getAddress(), refAddr, index);
if (ref == null) { if (ref == null) {
return; return;
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.framework.data.OpenMode;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.lang.Language; 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.program.model.listing.Listing;
import ghidra.trace.database.DBTrace; import ghidra.trace.database.DBTrace;
import ghidra.trace.database.DBTraceUtils; import ghidra.trace.database.DBTraceUtils;
@ -52,8 +52,6 @@ import ghidra.util.task.TaskMonitor;
public class DBTraceCommentAdapter public class DBTraceCommentAdapter
extends DBTraceAddressSnapRangePropertyMap<DBTraceCommentEntry, DBTraceCommentEntry> { extends DBTraceAddressSnapRangePropertyMap<DBTraceCommentEntry, DBTraceCommentEntry> {
protected static final String[] EMPTY_STRING_ARRAY = new String[] {}; 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 * 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 commentType the type of comment as in {@link Listing#setComment(Address, int, String)}
* @param comment the comment * @param comment the comment
*/ */
public void setComment(Lifespan lifespan, Address address, int commentType, String comment) { public void setComment(Lifespan lifespan, Address address, CommentType commentType,
if (commentType < MIN_COMMENT_TYPE || commentType > MAX_COMMENT_TYPE) { String comment) {
throw new IllegalArgumentException("commentType"); if (commentType == null) {
throw new IllegalArgumentException("null commentType");
} }
String oldValue = null; String oldValue = null;
try (LockHold hold = LockHold.lock(lock.writeLock())) { try (LockHold hold = LockHold.lock(lock.writeLock())) {
for (DBTraceCommentEntry entry : reduce(TraceAddressSnapRangeQuery for (DBTraceCommentEntry entry : reduce(TraceAddressSnapRangeQuery
.intersecting(new AddressRangeImpl(address, address), lifespan)).values()) { .intersecting(new AddressRangeImpl(address, address), lifespan)).values()) {
if (entry.type == commentType) { if (entry.type == commentType.ordinal()) {
if (entry.getLifespan().contains(lifespan.lmin())) { if (entry.getLifespan().contains(lifespan.lmin())) {
oldValue = entry.comment; oldValue = entry.comment;
} }
@ -153,7 +152,7 @@ public class DBTraceCommentAdapter
} }
if (comment != null) { if (comment != null) {
DBTraceCommentEntry entry = put(address, lifespan, null); DBTraceCommentEntry entry = put(address, lifespan, null);
entry.set((byte) commentType, comment); entry.set((byte) commentType.ordinal(), comment);
} }
} }
trace.setChanged(new TraceChangeRecord<TraceAddressSnapRange, String>( trace.setChanged(new TraceChangeRecord<TraceAddressSnapRange, String>(
@ -190,11 +189,11 @@ public class DBTraceCommentAdapter
* @param commentType the type of comment * @param commentType the type of comment
* @return the comment text * @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())) { try (LockHold hold = LockHold.lock(lock.readLock())) {
for (DBTraceCommentEntry entry : reduce(TraceAddressSnapRangeQuery.at(address, snap)) for (DBTraceCommentEntry entry : reduce(TraceAddressSnapRangeQuery.at(address, snap))
.values()) { .values()) {
if (entry.type != commentType) { if (entry.type != commentType.ordinal()) {
continue; continue;
} }
return entry.comment; return entry.comment;
@ -208,13 +207,13 @@ public class DBTraceCommentAdapter
* *
* @param span the lifespan fo the box * @param span the lifespan fo the box
* @param range the address range of 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())) { try (LockHold hold = LockHold.lock(lock.writeLock())) {
for (DBTraceCommentEntry entry : reduce( for (DBTraceCommentEntry entry : reduce(
TraceAddressSnapRangeQuery.intersecting(range, span)).values()) { TraceAddressSnapRangeQuery.intersecting(range, span)).values()) {
if (commentType == CodeUnit.NO_COMMENT || entry.type == commentType) { if (commentType == null || entry.type == commentType.ordinal()) {
makeWay(entry, span); makeWay(entry, span);
} }
} }

View file

@ -145,8 +145,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
protected Comparator<CodeUnit> getUnitComparator(boolean forward) { protected Comparator<CodeUnit> getUnitComparator(boolean forward) {
return forward return forward ? (u1, u2) -> u1.getMinAddress().compareTo(u2.getMinAddress())
? (u1, u2) -> u1.getMinAddress().compareTo(u2.getMinAddress())
: (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) { protected AddressSet getAddressSet(Address start, boolean forward) {
AddressFactory factory = program.getAddressFactory(); AddressFactory factory = program.getAddressFactory();
AddressSetView all = program.getAllAddresses(); AddressSetView all = program.getAllAddresses();
return forward return forward ? factory.getAddressSet(start, all.getMaxAddress())
? factory.getAddressSet(start, all.getMaxAddress())
: factory.getAddressSet(all.getMinAddress(), start); : factory.getAddressSet(all.getMinAddress(), start);
} }
@ -184,8 +182,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
protected Iterator<? extends TraceInstruction> getInstructionIterator(boolean forward) { protected Iterator<? extends TraceInstruction> getInstructionIterator(boolean forward) {
return getTopCodeIterator( return getTopCodeIterator(s -> codeOperations.instructions().get(s, forward).iterator(),
s -> codeOperations.instructions().get(s, forward).iterator(), forward); forward);
} }
protected Iterator<? extends TraceData> getDefinedDataIterator(Address start, boolean forward) { protected Iterator<? extends TraceData> getDefinedDataIterator(Address start, boolean forward) {
@ -195,13 +193,13 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
protected Iterator<? extends TraceData> getDefinedDataIterator(AddressSetView set, protected Iterator<? extends TraceData> getDefinedDataIterator(AddressSetView set,
boolean forward) { boolean forward) {
return getTopCodeIterator( return getTopCodeIterator(s -> codeOperations.definedData().get(s, set, forward).iterator(),
s -> codeOperations.definedData().get(s, set, forward).iterator(), forward); forward);
} }
protected Iterator<? extends TraceData> getDefinedDataIterator(boolean forward) { protected Iterator<? extends TraceData> getDefinedDataIterator(boolean forward) {
return getTopCodeIterator( return getTopCodeIterator(s -> codeOperations.definedData().get(s, forward).iterator(),
s -> codeOperations.definedData().get(s, forward).iterator(), forward); forward);
} }
protected Iterator<? extends TraceCodeUnit> getDefinedUnitIterator(Address start, protected Iterator<? extends TraceCodeUnit> getDefinedUnitIterator(Address start,
@ -226,8 +224,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
defStart = defUnit.getMinAddress(); defStart = defUnit.getMinAddress();
} }
} }
Iterator<AddressRange> defIter = IteratorUtils.transformedIterator( Iterator<AddressRange> defIter = IteratorUtils
getDefinedUnitIterator(defStart, forward), u -> u.getRange()); .transformedIterator(getDefinedUnitIterator(defStart, forward), u -> u.getRange());
AddressRangeIterator undefIter = AddressRangeIterator undefIter =
AddressRangeIterators.subtract(set.iterator(forward), defIter, start, forward); AddressRangeIterators.subtract(set.iterator(forward), defIter, start, forward);
AddressIteratorAdapter undefAddrIter = new AddressIteratorAdapter(undefIter, forward); AddressIteratorAdapter undefAddrIter = new AddressIteratorAdapter(undefIter, forward);
@ -236,8 +234,8 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
protected AddressRangeIterator getUndefinedRangeIterator(AddressSetView set, boolean forward) { protected AddressRangeIterator getUndefinedRangeIterator(AddressSetView set, boolean forward) {
Iterator<AddressRange> defIter = IteratorUtils.transformedIterator( Iterator<AddressRange> defIter = IteratorUtils
getDefinedUnitIterator(set, forward), u -> u.getRange()); .transformedIterator(getDefinedUnitIterator(set, forward), u -> u.getRange());
return AddressRangeIterators.subtract(set.iterator(forward), defIter, return AddressRangeIterators.subtract(set.iterator(forward), defIter,
forward ? set.getMinAddress() : set.getMaxAddress(), forward); forward ? set.getMinAddress() : set.getMaxAddress(), forward);
} }
@ -267,17 +265,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
protected Iterator<TraceCodeUnit> getCodeUnitIterator(AddressSetView set, boolean forward) { protected Iterator<TraceCodeUnit> getCodeUnitIterator(AddressSetView set, boolean forward) {
return new MergeSortingIterator<>(List.of( return new MergeSortingIterator<>(
getDefinedUnitIterator(set, forward), List.of(getDefinedUnitIterator(set, forward), getUndefinedDataIterator(set, forward)),
getUndefinedDataIterator(set, forward)),
getUnitComparator(forward)); getUnitComparator(forward));
} }
protected Iterator<TraceCodeUnit> getCodeUnitIterator(Address start, boolean forward) { protected Iterator<TraceCodeUnit> getCodeUnitIterator(Address start, boolean forward) {
return new MergeSortingIterator<>(List.of( return new MergeSortingIterator<>(List.of(getDefinedUnitIterator(start, forward),
getDefinedUnitIterator(start, forward), getUndefinedDataIterator(start, forward)), getUnitComparator(forward));
getUndefinedDataIterator(start, forward)),
getUnitComparator(forward));
} }
protected Iterator<TraceCodeUnit> getCodeUnitIterator(boolean forward) { protected Iterator<TraceCodeUnit> getCodeUnitIterator(boolean forward) {
@ -286,17 +281,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
protected Iterator<TraceData> getDataIterator(AddressSetView set, boolean forward) { protected Iterator<TraceData> getDataIterator(AddressSetView set, boolean forward) {
return new MergeSortingIterator<>(List.of( return new MergeSortingIterator<>(
getDefinedDataIterator(set, forward), List.of(getDefinedDataIterator(set, forward), getUndefinedDataIterator(set, forward)),
getUndefinedDataIterator(set, forward)),
getUnitComparator(forward)); getUnitComparator(forward));
} }
protected Iterator<TraceData> getDataIterator(Address start, boolean forward) { protected Iterator<TraceData> getDataIterator(Address start, boolean forward) {
return new MergeSortingIterator<>(List.of( return new MergeSortingIterator<>(List.of(getDefinedDataIterator(start, forward),
getDefinedDataIterator(start, forward), getUndefinedDataIterator(start, forward)), getUnitComparator(forward));
getUndefinedDataIterator(start, forward)),
getUnitComparator(forward));
} }
protected Iterator<TraceData> getDataIterator(boolean forward) { protected Iterator<TraceData> getDataIterator(boolean forward) {
@ -355,11 +347,12 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
return new WrappingCodeUnitIterator(Collections.emptyIterator()); return new WrappingCodeUnitIterator(Collections.emptyIterator());
} }
// TODO: The property map doesn't heed forking. // TODO: The property map doesn't heed forking.
return new WrappingCodeUnitIterator(NestedIterator.start( return new WrappingCodeUnitIterator(
map.getAddressSetView(Lifespan.at(program.snap)).iterator(forward), NestedIterator
rng -> getTopCodeIterator( .start(map.getAddressSetView(Lifespan.at(program.snap)).iterator(forward),
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(), rng -> getTopCodeIterator(
forward))); s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
} }
@Override @Override
@ -377,11 +370,12 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
return new WrappingCodeUnitIterator(Collections.emptyIterator()); return new WrappingCodeUnitIterator(Collections.emptyIterator());
} }
// TODO: The property map doesn't heed forking. // TODO: The property map doesn't heed forking.
return new WrappingCodeUnitIterator(NestedIterator.start( return new WrappingCodeUnitIterator(
map.getAddressSetView(Lifespan.at(program.snap)).iterator(addr, forward), NestedIterator
rng -> getTopCodeIterator( .start(map.getAddressSetView(Lifespan.at(program.snap)).iterator(addr, forward),
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(), rng -> getTopCodeIterator(
forward))); s -> codeOperations.codeUnits().get(s, rng, forward).iterator(),
forward)));
} }
@Override @Override
@ -404,31 +398,30 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
new IntersectionAddressSetView(map.getAddressSetView(Lifespan.at(program.snap)), new IntersectionAddressSetView(map.getAddressSetView(Lifespan.at(program.snap)),
addrSet).iterator(forward), addrSet).iterator(forward),
rng -> getTopCodeIterator( rng -> getTopCodeIterator(
s -> codeOperations.codeUnits().get(s, rng, forward).iterator(), s -> codeOperations.codeUnits().get(s, rng, forward).iterator(), forward)));
forward)));
} }
protected AddressSetView getCommentAddresses(int commentType, AddressSetView addrSet) { protected AddressSetView getCommentAddresses(CommentType commentType, AddressSetView addrSet) {
return new IntersectionAddressSetView(addrSet, program.viewport.unionedAddresses( return new IntersectionAddressSetView(addrSet,
s -> program.trace.getCommentAdapter() program.viewport.unionedAddresses(s -> program.trace.getCommentAdapter()
.getAddressSetView(Lifespan.at(s), e -> e.getType() == commentType))); .getAddressSetView(Lifespan.at(s), e -> e.getType() == commentType.ordinal())));
} }
protected AddressSetView getCommentAddresses(AddressSetView addrSet) { protected AddressSetView getCommentAddresses(AddressSetView addrSet) {
return new IntersectionAddressSetView(addrSet, program.viewport.unionedAddresses( return new IntersectionAddressSetView(addrSet, program.viewport.unionedAddresses(
s -> program.trace.getCommentAdapter() s -> program.trace.getCommentAdapter().getAddressSetView(Lifespan.at(s))));
.getAddressSetView(Lifespan.at(s))));
} }
@Override @Override
public CodeUnitIterator getCommentCodeUnitIterator(int commentType, AddressSetView addrSet) { public CodeUnitIterator getCommentCodeUnitIterator(CommentType commentType,
AddressSetView addrSet) {
return new WrappingCodeUnitIterator( return new WrappingCodeUnitIterator(
getCodeUnitIterator(getCommentAddresses(commentType, addrSet), true)); getCodeUnitIterator(getCommentAddresses(commentType, addrSet), true));
} }
@Override @Override
public AddressIterator getCommentAddressIterator(int commentType, AddressSetView addrSet, public AddressIterator getCommentAddressIterator(CommentType commentType,
boolean forward) { AddressSetView addrSet, boolean forward) {
return getCommentAddresses(commentType, addrSet).getAddresses(forward); return getCommentAddresses(commentType, addrSet).getAddresses(forward);
} }
@ -439,13 +432,14 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
@Override @Override
public long getCommentAddressCount() { public long getCommentAddressCount() {
return program.viewport.unionedAddresses( return program.viewport
s -> program.trace.getCommentAdapter().getAddressSetView(Lifespan.at(s))) .unionedAddresses(
s -> program.trace.getCommentAdapter().getAddressSetView(Lifespan.at(s)))
.getNumAddresses(); .getNumAddresses();
} }
@Override @Override
public String getComment(int commentType, Address address) { public String getComment(CommentType commentType, Address address) {
try (LockHold hold = program.trace.lockRead()) { try (LockHold hold = program.trace.lockRead()) {
return program.viewport.getTop( return program.viewport.getTop(
s -> program.trace.getCommentAdapter().getComment(s, address, commentType)); s -> program.trace.getCommentAdapter().getComment(s, address, commentType));
@ -463,10 +457,9 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
@Override @Override
public void setComment(Address address, int commentType, String comment) { public void setComment(Address address, CommentType commentType, String comment) {
program.trace.getCommentAdapter() program.trace.getCommentAdapter()
.setComment(Lifespan.nowOn(program.snap), address, .setComment(Lifespan.nowOn(program.snap), address, commentType, comment);
commentType, comment);
} }
@Override @Override
@ -787,7 +780,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
public void clearComments(Address startAddr, Address endAddr) { public void clearComments(Address startAddr, Address endAddr) {
program.trace.getCommentAdapter() program.trace.getCommentAdapter()
.clearComments(Lifespan.nowOn(program.snap), .clearComments(Lifespan.nowOn(program.snap),
new AddressRangeImpl(startAddr, endAddr), CodeUnit.NO_COMMENT); new AddressRangeImpl(startAddr, endAddr), null);
} }
@Override @Override
@ -957,7 +950,7 @@ public abstract class AbstractDBTraceProgramViewListing implements TraceProgramV
} }
@Override @Override
public CommentHistory[] getCommentHistory(Address addr, int commentType) { public CommentHistory[] getCommentHistory(Address addr, CommentType commentType) {
return new CommentHistory[] {}; return new CommentHistory[] {};
} }
} }

View file

@ -341,7 +341,7 @@ public class DBTraceProgramView implements TraceProgramView {
return; return;
} }
queues.fireEvent( queues.fireEvent(
new CommentChangeRecord(commentType.ordinal(), range.getX1(), oldValue, newValue)); new CommentChangeRecord(commentType, range.getX1(), oldValue, newValue));
} }
private void commentEolChanged(TraceAddressSpace space, TraceAddressSnapRange range, private void commentEolChanged(TraceAddressSpace space, TraceAddressSnapRange range,

View file

@ -19,7 +19,7 @@ import java.util.*;
import ghidra.framework.model.EventType; import ghidra.framework.model.EventType;
import ghidra.program.model.address.Address; 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.DBTraceObject;
import ghidra.trace.database.target.DBTraceObjectInterface; import ghidra.trace.database.target.DBTraceObjectInterface;
import ghidra.trace.model.Lifespan; import ghidra.trace.model.Lifespan;
@ -117,9 +117,7 @@ public class DBTraceObjectStackFrame implements TraceObjectStackFrame, DBTraceOb
try (LockHold hold = object.getTrace().lockRead()) { try (LockHold hold = object.getTrace().lockRead()) {
Address pc = getProgramCounter(snap); Address pc = getProgramCounter(snap);
return pc == null ? null return pc == null ? null
: object.getTrace() : object.getTrace().getCommentAdapter().getComment(snap, pc, CommentType.EOL);
.getCommentAdapter()
.getComment(snap, pc, CodeUnit.EOL_COMMENT);
} }
} }
@ -130,8 +128,8 @@ public class DBTraceObjectStackFrame implements TraceObjectStackFrame, DBTraceOb
TraceObjectValue pcAttr = object.getValue(snap, TraceObjectStackFrame.KEY_PC); TraceObjectValue pcAttr = object.getValue(snap, TraceObjectStackFrame.KEY_PC);
object.getTrace() object.getTrace()
.getCommentAdapter() .getCommentAdapter()
.setComment(pcAttr.getLifespan(), (Address) pcAttr.getValue(), .setComment(pcAttr.getLifespan(), (Address) pcAttr.getValue(), CommentType.EOL,
CodeUnit.EOL_COMMENT, comment); comment);
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.docking.settings.Settings;
import ghidra.program.model.address.AddressSpace; import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.data.*; 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.program.model.listing.ProgramFragment;
import ghidra.trace.model.Trace; import ghidra.trace.model.Trace;
import ghidra.trace.model.bookmark.TraceBookmark; import ghidra.trace.model.bookmark.TraceBookmark;
@ -150,13 +150,13 @@ public interface TraceEvents {
* @param commentType the comment type * @param commentType the comment type
* @return the event type * @return the event type
*/ */
static TraceCommentEvent byCommentType(int commentType) { static TraceCommentEvent byCommentType(CommentType commentType) {
return switch (commentType) { return switch (commentType) {
case CodeUnit.PLATE_COMMENT -> PLATE_COMMENT_CHANGED; case CommentType.PLATE -> PLATE_COMMENT_CHANGED;
case CodeUnit.PRE_COMMENT -> PRE_COMMENT_CHANGED; case CommentType.PRE -> PRE_COMMENT_CHANGED;
case CodeUnit.POST_COMMENT -> POST_COMMENT_CHANGED; case CommentType.POST -> POST_COMMENT_CHANGED;
case CodeUnit.EOL_COMMENT -> EOL_COMMENT_CHANGED; case CommentType.EOL -> EOL_COMMENT_CHANGED;
case CodeUnit.REPEATABLE_COMMENT -> REPEATABLE_COMMENT_CHANGED; case CommentType.REPEATABLE -> REPEATABLE_COMMENT_CHANGED;
default -> throw new AssertionError(); default -> throw new AssertionError();
}; };
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -18,7 +18,6 @@ package ghidra.trace.database.listing;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.*; import java.util.*;
@ -210,8 +209,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
b.trace.getMemoryManager() b.trace.getMemoryManager()
.addRegion(".text", Lifespan.nowOn(0), .addRegion(".text", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ); TraceMemoryFlag.READ);
} }
assertEquals("00004004", ins.getAddressString(false, false)); assertEquals("00004004", ins.getAddressString(false, false));
@ -364,13 +363,10 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
} }
@Test @Test
public void testDetectNewCommentTypes() public void testDetectNewCommentTypes() {
throws IllegalArgumentException, IllegalAccessException { for (CommentType type : CommentType.values()) {
for (Field f : CodeUnit.class.getFields()) { if (type.ordinal() > CommentType.REPEATABLE.ordinal()) {
if (f.getName().endsWith("_COMMENT")) { fail("It appears a new comment type was added");
if (f.getInt(null) > CodeUnit.REPEATABLE_COMMENT) {
fail("It appears a new comment type was added");
}
} }
} }
} }
@ -385,7 +381,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
} }
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
i4004.setComment(CodeUnit.NO_COMMENT, "Shouldn't work"); i4004.setComment(null, "Shouldn't work");
fail(); fail();
} }
catch (IllegalArgumentException e) { catch (IllegalArgumentException e) {
@ -399,28 +395,28 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
// pass // pass
} }
assertNull(i4004.getComment(CodeUnit.EOL_COMMENT)); assertNull(i4004.getComment(CommentType.EOL));
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
i4004.setComment(CodeUnit.EOL_COMMENT, "My EOL Comment"); i4004.setComment(CommentType.EOL, "My EOL Comment");
} }
assertEquals("My EOL Comment", i4004.getComment(CodeUnit.EOL_COMMENT)); assertEquals("My EOL Comment", i4004.getComment(CommentType.EOL));
assertNull(i4006.getComment(CodeUnit.EOL_COMMENT)); assertNull(i4006.getComment(CommentType.EOL));
assertArrayEquals(EMPTY_STRING_ARRAY, i4004.getCommentAsArray(CodeUnit.PRE_COMMENT)); assertArrayEquals(EMPTY_STRING_ARRAY, i4004.getCommentAsArray(CommentType.PRE));
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
i4004.setCommentAsArray(CodeUnit.PRE_COMMENT, new String[] { "My", "Pre", "Comment" }); i4004.setCommentAsArray(CommentType.PRE, new String[] { "My", "Pre", "Comment" });
} }
assertEquals("My EOL Comment", i4004.getComment(CodeUnit.EOL_COMMENT)); assertEquals("My EOL Comment", i4004.getComment(CommentType.EOL));
assertArrayEquals(new String[] { "My", "Pre", "Comment" }, assertArrayEquals(new String[] { "My", "Pre", "Comment" },
i4004.getCommentAsArray(CodeUnit.PRE_COMMENT)); i4004.getCommentAsArray(CommentType.PRE));
assertArrayEquals(EMPTY_STRING_ARRAY, i4006.getCommentAsArray(CodeUnit.PRE_COMMENT)); assertArrayEquals(EMPTY_STRING_ARRAY, i4006.getCommentAsArray(CommentType.PRE));
assertEquals("My\nPre\nComment", i4004.getComment(CodeUnit.PRE_COMMENT)); assertEquals("My\nPre\nComment", i4004.getComment(CommentType.PRE));
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
i4004.setCommentAsArray(CodeUnit.PRE_COMMENT, null); i4004.setCommentAsArray(CommentType.PRE, null);
i4006.setCommentAsArray(CodeUnit.PRE_COMMENT, null); // NOP i4006.setCommentAsArray(CommentType.PRE, null); // NOP
} }
assertNull(i4004.getComment(CodeUnit.PRE_COMMENT)); assertNull(i4004.getComment(CommentType.PRE));
TraceInstruction i4004_10; TraceInstruction i4004_10;
DBTraceCommentAdapter commentAdapter = b.trace.getCommentAdapter(); DBTraceCommentAdapter commentAdapter = b.trace.getCommentAdapter();
@ -436,25 +432,24 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
assertEquals(Lifespan.nowOn(0), c4004.getLifespan()); assertEquals(Lifespan.nowOn(0), c4004.getLifespan());
i4004_10 = b.addInstruction(10, b.addr(0x4004), b.host); i4004_10 = b.addInstruction(10, b.addr(0x4004), b.host);
i4004_10.setComment(CodeUnit.PRE_COMMENT, "Get this back in the mix"); i4004_10.setComment(CommentType.PRE, "Get this back in the mix");
i4004_10.setComment(CodeUnit.EOL_COMMENT, "A different comment"); i4004_10.setComment(CommentType.EOL, "A different comment");
} }
assertEquals(Lifespan.span(0, 9), c4004.getLifespan()); assertEquals(Lifespan.span(0, 9), c4004.getLifespan());
assertEquals("My EOL Comment", i4004.getComment(CodeUnit.EOL_COMMENT)); assertEquals("My EOL Comment", i4004.getComment(CommentType.EOL));
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000), commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000),
CodeUnit.EOL_COMMENT); CommentType.EOL);
} }
assertNull(i4004.getComment(CodeUnit.EOL_COMMENT)); assertNull(i4004.getComment(CommentType.EOL));
assertEquals("Get this back in the mix", i4004_10.getComment(CodeUnit.PRE_COMMENT)); assertEquals("Get this back in the mix", i4004_10.getComment(CommentType.PRE));
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000), commentAdapter.clearComments(Lifespan.nowOn(0), b.range(0x4000, 0x5000), null);
CodeUnit.NO_COMMENT);
} }
assertNull(i4004.getComment(CodeUnit.EOL_COMMENT)); assertNull(i4004.getComment(CommentType.EOL));
assertNull(i4004_10.getComment(CodeUnit.PRE_COMMENT)); assertNull(i4004_10.getComment(CommentType.PRE));
} }
@Test @Test
@ -579,9 +574,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
DBTraceReference refTo; DBTraceReference refTo;
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
refTo = b.trace.getReferenceManager() refTo = b.trace.getReferenceManager()
.addMemoryReference(Lifespan.ALL, b.addr(0x3000), .addMemoryReference(Lifespan.ALL, b.addr(0x3000), b.addr(0x4004),
b.addr(0x4004), RefType.COMPUTED_JUMP, SourceType.USER_DEFINED, RefType.COMPUTED_JUMP, SourceType.USER_DEFINED, CodeUnit.MNEMONIC);
CodeUnit.MNEMONIC);
} }
assertEquals(Set.of(refTo), set((Iterator<Reference>) i4004.getReferenceIteratorTo())); assertEquals(Set.of(refTo), set((Iterator<Reference>) i4004.getReferenceIteratorTo()));
@ -636,8 +630,7 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
thread = b.getOrAddThread("Thread 1", 0); thread = b.getOrAddThread("Thread 1", 0);
DBTraceCodeSpace regCode = manager.getCodeRegisterSpace(thread, true); DBTraceCodeSpace regCode = manager.getCodeRegisterSpace(thread, true);
data = regCode.definedData() data = regCode.definedData()
.create(Lifespan.nowOn(0), b.language.getRegister("r4"), .create(Lifespan.nowOn(0), b.language.getRegister("r4"), LongDataType.dataType);
LongDataType.dataType);
// getForRegister requires unit to match size // getForRegister requires unit to match size
undReg = regCode.undefinedData().getAt(0, b.language.getRegister("r5").getAddress()); undReg = regCode.undefinedData().getAt(0, b.language.getRegister("r5").getAddress());
} }
@ -832,8 +825,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
// StringDataType accesses memory via program view, so "block" must exist // StringDataType accesses memory via program view, so "block" must exist
b.trace.getMemoryManager() b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0), .addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ); TraceMemoryFlag.READ);
dl4000 = b.addData(0, b.addr(0x4000), LongDataType.dataType, b.buf(1, 2, 3, 4)); dl4000 = b.addData(0, b.addr(0x4000), LongDataType.dataType, b.buf(1, 2, 3, 4));
dp4006 = b.addData(0, b.addr(0x4006), PointerDataType.dataType, dp4006 = b.addData(0, b.addr(0x4006), PointerDataType.dataType,
@ -970,8 +963,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
// Disassembler's new cacheing in mem-buffer uses program view, so "block" must exist // Disassembler's new cacheing in mem-buffer uses program view, so "block" must exist
b.trace.getMemoryManager() b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0), .addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ); TraceMemoryFlag.READ);
i4004 = b.addInstruction(0, b.addr(0x4004), b.host, b.buf(0xc8, 0x47)); i4004 = b.addInstruction(0, b.addr(0x4004), b.host, b.buf(0xc8, 0x47));
assertEquals("add r4,#0x7", i4004.toString()); 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); i4004.addOperandReference(1, b.addr(0x5000), RefType.DATA_IND, SourceType.USER_DEFINED);
// TODO: This should probably be default for first/only reference // TODO: This should probably be default for first/only reference
b.trace.getReferenceManager() b.trace.getReferenceManager()
.getReference(0, b.addr(0x4004), b.addr(0x5000), .getReference(0, b.addr(0x4004), b.addr(0x5000), 1)
1)
.setPrimary(true); .setPrimary(true);
} }
assertEquals(OperandType.ADDRESS | OperandType.SCALAR, i4004.getOperandType(1)); assertEquals(OperandType.ADDRESS | OperandType.SCALAR, i4004.getOperandType(1));
@ -1247,8 +1239,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
// Disassembler's new cacheing in mem-buffer uses program view, so "block" must exist // Disassembler's new cacheing in mem-buffer uses program view, so "block" must exist
b.trace.getMemoryManager() b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0), .addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ); TraceMemoryFlag.READ);
guest = b.trace.getPlatformManager().addGuestPlatform(x86.getDefaultCompilerSpec()); guest = b.trace.getPlatformManager().addGuestPlatform(x86.getDefaultCompilerSpec());
guest.addMappedRange(b.addr(0x0000), b.addr(guest, 0x0000), 1L << 32); 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); thread = b.getOrAddThread("Thread 1", 0);
DBTraceCodeSpace regCode = manager.getCodeRegisterSpace(thread, true); DBTraceCodeSpace regCode = manager.getCodeRegisterSpace(thread, true);
dR4 = regCode.definedData() dR4 = regCode.definedData()
.create(Lifespan.nowOn(0), b.language.getRegister("r4"), .create(Lifespan.nowOn(0), b.language.getRegister("r4"), myStruct);
myStruct);
} }
myStruct = (Structure) b.trace.getDataTypeManager().getDataType("/myStruct"); myStruct = (Structure) b.trace.getDataTypeManager().getDataType("/myStruct");
myTypedef = (TypeDef) b.trace.getDataTypeManager().getDataType("/myTypedef"); myTypedef = (TypeDef) b.trace.getDataTypeManager().getDataType("/myTypedef");
@ -1603,8 +1594,8 @@ public class DBTraceCodeUnitTest extends AbstractGhidraHeadlessIntegrationTest
try (Transaction tx = b.startTransaction()) { try (Transaction tx = b.startTransaction()) {
// StringDataType accesses memory via program view, so "block" must exist // StringDataType accesses memory via program view, so "block" must exist
b.trace.getMemoryManager() b.trace.getMemoryManager()
.addRegion("myRegion", Lifespan.nowOn(0), .addRegion("myRegion", Lifespan.nowOn(0), b.range(0x4000, 0x4fff),
b.range(0x4000, 0x4fff), TraceMemoryFlag.READ); TraceMemoryFlag.READ);
d4000 = b.addData(0, b.addr(0x4000), LongDataType.dataType, b.buf(1, 2, 3, 4)); 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)); d4004 = b.addData(0, b.addr(0x4004), myStruct, b.buf(5, 6, 7, 8, 9));

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -18,17 +17,16 @@
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Listing;
public class AddCommentToProgramScript extends GhidraScript { public class AddCommentToProgramScript extends GhidraScript {
@Override @Override
public void run() throws Exception { public void run() throws Exception {
Address minAddress = currentProgram.getMinAddress(); Address minAddress = currentProgram.getMinAddress();
Listing listing = currentProgram.getListing(); Listing listing = currentProgram.getListing();
CodeUnit codeUnit = listing.getCodeUnitAt( minAddress ); CodeUnit codeUnit = listing.getCodeUnitAt(minAddress);
codeUnit.setComment( CodeUnit.PLATE_COMMENT, "AddCommentToProgramScript - This is an added comment!" ); codeUnit.setComment(CommentType.PLATE,
} "AddCommentToProgramScript - This is an added comment!");
}
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -31,7 +31,7 @@
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Instruction; import ghidra.program.model.listing.Instruction;
import ghidra.program.model.symbol.*; import ghidra.program.model.symbol.*;
@ -147,14 +147,14 @@ public class AutoRenameSimpleLabels extends GhidraScript {
// now also propogate the repeatable comment up as well // now also propogate the repeatable comment up as well
String comment = currentProgram.getListing().getComment(CodeUnit.REPEATABLE_COMMENT, String comment =
operand_addr); currentProgram.getListing().getComment(CommentType.REPEATABLE, operand_addr);
if (comment != null) { if (comment != null) {
if (currentProgram.getListing().getComment(CodeUnit.REPEATABLE_COMMENT, if (currentProgram.getListing()
startAddr) == null) { .getComment(CommentType.REPEATABLE, startAddr) == null) {
//println("updating comment for " + operand +" is " + comment); //println("updating comment for " + operand +" is " + comment);
currentProgram.getListing().setComment(startAddr, currentProgram.getListing()
CodeUnit.REPEATABLE_COMMENT, comment); .setComment(startAddr, CommentType.REPEATABLE, comment);
} }
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -19,37 +19,37 @@
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Listing;
public class DeleteDeadDefaultPlatesScript extends GhidraScript { public class DeleteDeadDefaultPlatesScript extends GhidraScript {
private static String DEAD_PLATE = " DEAD"; private static String DEAD_PLATE = " DEAD";
/* (non-Javadoc) /* (non-Javadoc)
* @see ghidra.app.script.GhidraScript#run() * @see ghidra.app.script.GhidraScript#run()
*/ */
@Override @Override
public void run() throws Exception { public void run() throws Exception {
Listing listing = currentProgram.getListing(); Listing listing = currentProgram.getListing();
AddressSetView set = currentProgram.getMemory(); AddressSetView set = currentProgram.getMemory();
if (currentSelection != null && !currentSelection.isEmpty()) { if (currentSelection != null && !currentSelection.isEmpty()) {
set = currentSelection; set = currentSelection;
} }
int updateCount=0; int updateCount = 0;
AddressIterator iter = listing.getCommentAddressIterator(CodeUnit.PLATE_COMMENT, set, true); AddressIterator iter = listing.getCommentAddressIterator(CommentType.PLATE, set, true);
while (iter.hasNext()) { while (iter.hasNext()) {
Address addr = iter.next(); Address addr = iter.next();
CodeUnit cu = listing.getCodeUnitAt(addr); CodeUnit cu = listing.getCodeUnitAt(addr);
if (cu != null) { if (cu != null) {
String[] comment = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] comment = cu.getCommentAsArray(CommentType.PLATE);
if (comment.length == 1 && comment[0].equals(DEAD_PLATE)) { if (comment.length == 1 && comment[0].equals(DEAD_PLATE)) {
cu.setComment(CodeUnit.PLATE_COMMENT, null); cu.setComment(CommentType.PLATE, null);
++updateCount; ++updateCount;
} }
} }
} }
if (updateCount > 0) { if (updateCount > 0) {
String cmt = updateCount > 1? "comments" : "comment"; String cmt = updateCount > 1 ? "comments" : "comment";
println("Removed " + updateCount + " default plate " + cmt + "."); println("Removed " + updateCount + " default plate " + cmt + ".");
} }
else { else {

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -19,37 +19,37 @@
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Listing;
public class DeleteEmptyPlateCommentsScript extends GhidraScript { public class DeleteEmptyPlateCommentsScript extends GhidraScript {
private static String EMPTY_PLATE = ""; private static String EMPTY_PLATE = "";
/* (non-Javadoc) /* (non-Javadoc)
* @see ghidra.app.script.GhidraScript#run() * @see ghidra.app.script.GhidraScript#run()
*/ */
@Override @Override
public void run() throws Exception { public void run() throws Exception {
Listing listing = currentProgram.getListing(); Listing listing = currentProgram.getListing();
AddressSetView set = currentProgram.getMemory(); AddressSetView set = currentProgram.getMemory();
if (currentSelection != null && !currentSelection.isEmpty()) { if (currentSelection != null && !currentSelection.isEmpty()) {
set = currentSelection; set = currentSelection;
} }
int updateCount=0; int updateCount = 0;
AddressIterator iter = listing.getCommentAddressIterator(CodeUnit.PLATE_COMMENT, set, true); AddressIterator iter = listing.getCommentAddressIterator(CommentType.PLATE, set, true);
while (iter.hasNext()) { while (iter.hasNext()) {
Address addr = iter.next(); Address addr = iter.next();
CodeUnit cu = listing.getCodeUnitAt(addr); CodeUnit cu = listing.getCodeUnitAt(addr);
if (cu != null) { if (cu != null) {
String[] comment = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] comment = cu.getCommentAsArray(CommentType.PLATE);
if (comment.length == 1 && comment[0].equals(EMPTY_PLATE)) { if (comment.length == 1 && comment[0].equals(EMPTY_PLATE)) {
cu.setComment(CodeUnit.PLATE_COMMENT, null); cu.setComment(CommentType.PLATE, null);
++updateCount; ++updateCount;
} }
} }
} }
if (updateCount > 0) { if (updateCount > 0) {
String cmt = updateCount > 1? "comments" : "comment"; String cmt = updateCount > 1 ? "comments" : "comment";
println("Removed " + updateCount + " emtpy plate " + cmt + "."); println("Removed " + updateCount + " emtpy plate " + cmt + ".");
} }
else { else {

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -18,38 +18,36 @@
//@category Update //@category Update
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address; import ghidra.program.model.address.*;
import ghidra.program.model.address.AddressIterator; import ghidra.program.model.listing.*;
import ghidra.program.model.address.AddressSetView;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Listing;
public class DeleteExitCommentsScript extends GhidraScript { public class DeleteExitCommentsScript extends GhidraScript {
private static String EXIT_COMMENT = " Exit **********\r\n "; private static String EXIT_COMMENT = " Exit **********\r\n ";
/* (non-Javadoc) /* (non-Javadoc)
* @see ghidra.app.script.GhidraScript#run() * @see ghidra.app.script.GhidraScript#run()
*/ */
@Override @Override
public void run() throws Exception { public void run() throws Exception {
Listing listing = currentProgram.getListing(); Listing listing = currentProgram.getListing();
AddressSetView set = currentProgram.getMemory(); AddressSetView set = currentProgram.getMemory();
if (currentSelection != null && !currentSelection.isEmpty()) { if (currentSelection != null && !currentSelection.isEmpty()) {
set = currentSelection; set = currentSelection;
} }
int updateCount=0; int updateCount = 0;
AddressIterator iter = listing.getCommentAddressIterator(CodeUnit.POST_COMMENT, set, true); AddressIterator iter = listing.getCommentAddressIterator(CommentType.POST, set, true);
while (iter.hasNext()) { while (iter.hasNext()) {
Address addr = iter.next(); Address addr = iter.next();
CodeUnit cu = listing.getCodeUnitAt(addr); CodeUnit cu = listing.getCodeUnitAt(addr);
String[] comment = cu.getCommentAsArray(CodeUnit.POST_COMMENT); String[] comment = cu.getCommentAsArray(CommentType.POST);
if (comment.length == 1 && comment[0].endsWith(EXIT_COMMENT)) { if (comment.length == 1 && comment[0].endsWith(EXIT_COMMENT)) {
cu.setComment(CodeUnit.POST_COMMENT, null); cu.setComment(CommentType.POST, null);
++updateCount; ++updateCount;
} }
} }
if (updateCount > 0) { if (updateCount > 0) {
String cmt = updateCount > 1? "comments" : "comment"; String cmt = updateCount > 1 ? "comments" : "comment";
println("Removed " + updateCount + " exit post " + cmt + "."); println("Removed " + updateCount + " exit post " + cmt + ".");
} }
else { else {

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.app.script.GhidraScript;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.mem.Memory; import ghidra.program.model.mem.Memory;
import ghidra.util.exception.CancelledException; import ghidra.util.exception.CancelledException;
@ -72,14 +73,14 @@ public class LocateMemoryAddressesForFileOffset extends GhidraScript {
println("File offset " + Long.toHexString(fileOffset) + println("File offset " + Long.toHexString(fileOffset) +
" is associated with memory block:address " + memBlockName + ":" + addr.toString()); " is associated with memory block:address " + memBlockName + ":" + addr.toString());
CodeUnit myCodeUnit = currentProgram.getListing().getCodeUnitContaining(addr); CodeUnit myCodeUnit = currentProgram.getListing().getCodeUnitContaining(addr);
String comment = myCodeUnit.getComment(0); String comment = myCodeUnit.getComment(CommentType.EOL);
if (comment == null) { if (comment == null) {
myCodeUnit.setComment(0, myCodeUnit.setComment(CommentType.EOL,
this.getScriptName() + ": File offset: " + Long.toHexString(fileOffset) + this.getScriptName() + ": File offset: " + Long.toHexString(fileOffset) +
", Memory block:address " + memBlockName + ":" + addr.toString()); ", Memory block:address " + memBlockName + ":" + addr.toString());
} }
else { else {
myCodeUnit.setComment(0, myCodeUnit.setComment(CommentType.EOL,
comment + ", " + this.getScriptName() + ": File offset: " + comment + ", " + this.getScriptName() + ": File offset: " +
Long.toHexString(fileOffset) + ", Memory block:address " + memBlockName + ":" + Long.toHexString(fileOffset) + ", Memory block:address " + memBlockName + ":" +
addr.toString()); addr.toString());

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.block.PartitionCodeSubModel;
import ghidra.program.model.data.DataType; import ghidra.program.model.data.DataType;
import ghidra.program.model.lang.*; import ghidra.program.model.lang.*;
import ghidra.program.model.listing.Function; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.pcode.PcodeOp; import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode; import ghidra.program.model.pcode.Varnode;
import ghidra.program.model.symbol.*; import ghidra.program.model.symbol.*;
@ -180,7 +179,8 @@ public class MultiInstructionMemReference extends GhidraScript {
public boolean evaluateReference(VarnodeContext context, Instruction instr, int pcodeop, public boolean evaluateReference(VarnodeContext context, Instruction instr, int pcodeop,
Address address, int size, DataType dataType, RefType refType) { 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, private boolean checkInstructionMatch(final int opIdx, boolean input,
@ -287,7 +287,7 @@ public class MultiInstructionMemReference extends GhidraScript {
} }
Address lastSetLocation = context.getLastSetLocation(singleRegister, null); Address lastSetLocation = context.getLastSetLocation(singleRegister, null);
String comment = instr.getComment(Instruction.EOL_COMMENT); String comment = instr.getComment(CommentType.EOL);
if (comment == null) { if (comment == null) {
comment = ""; comment = "";
} }
@ -300,7 +300,7 @@ public class MultiInstructionMemReference extends GhidraScript {
return false; return false;
} }
comment = (comment.trim().length() == 0 ? markup : comment + "\n" + markup); comment = (comment.trim().length() == 0 ? markup : comment + "\n" + markup);
instr.setComment(Instruction.EOL_COMMENT, comment); instr.setComment(CommentType.EOL, comment);
return false; return false;
} }

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -19,168 +18,141 @@
// function's plate comment. // function's plate comment.
//@category Analysis //@category Analysis
import java.util.*;
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.lang.Register; import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.*; import ghidra.program.model.listing.*;
import java.util.*; public class RegisterTouchesPerFunction extends GhidraScript {
private final static String DIVIDER =
"*************************************************************\r\n";
public class RegisterTouchesPerFunction extends GhidraScript @Override
{ public void run() throws Exception {
private final static String DIVIDER = "*************************************************************\r\n"; Listing l = this.currentProgram.getListing();
@Override if (this.askYesNo("Function Analysis - Register Touches", "Analyze complete listing?")) {
public void run() throws Exception FunctionIterator fi = l.getFunctions(true);
{ while (fi.hasNext() && !monitor.isCancelled()) {
Listing l = this.currentProgram.getListing(); doAnalysis(l, fi.next());
}
}
else {
doAnalysis(l, l.getFunctionContaining(this.currentAddress));
}
}
if (this.askYesNo("Function Analysis - Register Touches", private void doAnalysis(Listing list, Function func) {
"Analyze complete listing?")) if (func == null) {
{ println("No function to analyze.");
FunctionIterator fi = l.getFunctions(true); return;
while (fi.hasNext() && !monitor.isCancelled()) }
{ HashSet<String> affected, accessed;
doAnalysis(l, fi.next()); Vector<String> restored;
} Stack<String> pushPops;
} boolean reviewRestored = false;
else Instruction inst;
{ InstructionIterator iIter;
doAnalysis(l, l.getFunctionContaining(this.currentAddress));
}
}
private void doAnalysis(Listing list, Function func) monitor.setMessage("Analyzing registers in " + func.getName());
{
if (func == null) {
println("No function to analyze.");
return;
}
HashSet<String> affected, accessed;
Vector<String> restored;
Stack<String> pushPops;
boolean reviewRestored = false;
Instruction inst;
InstructionIterator iIter;
monitor.setMessage("Analyzing registers in " + func.getName());
String comment = list.getComment(CodeUnit.PLATE_COMMENT, func.getBody().getMinAddress()); String comment = list.getComment(CommentType.PLATE, func.getBody().getMinAddress());
if (comment != null && comment.indexOf("TOUCHED REGISTER SUMMARY") > -1) if (comment != null && comment.indexOf("TOUCHED REGISTER SUMMARY") > -1)
return; return;
pushPops = new Stack<String>(); pushPops = new Stack<String>();
affected = new HashSet<String>(); affected = new HashSet<String>();
accessed = new HashSet<String>(); accessed = new HashSet<String>();
restored = new Vector<String>(); restored = new Vector<String>();
iIter = list.getInstructions(func.getBody(), true); iIter = list.getInstructions(func.getBody(), true);
while (iIter.hasNext() && !monitor.isCancelled())
{
inst = iIter.next();
Object o[] = inst.getResultObjects(); while (iIter.hasNext() && !monitor.isCancelled()) {
for (int i = 0; i < o.length; i++) inst = iIter.next();
{
if (o[i] instanceof Register)
{
String name = ((Register) o[i]).getName();
if (inst.getMnemonicString().equalsIgnoreCase("pop")) Object o[] = inst.getResultObjects();
{ for (Object element : o) {
if (!name.equalsIgnoreCase("mult_addr") if (element instanceof Register) {
&& !name.equalsIgnoreCase("sp")) String name = ((Register) element).getName();
{
if (pushPops.size() > 0)
{
restored.add(pushPops.pop() + "->" + name);
}
else
{
reviewRestored = true;
}
}
}
else
{
affected.add(name);
}
}
}
o = inst.getInputObjects();
for (int i = 0; i < o.length; i++) if (inst.getMnemonicString().equalsIgnoreCase("pop")) {
{ if (!name.equalsIgnoreCase("mult_addr") && !name.equalsIgnoreCase("sp")) {
if (o[i] instanceof Register) if (pushPops.size() > 0) {
{ restored.add(pushPops.pop() + "->" + name);
String name = ((Register) o[i]).getName(); }
if (inst.getMnemonicString().equalsIgnoreCase("push")) else {
{ reviewRestored = true;
if (!name.equalsIgnoreCase("mult_addr") }
&& !name.equalsIgnoreCase("sp")) }
{ }
pushPops.push(name); else {
} affected.add(name);
} }
else }
{ }
accessed.add(name); o = inst.getInputObjects();
}
}
}
}
StringBuffer buffer = new StringBuffer(); for (Object element : o) {
if (comment != null) { if (element instanceof Register) {
buffer.append(comment); String name = ((Register) element).getName();
buffer.append("\r\n"); if (inst.getMnemonicString().equalsIgnoreCase("push")) {
buffer.append(DIVIDER); if (!name.equalsIgnoreCase("mult_addr") && !name.equalsIgnoreCase("sp")) {
} pushPops.push(name);
buffer.append("TOUCHED REGISTER SUMMARY:\r\n"); }
buffer.append(DIVIDER); }
buffer.append("Register(s) Affected:\r\n"); else {
buffer.append(getString(affected, 8)); accessed.add(name);
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(reviewRestored) StringBuffer buffer = new StringBuffer();
{ if (comment != null) {
buffer.append("##Review - due to branches this list may not be accurate\r\n"); buffer.append(comment);
println(func.getName() + " - Review - due to branches this list may not be accurate"); buffer.append("\r\n");
} buffer.append(DIVIDER);
buffer.append(DIVIDER); }
buffer.append("TOUCHED REGISTER SUMMARY:\r\n");
buffer.append(DIVIDER);
buffer.append("Register(s) Affected:\r\n");
buffer.append(getString(affected, 8));
buffer.append(DIVIDER);
buffer.append("Register(s) Accessed:\r\n");
buffer.append(getString(accessed, 8));
buffer.append(DIVIDER);
buffer.append("Register(s) Restored:\r\n");
buffer.append(getString(restored, 4));
if (pushPops.size() > 0) if (reviewRestored) {
{ buffer.append("##Review - due to branches this list may not be accurate\r\n");
println(func.getName() + " - Review - due to branches this list may not be accurate");
}
buffer.append(DIVIDER);
buffer.append("Registers Remaining on Stack:\r\n"); if (pushPops.size() > 0) {
buffer.append(" "+getString(pushPops, 8));
}
list.setComment(func.getEntryPoint(), CodeUnit.PLATE_COMMENT, buffer.toString()); buffer.append("Registers Remaining on Stack:\r\n");
} buffer.append(" " + getString(pushPops, 8));
}
private String getString(Collection<String> c, int itemsPerLine) list.setComment(func.getEntryPoint(), CommentType.PLATE, buffer.toString());
{ }
TreeSet<Object> ts = new TreeSet<Object>(c);
String temp = ts.toString();
temp = temp.substring(1, temp.length() - 1);
int i = 0;
int commaCount = 0;
while ((i = temp.indexOf(',', i + 1)) >= 0)
{
commaCount++;
if (commaCount % itemsPerLine == 0)
temp = temp.substring(0, i + 1) + "\r\n"
+ temp.substring(i + 1).trim();
}
return temp + "\r\n"; private String getString(Collection<String> c, int itemsPerLine) {
} TreeSet<Object> ts = new TreeSet<Object>(c);
String temp = ts.toString();
temp = temp.substring(1, temp.length() - 1);
int i = 0;
int commaCount = 0;
while ((i = temp.indexOf(',', i + 1)) >= 0) {
commaCount++;
if (commaCount % itemsPerLine == 0)
temp = temp.substring(0, i + 1) + "\r\n" + temp.substring(i + 1).trim();
}
return temp + "\r\n";
}
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -38,7 +38,7 @@ import java.util.List;
import ghidra.app.script.GhidraScript; import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Listing; import ghidra.program.model.listing.Listing;
import ghidra.program.model.mem.Memory; import ghidra.program.model.mem.Memory;
import ghidra.program.model.symbol.*; import ghidra.program.model.symbol.*;
@ -60,8 +60,8 @@ public class ZapBCTRScript extends GhidraScript {
} }
// first try input as class and search for symbol "<class>::__vtbl" // first try input as class and search for symbol "<class>::__vtbl"
List<Symbol> symbols = currentProgram.getSymbolTable().getSymbols("__vtbl", List<Symbol> symbols = currentProgram.getSymbolTable()
getNamespace(null, classNameOrAddr)); .getSymbols("__vtbl", getNamespace(null, classNameOrAddr));
// if symbol found, then vtblAddr is the symbol's address // if symbol found, then vtblAddr is the symbol's address
if (symbols.size() == 1) { if (symbols.size() == 1) {
vtblAddr = symbols.get(0).getAddress(); vtblAddr = symbols.get(0).getAddress();
@ -99,9 +99,9 @@ public class ZapBCTRScript extends GhidraScript {
// insert funcName as EOL comment and // insert funcName as EOL comment and
// add a mnemonic ref from instAddr to funcAddr // add a mnemonic ref from instAddr to funcAddr
listing.setComment(instAddr, CodeUnit.EOL_COMMENT, funcName); listing.setComment(instAddr, CommentType.EOL, funcName);
listing.getInstructionAt(instAddr).addMnemonicReference(funcAddr, RefType.COMPUTED_CALL, listing.getInstructionAt(instAddr)
SourceType.USER_DEFINED); .addMnemonicReference(funcAddr, RefType.COMPUTED_CALL, SourceType.USER_DEFINED);
/* old code that replaces the 'bctr' with a 'bl' /* old code that replaces the 'bctr' with a 'bl'
int code = 0x48000001 | ((int)displacement & 0x3ffffff); int code = 0x48000001 | ((int)displacement & 0x3ffffff);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -25,10 +25,9 @@ import ghidra.program.model.listing.*;
public class AppendCommentCmd implements Command<Program> { public class AppendCommentCmd implements Command<Program> {
private Address address; private Address address;
private int commentType; private CommentType commentType;
private String comment; private String comment;
private String separator; private String separator;
private String cmdName;
private String message; private String message;
/** /**
@ -40,17 +39,30 @@ public class AppendCommentCmd implements Command<Program> {
* @param separator characters to separate the new comment from the previous comment when * @param separator characters to separate the new comment from the previous comment when
* concatenating. * concatenating.
*/ */
@Deprecated(forRemoval = true, since = "11.4")
public AppendCommentCmd(Address addr, int commentType, String comment, String separator) { 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.address = addr;
this.commentType = commentType; this.commentType = commentType;
this.comment = comment; this.comment = comment;
this.separator = separator; this.separator = separator;
cmdName = "Append Comment";
} }
@Override @Override
public String getName() { public String getName() {
return cmdName; return "Append Comment";
} }
@Override @Override

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -325,24 +325,24 @@ public class CodeUnitInfoPasteCmd implements Command<Program> {
String[] repeatableComment = info.getRepeatableComment(); String[] repeatableComment = info.getRepeatableComment();
if (plateComment != null) { if (plateComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] oldComment = cu.getCommentAsArray(CommentType.PLATE);
cu.setCommentAsArray(CodeUnit.PLATE_COMMENT, appendComment(oldComment, plateComment)); cu.setCommentAsArray(CommentType.PLATE, appendComment(oldComment, plateComment));
} }
if (preComment != null) { if (preComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.PRE_COMMENT); String[] oldComment = cu.getCommentAsArray(CommentType.PRE);
cu.setCommentAsArray(CodeUnit.PRE_COMMENT, appendComment(oldComment, preComment)); cu.setCommentAsArray(CommentType.PRE, appendComment(oldComment, preComment));
} }
if (postComment != null) { if (postComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.POST_COMMENT); String[] oldComment = cu.getCommentAsArray(CommentType.POST);
cu.setCommentAsArray(CodeUnit.POST_COMMENT, appendComment(oldComment, postComment)); cu.setCommentAsArray(CommentType.POST, appendComment(oldComment, postComment));
} }
if (eolComment != null) { if (eolComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.EOL_COMMENT); String[] oldComment = cu.getCommentAsArray(CommentType.EOL);
cu.setCommentAsArray(CodeUnit.EOL_COMMENT, appendComment(oldComment, eolComment)); cu.setCommentAsArray(CommentType.EOL, appendComment(oldComment, eolComment));
} }
if (repeatableComment != null) { if (repeatableComment != null) {
String[] oldComment = cu.getCommentAsArray(CodeUnit.REPEATABLE_COMMENT); String[] oldComment = cu.getCommentAsArray(CommentType.REPEATABLE);
cu.setCommentAsArray(CodeUnit.REPEATABLE_COMMENT, cu.setCommentAsArray(CommentType.REPEATABLE,
appendComment(oldComment, repeatableComment)); appendComment(oldComment, repeatableComment));
} }
} }

View file

@ -26,7 +26,7 @@ import ghidra.program.model.listing.*;
public class SetCommentCmd implements Command<Program> { public class SetCommentCmd implements Command<Program> {
private Address address; private Address address;
private int commentType; private CommentType commentType;
private String comment; private String comment;
private String cmdName; private String cmdName;
private String message; private String message;
@ -37,7 +37,18 @@ public class SetCommentCmd implements Command<Program> {
* @param commentType valid comment type (see CodeUnit) * @param commentType valid comment type (see CodeUnit)
* @param comment comment for code unit * @param comment comment for code unit
*/ */
@Deprecated(forRemoval = true, since = "11.4")
public SetCommentCmd(Address addr, int commentType, String comment) { public SetCommentCmd(Address addr, int commentType, String comment) {
this(addr, CommentType.valueOf(commentType), comment);
}
/**
* Construct command
* @param addr address of code unit where comment will be placed
* @param commentType valid comment type (see CodeUnit)
* @param comment comment for code unit
*/
public SetCommentCmd(Address addr, CommentType commentType, String comment) {
this.address = addr; this.address = addr;
this.commentType = commentType; this.commentType = commentType;
this.comment = comment; this.comment = comment;
@ -112,12 +123,11 @@ public class SetCommentCmd implements Command<Program> {
* @param program the program being analyzed * @param program the program being analyzed
* @param addr the address where data is created * @param addr the address where data is created
* @param comment the comment about the data * @param comment the comment about the data
* @param commentType the type of comment ({@link CodeUnit#PLATE_COMMENT}, * @param commentType the type of comment
* {@link CodeUnit#PRE_COMMENT}, {@link CodeUnit#EOL_COMMENT}, {@link CodeUnit#POST_COMMENT},
* {@link CodeUnit#REPEATABLE_COMMENT})
*/ */
public static void createComment(Program program, Address addr, String comment, public static void createComment(Program program, Address addr, String comment,
int commentType) { CommentType commentType) {
SetCommentCmd commentCmd = new SetCommentCmd(addr, commentType, comment); SetCommentCmd commentCmd = new SetCommentCmd(addr, commentType, comment);
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -83,31 +83,31 @@ public class SetCommentsCmd implements Command<Program> {
CodeUnit cu = getCodeUnit(program); CodeUnit cu = getCodeUnit(program);
if (cu != null) { if (cu != null) {
if (commentChanged(cu.getComment(CodeUnit.PRE_COMMENT), preComment)) { if (commentChanged(cu.getComment(CommentType.PRE), preComment)) {
String updatedPreComment = CommentUtils.fixupAnnotations(preComment, program); String updatedPreComment = CommentUtils.fixupAnnotations(preComment, program);
updatedPreComment = CommentUtils.sanitize(updatedPreComment); updatedPreComment = CommentUtils.sanitize(updatedPreComment);
cu.setComment(CodeUnit.PRE_COMMENT, updatedPreComment); cu.setComment(CommentType.PRE, updatedPreComment);
} }
if (commentChanged(cu.getComment(CodeUnit.POST_COMMENT), postComment)) { if (commentChanged(cu.getComment(CommentType.POST), postComment)) {
String updatedPostComment = CommentUtils.fixupAnnotations(postComment, program); String updatedPostComment = CommentUtils.fixupAnnotations(postComment, program);
updatedPostComment = CommentUtils.sanitize(updatedPostComment); updatedPostComment = CommentUtils.sanitize(updatedPostComment);
cu.setComment(CodeUnit.POST_COMMENT, updatedPostComment); cu.setComment(CommentType.POST, updatedPostComment);
} }
if (commentChanged(cu.getComment(CodeUnit.EOL_COMMENT), eolComment)) { if (commentChanged(cu.getComment(CommentType.EOL), eolComment)) {
String updatedEOLComment = CommentUtils.fixupAnnotations(eolComment, program); String updatedEOLComment = CommentUtils.fixupAnnotations(eolComment, program);
updatedEOLComment = CommentUtils.sanitize(updatedEOLComment); updatedEOLComment = CommentUtils.sanitize(updatedEOLComment);
cu.setComment(CodeUnit.EOL_COMMENT, updatedEOLComment); cu.setComment(CommentType.EOL, updatedEOLComment);
} }
if (commentChanged(cu.getComment(CodeUnit.PLATE_COMMENT), plateComment)) { if (commentChanged(cu.getComment(CommentType.PLATE), plateComment)) {
String updatedPlateComment = CommentUtils.fixupAnnotations(plateComment, program); String updatedPlateComment = CommentUtils.fixupAnnotations(plateComment, program);
updatedPlateComment = CommentUtils.sanitize(updatedPlateComment); updatedPlateComment = CommentUtils.sanitize(updatedPlateComment);
cu.setComment(CodeUnit.PLATE_COMMENT, updatedPlateComment); cu.setComment(CommentType.PLATE, updatedPlateComment);
} }
if (commentChanged(cu.getComment(CodeUnit.REPEATABLE_COMMENT), repeatableComment)) { if (commentChanged(cu.getComment(CommentType.REPEATABLE), repeatableComment)) {
String updatedRepeatableComment = String updatedRepeatableComment =
CommentUtils.fixupAnnotations(repeatableComment, program); CommentUtils.fixupAnnotations(repeatableComment, program);
updatedRepeatableComment = CommentUtils.sanitize(updatedRepeatableComment); updatedRepeatableComment = CommentUtils.sanitize(updatedRepeatableComment);
cu.setComment(CodeUnit.REPEATABLE_COMMENT, updatedRepeatableComment); cu.setComment(CommentType.REPEATABLE, updatedRepeatableComment);
} }
} }
return true; return true;

View file

@ -184,7 +184,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
createFragment(sectionDT.getName(), sectionStart, sectionDT.getLength()); createFragment(sectionDT.getName(), sectionStart, sectionDT.getLength());
CodeUnit cu = listing.getCodeUnitAt(addr(offset)); CodeUnit cu = listing.getCodeUnitAt(addr(offset));
cu.setComment(CodeUnit.PLATE_COMMENT, cu.setComment(CommentType.PLATE,
"#" + i + ") " + name + " at 0x" + Long.toHexString(sections[i].getAddress())); "#" + i + ") " + name + " at 0x" + Long.toHexString(sections[i].getAddress()));
if (sections[i].getType() == ElfSectionHeaderConstants.SHT_NOBITS || if (sections[i].getType() == ElfSectionHeaderConstants.SHT_NOBITS ||
@ -203,7 +203,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
} }
cu = listing.getCodeUnitAt(dataStart); cu = listing.getCodeUnitAt(dataStart);
cu.setComment(CodeUnit.PRE_COMMENT, sections[i].getNameAsString() + " Size: 0x" + cu.setComment(CommentType.PRE, sections[i].getNameAsString() + " Size: 0x" +
Long.toHexString(sections[i].getSize())); Long.toHexString(sections[i].getSize()));
} }
} }
@ -228,7 +228,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
for (int i = 0; i < programHeaders.length; i++) { for (int i = 0; i < programHeaders.length; i++) {
monitor.checkCancelled(); monitor.checkCancelled();
Data d = array.getComponent(i); Data d = array.getComponent(i);
d.setComment(CodeUnit.EOL_COMMENT, programHeaders[i].getComment()); d.setComment(CommentType.EOL, programHeaders[i].getComment());
Address addr = addr(programHeaders[i].getOffset()); Address addr = addr(programHeaders[i].getOffset());
@ -238,8 +238,8 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
private void processInterpretor(ElfHeader elf, ByteProvider provider, Program program) private void processInterpretor(ElfHeader elf, ByteProvider provider, Program program)
throws CancelledException { throws CancelledException {
for (ElfProgramHeader programHeader : elf.getProgramHeaders( for (ElfProgramHeader programHeader : elf
ElfProgramHeaderConstants.PT_INTERP)) { .getProgramHeaders(ElfProgramHeaderConstants.PT_INTERP)) {
monitor.checkCancelled(); monitor.checkCancelled();
long offset = programHeader.getOffset(); long offset = programHeader.getOffset();
if (offset == 0) { if (offset == 0) {
@ -292,7 +292,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
dynamicType != null ? (dynamicType.name + " - " + dynamicType.description) dynamicType != null ? (dynamicType.name + " - " + dynamicType.description)
: ("DT_0x" + StringUtilities.pad(Integer.toHexString(tagType), '0', 8)); : ("DT_0x" + StringUtilities.pad(Integer.toHexString(tagType), '0', 8));
dynamicData.setComment(CodeUnit.EOL_COMMENT, comment); dynamicData.setComment(CommentType.EOL, comment);
Data valueData = dynamicData.getComponent(1); Data valueData = dynamicData.getComponent(1);
@ -323,7 +323,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
if (dynamicStringTable != null) { if (dynamicStringTable != null) {
String str = dynamicStringTable.readString(reader, dynamic.getValue()); String str = dynamicStringTable.readString(reader, dynamic.getValue());
if (str != null && str.length() != 0) { if (str != null && str.length() != 0) {
data.setComment(CodeUnit.EOL_COMMENT, str); data.setComment(CommentType.EOL, str);
} }
} }
} }
@ -339,8 +339,8 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
} }
Address refAddr = addr(programLoadHeader.getOffset(dynamicRefAddr)); Address refAddr = addr(programLoadHeader.getOffset(dynamicRefAddr));
program.getReferenceManager().addMemoryReference(fromAddr, refAddr, RefType.DATA, program.getReferenceManager()
SourceType.ANALYSIS, 0); .addMemoryReference(fromAddr, refAddr, RefType.DATA, SourceType.ANALYSIS, 0);
try { try {
createLabel(refAddr, "_" + dynamic.getTagAsString(), true, SourceType.ANALYSIS); createLabel(refAddr, "_" + dynamic.getTagAsString(), true, SourceType.ANALYSIS);
@ -384,7 +384,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
try { try {
Address currAddr = symbolTableAddr.add(j * symbolTable2.getEntrySize()); Address currAddr = symbolTableAddr.add(j * symbolTable2.getEntrySize());
listing.setComment(currAddr, CodeUnit.EOL_COMMENT, listing.setComment(currAddr, CommentType.EOL,
name + " at 0x" + Long.toHexString(symbols[j].getValue())); name + " at 0x" + Long.toHexString(symbols[j].getValue()));
} }
catch (Exception e) { catch (Exception e) {
@ -418,7 +418,7 @@ public class ElfBinaryAnalysisCommand extends FlatProgramAPI
createData(relocationTableAddress, dataType); createData(relocationTableAddress, dataType);
} }
else { else {
listing.setComment(relocationTableAddress, CodeUnit.PRE_COMMENT, listing.setComment(relocationTableAddress, CommentType.PRE,
"ELF Relocation Table (markup not yet supported)"); "ELF Relocation Table (markup not yet supported)");
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -105,6 +105,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {
CliStreamMetadata metadataStream = metadataRoot.getMetadataStream(); CliStreamMetadata metadataStream = metadataRoot.getMetadataStream();
InstructionIterator instIter = program.getListing().getInstructions(set, true); InstructionIterator instIter = program.getListing().getInstructions(set, true);
while (instIter.hasNext()) { while (instIter.hasNext()) {
monitor.checkCancelled();
try { try {
Instruction inst = instIter.next(); Instruction inst = instIter.next();
/* Base Instructions (Partition II.3) */ /* Base Instructions (Partition II.3) */
@ -194,7 +195,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {
int strIndex = (int) strIndexOp.getUnsignedValue(); int strIndex = (int) strIndexOp.getUnsignedValue();
inst.setComment(CodeUnit.EOL_COMMENT, inst.setComment(CommentType.EOL,
"\"" + metaStream.getUserStringsStream().getUserString(strIndex) + "\""); "\"" + metaStream.getUserStringsStream().getUserString(strIndex) + "\"");
} }
@ -229,7 +230,7 @@ public class CliMetadataTokenAnalyzer extends AbstractAnalyzer {
private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow, private void markMetadataRow(Instruction inst, CliAbstractTableRow tableRow,
String prependComment, String appendComment, CliStreamMetadata stream) { String prependComment, String appendComment, CliStreamMetadata stream) {
inst.setComment(CodeUnit.EOL_COMMENT, String.format("%s%s%s", prependComment, inst.setComment(CommentType.EOL, String.format("%s%s%s", prependComment,
tableRow.getShortRepresentation(stream), appendComment)); tableRow.getShortRepresentation(stream), appendComment));
} }

View file

@ -166,8 +166,7 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
"Golang symbol analyzer: scheduling RTTI propagation after reference analysis"); "Golang symbol analyzer: scheduling RTTI propagation after reference analysis");
aam.schedule(new PropagateRttiBackgroundCommand(goBinary, markupSession), aam.schedule(new PropagateRttiBackgroundCommand(goBinary, markupSession),
PROP_RTTI_PRIORITY.priority()); PROP_RTTI_PRIORITY.priority());
Msg.info(this, Msg.info(this, "Golang symbol analyzer: scheduling closure function fixup");
"Golang symbol analyzer: scheduling closure function fixup");
aam.schedule(new FixClosureFuncArgsBackgroundCommand(goBinary), aam.schedule(new FixClosureFuncArgsBackgroundCommand(goBinary),
FIX_CLOSURES_PRIORITY.priority()); FIX_CLOSURES_PRIORITY.priority());
} }
@ -328,8 +327,7 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
: null; : null;
String typeStr = typeStructAddr != null String typeStr = typeStructAddr != null
? AddressAnnotatedStringHandler.createAddressAnnotationString( ? AddressAnnotatedStringHandler.createAddressAnnotationString(
typeStructAddr, typeStructAddr, recvType.getName())
recvType.getName())
: funcDefResult.symbolName().receiverString(); : funcDefResult.symbolName().receiverString();
markupSession.appendComment(func, "", markupSession.appendComment(func, "",
"Golang method in type %s".formatted(typeStr)); "Golang method in type %s".formatted(typeStr));
@ -354,7 +352,6 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
.formatted(functionSignatureFromMethod)); .formatted(functionSignatureFromMethod));
} }
private void fixGcWriteBarrierFunctions() { private void fixGcWriteBarrierFunctions() {
if (GoConstants.GCWRITE_BUFFERED_VERS.contains(goBinary.getGoVer())) { if (GoConstants.GCWRITE_BUFFERED_VERS.contains(goBinary.getGoVer())) {
fixGcWriteBarrierBufferedFunctions(); fixGcWriteBarrierBufferedFunctions();
@ -390,8 +387,7 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
func = funcData != null ? funcData.getFunction() : null; func = funcData != null ? funcData.getFunction() : null;
if (func != null) { if (func != null) {
func.updateFunction(ccname, retVal, List.of(), func.updateFunction(ccname, retVal, List.of(),
FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS);
SourceType.ANALYSIS);
} }
} }
} }
@ -460,9 +456,9 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
DataType voidPtr = program.getDataTypeManager().getPointer(VoidDataType.dataType); DataType voidPtr = program.getDataTypeManager().getPointer(VoidDataType.dataType);
GoFuncData duffzeroFuncdata = goBinary.getFunctionByName("runtime.duffzero"); GoFuncData duffzeroFuncdata = goBinary.getFunctionByName("runtime.duffzero");
Function duffzeroFunc = duffzeroFuncdata != null Function duffzeroFunc =
? funcMgr.getFunctionAt(duffzeroFuncdata.getFuncAddress()) duffzeroFuncdata != null ? funcMgr.getFunctionAt(duffzeroFuncdata.getFuncAddress())
: null; : null;
List<Variable> duffzeroParams = regInfo.getDuffzeroParams(program); List<Variable> duffzeroParams = regInfo.getDuffzeroParams(program);
if (duffzeroFunc != null && !duffzeroParams.isEmpty()) { if (duffzeroFunc != null && !duffzeroParams.isEmpty()) {
// NOTE: some go archs don't create duffzero functions. See // 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"); GoFuncData duffcopyFuncdata = goBinary.getFunctionByName("runtime.duffcopy");
Function duffcopyFunc = duffcopyFuncdata != null Function duffcopyFunc =
? funcMgr.getFunctionAt(duffcopyFuncdata.getFuncAddress()) duffcopyFuncdata != null ? funcMgr.getFunctionAt(duffcopyFuncdata.getFuncAddress())
: null; : null;
if (duffcopyFuncdata != null && if (duffcopyFuncdata != null &&
goBinary.hasCallingConvention(GOLANG_DUFFCOPY_CALLINGCONVENTION_NAME)) { goBinary.hasCallingConvention(GOLANG_DUFFCOPY_CALLINGCONVENTION_NAME)) {
try { try {
List<Variable> params = List<Variable> params = List.of(new ParameterImpl("dest", voidPtr, program),
List.of(new ParameterImpl("dest", voidPtr, program), new ParameterImpl("src", voidPtr, program));
new ParameterImpl("src", voidPtr, program));
duffcopyFunc.updateFunction(GOLANG_DUFFCOPY_CALLINGCONVENTION_NAME, duffcopyFunc.updateFunction(GOLANG_DUFFCOPY_CALLINGCONVENTION_NAME,
new ReturnParameterImpl(VoidDataType.dataType, program), params, new ReturnParameterImpl(VoidDataType.dataType, program), params,
FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS); FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true, SourceType.ANALYSIS);
@ -672,13 +667,13 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
func.setName(duffFunc.getName() + "_" + func.getEntryPoint(), func.setName(duffFunc.getName() + "_" + func.getEntryPoint(),
SourceType.ANALYSIS); SourceType.ANALYSIS);
func.setParentNamespace(funcNS); func.setParentNamespace(funcNS);
FunctionUpdateType fut = duffFunc.hasCustomVariableStorage() FunctionUpdateType fut =
? FunctionUpdateType.CUSTOM_STORAGE duffFunc.hasCustomVariableStorage() ? FunctionUpdateType.CUSTOM_STORAGE
: FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS; : FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS;
func.updateFunction(ccName, duffFunc.getReturn(), func.updateFunction(ccName, duffFunc.getReturn(),
Arrays.asList(duffFunc.getParameters()), fut, true, SourceType.ANALYSIS); Arrays.asList(duffFunc.getParameters()), fut, true, SourceType.ANALYSIS);
if (duffComment != null && !duffComment.isBlank()) { if (duffComment != null && !duffComment.isBlank()) {
new SetCommentCmd(func.getEntryPoint(), CodeUnit.PLATE_COMMENT, duffComment) new SetCommentCmd(func.getEntryPoint(), CommentType.PLATE, duffComment)
.applyTo(program); .applyTo(program);
} }
} }
@ -1079,8 +1074,8 @@ public class GolangSymbolAnalyzer extends AbstractAnalyzer {
} }
record CallSiteInfo(Reference ref, Function callingFunc, Function calledFunc, record CallSiteInfo(Reference ref, Function callingFunc, Function calledFunc,
Register register, Register register, java.util.function.Function<GoType, DataType> returnTypeMapper) {
java.util.function.Function<GoType, DataType> returnTypeMapper) {} }
private GoRttiMapper goBinary; private GoRttiMapper goBinary;
private Program program; private Program program;

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -62,9 +62,8 @@ public class MingwRelocationAnalyzer extends AbstractAnalyzer {
if (!program.hasExclusiveAccess()) { if (!program.hasExclusiveAccess()) {
// Exclusive access required since relocation table lacks merge support // Exclusive access required since relocation table lacks merge support
if (!alreadyProcessed(program)) { if (!alreadyProcessed(program)) {
Msg.error(this, Msg.error(this, NAME + " analyzer disabled; requires exclusive access to " +
NAME + " analyzer disabled; requires exclusive access to " + program.getDomainFile());
program.getDomainFile());
} }
return false; return false;
} }
@ -226,11 +225,9 @@ class MinGWPseudoRelocationHandler {
static boolean isSupportedProgram(Program program) { static boolean isSupportedProgram(Program program) {
Language language = program.getLanguage(); Language language = program.getLanguage();
int size = language.getLanguageDescription().getSize(); int size = language.getLanguageDescription().getSize();
return "x86".equals(language.getProcessor().toString()) && return "x86".equals(language.getProcessor().toString()) && (size == 32 || size == 64) &&
(size == 32 || size == 64) &&
"windows".equals(program.getCompilerSpec().getCompilerSpecID().toString()) && "windows".equals(program.getCompilerSpec().getCompilerSpecID().toString()) &&
CompilerEnum.GCC.label.equals(program.getCompiler()) && CompilerEnum.GCC.label.equals(program.getCompiler()) && getRDataBlock(program) != null;
getRDataBlock(program) != null;
} }
private static MemoryBlock getRDataBlock(Program program) { private static MemoryBlock getRDataBlock(Program program) {
@ -252,7 +249,6 @@ class MinGWPseudoRelocationHandler {
} }
} }
boolean processRelocations(MessageLog log, TaskMonitor monitor) throws CancelledException { boolean processRelocations(MessageLog log, TaskMonitor monitor) throws CancelledException {
Address pdwListBeginAddr = relocList.getListStartAddress(); Address pdwListBeginAddr = relocList.getListStartAddress();
@ -297,8 +293,8 @@ class MinGWPseudoRelocationHandler {
boolean success; boolean success;
switch (version) { switch (version) {
case RP_VERSION_V1: case RP_VERSION_V1:
success = relocateV1(pdwListBeginAddr, (int) (size / OLD_STYLE_ENTRY_SIZE), log, success =
monitor); relocateV1(pdwListBeginAddr, (int) (size / OLD_STYLE_ENTRY_SIZE), log, monitor);
break; break;
case RP_VERSION_V2: case RP_VERSION_V2:
success = relocateV2(pdwListBeginAddr, (int) (size / NEW_STYLE_ENTRY_HEADER_SIZE), success = relocateV2(pdwListBeginAddr, (int) (size / NEW_STYLE_ENTRY_HEADER_SIZE),
@ -369,8 +365,7 @@ class MinGWPseudoRelocationHandler {
return existingEntry; return existingEntry;
} }
Reference ref = Reference ref = program.getReferenceManager().getPrimaryReferenceFrom(iatEntryAddr, 0);
program.getReferenceManager().getPrimaryReferenceFrom(iatEntryAddr, 0);
if (!ref.isExternalReference()) { if (!ref.isExternalReference()) {
return null; return null;
} }
@ -380,8 +375,7 @@ class MinGWPseudoRelocationHandler {
return null; return null;
} }
ExternalLocation extLoc = ExternalLocation extLoc = program.getExternalManager().getExternalLocation(extSym);
program.getExternalManager().getExternalLocation(extSym);
if (extLoc == null) { if (extLoc == null) {
return null; return null;
} }
@ -410,7 +404,7 @@ class MinGWPseudoRelocationHandler {
else { else {
// TODO: Not sure how to preserve relationship to external symbol // TODO: Not sure how to preserve relationship to external symbol
// which refers to Library // which refers to Library
listing.setComment(nextExtAddr, CodeUnit.PLATE_COMMENT, listing.setComment(nextExtAddr, CommentType.PLATE,
"External Location: " + extSym.getName(true)); "External Location: " + extSym.getName(true));
String name = extLoc.getOriginalImportedName(); String name = extLoc.getOriginalImportedName();
boolean demangle = true; boolean demangle = true;
@ -583,12 +577,12 @@ class MinGWPseudoRelocationHandler {
} }
if (addend != 0) { if (addend != 0) {
ElfRelocationHandler.warnExternalOffsetRelocation(program, ElfRelocationHandler.warnExternalOffsetRelocation(program, targetAddr,
targetAddr, pointerValue, symbolName, addend, null); pointerValue, symbolName, addend, null);
if (!memory.getBlock(targetAddr).isExecute()) { if (!memory.getBlock(targetAddr).isExecute()) {
// assume pointer if not in execute block // assume pointer if not in execute block
ElfRelocationHandler.applyComponentOffsetPointer(program, ElfRelocationHandler.applyComponentOffsetPointer(program, targetAddr,
targetAddr, addend); addend);
} }
} }
} }
@ -624,8 +618,7 @@ class MinGWPseudoRelocationHandler {
ClearDataMode.CLEAR_ALL_CONFLICT_DATA); ClearDataMode.CLEAR_ALL_CONFLICT_DATA);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
log.appendMsg( log.appendMsg("Failed to markup Mingw pseudo-relocation List at: " + pdwListBeginAddr);
"Failed to markup Mingw pseudo-relocation List at: " + pdwListBeginAddr);
} }
return true; return true;
} }
@ -640,8 +633,8 @@ class MinGWPseudoRelocationHandler {
relocHeaderStruct.add(DWordDataType.dataType, "version", null); relocHeaderStruct.add(DWordDataType.dataType, "version", null);
try { try {
DataUtilities.createData(program, relocHeaderAddr, relocHeaderStruct, -1, DataUtilities.createData(program, relocHeaderAddr, relocHeaderStruct, -1, false,
false, ClearDataMode.CLEAR_ALL_CONFLICT_DATA); ClearDataMode.CLEAR_ALL_CONFLICT_DATA);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
log.appendMsg( log.appendMsg(

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -31,7 +31,7 @@ import ghidra.util.task.TaskMonitor;
public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer { public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private static final String DESCRIPTION = 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"; private static final String NAME = "Objective-C Message";
@ -87,7 +87,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
return; return;
} }
InstructionIterator instructionIterator = InstructionIterator instructionIterator =
program.getListing().getInstructions(function.getBody(), true); program.getListing().getInstructions(function.getBody(), true);
while (instructionIterator.hasNext()) { while (instructionIterator.hasNext()) {
if (monitor.isCancelled()) { if (monitor.isCancelled()) {
break; break;
@ -96,7 +96,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
Instruction instruction = instructionIterator.next(); Instruction instruction = instructionIterator.next();
if (isCallingObjcMsgSend(instruction)) { if (isCallingObjcMsgSend(instruction)) {
String eolComment = instruction.getComment(CodeUnit.EOL_COMMENT); String eolComment = instruction.getComment(CommentType.EOL);
if (eolComment != null) {//if a comment already exists, ignore... if (eolComment != null) {//if a comment already exists, ignore...
continue; continue;
@ -126,8 +126,8 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private boolean isObjcNameMatch(Symbol symbol) { private boolean isObjcNameMatch(Symbol symbol) {
String name = symbol.getName(); String name = symbol.getName();
return name.startsWith(ObjectiveC1_Constants.OBJC_MSG_SEND) || return name.startsWith(ObjectiveC1_Constants.OBJC_MSG_SEND) ||
name.equals(ObjectiveC1_Constants.READ_UNIX2003) || name.equals(ObjectiveC1_Constants.READ_UNIX2003) ||
name.startsWith("thunk" + ObjectiveC1_Constants.OBJC_MSG_SEND); name.startsWith("thunk" + ObjectiveC1_Constants.OBJC_MSG_SEND);
} }
private class CurrentState { private class CurrentState {
@ -224,7 +224,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
pullNameThrough(state, toAddress, null); pullNameThrough(state, toAddress, null);
if (state.isValid()) { if (state.isValid()) {
instruction.setComment(CodeUnit.EOL_COMMENT, state.toString()); instruction.setComment(CommentType.EOL, state.toString());
setReference(fromAddress, state); setReference(fromAddress, state);
break; break;
} }
@ -310,7 +310,7 @@ public class ObjectiveC1_MessageAnalyzer extends AbstractAnalyzer {
private boolean isClassBlock(MemoryBlock block) { private boolean isClassBlock(MemoryBlock block) {
return block.getName().equals(ObjectiveC1_Constants.OBJC_SECTION_CLASS_REFS) || 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) { private boolean isValidInstruction(Instruction instruction) {

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -44,6 +44,7 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
setPriority(AnalysisPriority.FORMAT_ANALYSIS.after()); setPriority(AnalysisPriority.FORMAT_ANALYSIS.after());
} }
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
throws CancelledException { throws CancelledException {
AddressIterator iterator = set.getAddresses(true); AddressIterator iterator = set.getAddresses(true);
@ -63,6 +64,7 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
return true; return true;
} }
@Override
public boolean canAnalyze(Program program) { public boolean canAnalyze(Program program) {
return ObjectiveC2_Constants.isObjectiveC2(program); return ObjectiveC2_Constants.isObjectiveC2(program);
} }
@ -81,7 +83,7 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
Instruction instruction = instructionIterator.next(); Instruction instruction = instructionIterator.next();
if (isCallingObjcMsgSend(instruction)) { if (isCallingObjcMsgSend(instruction)) {
String eolComment = instruction.getComment(CodeUnit.EOL_COMMENT); String eolComment = instruction.getComment(CommentType.EOL);
if (eolComment != null) {//if a comment already exists, ignore... if (eolComment != null) {//if a comment already exists, ignore...
continue; continue;
@ -194,8 +196,8 @@ public class ObjectiveC2_MessageAnalyzer extends AbstractAnalyzer {
} }
if (currentClass != null && currentMethod != null) { if (currentClass != null && currentMethod != null) {
instruction.setComment(CodeUnit.EOL_COMMENT, "[" + currentClass + " " + instruction.setComment(CommentType.EOL,
currentMethod + "]"); "[" + currentClass + " " + currentMethod + "]");
break; break;
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -185,7 +185,7 @@ public class CreateBookmarkDialog extends DialogComponentProvider {
} }
private String getEolComment(CodeUnit codeUnit) { private String getEolComment(CodeUnit codeUnit) {
String comment = codeUnit.getComment(CodeUnit.EOL_COMMENT); String comment = codeUnit.getComment(CommentType.EOL);
if (comment == null) { if (comment == null) {
return ""; return "";
} }

View file

@ -66,7 +66,7 @@ public class CodeBrowserClipboardProvider extends ByteCopier
implements ClipboardContentProviderService, OptionsChangeListener { implements ClipboardContentProviderService, OptionsChangeListener {
protected static final PaintContext PAINT_CONTEXT = new PaintContext(); 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 = public static final ClipboardType ADDRESS_TEXT_TYPE =
new ClipboardType(DataFlavor.stringFlavor, "Address"); new ClipboardType(DataFlavor.stringFlavor, "Address");
@ -757,7 +757,7 @@ public class CodeBrowserClipboardProvider extends ByteCopier
if (currentLocation instanceof CommentFieldLocation) { if (currentLocation instanceof CommentFieldLocation) {
CommentFieldLocation commentFieldLocation = (CommentFieldLocation) currentLocation; CommentFieldLocation commentFieldLocation = (CommentFieldLocation) currentLocation;
Address address = commentFieldLocation.getAddress(); Address address = commentFieldLocation.getAddress();
int commentType = commentFieldLocation.getCommentType(); CommentType commentType = commentFieldLocation.getCommentType();
SetCommentCmd cmd = new SetCommentCmd(address, commentType, string); SetCommentCmd cmd = new SetCommentCmd(address, commentType, string);
return tool.execute(cmd, currentProgram); return tool.execute(cmd, currentProgram);
} }
@ -802,11 +802,10 @@ public class CodeBrowserClipboardProvider extends ByteCopier
} }
private void setCommentInfo(CodeUnit cu, CodeUnitInfo info) { private void setCommentInfo(CodeUnit cu, CodeUnitInfo info) {
for (CommentType type : CommentType.values()) {
for (int element : COMMENT_TYPES) { String[] comments = cu.getCommentAsArray(type);
String[] comments = cu.getCommentAsArray(element);
if (comments != null && comments.length > 0) { if (comments != null && comments.length > 0) {
info.setComment(element, comments); info.setComment(type, comments);
} }
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -22,6 +22,7 @@ import javax.swing.*;
import docking.DialogComponentProvider; import docking.DialogComponentProvider;
import ghidra.app.util.HelpTopics; import ghidra.app.util.HelpTopics;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.util.HelpLocation; import ghidra.util.HelpLocation;
/** /**
@ -37,7 +38,7 @@ public class CommentHistoryDialog extends DialogComponentProvider {
private CommentHistoryPanel platePanel; private CommentHistoryPanel platePanel;
private CommentHistoryPanel repeatablePanel; private CommentHistoryPanel repeatablePanel;
CommentHistoryDialog(CodeUnit cu, int initialCommentType) { CommentHistoryDialog(CodeUnit cu, CommentType initialCommentType) {
super("Show Comment History"); super("Show Comment History");
setHelpLocation(new HelpLocation(HelpTopics.COMMENTS, "Show_Comment_History")); setHelpLocation(new HelpLocation(HelpTopics.COMMENTS, "Show_Comment_History"));
addWorkPanel(buildMainPanel(cu, initialCommentType)); addWorkPanel(buildMainPanel(cu, initialCommentType));
@ -45,7 +46,7 @@ public class CommentHistoryDialog extends DialogComponentProvider {
setPreferredSize(500, 300); setPreferredSize(500, 300);
} }
private JPanel buildMainPanel(CodeUnit cu, int initialCommentType) { private JPanel buildMainPanel(CodeUnit cu, CommentType initialCommentType) {
JPanel mainPanel = new JPanel(new BorderLayout()); JPanel mainPanel = new JPanel(new BorderLayout());
tabbedPane = new JTabbedPane(); tabbedPane = new JTabbedPane();
mainPanel.add(tabbedPane); 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 // corresponding tab. This will cause a screen reader to read the history for a tab
// when it is selected. // when it is selected.
eolPanel = new CommentHistoryPanel(CodeUnit.EOL_COMMENT, cu); eolPanel = new CommentHistoryPanel(CommentType.EOL, cu);
prePanel = new CommentHistoryPanel(CodeUnit.PRE_COMMENT, cu); prePanel = new CommentHistoryPanel(CommentType.PRE, cu);
postPanel = new CommentHistoryPanel(CodeUnit.POST_COMMENT, cu); postPanel = new CommentHistoryPanel(CommentType.POST, cu);
platePanel = new CommentHistoryPanel(CodeUnit.PLATE_COMMENT, cu); platePanel = new CommentHistoryPanel(CommentType.PLATE, cu);
repeatablePanel = new CommentHistoryPanel(CodeUnit.REPEATABLE_COMMENT, cu); repeatablePanel = new CommentHistoryPanel(CommentType.REPEATABLE, cu);
addTab(" EOL Comment ", eolPanel); addTab(" EOL Comment ", eolPanel);
addTab(" Pre Comment ", prePanel); addTab(" Pre Comment ", prePanel);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -44,9 +44,9 @@ class CommentHistoryPanel extends JPanel {
private StyledDocument doc; private StyledDocument doc;
private JTextPane textPane; private JTextPane textPane;
private int commentType; private CommentType commentType;
CommentHistoryPanel(int commentType, CodeUnit cu) { CommentHistoryPanel(CommentType commentType, CodeUnit cu) {
super(new BorderLayout()); super(new BorderLayout());
setUpAttributes(); setUpAttributes();

View file

@ -15,123 +15,129 @@
*/ */
package ghidra.app.plugin.core.comments; package ghidra.app.plugin.core.comments;
import ghidra.app.context.*; import java.awt.event.KeyEvent;
import ghidra.framework.*;
import ghidra.program.model.listing.*;
import ghidra.program.util.*;
import ghidra.util.*;
import java.awt.event.*; import docking.ActionContext;
import docking.*;
import docking.action.*; 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 { public class CommentsActionFactory {
static { static {
PluggableServiceRegistry.registerPluggableService(CommentsActionFactory.class, new CommentsActionFactory()); PluggableServiceRegistry.registerPluggableService(CommentsActionFactory.class,
} new CommentsActionFactory());
}
public static DockingAction getSetCommentsAction(CommentsDialog dialog, public static DockingAction getSetCommentsAction(CommentsDialog dialog, String name,
String name, String actionName, int commentType) { String actionName, CommentType commentType) {
CommentsActionFactory factory = PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class); CommentsActionFactory factory =
return factory.doGetSetCommentsAction(dialog, name, actionName, commentType); PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
} return factory.doGetSetCommentsAction(dialog, name, actionName, commentType);
}
public static DockingAction getEditCommentsAction(CommentsDialog dialog, public static DockingAction getEditCommentsAction(CommentsDialog dialog, String name) {
String name) { CommentsActionFactory factory =
CommentsActionFactory factory = PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class); PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doGetEditCommentsAction(dialog, name); return factory.doGetEditCommentsAction(dialog, name);
} }
public static boolean isCommentSupported(ProgramLocation loc) { public static boolean isCommentSupported(ProgramLocation loc) {
CommentsActionFactory factory = PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class); CommentsActionFactory factory =
return factory.doIsCommentSupported(loc); PluggableServiceRegistry.getPluggableService(CommentsActionFactory.class);
return factory.doIsCommentSupported(loc);
} }
protected DockingAction doGetSetCommentsAction(CommentsDialog dialog, protected DockingAction doGetSetCommentsAction(CommentsDialog dialog, String name,
String name, String actionName, int commentType) { String actionName, CommentType commentType) {
return new SetCommentsAction(dialog, name, actionName, commentType); return new SetCommentsAction(dialog, name, actionName, commentType);
} }
protected DockingAction doGetEditCommentsAction(CommentsDialog dialog, protected DockingAction doGetEditCommentsAction(CommentsDialog dialog, String name) {
String name) { return new EditCommentsAction(dialog, name);
return new EditCommentsAction(dialog, name); }
}
protected boolean doIsCommentSupported(ProgramLocation loc) { protected boolean doIsCommentSupported(ProgramLocation loc) {
if (loc == null || loc.getAddress() == null) { if (loc == null || loc.getAddress() == null) {
return false; return false;
} }
return ((loc instanceof CodeUnitLocation) || ((loc instanceof FunctionLocation) && !(loc instanceof VariableLocation))); return ((loc instanceof CodeUnitLocation) ||
} ((loc instanceof FunctionLocation) && !(loc instanceof VariableLocation)));
}
private static class SetCommentsAction extends DockingAction { private static class SetCommentsAction extends DockingAction {
private final CommentsDialog dialog; private final CommentsDialog dialog;
private final int commentType; private final CommentType commentType; // may be null for Generic Comment
SetCommentsAction(CommentsDialog dialog, String name, SetCommentsAction(CommentsDialog dialog, String name, String actionName,
String actionName, int commentType) { CommentType commentType) {
super(actionName, name); super(actionName, name);
this.dialog = dialog; this.dialog = dialog;
this.commentType = commentType; this.commentType = commentType;
setPopupMenuData(new MenuData(new String[] { "Comments", setPopupMenuData(
actionName + "..." }, "comments")); new MenuData(new String[] { "Comments", actionName + "..." }, "comments"));
setHelpLocation(new HelpLocation("CommentsPlugin", "Edit_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 @Override
public void actionPerformed(ActionContext context) { public void actionPerformed(ActionContext context) {
CodeUnit cu = getCodeUnit(context); CodeUnit cu = getCodeUnit(context);
int type = getEditCommentType(context); CommentType type = getEditCommentType(context);
dialog.showDialog(cu, type); dialog.showDialog(cu, type);
} }
@Override @Override
public boolean isEnabledForContext(ActionContext actionContext) { public boolean isEnabledForContext(ActionContext actionContext) {
ProgramLocation loc = getLocationForContext(actionContext); ProgramLocation loc = getLocationForContext(actionContext);
if (!isCommentSupported(loc)) { if (!isCommentSupported(loc)) {
return false; return false;
} }
return CommentTypeUtils.isCommentAllowed(getCodeUnit(actionContext), loc); return CommentTypeUtils.isCommentAllowed(getCodeUnit(actionContext), loc);
} }
@Override @Override
public boolean isValidContext(ActionContext context) { public boolean isValidContext(ActionContext context) {
return (context instanceof ListingActionContext); return (context instanceof ListingActionContext);
} }
protected CodeUnit getCodeUnit(ActionContext actionContext) { protected CodeUnit getCodeUnit(ActionContext actionContext) {
ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext; ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext;
return context.getCodeUnit(); return context.getCodeUnit();
} }
protected ProgramLocation getLocationForContext( protected ProgramLocation getLocationForContext(ActionContext actionContext) {
ActionContext actionContext) { ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext;
ProgramLocationActionContext context = (ProgramLocationActionContext) actionContext; return context.getLocation();
return context.getLocation(); }
} }
}
private static class EditCommentsAction extends SetCommentsAction { private static class EditCommentsAction extends SetCommentsAction {
// Edit Comments Action info // Edit Comments Action info
private final static String[] EDIT_MENUPATH = new String[] { private final static String[] EDIT_MENUPATH = new String[] { "Comments", "Set..." };
"Comments", "Set..." };
EditCommentsAction(CommentsDialog dialog, String name) { EditCommentsAction(CommentsDialog dialog, String name) {
super(dialog, name, "Edit Comments", CodeUnit.NO_COMMENT); super(dialog, name, "Edit Comments", null);
setPopupMenuData(new MenuData(EDIT_MENUPATH, "comments")); setPopupMenuData(new MenuData(EDIT_MENUPATH, "comments"));
setKeyBindingData(new KeyBindingData(KeyEvent.VK_SEMICOLON, 0)); setKeyBindingData(new KeyBindingData(KeyEvent.VK_SEMICOLON, 0));
} }
@Override @Override
protected int getEditCommentType(ActionContext context) { protected CommentType getEditCommentType(ActionContext context) {
CodeUnit cu = getCodeUnit(context); CodeUnit cu = getCodeUnit(context);
return CommentTypeUtils.getCommentType(cu, getLocationForContext(context), CodeUnit.NO_COMMENT); return CommentTypeUtils.getCommentType(cu, getLocationForContext(context), null);
} }
} }
} }

View file

@ -35,7 +35,9 @@ import ghidra.app.util.viewer.field.AnnotatedStringHandler;
import ghidra.app.util.viewer.field.CommentUtils; import ghidra.app.util.viewer.field.CommentUtils;
import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.CommentType;
import ghidra.util.HelpLocation; import ghidra.util.HelpLocation;
import ghidra.util.exception.AssertException;
/** /**
* Dialog for setting the comments for a CodeUnit. * Dialog for setting the comments for a CodeUnit.
@ -89,15 +91,15 @@ public class CommentsDialog extends ReusableDialogComponentProvider implements K
* @param cu code unit * @param cu code unit
* @param type comment type * @param type comment type
*/ */
void showDialog(CodeUnit cu, int type) { void showDialog(CodeUnit cu, CommentType type) {
setTitle("Set Comment(s) at Address " + cu.getMinAddress()); setTitle("Set Comment(s) at Address " + cu.getMinAddress());
codeUnit = cu; codeUnit = cu;
preComment = cu.getComment(CodeUnit.PRE_COMMENT); preComment = cu.getComment(CommentType.PRE);
postComment = cu.getComment(CodeUnit.POST_COMMENT); postComment = cu.getComment(CommentType.POST);
eolComment = cu.getComment(CodeUnit.EOL_COMMENT); eolComment = cu.getComment(CommentType.EOL);
plateComment = cu.getComment(CodeUnit.PLATE_COMMENT); plateComment = cu.getComment(CommentType.PLATE);
repeatableComment = cu.getComment(CodeUnit.REPEATABLE_COMMENT); repeatableComment = cu.getComment(CommentType.REPEATABLE);
preComment = (preComment == null) ? "" : preComment; preComment = (preComment == null) ? "" : preComment;
postComment = (postComment == null) ? "" : postComment; postComment = (postComment == null) ? "" : postComment;
@ -133,23 +135,29 @@ public class CommentsDialog extends ReusableDialogComponentProvider implements K
tool.showDialog(this); tool.showDialog(this);
} }
void setCommentType(int type) { void setCommentType(CommentType type) {
if (type == null) {
tab.setSelectedIndex(0);
return;
}
switch (type) { switch (type) {
case CodeUnit.EOL_COMMENT: case CommentType.EOL:
tab.setSelectedIndex(0); tab.setSelectedIndex(0);
break; break;
case CodeUnit.PRE_COMMENT: case CommentType.PRE:
tab.setSelectedIndex(1); tab.setSelectedIndex(1);
break; break;
case CodeUnit.POST_COMMENT: case CommentType.POST:
tab.setSelectedIndex(2); tab.setSelectedIndex(2);
break; break;
case CodeUnit.PLATE_COMMENT: case CommentType.PLATE:
tab.setSelectedIndex(3); tab.setSelectedIndex(3);
break; break;
case CodeUnit.REPEATABLE_COMMENT: case CommentType.REPEATABLE:
tab.setSelectedIndex(4); tab.setSelectedIndex(4);
break; break;
default:
throw new AssertException("Unsupported comment type: " + type.name());
} }
} }

View file

@ -27,8 +27,7 @@ import ghidra.app.plugin.PluginCategoryNames;
import ghidra.framework.options.*; import ghidra.framework.options.*;
import ghidra.framework.plugintool.*; import ghidra.framework.plugintool.*;
import ghidra.framework.plugintool.util.PluginStatus; import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Program;
import ghidra.program.util.*; import ghidra.program.util.*;
import ghidra.util.HelpLocation; 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 * @param loc the {@link ProgramLocation} for which to delete the comment
*/ */
void deleteComments(Program program, ProgramLocation loc) { 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); SetCommentCmd cmd = new SetCommentCmd(loc.getByteAddress(), commentType, null);
tool.execute(cmd, program); tool.execute(cmd, program);
} }
@ -138,8 +137,8 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
if (codeUnit == null) { if (codeUnit == null) {
return false; return false;
} }
int commentType = CommentTypeUtils.getCommentType(null, loc, CodeUnit.NO_COMMENT); CommentType commentType = CommentTypeUtils.getCommentType(null, loc, null);
return (commentType != CodeUnit.NO_COMMENT && codeUnit.getComment(commentType) != null); return (commentType != null && codeUnit.getComment(commentType) != null);
} }
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
@ -151,23 +150,23 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
editAction = CommentsActionFactory.getEditCommentsAction(dialog, name); editAction = CommentsActionFactory.getEditCommentsAction(dialog, name);
tool.addAction(editAction); tool.addAction(editAction);
preCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name, preCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Pre Comment", CodeUnit.PRE_COMMENT); "Set Pre Comment", CommentType.PRE);
tool.addAction(preCommentEditAction); tool.addAction(preCommentEditAction);
postCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name, postCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Post Comment", CodeUnit.POST_COMMENT); "Set Post Comment", CommentType.POST);
tool.addAction(postCommentEditAction); tool.addAction(postCommentEditAction);
plateCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name, plateCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Plate Comment", CodeUnit.PLATE_COMMENT); "Set Plate Comment", CommentType.PLATE);
tool.addAction(plateCommentEditAction); tool.addAction(plateCommentEditAction);
eolCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name, eolCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set EOL Comment", CodeUnit.EOL_COMMENT); "Set EOL Comment", CommentType.EOL);
tool.addAction(eolCommentEditAction); tool.addAction(eolCommentEditAction);
repeatableCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name, repeatableCommentEditAction = CommentsActionFactory.getSetCommentsAction(dialog, name,
"Set Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); "Set Repeatable Comment", CommentType.REPEATABLE);
tool.addAction(repeatableCommentEditAction); tool.addAction(repeatableCommentEditAction);
deleteAction = new ListingContextAction("Delete Comments", pluginName) { deleteAction = new ListingContextAction("Delete Comments", pluginName) {
@ -215,7 +214,8 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
else { else {
historyAction.getPopupMenuData().setMenuPath(HISTORY_MENUPATH); historyAction.getPopupMenuData().setMenuPath(HISTORY_MENUPATH);
} }
historyAction.setEnabled(CommentTypeUtils.isCommentAllowed(context.getCodeUnit(), loc)); historyAction
.setEnabled(CommentTypeUtils.isCommentAllowed(context.getCodeUnit(), loc));
return true; return true;
} }
}; };
@ -227,7 +227,7 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
private void showCommentHistory(ListingActionContext context) { private void showCommentHistory(ListingActionContext context) {
CodeUnit cu = context.getCodeUnit(); CodeUnit cu = context.getCodeUnit();
ProgramLocation loc = context.getLocation(); 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); CommentHistoryDialog historyDialog = new CommentHistoryDialog(cu, commentType);
tool.showDialog(historyDialog, context.getComponentProvider()); tool.showDialog(historyDialog, context.getComponentProvider());
} }
@ -254,31 +254,34 @@ public class CommentsPlugin extends Plugin implements OptionsChangeListener {
} }
CommentFieldLocation cfLoc = (CommentFieldLocation) loc; CommentFieldLocation cfLoc = (CommentFieldLocation) loc;
int type = cfLoc.getCommentType(); CommentType type = cfLoc.getCommentType();
switch (type) { switch (type) {
case CodeUnit.PRE_COMMENT: case PRE:
action.getPopupMenuData() action.getPopupMenuData()
.setMenuPath( .setMenuPath(
new String[] { "Comments", actionString + " Pre-Comment" + endString }); new String[] { "Comments", actionString + " Pre-Comment" + endString });
break; break;
case CodeUnit.POST_COMMENT: case POST:
action.getPopupMenuData() action.getPopupMenuData()
.setMenuPath(new String[] { "Comments", .setMenuPath(new String[] { "Comments",
actionString + " Post-Comment" + endString }); actionString + " Post-Comment" + endString });
break; break;
case CodeUnit.EOL_COMMENT: case EOL:
action.getPopupMenuData() action.getPopupMenuData()
.setMenuPath( .setMenuPath(
new String[] { "Comments", actionString + " EOL Comment" + endString }); new String[] { "Comments", actionString + " EOL Comment" + endString });
break; break;
case CodeUnit.REPEATABLE_COMMENT: case REPEATABLE:
action.getPopupMenuData() action.getPopupMenuData()
.setMenuPath(new String[] { "Comments", .setMenuPath(new String[] { "Comments",
actionString + " Repeatable Comment" + endString }); actionString + " Repeatable Comment" + endString });
break; break;
default:
break;
} }
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -16,13 +16,14 @@
package ghidra.app.plugin.core.commentwindow; package ghidra.app.plugin.core.commentwindow;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType;
class CommentRowObject implements Comparable<CommentRowObject> { class CommentRowObject implements Comparable<CommentRowObject> {
private final Address address; 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.address = address;
this.commentType = commentType; this.commentType = commentType;
} }
@ -31,7 +32,7 @@ class CommentRowObject implements Comparable<CommentRowObject> {
return address; return address;
} }
int getCommentType() { CommentType getCommentType() {
return commentType; return commentType;
} }
@ -40,7 +41,7 @@ class CommentRowObject implements Comparable<CommentRowObject> {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + commentType; result = prime * result + commentType.hashCode();
return result; return result;
} }
@ -75,7 +76,7 @@ class CommentRowObject implements Comparable<CommentRowObject> {
int result = address.compareTo(o.address); int result = address.compareTo(o.address);
if (result == 0) { if (result == 0) {
result = commentType - o.commentType; result = commentType.compareTo(o.commentType);
} }
return result; return result;
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -94,26 +94,26 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
continue; continue;
} }
if (cu.getComment(CodeUnit.PRE_COMMENT) != null) { if (cu.getComment(CommentType.PRE) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.PRE_COMMENT)); accumulator.add(new CommentRowObject(commentAddr, CommentType.PRE));
} }
if (cu.getComment(CodeUnit.POST_COMMENT) != null) { if (cu.getComment(CommentType.POST) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.POST_COMMENT)); accumulator.add(new CommentRowObject(commentAddr, CommentType.POST));
} }
if (cu.getComment(CodeUnit.EOL_COMMENT) != null) { if (cu.getComment(CommentType.EOL) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.EOL_COMMENT)); accumulator.add(new CommentRowObject(commentAddr, CommentType.EOL));
} }
if (cu.getComment(CodeUnit.PLATE_COMMENT) != null) { if (cu.getComment(CommentType.PLATE) != null) {
accumulator.add(new CommentRowObject(commentAddr, CodeUnit.PLATE_COMMENT)); accumulator.add(new CommentRowObject(commentAddr, CommentType.PLATE));
} }
if (cu.getComment(CodeUnit.REPEATABLE_COMMENT) != null) { 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); String comment = listing.getComment(commentType, addr);
if (comment == null) { if (comment == null) {
@ -125,7 +125,7 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
} }
void commentRemoved(Address addr, int commentType) { void commentRemoved(Address addr, CommentType commentType) {
removeObject(new CommentRowObject(addr, commentType)); removeObject(new CommentRowObject(addr, commentType));
} }
@ -161,23 +161,23 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
} }
@Override @Override
public String getValue(CommentRowObject rowObject, Settings settings, Program program, public String getValue(CommentRowObject rowObject, Settings settings, Program p,
ServiceProvider provider) throws IllegalArgumentException { ServiceProvider provider) throws IllegalArgumentException {
String returnString = ""; String returnString = "";
if (rowObject.getCommentType() == CodeUnit.EOL_COMMENT) { if (rowObject.getCommentType() == CommentType.EOL) {
return "EOL Comment"; return "EOL Comment";
} }
if (rowObject.getCommentType() == CodeUnit.PLATE_COMMENT) { if (rowObject.getCommentType() == CommentType.PLATE) {
return "Plate Comment"; return "Plate Comment";
} }
if (rowObject.getCommentType() == CodeUnit.PRE_COMMENT) { if (rowObject.getCommentType() == CommentType.PRE) {
return "Pre Comment"; return "Pre Comment";
} }
if (rowObject.getCommentType() == CodeUnit.POST_COMMENT) { if (rowObject.getCommentType() == CommentType.POST) {
return "Post Comment"; return "Post Comment";
} }
if (rowObject.getCommentType() == CodeUnit.REPEATABLE_COMMENT) { if (rowObject.getCommentType() == CommentType.REPEATABLE) {
return "Repeatable Comment"; return "Repeatable Comment";
} }
return returnString; return returnString;
@ -198,7 +198,7 @@ class CommentTableModel extends AddressBasedTableModel<CommentRowObject> {
} }
@Override @Override
public String getValue(CommentRowObject rowObject, Settings settings, Program program, public String getValue(CommentRowObject rowObject, Settings settings, Program p,
ServiceProvider provider) throws IllegalArgumentException { ServiceProvider provider) throws IllegalArgumentException {
String comment = getCommentForRowObject(rowObject); String comment = getCommentForRowObject(rowObject);
return comment; return comment;

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.PluginTool;
import ghidra.framework.plugintool.util.PluginStatus; import ghidra.framework.plugintool.util.PluginStatus;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.util.CommentChangeRecord; import ghidra.program.util.CommentChangeRecord;
import ghidra.program.util.ProgramSelection; import ghidra.program.util.ProgramSelection;
@ -94,7 +95,7 @@ public class CommentWindowPlugin extends ProgramPlugin {
} }
private void handleCommentChanged(CommentChangeRecord ccr) { private void handleCommentChanged(CommentChangeRecord ccr) {
int commentType = ccr.getCommentType(); CommentType commentType = ccr.getCommentType();
String oldComment = ccr.getOldComment(); String oldComment = ccr.getOldComment();
String newComment = ccr.getNewComment(); String newComment = ccr.getNewComment();
Address commentAddress = ccr.getStart(); Address commentAddress = ccr.getStart();

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -25,6 +25,7 @@ import javax.swing.table.JTableHeader;
import docking.ActionContext; import docking.ActionContext;
import ghidra.framework.plugintool.ComponentProviderAdapter; import ghidra.framework.plugintool.ComponentProviderAdapter;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.util.HelpLocation; import ghidra.util.HelpLocation;
import ghidra.util.table.*; 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()) { if (isVisible()) {
commentModel.commentAdded(address, commentType); commentModel.commentAdded(address, commentType);
} }
} }
void commentRemoved(Address address, int commentType) { void commentRemoved(Address address, CommentType commentType) {
if (isVisible()) { if (isVisible()) {
commentModel.commentRemoved(address, commentType); commentModel.commentRemoved(address, commentType);
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -97,7 +97,6 @@ public class AddressTable {
this.skipAmount = skipAmount; this.skipAmount = skipAmount;
this.shiftedAddr = shiftedAddr; this.shiftedAddr = shiftedAddr;
} }
/** /**
* Create a new address table from any remaining table entries starting at startPos * Create a new address table from any remaining table entries starting at startPos
@ -388,8 +387,7 @@ public class AddressTable {
Address lastAddress = null; Address lastAddress = null;
DataType ptrDT = program.getDataTypeManager() DataType ptrDT = program.getDataTypeManager()
.addDataType( .addDataType(PointerDataType.getPointer(null, addrSize), null);
PointerDataType.getPointer(null, addrSize), null);
for (int i = 0; i < tableSize; i++) { for (int i = 0; i < tableSize; i++) {
Address loc = tableAddr.add(i * addrSize); Address loc = tableAddr.add(i * addrSize);
try { try {
@ -472,8 +470,8 @@ public class AddressTable {
if (!flagNewCode || !newCodeFound) { if (!flagNewCode || !newCodeFound) {
// create a case label // create a case label
if (!ftype.isCall()) { if (!ftype.isCall()) {
AddLabelCmd lcmd = new AddLabelCmd(target, AddLabelCmd lcmd = new AddLabelCmd(target, caseName + Integer.toHexString(i),
caseName + Integer.toHexString(i), true, SourceType.ANALYSIS); true, SourceType.ANALYSIS);
switchLabelList.add(lcmd); switchLabelList.add(lcmd);
} }
@ -496,7 +494,7 @@ public class AddressTable {
} }
if (comment != null) { if (comment != null) {
program.getListing().setComment(topAddress, CodeUnit.EOL_COMMENT, comment); program.getListing().setComment(topAddress, CommentType.EOL, comment);
} }
if (flagNewCode && newCodeFound) { if (flagNewCode && newCodeFound) {
@ -574,8 +572,9 @@ public class AddressTable {
// not putting switch into functions anymore // not putting switch into functions anymore
// program.getSymbolTable().getNamespace(start_inst.getMinAddress()); // program.getSymbolTable().getNamespace(start_inst.getMinAddress());
try { try {
space = program.getSymbolTable().createNameSpace(null, space = program.getSymbolTable()
"switch_" + start_inst.getMinAddress(), SourceType.ANALYSIS); .createNameSpace(null, "switch_" + start_inst.getMinAddress(),
SourceType.ANALYSIS);
} }
catch (DuplicateNameException e) { catch (DuplicateNameException e) {
// just go with default space // just go with default space
@ -607,8 +606,8 @@ public class AddressTable {
} }
// make sure the reference is associated with this symbol // make sure the reference is associated with this symbol
Symbol s = program.getSymbolTable().getGlobalSymbol(tableNameLabel.getLabelName(), Symbol s = program.getSymbolTable()
tableNameLabel.getLabelAddr()); .getGlobalSymbol(tableNameLabel.getLabelName(), tableNameLabel.getLabelAddr());
for (int op = 0; op < start_inst.getNumOperands(); op++) { for (int op = 0; op < start_inst.getNumOperands(); op++) {
Reference fromRefs[] = start_inst.getOperandReferences(op); Reference fromRefs[] = start_inst.getOperandReferences(op);
for (Reference fromRef : fromRefs) { for (Reference fromRef : fromRefs) {
@ -1233,12 +1232,12 @@ public class AddressTable {
continue; continue;
} }
} }
// undefined data is OK, could be a pointer // undefined data is OK, could be a pointer
if (data.getDataType() instanceof Undefined) { if (data.getDataType() instanceof Undefined) {
continue; continue;
} }
// data intersects, calculate valid entries and stop looking // data intersects, calculate valid entries and stop looking
if (pointerSet.intersects(dataAddr, data.getMaxAddress())) { if (pointerSet.intersects(dataAddr, data.getMaxAddress())) {
count = (int) (dataAddr.subtract(topAddr) / (addrSize + skipAmount)); count = (int) (dataAddr.subtract(topAddr) / (addrSize + skipAmount));

View file

@ -28,11 +28,11 @@ import ghidra.util.StringUtilities;
public class CommentFieldSearcher extends ProgramDatabaseFieldSearcher { public class CommentFieldSearcher extends ProgramDatabaseFieldSearcher {
private AddressIterator iterator; private AddressIterator iterator;
private final int commentType; private final CommentType commentType;
private Program program; private Program program;
public CommentFieldSearcher(Program program, ProgramLocation startLoc, AddressSetView set, 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); super(pattern, forward, startLoc, set);
this.commentType = commentType; this.commentType = commentType;
@ -89,16 +89,16 @@ public class CommentFieldSearcher extends ProgramDatabaseFieldSearcher {
int charOffset = getRelativeCharOffset(index, rowIndex, comments); int charOffset = getRelativeCharOffset(index, rowIndex, comments);
int[] dataPath = getDataComponentPath(address); int[] dataPath = getDataComponentPath(address);
switch (commentType) { switch (commentType) {
case CodeUnit.EOL_COMMENT: case EOL:
return new EolCommentFieldLocation(program, address, dataPath, comments, rowIndex, return new EolCommentFieldLocation(program, address, dataPath, comments, rowIndex,
charOffset, rowIndex); charOffset, rowIndex);
case CodeUnit.PLATE_COMMENT: case PLATE:
return new PlateFieldLocation(program, address, dataPath, rowIndex, charOffset, return new PlateFieldLocation(program, address, dataPath, rowIndex, charOffset,
comments, rowIndex); comments, rowIndex);
case CodeUnit.REPEATABLE_COMMENT: case REPEATABLE:
return new RepeatableCommentFieldLocation(program, address, dataPath, comments, return new RepeatableCommentFieldLocation(program, address, dataPath, comments,
rowIndex, charOffset, rowIndex); // TODO One of searchStrIndex parameters is wrong. rowIndex, charOffset, rowIndex); // TODO One of searchStrIndex parameters is wrong.
case CodeUnit.POST_COMMENT: case POST:
return new PostCommentFieldLocation(program, address, dataPath, comments, rowIndex, return new PostCommentFieldLocation(program, address, dataPath, comments, rowIndex,
charOffset); charOffset);
default: default:

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.app.util.viewer.field.BrowserCodeUnitFormat;
import ghidra.framework.plugintool.ServiceProvider; import ghidra.framework.plugintool.ServiceProvider;
import ghidra.program.model.address.*; 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.model.listing.Program;
import ghidra.program.util.ProgramLocation; import ghidra.program.util.ProgramLocation;
import ghidra.util.UserSearchUtils; import ghidra.util.UserSearchUtils;
@ -181,7 +181,7 @@ public class ProgramDatabaseSearcher implements Searcher {
if (options.searchComments()) { if (options.searchComments()) {
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward, searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.PLATE_COMMENT)); pattern, CommentType.PLATE));
} }
if (options.searchFunctions()) { if (options.searchFunctions()) {
searchers.add( searchers.add(
@ -189,7 +189,7 @@ public class ProgramDatabaseSearcher implements Searcher {
} }
if (options.searchComments()) { if (options.searchComments()) {
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward, searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.PRE_COMMENT)); pattern, CommentType.PRE));
} }
if (options.searchLabels()) { if (options.searchLabels()) {
searchers.add( searchers.add(
@ -209,10 +209,9 @@ public class ProgramDatabaseSearcher implements Searcher {
program, adjustedStart, trimmedSet, forward, pattern, format)); program, adjustedStart, trimmedSet, forward, pattern, format));
} }
if (options.searchBothInstructionMnemonicAndOperands()) { if (options.searchBothInstructionMnemonicAndOperands()) {
searchers.add( searchers.add(InstructionMnemonicOperandFieldSearcher
InstructionMnemonicOperandFieldSearcher .createInstructionMnemonicAndOperandFieldSearcher(program, adjustedStart,
.createInstructionMnemonicAndOperandFieldSearcher( trimmedSet, forward, pattern, format));
program, adjustedStart, trimmedSet, forward, pattern, format));
} }
if (options.searchOnlyInstructionMnemonics()) { if (options.searchOnlyInstructionMnemonics()) {
searchers.add( searchers.add(
@ -226,11 +225,11 @@ public class ProgramDatabaseSearcher implements Searcher {
} }
if (options.searchComments()) { if (options.searchComments()) {
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward, searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.EOL_COMMENT)); pattern, CommentType.EOL));
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward, searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.REPEATABLE_COMMENT)); pattern, CommentType.REPEATABLE));
searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward, searchers.add(new CommentFieldSearcher(program, adjustedStart, trimmedSet, forward,
pattern, CodeUnit.POST_COMMENT)); pattern, CommentType.POST));
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -19,7 +19,7 @@ import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.cmd.data.CreateDataCmd; import ghidra.app.cmd.data.CreateDataCmd;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.data.*; import ghidra.program.model.data.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.util.CodeUnitInsertionException; import ghidra.program.model.util.CodeUnitInsertionException;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
@ -100,12 +100,10 @@ public abstract class GccAnalysisClass {
* @param addr the address where data is created * @param addr the address where data is created
* @param dt the type for the data * @param dt the type for the data
* @param comment the comment about the data * @param comment the comment about the data
* @param commentType the type of comment ({@link CodeUnit#PLATE_COMMENT}, * @param commentType the type of comment
* {@link CodeUnit#PRE_COMMENT}, {@link CodeUnit#EOL_COMMENT}, {@link CodeUnit#POST_COMMENT},
* {@link CodeUnit#REPEATABLE_COMMENT})
*/ */
protected static void createAndCommentData(Program program, Address addr, DataType dt, protected static void createAndCommentData(Program program, Address addr, DataType dt,
String comment, int commentType) { String comment, CommentType commentType) {
createData(program, addr, dt); createData(program, addr, dt);
SetCommentCmd.createComment(program, addr, comment, commentType); SetCommentCmd.createComment(program, addr, comment, commentType);
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -46,14 +46,12 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
public static final String DESCRIPTION = public static final String DESCRIPTION =
"Locates and annotates exception-handling infrastructure installed by the GCC compiler"; "Locates and annotates exception-handling infrastructure installed by the GCC compiler";
protected static final String OPTION_NAME_CREATE_TRY_CATCH_COMMENTS = protected static final String OPTION_NAME_CREATE_TRY_CATCHS = "Create Try Catch Comments";
"Create Try Catch Comments"; private static final String OPTION_DESCRIPTION_CREATE_TRY_CATCHS =
private static final String OPTION_DESCRIPTION_CREATE_TRY_CATCH_COMMENTS =
"Selecting this check box causes the analyzer to create comments in the " + "Selecting this check box causes the analyzer to create comments in the " +
"disassembly listing for the try and catch code."; "disassembly listing for the try and catch code.";
private static final boolean OPTION_DEFAULT_CREATE_TRY_CATCH_COMMENTS_ENABLED = true; private static final boolean OPTION_DEFAULT_CREATE_TRY_CATCHS_ENABLED = true;
private boolean createTryCatchCommentsEnabled = private boolean createTryCatchCommentsEnabled = OPTION_DEFAULT_CREATE_TRY_CATCHS_ENABLED;
OPTION_DEFAULT_CREATE_TRY_CATCH_COMMENTS_ENABLED;
private Set<Program> visitedPrograms = new HashSet<>(); private Set<Program> visitedPrograms = new HashSet<>();
private AutoAnalysisManagerListener analysisListener = private AutoAnalysisManagerListener analysisListener =
@ -288,11 +286,11 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
Address csMaxAddr = callSite.getMaxAddress(); Address csMaxAddr = callSite.getMaxAddress();
String startTryComment = "try { // try from " + csMinAddr + " to " + csMaxAddr + String startTryComment = "try { // try from " + csMinAddr + " to " + csMaxAddr +
" has its CatchHandler @ " + lpAddr; " has its CatchHandler @ " + lpAddr;
String existingComment = program.getListing().getComment(CodeUnit.PRE_COMMENT, csMinAddr); String existingComment = program.getListing().getComment(CommentType.PRE, csMinAddr);
if (existingComment == null || !existingComment.contains(startTryComment)) { if (existingComment == null || !existingComment.contains(startTryComment)) {
String mergedComment = StringUtilities.mergeStrings(existingComment, startTryComment); String mergedComment = StringUtilities.mergeStrings(existingComment, startTryComment);
SetCommentCmd setCommentCmd = SetCommentCmd setCommentCmd =
new SetCommentCmd(csMinAddr, CodeUnit.PRE_COMMENT, mergedComment); new SetCommentCmd(csMinAddr, CommentType.PRE, mergedComment);
setCommentCmd.applyTo(program); setCommentCmd.applyTo(program);
} }
} }
@ -304,12 +302,11 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
if (csMaxCodeUnit != null) { if (csMaxCodeUnit != null) {
Address commentAddr = csMaxCodeUnit.getMinAddress(); Address commentAddr = csMaxCodeUnit.getMinAddress();
String endTryComment = "} // end try from " + csMinAddr + " to " + csMaxAddr; String endTryComment = "} // end try from " + csMinAddr + " to " + csMaxAddr;
String existingComment = String existingComment = program.getListing().getComment(CommentType.POST, commentAddr);
program.getListing().getComment(CodeUnit.POST_COMMENT, commentAddr);
if (existingComment == null || !existingComment.contains(endTryComment)) { if (existingComment == null || !existingComment.contains(endTryComment)) {
String mergedComment = StringUtilities.mergeStrings(existingComment, endTryComment); String mergedComment = StringUtilities.mergeStrings(existingComment, endTryComment);
SetCommentCmd setCommentCmd = SetCommentCmd setCommentCmd =
new SetCommentCmd(commentAddr, CodeUnit.POST_COMMENT, mergedComment); new SetCommentCmd(commentAddr, CommentType.POST, mergedComment);
setCommentCmd.applyTo(program); setCommentCmd.applyTo(program);
} }
} }
@ -322,11 +319,10 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
typeInfos.stream().map(a -> getCatchParamInfo(a)).collect(Collectors.joining(", ")); typeInfos.stream().map(a -> getCatchParamInfo(a)).collect(Collectors.joining(", "));
String startCatchComment = String startCatchComment =
"catch(" + typeString + ") { ... } // from try @ " + csAddr + " with catch @ " + lpAddr; "catch(" + typeString + ") { ... } // from try @ " + csAddr + " with catch @ " + lpAddr;
String existingComment = program.getListing().getComment(CodeUnit.PRE_COMMENT, lpAddr); String existingComment = program.getListing().getComment(CommentType.PRE, lpAddr);
if (existingComment == null || !existingComment.contains(startCatchComment)) { if (existingComment == null || !existingComment.contains(startCatchComment)) {
String mergedComment = StringUtilities.mergeStrings(existingComment, startCatchComment); String mergedComment = StringUtilities.mergeStrings(existingComment, startCatchComment);
SetCommentCmd setCommentCmd = SetCommentCmd setCommentCmd = new SetCommentCmd(lpAddr, CommentType.PRE, mergedComment);
new SetCommentCmd(lpAddr, CodeUnit.PRE_COMMENT, mergedComment);
setCommentCmd.applyTo(program); setCommentCmd.applyTo(program);
} }
} }
@ -346,12 +342,12 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
// // TODO If we can determine the length of the catch handler we could mark its end too. // // TODO If we can determine the length of the catch handler we could mark its end too.
// Address lpMaxAddr = ?; // Address lpMaxAddr = ?;
// String endCatchComment = "} // end catchHandler()"; // String endCatchComment = "} // end catchHandler()";
// String existingComment = program.getListing().getComment(CodeUnit.POST_COMMENT, lpMaxAddr); // String existingComment = program.getListing().getComment(CommentType.POST, lpMaxAddr);
// if (existingComment == null || !existingComment.contains(endCatchComment)) { // if (existingComment == null || !existingComment.contains(endCatchComment)) {
// String mergedComment = // String mergedComment =
// StringUtilities.mergeStrings(existingComment, endCatchComment); // StringUtilities.mergeStrings(existingComment, endCatchComment);
// SetCommentCmd setCommentCmd = // SetCommentCmd setCommentCmd =
// new SetCommentCmd(lpMaxAddr, CodeUnit.POST_COMMENT, endCatchComment); // new SetCommentCmd(lpMaxAddr, CommentType.POST, endCatchComment);
// setCommentCmd.applyTo(program); // setCommentCmd.applyTo(program);
// } // }
} }
@ -429,14 +425,14 @@ public class GccExceptionAnalyzer extends AbstractAnalyzer {
@Override @Override
public void registerOptions(Options options, Program program) { public void registerOptions(Options options, Program program) {
options.registerOption(OPTION_NAME_CREATE_TRY_CATCH_COMMENTS, createTryCatchCommentsEnabled, options.registerOption(OPTION_NAME_CREATE_TRY_CATCHS, createTryCatchCommentsEnabled, null,
null, OPTION_DESCRIPTION_CREATE_TRY_CATCH_COMMENTS); OPTION_DESCRIPTION_CREATE_TRY_CATCHS);
} }
@Override @Override
public void optionsChanged(Options options, Program program) { 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);
} }
} }

View file

@ -5,9 +5,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -24,7 +24,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.RegionDescriptor;
import ghidra.app.plugin.exceptionhandlers.gcc.structures.ehFrame.*; import ghidra.app.plugin.exceptionhandlers.gcc.structures.ehFrame.*;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.data.ByteDataType; import ghidra.program.model.data.ByteDataType;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.mem.MemoryBlock; import ghidra.program.model.mem.MemoryBlock;
@ -176,8 +176,7 @@ abstract class AbstractFrameSection implements CieSource {
private void createPlateComment(Address curAddress, String fdeComment) { private void createPlateComment(Address curAddress, String fdeComment) {
SetCommentCmd commentCmd = SetCommentCmd commentCmd = new SetCommentCmd(curAddress, CommentType.PLATE, fdeComment);
new SetCommentCmd(curAddress, CodeUnit.PLATE_COMMENT, fdeComment);
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -22,7 +22,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.structures.ehFrame.*;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressOutOfBoundsException; import ghidra.program.model.address.AddressOutOfBoundsException;
import ghidra.program.model.data.DataType; import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.mem.MemoryBlock; import ghidra.program.model.mem.MemoryBlock;
@ -127,7 +127,7 @@ public class EhFrameHeaderSection {
dataCmd.applyTo(program); dataCmd.applyTo(program);
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.EOL_COMMENT, "Encoded FDE count"); new SetCommentCmd(curAddress, CommentType.EOL, "Encoded FDE count");
commentCmd.applyTo(program); commentCmd.applyTo(program);
curAddress = curAddress.add(ctx.getEncodedLength()); curAddress = curAddress.add(ctx.getEncodedLength());
@ -160,8 +160,8 @@ public class EhFrameHeaderSection {
DwarfDecodeContext ctx = new DwarfDecodeContext(program, curAddress, curMemBlock); DwarfDecodeContext ctx = new DwarfDecodeContext(program, curAddress, curMemBlock);
Address frmPtrAddr = frmPtrDecoder.decodeAddress(ctx); Address frmPtrAddr = frmPtrDecoder.decodeAddress(ctx);
program.getReferenceManager().addMemoryReference(curAddress, frmPtrAddr, RefType.DATA, program.getReferenceManager()
SourceType.ANALYSIS, 0); .addMemoryReference(curAddress, frmPtrAddr, RefType.DATA, SourceType.ANALYSIS, 0);
DataType frmPtrDataType = frmPtrDecoder.getDataType(program); DataType frmPtrDataType = frmPtrDecoder.getDataType(program);
@ -169,7 +169,7 @@ public class EhFrameHeaderSection {
dataCmd.applyTo(program); dataCmd.applyTo(program);
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.EOL_COMMENT, "Encoded eh_frame_ptr"); new SetCommentCmd(curAddress, CommentType.EOL, "Encoded eh_frame_ptr");
commentCmd.applyTo(program); commentCmd.applyTo(program);
curAddress = curAddress.add(ctx.getEncodedLength()); curAddress = curAddress.add(ctx.getEncodedLength());
@ -185,8 +185,8 @@ public class EhFrameHeaderSection {
} }
private void createFdeTable(Address curAddress, ExceptionHandlerFrameHeader eh_frame_hdr, private void createFdeTable(Address curAddress, ExceptionHandlerFrameHeader eh_frame_hdr,
int fdeTableCnt, TaskMonitor monitor) throws MemoryAccessException, int fdeTableCnt, TaskMonitor monitor)
ExceptionHandlerFrameException { throws MemoryAccessException, ExceptionHandlerFrameException {
/* Build the Frame Descriptor Entry Table */ /* Build the Frame Descriptor Entry Table */
int fdeTblEnc = eh_frame_hdr.getEh_FrameTableEncoding(); int fdeTblEnc = eh_frame_hdr.getEh_FrameTableEncoding();
@ -196,7 +196,7 @@ public class EhFrameHeaderSection {
fde_table.create(curAddress, fdeTblDecoder, fdeTableCnt); fde_table.create(curAddress, fdeTblDecoder, fdeTableCnt);
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(curAddress, CodeUnit.PLATE_COMMENT, "Frame Description Entry Table"); new SetCommentCmd(curAddress, CommentType.PLATE, "Frame Description Entry Table");
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -134,7 +134,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure. * appropriate comment for the new structure.
*/ */
String comment = "(CIE) Length"; String comment = "(CIE) Length";
createAndCommentData(program, addr, dwordDT, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, dwordDT, comment, CommentType.EOL);
program.getMemory().getBytes(addr, enc_length); program.getMemory().getBytes(addr, enc_length);
curSize += DWORD_LEN; curSize += DWORD_LEN;
@ -161,7 +161,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure. * appropriate comment for the new structure.
*/ */
String comment = "(CIE) ID"; String comment = "(CIE) ID";
createAndCommentData(program, addr, dwordDT, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, dwordDT, comment, CommentType.EOL);
program.getMemory().getBytes(addr, enc_cieId); program.getMemory().getBytes(addr, enc_cieId);
cieId = (int) GccAnalysisUtils.readDWord(program, addr); cieId = (int) GccAnalysisUtils.readDWord(program, addr);
@ -184,7 +184,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure. * appropriate comment for the new structure.
*/ */
String comment = "(CIE) Version"; String comment = "(CIE) Version";
createAndCommentData(program, addr, new ByteDataType(), comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, new ByteDataType(), comment, CommentType.EOL);
version = GccAnalysisUtils.readByte(program, addr); version = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN; curSize += BYTE_LEN;
@ -208,7 +208,7 @@ public class Cie extends GccAnalysisClass {
* and sets an appropriate comment for the new structure. * and sets an appropriate comment for the new structure.
*/ */
String comment = "(CIE) Augmentation String"; String comment = "(CIE) Augmentation String";
createAndCommentData(program, addr, new StringDataType(), comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, new StringDataType(), comment, CommentType.EOL);
Data dataAt = program.getListing().getDataAt(addr); Data dataAt = program.getListing().getDataAt(addr);
if (dataAt == null) { if (dataAt == null) {
throw new ExceptionHandlerFrameException( throw new ExceptionHandlerFrameException(
@ -236,7 +236,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure. * appropriate comment for the new structure.
*/ */
String comment = "(CIE) Pointer Size"; String comment = "(CIE) Pointer Size";
createAndCommentData(program, addr, new ByteDataType(), comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, new ByteDataType(), comment, CommentType.EOL);
ptrSize = GccAnalysisUtils.readByte(program, addr); ptrSize = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN; curSize += BYTE_LEN;
@ -258,7 +258,7 @@ public class Cie extends GccAnalysisClass {
* appropriate comment for the new structure. * appropriate comment for the new structure.
*/ */
String comment = "(CIE) Segment Size"; String comment = "(CIE) Segment Size";
createAndCommentData(program, addr, new ByteDataType(), comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, new ByteDataType(), comment, CommentType.EOL);
segmentSize = GccAnalysisUtils.readByte(program, addr); segmentSize = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN; curSize += BYTE_LEN;
@ -285,7 +285,7 @@ public class Cie extends GccAnalysisClass {
codeAlignFactor = (int) uleb128.asLong(); codeAlignFactor = (int) uleb128.asLong();
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += uleb128.getLength(); curSize += uleb128.getLength();
@ -312,7 +312,7 @@ public class Cie extends GccAnalysisClass {
dataAlignFactor = (int) sleb128.asLong(); dataAlignFactor = (int) sleb128.asLong();
createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += sleb128.getLength(); curSize += sleb128.getLength();
@ -356,7 +356,7 @@ public class Cie extends GccAnalysisClass {
} }
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
curSize += encodedLen; curSize += encodedLen;
return addr.add(encodedLen); return addr.add(encodedLen);
@ -382,7 +382,7 @@ public class Cie extends GccAnalysisClass {
augmentationDataLength = (int) uleb128.asLong(); augmentationDataLength = (int) uleb128.asLong();
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += uleb128.getLength(); curSize += uleb128.getLength();
@ -430,8 +430,7 @@ public class Cie extends GccAnalysisClass {
initialInstructionCount = intLength - curSize; initialInstructionCount = intLength - curSize;
arrayCmd = new CreateArrayCmd(addr, initialInstructionCount, new ByteDataType(), BYTE_LEN); arrayCmd = new CreateArrayCmd(addr, initialInstructionCount, new ByteDataType(), BYTE_LEN);
arrayCmd.applyTo(program); arrayCmd.applyTo(program);
SetCommentCmd.createComment(program, addr, "(CIE) Initial Instructions", SetCommentCmd.createComment(program, addr, "(CIE) Initial Instructions", CommentType.EOL);
CodeUnit.EOL_COMMENT);
initialInstructions = new byte[initialInstructionCount]; initialInstructions = new byte[initialInstructionCount];
int numBytesRead = program.getMemory().getBytes(addr, initialInstructions); int numBytesRead = program.getMemory().getBytes(addr, initialInstructions);
@ -525,8 +524,8 @@ public class Cie extends GccAnalysisClass {
} }
private void markEndOfFrame(Address addr) { private void markEndOfFrame(Address addr) {
createAndCommentData(program, addr, dwordDT, "End of Frame", CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, dwordDT, "End of Frame", CommentType.EOL);
SetCommentCmd commentCmd = new SetCommentCmd(addr, CodeUnit.PLATE_COMMENT, "END OF FRAME"); SetCommentCmd commentCmd = new SetCommentCmd(addr, CommentType.PLATE, "END OF FRAME");
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }
@ -549,7 +548,7 @@ public class Cie extends GccAnalysisClass {
if (intLength == 0xffffffff) { if (intLength == 0xffffffff) {
hasExtLength = true; hasExtLength = true;
String comment = "(CIE) Extended Length"; String comment = "(CIE) Extended Length";
createAndCommentData(program, addr, new QWordDataType(), comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, new QWordDataType(), comment, CommentType.EOL);
program.getMemory().getBytes(addr, enc_extLength); program.getMemory().getBytes(addr, enc_extLength);
addr = addr.add(QWORD_LEN); addr = addr.add(QWORD_LEN);
curSize += QWORD_LEN; curSize += QWORD_LEN;
@ -620,7 +619,7 @@ public class Cie extends GccAnalysisClass {
String lsdaComment = "(CIE Augmentation Data) LSDA Personality Function Pointer Encoding"; String lsdaComment = "(CIE Augmentation Data) LSDA Personality Function Pointer Encoding";
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex), createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
new DwarfEncodingModeDataType(), lsdaComment, CodeUnit.EOL_COMMENT); new DwarfEncodingModeDataType(), lsdaComment, CommentType.EOL);
} }
private void processFdeEncoding(Address augmentationDataAddr, int augmentationDataIndex, private void processFdeEncoding(Address augmentationDataAddr, int augmentationDataIndex,
@ -630,7 +629,7 @@ public class Cie extends GccAnalysisClass {
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex), createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
new DwarfEncodingModeDataType(), "(CIE Augmentation Data) FDE Encoding", new DwarfEncodingModeDataType(), "(CIE Augmentation Data) FDE Encoding",
CodeUnit.EOL_COMMENT); CommentType.EOL);
} }
private DwarfEHDecoder processPersonalityEncoding(Address augmentationDataAddr, private DwarfEHDecoder processPersonalityEncoding(Address augmentationDataAddr,
@ -643,7 +642,7 @@ public class Cie extends GccAnalysisClass {
String prsnltyComment = "(CIE Augmentation Data) Personality Function Pointer Encoding"; String prsnltyComment = "(CIE Augmentation Data) Personality Function Pointer Encoding";
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex), createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
new DwarfEncodingModeDataType(), prsnltyComment, CodeUnit.EOL_COMMENT); new DwarfEncodingModeDataType(), prsnltyComment, CommentType.EOL);
return personalityDecoder; return personalityDecoder;
} }
@ -660,11 +659,11 @@ public class Cie extends GccAnalysisClass {
createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex), createAndCommentData(program, augmentationDataAddr.add(augmentationDataIndex),
prnsFuncPtrDt, prnsFuncPtrDt,
"(CIE Augmentation Data) Personality Function Pointer (" + personalityFuncAddr + ")", "(CIE Augmentation Data) Personality Function Pointer (" + personalityFuncAddr + ")",
CodeUnit.EOL_COMMENT); CommentType.EOL);
program.getReferenceManager().addMemoryReference( program.getReferenceManager()
augmentationDataAddr.add(augmentationDataIndex), personalityFuncAddr, RefType.DATA, .addMemoryReference(augmentationDataAddr.add(augmentationDataIndex),
SourceType.ANALYSIS, 0); personalityFuncAddr, RefType.DATA, SourceType.ANALYSIS, 0);
return personalityDecodeContext; return personalityDecodeContext;
} }

View file

@ -5,9 +5,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -20,8 +20,7 @@ import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.plugin.exceptionhandlers.gcc.GccAnalysisUtils; import ghidra.app.plugin.exceptionhandlers.gcc.GccAnalysisUtils;
import ghidra.app.util.bin.LEB128Info; import ghidra.app.util.bin.LEB128Info;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.Msg; import ghidra.util.Msg;
@ -393,7 +392,7 @@ public class DwarfCallFrameOpcodeParser {
} }
} }
SetCommentCmd.createComment(program, instrAddr, sb.toString(), CodeUnit.EOL_COMMENT); SetCommentCmd.createComment(program, instrAddr, sb.toString(), CommentType.EOL);
Msg.info(this, sb.toString()); Msg.info(this, sb.toString());
} }

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -22,7 +21,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.datatype.DwarfEncodingModeDataTyp
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressOutOfBoundsException; import ghidra.program.model.address.AddressOutOfBoundsException;
import ghidra.program.model.data.*; import ghidra.program.model.data.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
@ -39,7 +38,7 @@ import ghidra.util.task.TaskMonitor;
* </pre> * </pre>
*/ */
public class ExceptionHandlerFrameHeader { public class ExceptionHandlerFrameHeader {
/* Class Members */ /* Class Members */
private TaskMonitor monitor; private TaskMonitor monitor;
private Program prog; private Program prog;
@ -48,7 +47,7 @@ public class ExceptionHandlerFrameHeader {
private int eh_FramePtrEncoding; private int eh_FramePtrEncoding;
private int eh_FrameDescEntryCntEncoding; private int eh_FrameDescEntryCntEncoding;
private int eh_FrameTableEncoding; private int eh_FrameTableEncoding;
/** /**
* Constructor for an ExceptionHandlerFrameHeader. * Constructor for an ExceptionHandlerFrameHeader.
* @param monitor a status monitor for indicating progress or allowing a task to be cancelled. * @param monitor a status monitor for indicating progress or allowing a task to be cancelled.
@ -75,11 +74,11 @@ public class ExceptionHandlerFrameHeader {
*/ */
public void addToDataTypeManager() { public void addToDataTypeManager() {
DataTypeManager dtManager = prog.getDataTypeManager(); DataTypeManager dtManager = prog.getDataTypeManager();
/* Add the ehFrameHdr Structure to the dataTypeManager */ /* 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 * Method that creates an Exception Handler Frame Header Structure
* at the address specified by 'addr'. If addr is 'null', this method returns without creating * at the address specified by 'addr'. If addr is 'null', this method returns without creating
@ -91,19 +90,20 @@ public class ExceptionHandlerFrameHeader {
*/ */
public void create(Address addr) throws MemoryAccessException, AddressOutOfBoundsException { public void create(Address addr) throws MemoryAccessException, AddressOutOfBoundsException {
CreateStructureCmd dataCmd = null; CreateStructureCmd dataCmd = null;
if (addr == null || monitor.isCancelled()) { if (addr == null || monitor.isCancelled()) {
return; return;
} }
/* Create a new structure at the start of the .eh_frame_hdr section */ /* 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); dataCmd.applyTo(prog);
/* Set a comment on the newly created structure */ /* Set a comment on the newly created structure */
SetCommentCmd commentCmd = new SetCommentCmd(addr, CodeUnit.PLATE_COMMENT, "Exception Handler Frame Header"); SetCommentCmd commentCmd =
new SetCommentCmd(addr, CommentType.PLATE, "Exception Handler Frame Header");
commentCmd.applyTo(prog); commentCmd.applyTo(prog);
// Set the class members accordingly // Set the class members accordingly
eh_version = prog.getMemory().getByte(addr) & 0xFF; eh_version = prog.getMemory().getByte(addr) & 0xFF;
eh_FramePtrEncoding = prog.getMemory().getByte(addr.add(1)) & 0xFF; eh_FramePtrEncoding = prog.getMemory().getByte(addr.add(1)) & 0xFF;

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -177,7 +177,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
* and sets an appropriate comment for the new structure. * and sets an appropriate comment for the new structure.
*/ */
String comment = "(FDE) Length"; String comment = "(FDE) Length";
createAndCommentData(program, addr, dwordDT, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, dwordDT, comment, CommentType.EOL);
intLength = program.getMemory().getInt(addr); intLength = program.getMemory().getInt(addr);
return addr.add(DWORD_LEN); return addr.add(DWORD_LEN);
@ -202,7 +202,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
DataType locType = new DWordDataType(); DataType locType = new DWordDataType();
int locTypeSize = locType.getLength(); int locTypeSize = locType.getLength();
createAndCommentData(program, addr, locType, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, locType, comment, CommentType.EOL);
intPtr = (int) GccAnalysisUtils.readDWord(program, addr); intPtr = (int) GccAnalysisUtils.readDWord(program, addr);
@ -266,7 +266,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
DataType encodedDt = cie.getFDEDecoder().getDataType(program); DataType encodedDt = cie.getFDEDecoder().getDataType(program);
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
if (pcBeginAddr.getOffset() != 0x0) { if (pcBeginAddr.getOffset() != 0x0) {
program.getReferenceManager() program.getReferenceManager()
.addMemoryReference(addr, pcBeginAddr, RefType.DATA, SourceType.ANALYSIS, 0); .addMemoryReference(addr, pcBeginAddr, RefType.DATA, SourceType.ANALYSIS, 0);
@ -324,7 +324,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
} }
int dtLength = dataType.getLength(); int dtLength = dataType.getLength();
createAndCommentData(program, addr, dataType, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, dataType, comment, CommentType.EOL);
curSize += dtLength; curSize += dtLength;
@ -358,7 +358,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
intAugmentationDataLength = (int) uleb128.asLong(); intAugmentationDataLength = (int) uleb128.asLong();
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += uleb128.getLength(); curSize += uleb128.getLength();
@ -377,7 +377,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
* Create a new Augmentation Data field at the specified address * Create a new Augmentation Data field at the specified address
* and sets an appropriate comment for the new structure. * and sets an appropriate comment for the new structure.
*/ */
SetCommentCmd.createComment(program, addr, "(FDE) Augmentation Data", CodeUnit.EOL_COMMENT); SetCommentCmd.createComment(program, addr, "(FDE) Augmentation Data", CommentType.EOL);
this.augmentationData = new byte[intAugmentationDataLength]; this.augmentationData = new byte[intAugmentationDataLength];
program.getMemory().getBytes(addr, augmentationData); program.getMemory().getBytes(addr, augmentationData);
@ -406,7 +406,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
} }
SetCommentCmd.createComment(program, addr, "(FDE) Call Frame Instructions", SetCommentCmd.createComment(program, addr, "(FDE) Call Frame Instructions",
CodeUnit.EOL_COMMENT); CommentType.EOL);
callFrameInstructions = new byte[instructionLength]; callFrameInstructions = new byte[instructionLength];
program.getMemory().getBytes(addr, callFrameInstructions); program.getMemory().getBytes(addr, callFrameInstructions);
@ -512,8 +512,8 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
} }
private void markEndOfFrame(Address addr) { private void markEndOfFrame(Address addr) {
createAndCommentData(program, addr, dwordDT, "End of Frame", CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, dwordDT, "End of Frame", CommentType.EOL);
SetCommentCmd commentCmd = new SetCommentCmd(addr, CodeUnit.PLATE_COMMENT, "END OF FRAME"); SetCommentCmd commentCmd = new SetCommentCmd(addr, CommentType.PLATE, "END OF FRAME");
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }
@ -526,7 +526,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
if (intLength == -1) { if (intLength == -1) {
hasExtLength = true; hasExtLength = true;
String comment = "(FDE) Extended Length"; String comment = "(FDE) Extended Length";
createAndCommentData(program, addr, new QWordDataType(), comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, new QWordDataType(), comment, CommentType.EOL);
// prog.getMemory().getBytes(addr, extLength); // prog.getMemory().getBytes(addr, extLength);
addr = addr.add(QWORD_LEN); addr = addr.add(QWORD_LEN);
curSize += QWORD_LEN; curSize += QWORD_LEN;
@ -631,7 +631,7 @@ public class FrameDescriptionEntry extends GccAnalysisClass {
String lsdaComment = "(FDE Augmentation Data) LSDA Data Pointer"; String lsdaComment = "(FDE Augmentation Data) LSDA Data Pointer";
createAndCommentData(program, augmentationDataAddr, lsdaDecoder.getDataType(program), createAndCommentData(program, augmentationDataAddr, lsdaDecoder.getDataType(program),
lsdaComment, CodeUnit.EOL_COMMENT); lsdaComment, CommentType.EOL);
if (augmentationDataAddr.equals(lsdaAddr)) { if (augmentationDataAddr.equals(lsdaAddr)) {
// decoded a reference that returned here -- a null reference // decoded a reference that returned here -- a null reference

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -20,8 +20,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.*;
import ghidra.app.util.bin.LEB128Info; import ghidra.app.util.bin.LEB128Info;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.data.SignedLeb128DataType; import ghidra.program.model.data.SignedLeb128DataType;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
@ -83,7 +82,7 @@ public class LSDAActionRecord extends GccAnalysisClass {
addr = createNextActionRef(addr); addr = createNextActionRef(addr);
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(address, CodeUnit.PLATE_COMMENT, "(LSDA) Action Record"); new SetCommentCmd(address, CommentType.PLATE, "(LSDA) Action Record");
commentCmd.applyTo(program); commentCmd.applyTo(program);
nextAddress = addr; nextAddress = addr;
@ -98,7 +97,7 @@ public class LSDAActionRecord extends GccAnalysisClass {
typeFilter = (int) sleb128.asLong(); typeFilter = (int) sleb128.asLong();
createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
size += sleb128.getLength(); size += sleb128.getLength();
@ -120,7 +119,7 @@ public class LSDAActionRecord extends GccAnalysisClass {
} }
createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, SignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
size += sleb128.getLength(); size += sleb128.getLength();

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -20,7 +20,7 @@ import java.util.*;
import ghidra.app.cmd.comments.SetCommentCmd; import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.plugin.exceptionhandlers.gcc.RegionDescriptor; import ghidra.app.plugin.exceptionhandlers.gcc.RegionDescriptor;
import ghidra.program.model.address.Address; 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.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
@ -76,7 +76,7 @@ public class LSDAActionTable {
monitor.setMessage("Creating LSDA Action Table"); monitor.setMessage("Creating LSDA Action Table");
LSDAActionRecord rec = null; LSDAActionRecord rec = null;
while (address.compareTo(maxAddress) <= 0) { while (address.compareTo(maxAddress) <= 0) {
rec = new LSDAActionRecord(monitor, program, region, this); rec = new LSDAActionRecord(monitor, program, region, this);
rec.create(address); rec.create(address);
@ -89,7 +89,7 @@ public class LSDAActionTable {
nextAddress = address; nextAddress = address;
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(tableAddress, CodeUnit.PLATE_COMMENT, "(LSDA) Action Table"); new SetCommentCmd(tableAddress, CommentType.PLATE, "(LSDA) Action Table");
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -21,7 +21,7 @@ import ghidra.app.util.bin.LEB128Info;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.data.DataType; import ghidra.program.model.data.DataType;
import ghidra.program.model.data.UnsignedLeb128DataType; import ghidra.program.model.data.UnsignedLeb128DataType;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.symbol.RefType; import ghidra.program.model.symbol.RefType;
@ -96,17 +96,19 @@ public class LSDACallSiteRecord extends GccAnalysisClass {
landingPadAddr = lpStart.add(getLandingPadOffset()); landingPadAddr = lpStart.add(getLandingPadOffset());
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(baseAddr, CodeUnit.PLATE_COMMENT, "(LSDA) Call Site Record"); new SetCommentCmd(baseAddr, CommentType.PLATE, "(LSDA) Call Site Record");
commentCmd.applyTo(program); commentCmd.applyTo(program);
if (program.getMemory().contains(callSiteBaseAddr)) { if (program.getMemory().contains(callSiteBaseAddr)) {
program.getReferenceManager().addMemoryReference(callSiteDataAddr, callSiteBaseAddr, program.getReferenceManager()
RefType.DATA, SourceType.ANALYSIS, 0); .addMemoryReference(callSiteDataAddr, callSiteBaseAddr, RefType.DATA,
SourceType.ANALYSIS, 0);
} }
if (program.getMemory().contains(landingPadAddr)) { if (program.getMemory().contains(landingPadAddr)) {
program.getReferenceManager().addMemoryReference(lpDataAddr, landingPadAddr, program.getReferenceManager()
RefType.DATA, SourceType.ANALYSIS, 0); .addMemoryReference(lpDataAddr, landingPadAddr, RefType.DATA,
SourceType.ANALYSIS, 0);
} }
nextAddress = addr; nextAddress = addr;
@ -124,7 +126,7 @@ public class LSDACallSiteRecord extends GccAnalysisClass {
DataType encodedDt = decoder.getDataType(program); DataType encodedDt = decoder.getDataType(program);
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
return addr.add(encodedLen); return addr.add(encodedLen);
} }
@ -141,7 +143,7 @@ public class LSDACallSiteRecord extends GccAnalysisClass {
DataType encodedDt = decoder.getDataType(program); DataType encodedDt = decoder.getDataType(program);
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
return addr.add(encodedLen); return addr.add(encodedLen);
} }
@ -158,7 +160,7 @@ public class LSDACallSiteRecord extends GccAnalysisClass {
DataType encodedDt = decoder.getDataType(program); DataType encodedDt = decoder.getDataType(program);
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
return addr.add(encodedLen); return addr.add(encodedLen);
} }
@ -175,7 +177,7 @@ public class LSDACallSiteRecord extends GccAnalysisClass {
} }
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
return addr.add(uleb128.getLength()); return addr.add(uleb128.getLength());
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -20,8 +20,7 @@ import java.util.*;
import ghidra.app.cmd.comments.SetCommentCmd; import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.plugin.exceptionhandlers.gcc.*; import ghidra.app.plugin.exceptionhandlers.gcc.*;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.*;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.Msg; import ghidra.util.Msg;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
@ -78,7 +77,7 @@ public class LSDACallSiteTable extends GccAnalysisClass {
monitor.setMessage("Creating GCC LSDA Call Site Table "); monitor.setMessage("Creating GCC LSDA Call Site Table ");
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(baseAddr, CodeUnit.PLATE_COMMENT, "(LSDA) Call Site Table"); new SetCommentCmd(baseAddr, CommentType.PLATE, "(LSDA) Call Site Table");
commentCmd.applyTo(program); commentCmd.applyTo(program);
Address limit = baseAddr.add(header.getCallSiteTableLength() - 1); Address limit = baseAddr.add(header.getCallSiteTableLength() - 1);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -21,7 +21,7 @@ import ghidra.app.plugin.exceptionhandlers.gcc.datatype.DwarfEncodingModeDataTyp
import ghidra.app.util.bin.LEB128Info; import ghidra.app.util.bin.LEB128Info;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.data.*; import ghidra.program.model.data.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.symbol.SourceType; import ghidra.program.model.symbol.SourceType;
@ -40,7 +40,6 @@ public class LSDAHeader extends GccAnalysisClass {
static final int OMITTED_ENCODING_TYPE = 0xFF; static final int OMITTED_ENCODING_TYPE = 0xFF;
/* Class Members */ /* Class Members */
private RegionDescriptor region; private RegionDescriptor region;
@ -84,7 +83,7 @@ public class LSDAHeader extends GccAnalysisClass {
String comment = "(LSDA) LPStart Encoding"; String comment = "(LSDA) LPStart Encoding";
createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment, createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
lpStartEncoding = GccAnalysisUtils.readByte(program, addr); lpStartEncoding = GccAnalysisUtils.readByte(program, addr);
curSize += BYTE_LEN; curSize += BYTE_LEN;
@ -122,7 +121,7 @@ public class LSDAHeader extends GccAnalysisClass {
DataType encodedDt = decoder.getDataType(program); DataType encodedDt = decoder.getDataType(program);
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
curSize += encodedLen; curSize += encodedLen;
return addr.add(encodedLen); return addr.add(encodedLen);
@ -134,7 +133,7 @@ public class LSDAHeader extends GccAnalysisClass {
ttypeEncoding = GccAnalysisUtils.readByte(program, addr); ttypeEncoding = GccAnalysisUtils.readByte(program, addr);
createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment, createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += BYTE_LEN; curSize += BYTE_LEN;
return addr.add(BYTE_LEN); return addr.add(BYTE_LEN);
@ -155,7 +154,7 @@ public class LSDAHeader extends GccAnalysisClass {
ttypeOffset = uleb128.asLong() + curSize; ttypeOffset = uleb128.asLong() + curSize;
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
return addr.add(uleb128.getLength()); return addr.add(uleb128.getLength());
} }
@ -165,7 +164,7 @@ public class LSDAHeader extends GccAnalysisClass {
callSiteTableEncoding = GccAnalysisUtils.readByte(program, addr); callSiteTableEncoding = GccAnalysisUtils.readByte(program, addr);
createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment, createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += BYTE_LEN; curSize += BYTE_LEN;
return addr.add(BYTE_LEN); return addr.add(BYTE_LEN);
@ -179,7 +178,7 @@ public class LSDAHeader extends GccAnalysisClass {
callSiteTableLength = (int) uleb128.asLong(); callSiteTableLength = (int) uleb128.asLong();
createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment, createAndCommentData(program, addr, UnsignedLeb128DataType.dataType, comment,
CodeUnit.EOL_COMMENT); CommentType.EOL);
curSize += uleb128.getLength(); curSize += uleb128.getLength();
return addr.add(uleb128.getLength()); return addr.add(uleb128.getLength());
@ -243,7 +242,7 @@ public class LSDAHeader extends GccAnalysisClass {
} }
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(baseAddr, CodeUnit.PLATE_COMMENT, "(LSDA) Exception Table"); new SetCommentCmd(baseAddr, CommentType.PLATE, "(LSDA) Exception Table");
commentCmd.applyTo(program); commentCmd.applyTo(program);
nextAddress = addr; nextAddress = addr;

View file

@ -18,7 +18,7 @@ package ghidra.app.plugin.exceptionhandlers.gcc.structures.gccexcepttable;
import ghidra.app.cmd.comments.SetCommentCmd; import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.plugin.exceptionhandlers.gcc.RegionDescriptor; import ghidra.app.plugin.exceptionhandlers.gcc.RegionDescriptor;
import ghidra.program.model.address.Address; 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.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
@ -78,8 +78,7 @@ public class LSDATable {
* @param region the region of the program associated with this table * @param region the region of the program associated with this table
* @throws MemoryAccessException if memory couldn't be accessed for the LSDA table * @throws MemoryAccessException if memory couldn't be accessed for the LSDA table
*/ */
public void create(Address tableAddr, RegionDescriptor region) public void create(Address tableAddr, RegionDescriptor region) throws MemoryAccessException {
throws MemoryAccessException {
region.setLSDATable(this); region.setLSDATable(this);
@ -125,7 +124,8 @@ public class LSDATable {
} }
} }
SetCommentCmd commentCmd = new SetCommentCmd(baseAdress, CodeUnit.PLATE_COMMENT, "Language-Specific Data Area"); SetCommentCmd commentCmd =
new SetCommentCmd(baseAdress, CommentType.PLATE, "Language-Specific Data Area");
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -23,7 +22,7 @@ import ghidra.app.cmd.comments.SetCommentCmd;
import ghidra.app.plugin.exceptionhandlers.gcc.*; import ghidra.app.plugin.exceptionhandlers.gcc.*;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.data.*; import ghidra.program.model.data.*;
import ghidra.program.model.listing.CodeUnit; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.symbol.RefType; import ghidra.program.model.symbol.RefType;
@ -92,25 +91,25 @@ public class LSDATypeTable extends GccAnalysisClass {
typeInfoAddrs.add(typeRef); typeInfoAddrs.add(typeRef);
createAndCommentData(program, addr, encodedDt, comment, CodeUnit.EOL_COMMENT); createAndCommentData(program, addr, encodedDt, comment, CommentType.EOL);
if (typeRef.getOffset() != 0) { if (typeRef.getOffset() != 0) {
program.getReferenceManager().addMemoryReference(addr, typeRef, RefType.DATA, program.getReferenceManager()
SourceType.ANALYSIS, 0); .addMemoryReference(addr, typeRef, RefType.DATA, SourceType.ANALYSIS,
0);
} }
} }
catch (MemoryAccessException mae) { catch (MemoryAccessException mae) {
SetCommentCmd commentCmd = SetCommentCmd commentCmd =
new SetCommentCmd(addr, CodeUnit.EOL_COMMENT, "Unable to resolve pointer"); new SetCommentCmd(addr, CommentType.EOL, "Unable to resolve pointer");
commentCmd.applyTo(program); commentCmd.applyTo(program);
} }
addr = addr.subtract(stride); addr = addr.subtract(stride);
} }
SetCommentCmd commentCmd = SetCommentCmd commentCmd = new SetCommentCmd(top, CommentType.PLATE, "(LSDA) Type Table");
new SetCommentCmd(top, CodeUnit.PLATE_COMMENT, "(LSDA) Type Table");
commentCmd.applyTo(program); commentCmd.applyTo(program);
nextAddress = bottom.add(1); nextAddress = bottom.add(1);
@ -124,7 +123,7 @@ public class LSDATypeTable extends GccAnalysisClass {
} }
createAndCommentData(program, addr, new ArrayDataType(new ByteDataType(), incr, 1), createAndCommentData(program, addr, new ArrayDataType(new ByteDataType(), incr, 1),
" -- alignment pad", CodeUnit.EOL_COMMENT); " -- alignment pad", CommentType.EOL);
return addr.add(incr); return addr.add(incr);

View file

@ -3855,7 +3855,7 @@ public abstract class GhidraScript extends FlatProgramAPI {
* @see #getPlateComment(Address) * @see #getPlateComment(Address)
*/ */
public String getPlateCommentAsRendered(Address address) { public String getPlateCommentAsRendered(Address address) {
String comment = currentProgram.getListing().getComment(CodeUnit.PLATE_COMMENT, address); String comment = currentProgram.getListing().getComment(CommentType.PLATE, address);
PluginTool tool = state.getTool(); PluginTool tool = state.getTool();
if (tool != null) { if (tool != null) {
comment = CommentUtils.getDisplayString(comment, currentProgram); comment = CommentUtils.getDisplayString(comment, currentProgram);
@ -3874,7 +3874,7 @@ public abstract class GhidraScript extends FlatProgramAPI {
* @see #getPreComment(Address) * @see #getPreComment(Address)
*/ */
public String getPreCommentAsRendered(Address address) { public String getPreCommentAsRendered(Address address) {
String comment = currentProgram.getListing().getComment(CodeUnit.PRE_COMMENT, address); String comment = currentProgram.getListing().getComment(CommentType.PRE, address);
PluginTool tool = state.getTool(); PluginTool tool = state.getTool();
if (tool != null) { if (tool != null) {
comment = CommentUtils.getDisplayString(comment, currentProgram); comment = CommentUtils.getDisplayString(comment, currentProgram);
@ -3892,7 +3892,7 @@ public abstract class GhidraScript extends FlatProgramAPI {
* @see #getPostComment(Address) * @see #getPostComment(Address)
*/ */
public String getPostCommentAsRendered(Address address) { public String getPostCommentAsRendered(Address address) {
String comment = currentProgram.getListing().getComment(CodeUnit.POST_COMMENT, address); String comment = currentProgram.getListing().getComment(CommentType.POST, address);
PluginTool tool = state.getTool(); PluginTool tool = state.getTool();
if (tool != null) { if (tool != null) {
comment = CommentUtils.getDisplayString(comment, currentProgram); comment = CommentUtils.getDisplayString(comment, currentProgram);
@ -3910,7 +3910,7 @@ public abstract class GhidraScript extends FlatProgramAPI {
* @see #getEOLComment(Address) * @see #getEOLComment(Address)
*/ */
public String getEOLCommentAsRendered(Address address) { public String getEOLCommentAsRendered(Address address) {
String comment = currentProgram.getListing().getComment(CodeUnit.EOL_COMMENT, address); String comment = currentProgram.getListing().getComment(CommentType.EOL, address);
PluginTool tool = state.getTool(); PluginTool tool = state.getTool();
if (tool != null) { if (tool != null) {
comment = CommentUtils.getDisplayString(comment, currentProgram); comment = CommentUtils.getDisplayString(comment, currentProgram);
@ -3928,8 +3928,7 @@ public abstract class GhidraScript extends FlatProgramAPI {
* @see #getRepeatableComment(Address) * @see #getRepeatableComment(Address)
*/ */
public String getRepeatableCommentAsRendered(Address address) { public String getRepeatableCommentAsRendered(Address address) {
String comment = String comment = currentProgram.getListing().getComment(CommentType.REPEATABLE, address);
currentProgram.getListing().getComment(CodeUnit.REPEATABLE_COMMENT, address);
PluginTool tool = state.getTool(); PluginTool tool = state.getTool();
if (tool != null) { if (tool != null) {
comment = CommentUtils.getDisplayString(comment, currentProgram); comment = CommentUtils.getDisplayString(comment, currentProgram);

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -16,14 +15,14 @@
*/ */
package ghidra.app.util; package ghidra.app.util;
import java.util.ArrayList;
import java.util.List;
import ghidra.program.model.address.Address; import ghidra.program.model.address.Address;
import ghidra.program.model.listing.*; import ghidra.program.model.listing.*;
import ghidra.program.model.pcode.Varnode; import ghidra.program.model.pcode.Varnode;
import ghidra.program.model.symbol.*; import ghidra.program.model.symbol.*;
import java.util.ArrayList;
import java.util.List;
/** /**
* Container object to keep a relative index, label, and comments. Used * Container object to keep a relative index, label, and comments. Used
* in a list for copying/pasting labels and comments from one program to * in a list for copying/pasting labels and comments from one program to
@ -91,23 +90,23 @@ public class CodeUnitInfo {
List<SourceType> scopeSymSourceList = new ArrayList<SourceType>(); List<SourceType> scopeSymSourceList = new ArrayList<SourceType>();
List<String> otherSymList = new ArrayList<String>(); List<String> otherSymList = new ArrayList<String>();
List<SourceType> otherSymSourceList = new ArrayList<SourceType>(); List<SourceType> otherSymSourceList = new ArrayList<SourceType>();
for (int i = 0; i < symbols.length; i++) { for (Symbol symbol : symbols) {
SymbolType symbolType = symbols[i].getSymbolType(); SymbolType symbolType = symbol.getSymbolType();
if (symbols[i].isDynamic()) { if (symbol.isDynamic()) {
hasDynamicSymbol = true; hasDynamicSymbol = true;
} }
else if (symbols[i].isPrimary()) { else if (symbol.isPrimary()) {
primarySymbolName = symbols[i].getName(); primarySymbolName = symbol.getName();
primarySymbolSource = symbols[i].getSource(); primarySymbolSource = symbol.getSource();
primarySymbolInFunctionScope = (symbolType == SymbolType.FUNCTION); primarySymbolInFunctionScope = (symbolType == SymbolType.FUNCTION);
} }
else if (symbolType == SymbolType.FUNCTION) { else if (symbolType == SymbolType.FUNCTION) {
scopeSymList.add(symbols[i].getName()); scopeSymList.add(symbol.getName());
scopeSymSourceList.add(symbols[i].getSource()); scopeSymSourceList.add(symbol.getSource());
} }
else { else {
otherSymList.add(symbols[i].getName()); otherSymList.add(symbol.getName());
otherSymSourceList.add(symbols[i].getSource()); otherSymSourceList.add(symbol.getSource());
} }
} }
functionScopeSymbolNames = new String[scopeSymList.size()]; functionScopeSymbolNames = new String[scopeSymList.size()];
@ -122,30 +121,34 @@ public class CodeUnitInfo {
/** /**
* Set the comment to be transferred. * Set the comment to be transferred.
* @param commentType CodeUnit.PRE_COMMENT, POST_COMMENT, * @param commentType comment type
* PLATE_COMMENT, EOL_COMMENT, or REPEATABLE.
* @param comment comment * @param comment comment
*/ */
public void setComment(int commentType, String[] comment) { public void setComment(CommentType commentType, String[] comment) {
switch (commentType) { switch (commentType) {
case CodeUnit.PLATE_COMMENT: case PLATE:
plateComment = comment; plateComment = comment;
break; break;
case CodeUnit.PRE_COMMENT: case PRE:
preComment = comment; preComment = comment;
break; break;
case CodeUnit.POST_COMMENT: case POST:
postComment = comment; postComment = comment;
break; break;
case CodeUnit.REPEATABLE_COMMENT: case REPEATABLE:
repeatableComment = comment; repeatableComment = comment;
break; break;
case CodeUnit.EOL_COMMENT: case EOL:
eolComment = comment; eolComment = comment;
break;
default:
throw new IllegalArgumentException(
"Unsupported comment type: " + commentType.name());
} }
} }
@ -387,17 +390,17 @@ public class CodeUnitInfo {
*/ */
private void setNonStackVarInfo(Variable[] vars) { private void setNonStackVarInfo(Variable[] vars) {
int variableIndex = 0; int variableIndex = 0;
for (int i = 0; i < vars.length; i++) { for (Variable var : vars) {
if (vars[i].isStackVariable()) { if (var.isStackVariable()) {
continue; // skip stack variables continue; // skip stack variables
} }
varNames[variableIndex] = vars[i].getName(); varNames[variableIndex] = var.getName();
varSources[variableIndex] = vars[i].getSource(); varSources[variableIndex] = var.getSource();
Varnode firstVarnode = vars[i].getFirstStorageVarnode(); Varnode firstVarnode = var.getFirstStorageVarnode();
varAddrs[variableIndex] = varAddrs[variableIndex] =
firstVarnode != null ? firstVarnode.getAddress() : Address.NO_ADDRESS; firstVarnode != null ? firstVarnode.getAddress() : Address.NO_ADDRESS;
varFUOffsets[variableIndex] = vars[i].getFirstUseOffset(); varFUOffsets[variableIndex] = var.getFirstUseOffset();
varComments[variableIndex] = vars[i].getComment(); varComments[variableIndex] = var.getComment();
++variableIndex; ++variableIndex;
} }
} }

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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 * Class with a convenience method to get an array of the CodeUnit
* comment types. The method is useful to loop through the comment types * comment types. The method is useful to loop through the comment types
* once you have a code unit. * 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 { public class CommentTypes {
private static int[] COMMENT_TYPES; private static int[] COMMENT_TYPES;
private static int NUMBER_OF_COMMENT_TYPES=5; private static int NUMBER_OF_COMMENT_TYPES = 5;
CommentTypes() { CommentTypes() {
} }
static {
COMMENT_TYPES = new int[NUMBER_OF_COMMENT_TYPES]; static {
COMMENT_TYPES = new int[NUMBER_OF_COMMENT_TYPES];
COMMENT_TYPES[0] = CodeUnit.PRE_COMMENT; COMMENT_TYPES[0] = CodeUnit.PRE_COMMENT;
COMMENT_TYPES[1] = CodeUnit.POST_COMMENT; COMMENT_TYPES[1] = CodeUnit.POST_COMMENT;
COMMENT_TYPES[2] = CodeUnit.EOL_COMMENT; COMMENT_TYPES[2] = CodeUnit.EOL_COMMENT;
COMMENT_TYPES[3] = CodeUnit.PLATE_COMMENT; COMMENT_TYPES[3] = CodeUnit.PLATE_COMMENT;
COMMENT_TYPES[4] = CodeUnit.REPEATABLE_COMMENT; COMMENT_TYPES[4] = CodeUnit.REPEATABLE_COMMENT;
} }
/** /**
* Get an array containing the comment types on a code unit. * Get an array containing the comment types on a code unit.
*/ */
public static int[] getTypes() { public static int[] getTypes() {
return COMMENT_TYPES; return COMMENT_TYPES;
} }
} }

View file

@ -101,8 +101,7 @@ public class EolComments {
} }
private void loadEols() { private void loadEols() {
Collection<String> comments = Collection<String> comments = Arrays.asList(codeUnit.getCommentAsArray(CommentType.EOL));
Arrays.asList(codeUnit.getCommentAsArray(CommentType.EOL));
addStrings(comments, eols); addStrings(comments, eols);
} }
@ -118,7 +117,7 @@ public class EolComments {
} }
Collection<String> comments = Collection<String> comments =
Arrays.asList(codeUnit.getCommentAsArray(CodeUnit.REPEATABLE_COMMENT)); Arrays.asList(codeUnit.getCommentAsArray(CommentType.REPEATABLE));
addStrings(comments, repeatables); addStrings(comments, repeatables);
} }
@ -582,7 +581,7 @@ public class EolComments {
Listing listing = program.getListing(); Listing listing = program.getListing();
// prefer listing comments first since there may not be a code unit at this address // prefer listing comments first since there may not be a code unit at this address
String repeatable = listing.getComment(CodeUnit.REPEATABLE_COMMENT, address); String repeatable = listing.getComment(CommentType.REPEATABLE, address);
if (repeatable != null) { if (repeatable != null) {
return StringUtilities.toLines(repeatable); return StringUtilities.toLines(repeatable);
} }
@ -597,7 +596,7 @@ public class EolComments {
return f.getRepeatableCommentAsArray(); return f.getRepeatableCommentAsArray();
} }
return cu.getCommentAsArray(CodeUnit.REPEATABLE_COMMENT); return cu.getCommentAsArray(CommentType.REPEATABLE);
} }
/** /**

View file

@ -78,15 +78,15 @@ public class DWARFUtil {
*/ */
public static Field getStaticFinalFieldWithValue(Class<?> clazz, long value) { public static Field getStaticFinalFieldWithValue(Class<?> clazz, long value) {
Field[] fields = clazz.getDeclaredFields(); Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) { for (Field field : fields) {
if ((!Modifier.isFinal(fields[i].getModifiers())) || if ((!Modifier.isFinal(field.getModifiers())) ||
(!Modifier.isStatic(fields[i].getModifiers()))) { (!Modifier.isStatic(field.getModifiers()))) {
continue; continue;
} }
try { try {
long fieldValue = fields[i].getLong(null); long fieldValue = field.getLong(null);
if (fieldValue == value) { if (fieldValue == value) {
return fields[i]; return field;
} }
} }
catch (IllegalArgumentException | IllegalAccessException e) { catch (IllegalArgumentException | IllegalAccessException e) {
@ -98,10 +98,6 @@ public class DWARFUtil {
//-------------------------------------- //--------------------------------------
private static Pattern MANGLED_NESTING_REGEX = Pattern.compile("(.*_Z)?N([0-9]+.*)"); private static Pattern MANGLED_NESTING_REGEX = Pattern.compile("(.*_Z)?N([0-9]+.*)");
/** /**
@ -286,8 +282,7 @@ public class DWARFUtil {
String memberName = childDIEA.getName(); String memberName = childDIEA.getName();
int memberOffset = 0; int memberOffset = 0;
try { try {
memberOffset = memberOffset = childDIEA.parseDataMemberOffset(DW_AT_data_member_location, 0);
childDIEA.parseDataMemberOffset(DW_AT_data_member_location, 0);
} }
catch (DWARFExpressionException | IOException e) { catch (DWARFExpressionException | IOException e) {
// ignore, leave as default value 0 // ignore, leave as default value 0
@ -359,7 +354,7 @@ public class DWARFUtil {
return; return;
} }
} }
AppendCommentCmd cmd = new AppendCommentCmd(address, commentType.ordinal(), AppendCommentCmd cmd = new AppendCommentCmd(address, commentType,
Objects.requireNonNullElse(prefix, "") + comment, sep); Objects.requireNonNullElse(prefix, "") + comment, sep);
cmd.applyTo(program); cmd.applyTo(program);
} }
@ -398,8 +393,7 @@ public class DWARFUtil {
} }
DIEAggregate funcDIEA = paramDIEA.getParent(); DIEAggregate funcDIEA = paramDIEA.getParent();
DWARFAttributeValue dwATObjectPointer = DWARFAttributeValue dwATObjectPointer = funcDIEA.getAttribute(DW_AT_object_pointer);
funcDIEA.getAttribute(DW_AT_object_pointer);
if (dwATObjectPointer != null && dwATObjectPointer instanceof DWARFNumericAttribute dnum && if (dwATObjectPointer != null && dwATObjectPointer instanceof DWARFNumericAttribute dnum &&
paramDIEA.hasOffset(dnum.getUnsignedValue())) { paramDIEA.hasOffset(dnum.getUnsignedValue())) {
return true; return true;
@ -442,8 +436,7 @@ public class DWARFUtil {
public static ResourceFile getLanguageExternalFile(Language lang, String name) public static ResourceFile getLanguageExternalFile(Language lang, String name)
throws IOException { throws IOException {
String filename = getLanguageExternalNameValue(lang, name); String filename = getLanguageExternalNameValue(lang, name);
return filename != null return filename != null ? new ResourceFile(getLanguageDefinitionDirectory(lang), filename)
? new ResourceFile(getLanguageDefinitionDirectory(lang), filename)
: null; : null;
} }

View file

@ -82,7 +82,8 @@ public class NoteGnuProperty extends ElfNote {
/** /**
* Contains the information of an individual note property. * 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) private static NotePropertyElement readNextNotePropertyElement(BinaryReader reader, int intSize)
throws IOException { throws IOException {
@ -187,7 +188,7 @@ public class NoteGnuProperty extends ElfNote {
DataType elementDT = getElementDataType(dtm, element); DataType elementDT = getElementDataType(dtm, element);
Data elementData = DataUtilities.createData(program, address, elementDT, -1, false, Data elementData = DataUtilities.createData(program, address, elementDT, -1, false,
ClearDataMode.CLEAR_ALL_UNDEFINED_CONFLICT_DATA); ClearDataMode.CLEAR_ALL_UNDEFINED_CONFLICT_DATA);
listing.setComment(address, CodeUnit.EOL_COMMENT, listing.setComment(address, CommentType.EOL,
element.typeName() + "=" + element.value()); element.typeName() + "=" + element.value());
address = elementData.getMaxAddress().next(); address = elementData.getMaxAddress().next();
} }

View file

@ -120,8 +120,8 @@ public abstract class DataDirectory implements PeMarkupable {
} }
protected void createDirectoryBookmark(Program program, Address addr) { protected void createDirectoryBookmark(Program program, Address addr) {
program.getBookmarkManager().setBookmark(addr, BookmarkType.INFO, "PE Header", program.getBookmarkManager()
getDirectoryName()); .setBookmark(addr, BookmarkType.INFO, "PE Header", getDirectoryName());
} }
protected void setBookmark(Program prog, Address addr, String comment) { protected void setBookmark(Program prog, Address addr, String comment) {
@ -129,15 +129,15 @@ public abstract class DataDirectory implements PeMarkupable {
} }
protected void setPlateComment(Program prog, Address addr, String comment) { protected void setPlateComment(Program prog, Address addr, String comment) {
prog.getListing().setComment(addr, CodeUnit.PLATE_COMMENT, comment); prog.getListing().setComment(addr, CommentType.PLATE, comment);
} }
protected void setEolComment(Program prog, Address addr, String comment) { protected void setEolComment(Program prog, Address addr, String comment) {
prog.getListing().setComment(addr, CodeUnit.EOL_COMMENT, comment); prog.getListing().setComment(addr, CommentType.EOL, comment);
} }
protected void setPreComment(Program prog, Address addr, String comment) { protected void setPreComment(Program prog, Address addr, String comment) {
prog.getListing().setComment(addr, CodeUnit.PRE_COMMENT, comment); prog.getListing().setComment(addr, CommentType.PRE, comment);
} }
/** /**

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -439,13 +439,13 @@ public class CliTableMethodDef extends CliAbstractTable {
// Create the function, if already created, update the existing function // Create the function, if already created, update the existing function
Function func = funcMgr.getFunctionAt(startAddr); Function func = funcMgr.getFunctionAt(startAddr);
if (func == null) { if (func == null) {
func = funcMgr func = funcMgr.createFunction(funcName, startAddr, funcAddrSet,
.createFunction(funcName, startAddr, funcAddrSet, SourceType.ANALYSIS); SourceType.ANALYSIS);
} }
func.setReturnType(returnType, SourceType.ANALYSIS); func.setReturnType(returnType, SourceType.ANALYSIS);
func.updateFunction(null, null, FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, func.updateFunction(null, null, FunctionUpdateType.DYNAMIC_STORAGE_ALL_PARAMS, true,
true, SourceType.ANALYSIS, parameters); SourceType.ANALYSIS, parameters);
markToPreventIncorrectProcessorDisassembly(program, methodRow, startAddr, endAddr); markToPreventIncorrectProcessorDisassembly(program, methodRow, startAddr, endAddr);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
@ -503,9 +503,9 @@ public class CliTableMethodDef extends CliAbstractTable {
* @param endAddr end address of the function * @param endAddr end address of the function
* @throws CodeUnitInsertionException couldn't create dagta. * @throws CodeUnitInsertionException couldn't create dagta.
*/ */
private void markToPreventIncorrectProcessorDisassembly(Program program, CliMethodDefRow methodRow, private void markToPreventIncorrectProcessorDisassembly(Program program,
Address startAddr, Address endAddr) throws CodeUnitInsertionException { CliMethodDefRow methodRow, Address startAddr, Address endAddr)
throws CodeUnitInsertionException {
PrototypeModel cliCallingConvention = program.getLanguage() PrototypeModel cliCallingConvention = program.getLanguage()
.getDefaultCompilerSpec() .getDefaultCompilerSpec()
@ -520,9 +520,9 @@ public class CliTableMethodDef extends CliAbstractTable {
int codeLength = (int) endAddr.subtract(startAddr) + 1; int codeLength = (int) endAddr.subtract(startAddr) + 1;
ArrayDataType codeDT = new ArrayDataType(BYTE, codeLength, 1); ArrayDataType codeDT = new ArrayDataType(BYTE, codeLength, 1);
data = listing.createData(startAddr, codeDT); data = listing.createData(startAddr, codeDT);
// comment the type of code that should appear here // comment the type of code that should appear here
data.setComment(CodeUnit.PRE_COMMENT, data.setComment(CommentType.PRE,
(methodRow.isManaged() ? ".NET CLR Managed Code" : "Native Code")); (methodRow.isManaged() ? ".NET CLR Managed Code" : "Native Code"));
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -96,10 +96,9 @@ public class DemangledAddressTable extends DemangledObject {
Listing listing = program.getListing(); Listing listing = program.getListing();
if (program.getMemory().isExternalBlockAddress(address)) { if (program.getMemory().isExternalBlockAddress(address)) {
Msg.warn(this, Msg.warn(this, "Unable to fully apply external demangled Address Table at " + address +
"Unable to fully apply external demangled Address Table at " + address + ": " + ": " + s.getName(true));
s.getName(true)); listing.setComment(address, CommentType.EOL,
listing.setComment(address, CodeUnit.EOL_COMMENT,
"WARNING: Unable to apply demangled Address Table"); "WARNING: Unable to apply demangled Address Table");
return true; // don't complain return true; // don't complain
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -156,7 +156,7 @@ class ProgramTextWriter {
//// Plate Property //////////////////////////////////////////// //// Plate Property ////////////////////////////////////////////
boolean cuHasPlate = false; boolean cuHasPlate = false;
if (options.isShowProperties()) { if (options.isShowProperties()) {
String[] plate = currentCodeUnit.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] plate = currentCodeUnit.getCommentAsArray(CommentType.PLATE);
cuHasPlate = plate != null && plate.length > 0; cuHasPlate = plate != null && plate.length > 0;
if (cuHasPlate) { if (cuHasPlate) {
processPlate(currentCodeUnit, plate); processPlate(currentCodeUnit, plate);
@ -200,7 +200,7 @@ class ProgramTextWriter {
//// Pre-Comment /////////////////////////////////////////////// //// Pre-Comment ///////////////////////////////////////////////
if (options.isShowComments()) { if (options.isShowComments()) {
String[] pre = currentCodeUnit.getCommentAsArray(CodeUnit.PRE_COMMENT); String[] pre = currentCodeUnit.getCommentAsArray(CommentType.PRE);
if (pre != null && pre.length > 0) { if (pre != null && pre.length > 0) {
String fill = genFill(options.getAddrWidth() + options.getBytesWidth()); String fill = genFill(options.getAddrWidth() + options.getBytesWidth());
for (String element : pre) { for (String element : pre) {
@ -301,7 +301,7 @@ class ProgramTextWriter {
//// Post Comment ////////////////////////////////////////////// //// Post Comment //////////////////////////////////////////////
if (options.isShowComments()) { if (options.isShowComments()) {
String[] post = currentCodeUnit.getCommentAsArray(CodeUnit.POST_COMMENT); String[] post = currentCodeUnit.getCommentAsArray(CommentType.POST);
if (post != null) { if (post != null) {
String fill = genFill(options.getAddrWidth() + options.getBytesWidth()); String fill = genFill(options.getAddrWidth() + options.getBytesWidth());
for (String element : post) { for (String element : post) {
@ -355,9 +355,8 @@ class ProgramTextWriter {
return; return;
} }
int len = options.getAddrWidth() + options.getBytesWidth() + int len = options.getAddrWidth() + options.getBytesWidth() + options.getPreMnemonicWidth() +
options.getPreMnemonicWidth() + options.getMnemonicWidth() + options.getMnemonicWidth() + options.getOperandWidth();
options.getOperandWidth();
String fill = genFill(len); String fill = genFill(len);
for (int i = 0; i < comments.size(); ++i) { for (int i = 0; i < comments.size(); ++i) {

View file

@ -94,8 +94,8 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader {
maps.add(postCommentMap); maps.add(postCommentMap);
maps.add(eolCommentMap); maps.add(eolCommentMap);
int[] types = new int[] { CodeUnit.PLATE_COMMENT, CodeUnit.PRE_COMMENT, CommentType[] types = new CommentType[] { CommentType.PLATE, CommentType.PRE,
CodeUnit.POST_COMMENT, CodeUnit.EOL_COMMENT }; CommentType.POST, CommentType.EOL };
String[] typeNames = new String[] { "PLATE", "PRE", "POST", "EOL" }; String[] typeNames = new String[] { "PLATE", "PRE", "POST", "EOL" };
int index = 0; int index = 0;
for (HashMap<Address, StringBuffer> map : maps) { for (HashMap<Address, StringBuffer> map : maps) {
@ -273,7 +273,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader {
//log.appendMsg("Unable to demangle: "+name); //log.appendMsg("Unable to demangle: "+name);
} }
if (builder.length() > 0) { 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])); Address startAddr = addr.add(Conv.intToLong(starts[k]));
String cmt = "START-> " + file.getName() + ": " + "?"; String cmt = "START-> " + file.getName() + ": " + "?";
setComment(CodeUnit.PRE_COMMENT, startAddr, cmt); setComment(CommentType.PRE, startAddr, cmt);
Address endAddr = addr.add(Conv.intToLong(ends[k])); Address endAddr = addr.add(Conv.intToLong(ends[k]));
cmt = "END-> " + file.getName() + ": " + "?"; cmt = "END-> " + file.getName() + ": " + "?";
setComment(CodeUnit.PRE_COMMENT, endAddr, cmt); setComment(CommentType.PRE, endAddr, cmt);
if (monitor.isCancelled()) { if (monitor.isCancelled()) {
return; return;
@ -380,8 +380,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader {
} }
protected boolean processDebugCoffSymbol(DebugCOFFSymbol symbol, NTHeader ntHeader, protected boolean processDebugCoffSymbol(DebugCOFFSymbol symbol, NTHeader ntHeader,
Map<SectionHeader, Address> sectionToAddress, Program program, Map<SectionHeader, Address> sectionToAddress, Program program, TaskMonitor monitor) {
TaskMonitor monitor) {
if (symbol.getSectionNumber() == 0) { if (symbol.getSectionNumber() == 0) {
return true; return true;
@ -453,7 +452,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader {
if (aux == null) { if (aux == null) {
continue; continue;
} }
setComment(CodeUnit.PRE_COMMENT, address, aux.toString()); setComment(CommentType.PRE, address, aux.toString());
} }
return true; return true;
@ -482,7 +481,7 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader {
Address address = program.getImageBase().add(dd.getAddressOfRawData()); Address address = program.getImageBase().add(dd.getAddressOfRawData());
try { try {
program.getListing().createData(address, new StringDataType(), actualData.length()); program.getListing().createData(address, new StringDataType(), actualData.length());
program.getListing().setComment(address, CodeUnit.PLATE_COMMENT, "Debug Misc"); program.getListing().setComment(address, CommentType.PLATE, "Debug Misc");
address = address.add(actualData.length()); address = address.add(actualData.length());
program.getListing().createData(address, new DWordDataType()); program.getListing().createData(address, new DWordDataType());
} }
@ -499,54 +498,57 @@ abstract class AbstractPeDebugLoader extends AbstractOrdinalSupportLoader {
private void addLineComment(Address addr, int line) { private void addLineComment(Address addr, int line) {
String cmt = addr + " -> " + "Line #" + 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) { switch (type) {
case CodeUnit.PLATE_COMMENT: case PLATE:
return plateCommentMap.get(address) != null; return plateCommentMap.get(address) != null;
case CodeUnit.PRE_COMMENT: case PRE:
return preCommentMap.get(address) != null; return preCommentMap.get(address) != null;
case CodeUnit.POST_COMMENT: case POST:
return postCommentMap.get(address) != null; return postCommentMap.get(address) != null;
case CodeUnit.EOL_COMMENT: case EOL:
return eolCommentMap.get(address) != null; 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; StringBuffer buffer = null;
switch (type) { switch (type) {
case CodeUnit.PLATE_COMMENT: case CommentType.PLATE:
buffer = plateCommentMap.get(address); buffer = plateCommentMap.get(address);
if (buffer == null) { if (buffer == null) {
buffer = new StringBuffer(); buffer = new StringBuffer();
plateCommentMap.put(address, buffer); plateCommentMap.put(address, buffer);
} }
break; break;
case CodeUnit.PRE_COMMENT: case CommentType.PRE:
buffer = preCommentMap.get(address); buffer = preCommentMap.get(address);
if (buffer == null) { if (buffer == null) {
buffer = new StringBuffer(); buffer = new StringBuffer();
preCommentMap.put(address, buffer); preCommentMap.put(address, buffer);
} }
break; break;
case CodeUnit.POST_COMMENT: case CommentType.POST:
buffer = postCommentMap.get(address); buffer = postCommentMap.get(address);
if (buffer == null) { if (buffer == null) {
buffer = new StringBuffer(); buffer = new StringBuffer();
postCommentMap.put(address, buffer); postCommentMap.put(address, buffer);
} }
break; break;
case CodeUnit.EOL_COMMENT: case CommentType.EOL:
buffer = eolCommentMap.get(address); buffer = eolCommentMap.get(address);
if (buffer == null) { if (buffer == null) {
buffer = new StringBuffer(); buffer = new StringBuffer();
eolCommentMap.put(address, buffer); eolCommentMap.put(address, buffer);
} }
break; break;
default:
throw new IllegalArgumentException("Unsupported comment type: " + type.name());
} }
if (buffer != null) { if (buffer != null) {
if (buffer.length() > 0) { if (buffer.length() > 0) {

View file

@ -545,18 +545,18 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
comment = Long.toHexString(symbols[index].getValue()); comment = Long.toHexString(symbols[index].getValue());
} }
cu.setComment(CodeUnit.EOL_COMMENT, comment); cu.setComment(CommentType.EOL, comment);
// Scalar scalar = (Scalar)data.getValue(); // Scalar scalar = (Scalar)data.getValue();
// switch ((int)scalar.getValue()) { // switch ((int)scalar.getValue()) {
// case GNU_Constants.VER_NDX_LOCAL: // 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; // break;
// case GNU_Constants.VER_NDX_GLOBAL: // 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; // break;
// default: // default:
// data.setComment(Data.EOL_COMMENT, symbols[index].getNameAsString()+ " - ??"); // data.setComment(Data.EOL, symbols[index].getNameAsString()+ " - ??");
// break; // break;
// } // }
} }
@ -837,7 +837,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
} }
createData(interpStrAddr, TerminatedStringDataType.dataType); createData(interpStrAddr, TerminatedStringDataType.dataType);
listing.setComment(interpStrAddr, CodeUnit.EOL_COMMENT, "Initial Elf program interpreter"); listing.setComment(interpStrAddr, CommentType.EOL, "Initial Elf program interpreter");
} }
private void processImports(TaskMonitor monitor) throws CancelledException { private void processImports(TaskMonitor monitor) throws CancelledException {
@ -1230,7 +1230,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
monitor.incrementProgress(1); monitor.incrementProgress(1);
Data d = array.getComponent(i); Data d = array.getComponent(i);
d.setComment(CodeUnit.EOL_COMMENT, programHeaders[i].getComment()); d.setComment(CommentType.EOL, programHeaders[i].getComment());
if (programHeaders[i].getType() == ElfProgramHeaderConstants.PT_NULL) { if (programHeaders[i].getType() == ElfProgramHeaderConstants.PT_NULL) {
continue; continue;
} }
@ -1301,7 +1301,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
if (type != null) { if (type != null) {
comment = comment + " - " + type; comment = comment + " - " + type;
} }
d.setComment(CodeUnit.EOL_COMMENT, comment); d.setComment(CommentType.EOL, comment);
Address sectionAddr = findLoadAddress(sections[i], 0); Address sectionAddr = findLoadAddress(sections[i], 0);
if (sectionAddr != null) { if (sectionAddr != null) {
@ -1340,7 +1340,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
listing.createData(relocTableAddr, dataType); listing.createData(relocTableAddr, dataType);
} }
else { else {
listing.setComment(relocTableAddr, CodeUnit.PRE_COMMENT, listing.setComment(relocTableAddr, CommentType.PRE,
"ELF Relocation Table (markup not yet supported)"); "ELF Relocation Table (markup not yet supported)");
} }
} }
@ -2021,14 +2021,14 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
// Add versioned symbol as comment only // Add versioned symbol as comment only
Address address = s.getAddress(); Address address = s.getAddress();
String comment = listing.getComment(CodeUnit.PRE_COMMENT, address); String comment = listing.getComment(CommentType.PRE, address);
if (comment == null || comment.length() == 0) { if (comment == null || comment.length() == 0) {
comment = symName; comment = symName;
} }
else { else {
comment += "\n" + symName; comment += "\n" + symName;
} }
listing.setComment(address, CodeUnit.PRE_COMMENT, comment); listing.setComment(address, CommentType.PRE, comment);
setElfSymbolAddress(elfSymbol, address); setElfSymbolAddress(elfSymbol, address);
return true; return true;
} }
@ -2499,21 +2499,21 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
Address addr = hashTableAddr; Address addr = hashTableAddr;
Data d = listing.createData(addr, dt); Data d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "Hash Table - nbucket"); d.setComment(CommentType.EOL, "Hash Table - nbucket");
long nbucket = d.getScalar(0).getUnsignedValue(); long nbucket = d.getScalar(0).getUnsignedValue();
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "Hash Table - nchain"); d.setComment(CommentType.EOL, "Hash Table - nchain");
long nchain = d.getScalar(0).getUnsignedValue(); long nchain = d.getScalar(0).getUnsignedValue();
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, new ArrayDataType(dt, (int) nbucket, dt.getLength())); d = listing.createData(addr, new ArrayDataType(dt, (int) nbucket, dt.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "Hash Table - buckets"); d.setComment(CommentType.EOL, "Hash Table - buckets");
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, new ArrayDataType(dt, (int) nchain, dt.getLength())); d = listing.createData(addr, new ArrayDataType(dt, (int) nchain, dt.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "Hash Table - chains"); d.setComment(CommentType.EOL, "Hash Table - chains");
} }
catch (Exception e) { catch (Exception e) {
log("Failed to properly markup Hash table at " + hashTableAddr + ": " + getMessage(e)); log("Failed to properly markup Hash table at " + hashTableAddr + ": " + getMessage(e));
@ -2542,36 +2542,36 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
Address addr = hashTableAddr; Address addr = hashTableAddr;
Data d = listing.createData(addr, dt); Data d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU Hash Table - nbucket"); d.setComment(CommentType.EOL, "GNU Hash Table - nbucket");
long nbucket = d.getScalar(0).getUnsignedValue(); long nbucket = d.getScalar(0).getUnsignedValue();
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU Hash Table - symbase"); d.setComment(CommentType.EOL, "GNU Hash Table - symbase");
long symbolBase = d.getScalar(0).getUnsignedValue(); long symbolBase = d.getScalar(0).getUnsignedValue();
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU Hash Table - bloom_size"); d.setComment(CommentType.EOL, "GNU Hash Table - bloom_size");
long bloomSize = d.getScalar(0).getUnsignedValue(); long bloomSize = d.getScalar(0).getUnsignedValue();
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU Hash Table - bloom_shift"); d.setComment(CommentType.EOL, "GNU Hash Table - bloom_shift");
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
DataType bloomDataType = DataType bloomDataType =
elf.is64Bit() ? QWordDataType.dataType : DWordDataType.dataType; elf.is64Bit() ? QWordDataType.dataType : DWordDataType.dataType;
d = listing.createData(addr, d = listing.createData(addr,
new ArrayDataType(bloomDataType, (int) bloomSize, bloomDataType.getLength())); new ArrayDataType(bloomDataType, (int) bloomSize, bloomDataType.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "GNU Hash Table - bloom"); d.setComment(CommentType.EOL, "GNU Hash Table - bloom");
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, new ArrayDataType(dt, (int) nbucket, dt.getLength())); d = listing.createData(addr, new ArrayDataType(dt, (int) nbucket, dt.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "GNU Hash Table - buckets"); d.setComment(CommentType.EOL, "GNU Hash Table - buckets");
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
listing.setComment(addr, CodeUnit.EOL_COMMENT, "GNU Hash Table - chain"); listing.setComment(addr, CommentType.EOL, "GNU Hash Table - chain");
// Rely on dynamic symbol table for number of symbols // Rely on dynamic symbol table for number of symbols
ElfSymbolTable dynamicSymbolTable = elf.getDynamicSymbolTable(); ElfSymbolTable dynamicSymbolTable = elf.getDynamicSymbolTable();
@ -2612,30 +2612,30 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
// Elf32_Word ngnusyms; // number of entries in chains (and xlat); dynsymcount=symndx+ngnusyms // Elf32_Word ngnusyms; // number of entries in chains (and xlat); dynsymcount=symndx+ngnusyms
Address addr = hashTableAddr; Address addr = hashTableAddr;
Data d = listing.createData(addr, dt); Data d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - ngnusyms"); d.setComment(CommentType.EOL, "GNU XHash Table - ngnusyms");
long ngnusyms = d.getScalar(0).getUnsignedValue(); long ngnusyms = d.getScalar(0).getUnsignedValue();
// Elf32_Word nbuckets; // number of hash table buckets // Elf32_Word nbuckets; // number of hash table buckets
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - nbuckets"); d.setComment(CommentType.EOL, "GNU XHash Table - nbuckets");
long nbuckets = d.getScalar(0).getUnsignedValue(); long nbuckets = d.getScalar(0).getUnsignedValue();
// Elf32_Word symndx; // number of initial .dynsym entires skipped in chains[] (and xlat[]) // Elf32_Word symndx; // number of initial .dynsym entires skipped in chains[] (and xlat[])
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - symndx"); d.setComment(CommentType.EOL, "GNU XHash Table - symndx");
// Elf32_Word maskwords; // number of ElfW(Addr) words in bitmask // Elf32_Word maskwords; // number of ElfW(Addr) words in bitmask
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - maskwords"); d.setComment(CommentType.EOL, "GNU XHash Table - maskwords");
long maskwords = d.getScalar(0).getUnsignedValue(); long maskwords = d.getScalar(0).getUnsignedValue();
// Elf32_Word shift2; // bit shift of hashval for second Bloom filter bit // Elf32_Word shift2; // bit shift of hashval for second Bloom filter bit
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, dt); d = listing.createData(addr, dt);
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - shift2"); d.setComment(CommentType.EOL, "GNU XHash Table - shift2");
// ElfW(Addr) bitmask[maskwords]; // 2 bit Bloom filter on hashval // ElfW(Addr) bitmask[maskwords]; // 2 bit Bloom filter on hashval
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
@ -2643,22 +2643,22 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
elf.is64Bit() ? QWordDataType.dataType : DWordDataType.dataType; elf.is64Bit() ? QWordDataType.dataType : DWordDataType.dataType;
d = listing.createData(addr, d = listing.createData(addr,
new ArrayDataType(bloomDataType, (int) maskwords, bloomDataType.getLength())); new ArrayDataType(bloomDataType, (int) maskwords, bloomDataType.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - bitmask"); d.setComment(CommentType.EOL, "GNU XHash Table - bitmask");
// Elf32_Word buckets[nbuckets]; // indices into chains[] // Elf32_Word buckets[nbuckets]; // indices into chains[]
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, new ArrayDataType(dt, (int) nbuckets, dt.getLength())); d = listing.createData(addr, new ArrayDataType(dt, (int) nbuckets, dt.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - buckets"); d.setComment(CommentType.EOL, "GNU XHash Table - buckets");
// Elf32_Word chains[ngnusyms]; // consecutive hashvals in a given bucket; last entry in chain has LSB set // Elf32_Word chains[ngnusyms]; // consecutive hashvals in a given bucket; last entry in chain has LSB set
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, new ArrayDataType(dt, (int) ngnusyms, dt.getLength())); d = listing.createData(addr, new ArrayDataType(dt, (int) ngnusyms, dt.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - chains"); d.setComment(CommentType.EOL, "GNU XHash Table - chains");
// Elf32_Word xlat[ngnusyms]; // parallel to chains[]; index into .dynsym // Elf32_Word xlat[ngnusyms]; // parallel to chains[]; index into .dynsym
addr = addr.add(d.getLength()); addr = addr.add(d.getLength());
d = listing.createData(addr, new ArrayDataType(dt, (int) ngnusyms, dt.getLength())); d = listing.createData(addr, new ArrayDataType(dt, (int) ngnusyms, dt.getLength()));
d.setComment(CodeUnit.EOL_COMMENT, "GNU XHash Table - xlat"); d.setComment(CommentType.EOL, "GNU XHash Table - xlat");
} }
catch (Exception e) { catch (Exception e) {
log("Failed to properly markup GNU Hash table at " + hashTableAddr + ": " + log("Failed to properly markup GNU Hash table at " + hashTableAddr + ": " +
@ -2688,7 +2688,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
} }
Data structData = array.getComponent(i); Data structData = array.getComponent(i);
if (structData != null) { if (structData != null) {
structData.setComment(CodeUnit.EOL_COMMENT, name); structData.setComment(CommentType.EOL, name);
} }
} }
} }
@ -2736,7 +2736,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
String comment = String comment =
dynamicType != null ? (dynamicType.name + " - " + dynamicType.description) dynamicType != null ? (dynamicType.name + " - " + dynamicType.description)
: ("DT_0x" + StringUtilities.pad(Integer.toHexString(tagType), '0', 8)); : ("DT_0x" + StringUtilities.pad(Integer.toHexString(tagType), '0', 8));
dynamicData.setComment(CodeUnit.EOL_COMMENT, comment); dynamicData.setComment(CommentType.EOL, comment);
Data valueData = dynamicData.getComponent(1); Data valueData = dynamicData.getComponent(1);
@ -2749,7 +2749,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {
if (dynamicStringTable != null) { if (dynamicStringTable != null) {
String str = dynamicStringTable.readString(elf.getReader(), value); String str = dynamicStringTable.readString(elf.getReader(), value);
if (str != null && str.length() != 0) { if (str != null && str.length() != 0) {
valueData.setComment(CodeUnit.EOL_COMMENT, str); valueData.setComment(CommentType.EOL, str);
} }
} }
} }

View file

@ -233,7 +233,7 @@ public class NeLoader extends AbstractOrdinalSupportLoader {
buffer.append("Other Flags: " + Conv.toHexString(ib.getOtherFlags()) + "\n"); buffer.append("Other Flags: " + Conv.toHexString(ib.getOtherFlags()) + "\n");
buffer.append(ib.getOtherFlagsAsString()); buffer.append(ib.getOtherFlagsAsString());
firstCU.setComment(CodeUnit.PLATE_COMMENT, buffer.toString()); firstCU.setComment(CommentType.PLATE, buffer.toString());
} }
private void processSegmentTable(MessageLog log, InformationBlock ib, SegmentTable st, private void processSegmentTable(MessageLog log, InformationBlock ib, SegmentTable st,
@ -314,7 +314,7 @@ public class NeLoader extends AbstractOrdinalSupportLoader {
buff.append((segments[i].isReadOnly() ? TAB + "Read Only" + "\n" : "")); buff.append((segments[i].isReadOnly() ? TAB + "Read Only" + "\n" : ""));
buff.append((segments[i].is32bit() ? TAB + "Use 32 Bit" + "\n" : "")); buff.append((segments[i].is32bit() ? TAB + "Use 32 Bit" + "\n" : ""));
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
cu.setComment(CodeUnit.PRE_COMMENT, buff.toString()); cu.setComment(CommentType.PRE, buff.toString());
} }
for (Segment segment : segments) { for (Segment segment : segments) {
@ -392,7 +392,7 @@ public class NeLoader extends AbstractOrdinalSupportLoader {
buf.append("Usage: " + Conv.toHexString(resource.getUsage()) + "\n"); buf.append("Usage: " + Conv.toHexString(resource.getUsage()) + "\n");
CodeUnit cu = listing.getCodeUnitAt(addr); CodeUnit cu = listing.getCodeUnitAt(addr);
if (cu != null) { if (cu != null) {
cu.setComment(CodeUnit.PRE_COMMENT, buf.toString()); cu.setComment(CommentType.PRE, buf.toString());
} }
//if this resource is a string table, //if this resource is a string table,

View file

@ -254,7 +254,7 @@ public class PeLoader extends AbstractPeDebugLoader {
dt = section.toDataType(); dt = section.toDataType();
DataUtilities.createData(program, start, dt, -1, DataUtilities.createData(program, start, dt, -1,
DataUtilities.ClearDataMode.CHECK_FOR_SPACE); DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
setComment(CodeUnit.EOL_COMMENT, start, section.getName()); setComment(CommentType.EOL, start, section.getName());
start = start.add(dt.getLength()); start = start.add(dt.getLength());
} }
} }
@ -383,7 +383,7 @@ public class PeLoader extends AbstractPeDebugLoader {
Address address = space.getAddress(addr); Address address = space.getAddress(addr);
setComment(CodeUnit.PRE_COMMENT, address, importInfo.getComment()); setComment(CommentType.PRE, address, importInfo.getComment());
Data data = listing.getDefinedDataAt(address); Data data = listing.getDefinedDataAt(address);
if (data != null && data.isPointer()) { if (data != null && data.isPointer()) {
@ -547,7 +547,7 @@ public class PeLoader extends AbstractPeDebugLoader {
} }
Address address = space.getAddress(export.getAddress()); Address address = space.getAddress(export.getAddress());
setComment(CodeUnit.PRE_COMMENT, address, export.getComment()); setComment(CommentType.PRE, address, export.getComment());
symTable.addExternalEntryPoint(address); symTable.addExternalEntryPoint(address);
String name = export.getName(); String name = export.getName();
@ -713,9 +713,8 @@ public class PeLoader extends AbstractPeDebugLoader {
int dataSize = (virtualSize > 0 || rawDataSize < 0) ? virtualSize : 0; int dataSize = (virtualSize > 0 || rawDataSize < 0) ? virtualSize : 0;
if (dataSize > 0) { if (dataSize > 0) {
if (block != null) { if (block != null) {
MemoryBlock paddingBlock = MemoryBlock paddingBlock = MemoryBlockUtils.createInitializedBlock(prog,
MemoryBlockUtils.createInitializedBlock(prog, false, sectionName, false, sectionName, address, dataSize, "", "", r, w, x, log);
address, dataSize, "", "", r, w, x, log);
if (paddingBlock != null) { if (paddingBlock != null) {
try { try {
prog.getMemory().join(block, paddingBlock); prog.getMemory().join(block, paddingBlock);
@ -992,7 +991,7 @@ public class PeLoader extends AbstractPeDebugLoader {
catch (CancelledException e) { catch (CancelledException e) {
// Move on // Move on
} }
// Check for Swift // Check for Swift
List<String> sectionNames = List<String> sectionNames =
Arrays.stream(pe.getNTHeader().getFileHeader().getSectionHeaders()) Arrays.stream(pe.getNTHeader().getFileHeader().getSectionHeaders())

View file

@ -166,9 +166,8 @@ public class PlateFieldFactory extends FieldFactory {
ListingFieldHighlightFactoryAdapter hlFactory = ListingFieldHighlightFactoryAdapter hlFactory =
new ListingFieldHighlightFactoryAdapter(hlProvider); new ListingFieldHighlightFactoryAdapter(hlProvider);
PlateFieldTextField textField = PlateFieldTextField textField = new PlateFieldTextField(elements, this, proxy, startX,
new PlateFieldTextField(elements, this, proxy, startX, width, commentText, isClipped, width, commentText, isClipped, hlFactory);
hlFactory);
PlateListingTextField listingField = new PlateListingTextField(proxy, textField, hlFactory); PlateListingTextField listingField = new PlateListingTextField(proxy, textField, hlFactory);
return listingField; return listingField;
} }
@ -180,7 +179,7 @@ public class PlateFieldFactory extends FieldFactory {
addBlankLines(elements, numberBlankLines, cu); addBlankLines(elements, numberBlankLines, cu);
String[] comments = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] comments = cu.getCommentAsArray(CommentType.PLATE);
return generateFormattedPlateComment(elements, comments, offcutComments, cu.getProgram()); return generateFormattedPlateComment(elements, comments, offcutComments, cu.getProgram());
} }
@ -210,7 +209,7 @@ public class PlateFieldFactory extends FieldFactory {
} }
private String getCommentText(CodeUnit cu, List<String> offcutComments) { private String getCommentText(CodeUnit cu, List<String> offcutComments) {
String[] comments = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] comments = cu.getCommentAsArray(CommentType.PLATE);
if (comments == null) { if (comments == null) {
return null; return null;
} }
@ -256,8 +255,8 @@ public class PlateFieldFactory extends FieldFactory {
commentsList.add(CommentUtils.parseTextForAnnotations(c, p, prototype, row++)); commentsList.add(CommentUtils.parseTextForAnnotations(c, p, prototype, row++));
} }
for (String offcut : offcutComments) { for (String offcut : offcutComments) {
AttributedString as = new AttributedString(offcut, CommentColors.OFFCUT, AttributedString as =
getMetrics(style), false, null); new AttributedString(offcut, CommentColors.OFFCUT, getMetrics(style), false, null);
commentsList.add(new TextFieldElement(as, commentsList.size(), 0)); commentsList.add(new TextFieldElement(as, commentsList.size(), 0));
} }
@ -503,7 +502,7 @@ public class PlateFieldFactory extends FieldFactory {
} }
CodeUnit cu = (CodeUnit) proxyObject; CodeUnit cu = (CodeUnit) proxyObject;
String[] comments = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT); String[] comments = cu.getCommentAsArray(CommentType.PLATE);
RowColLocation dataLocation = RowColLocation dataLocation =
((ListingTextField) listingField).screenToDataLocation(row, col); ((ListingTextField) listingField).screenToDataLocation(row, col);
@ -540,7 +539,7 @@ public class PlateFieldFactory extends FieldFactory {
} }
CommentFieldLocation commentLocation = (CommentFieldLocation) programLoc; CommentFieldLocation commentLocation = (CommentFieldLocation) programLoc;
if (commentLocation.getCommentType() != CodeUnit.PLATE_COMMENT) { if (commentLocation.getCommentType() != CommentType.PLATE) {
return null; return null;
} }
@ -603,8 +602,8 @@ public class PlateFieldFactory extends FieldFactory {
@Override @Override
public FieldFactory newInstance(FieldFormatModel formatModel, public FieldFactory newInstance(FieldFormatModel formatModel,
ListingHighlightProvider hsProvider, ListingHighlightProvider hsProvider, ToolOptions toolOptions,
ToolOptions toolOptions, ToolOptions fieldOptions) { ToolOptions fieldOptions) {
return new PlateFieldFactory(formatModel, hsProvider, toolOptions, fieldOptions); return new PlateFieldFactory(formatModel, hsProvider, toolOptions, fieldOptions);
} }

View file

@ -139,7 +139,7 @@ public class PostCommentFieldFactory extends FieldFactory {
String[] autoComment = getAutoPostComment(cu); String[] autoComment = getAutoPostComment(cu);
List<String> offcutComments = CommentUtils.getOffcutComments(cu, CommentType.POST); List<String> offcutComments = CommentUtils.getOffcutComments(cu, CommentType.POST);
String[] comments = cu.getCommentAsArray(CodeUnit.POST_COMMENT); String[] comments = cu.getCommentAsArray(CommentType.POST);
if (comments != null && comments.length > 0 && (cu instanceof Data)) { if (comments != null && comments.length > 0 && (cu instanceof Data)) {
return getTextField(comments, autoComment, offcutComments, proxy, x, false); return getTextField(comments, autoComment, offcutComments, proxy, x, false);
} }
@ -291,7 +291,7 @@ public class PostCommentFieldFactory extends FieldFactory {
} }
CodeUnit cu = (CodeUnit) obj; CodeUnit cu = (CodeUnit) obj;
String[] comment = cu.getCommentAsArray(CodeUnit.POST_COMMENT); String[] comment = cu.getCommentAsArray(CommentType.POST);
int[] cpath = null; int[] cpath = null;
if (cu instanceof Data) { if (cu instanceof Data) {
@ -313,7 +313,7 @@ public class PostCommentFieldFactory extends FieldFactory {
} }
CommentFieldLocation loc = (CommentFieldLocation) programLoc; CommentFieldLocation loc = (CommentFieldLocation) programLoc;
if (loc.getCommentType() != CodeUnit.POST_COMMENT) { if (loc.getCommentType() != CommentType.POST) {
return null; return null;
} }
return new FieldLocation(index, fieldNum, loc.getRow(), loc.getCharOffset()); return new FieldLocation(index, fieldNum, loc.getRow(), loc.getCharOffset());

View file

@ -130,7 +130,7 @@ public class PreCommentFieldFactory extends FieldFactory {
} }
} }
return cu.getCommentAsArray(CodeUnit.PRE_COMMENT); return cu.getCommentAsArray(CommentType.PRE);
} }
private String[] getAutoPreComments(CodeUnit cu) { private String[] getAutoPreComments(CodeUnit cu) {
@ -147,13 +147,13 @@ public class PreCommentFieldFactory extends FieldFactory {
return null; return null;
} }
CodeUnit cu = (CodeUnit) obj; CodeUnit cu = (CodeUnit) obj;
String[] comment = cu.getCommentAsArray(CodeUnit.PRE_COMMENT); String[] comment = cu.getCommentAsArray(CommentType.PRE);
int[] cpath = null; int[] cpath = null;
if (cu instanceof Data) { if (cu instanceof Data) {
cpath = ((Data) cu).getComponentPath(); cpath = ((Data) cu).getComponentPath();
} }
return new CommentFieldLocation(cu.getProgram(), cu.getMinAddress(), cpath, comment, return new CommentFieldLocation(cu.getProgram(), cu.getMinAddress(), cpath, comment,
CodeUnit.PRE_COMMENT, row, col); CommentType.PRE, row, col);
} }
@Override @Override
@ -164,7 +164,7 @@ public class PreCommentFieldFactory extends FieldFactory {
} }
CommentFieldLocation loc = (CommentFieldLocation) programLoc; CommentFieldLocation loc = (CommentFieldLocation) programLoc;
if (loc.getCommentType() != CodeUnit.PRE_COMMENT) { if (loc.getCommentType() != CommentType.PRE) {
return null; return null;
} }
return new FieldLocation(index, fieldNum, loc.getRow(), loc.getCharOffset()); return new FieldLocation(index, fieldNum, loc.getRow(), loc.getCharOffset());

View file

@ -1,13 +1,12 @@
/* ### /* ###
* IP: GHIDRA * IP: GHIDRA
* REVIEWED: YES
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -16,11 +15,16 @@
*/ */
package ghidra.app.util.xml; 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.app.util.importer.MessageLog;
import ghidra.program.model.address.*; import ghidra.program.model.address.*;
import ghidra.program.model.listing.*; import ghidra.program.model.listing.*;
import ghidra.util.XmlProgramUtilities; import ghidra.util.XmlProgramUtilities;
import ghidra.util.exception.AssertException;
import ghidra.util.exception.CancelledException; import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor; import ghidra.util.task.TaskMonitor;
import ghidra.util.xml.XmlAttributes; import ghidra.util.xml.XmlAttributes;
@ -28,8 +32,6 @@ import ghidra.util.xml.XmlWriter;
import ghidra.xml.XmlElement; import ghidra.xml.XmlElement;
import ghidra.xml.XmlPullParser; import ghidra.xml.XmlPullParser;
import java.io.IOException;
/** /**
* XML manager for all types of comments. * XML manager for all types of comments.
*/ */
@ -39,31 +41,31 @@ class CommentsXmlMgr {
private AddressFactory factory; private AddressFactory factory;
private Listing listing; private Listing listing;
private static int[] COMMENT_TYPES; private static Map<CommentType, String> COMMENT_TAGS;
private static String[] COMMENT_TAGS;
static { static {
COMMENT_TYPES = CommentTypes.getTypes();
COMMENT_TAGS = new String[COMMENT_TYPES.length]; COMMENT_TAGS = new HashMap<>();
for (int i = 0; i < COMMENT_TAGS.length; i++) { for (CommentType type : CommentType.values()) {
switch (COMMENT_TYPES[i]) { switch (type) {
case CodeUnit.PRE_COMMENT: case CommentType.PRE:
COMMENT_TAGS[i] = "pre"; COMMENT_TAGS.put(type, "pre");
break; break;
case CodeUnit.POST_COMMENT: case CommentType.POST:
COMMENT_TAGS[i] = "post"; COMMENT_TAGS.put(type, "post");
break; break;
case CodeUnit.EOL_COMMENT: case CommentType.EOL:
COMMENT_TAGS[i] = "end-of-line"; COMMENT_TAGS.put(type, "end-of-line");
break; break;
case CodeUnit.PLATE_COMMENT: case CommentType.PLATE:
COMMENT_TAGS[i] = "plate"; COMMENT_TAGS.put(type, "plate");
break; break;
case CodeUnit.REPEATABLE_COMMENT: case CommentType.REPEATABLE:
COMMENT_TAGS[i] = "repeatable"; COMMENT_TAGS.put(type, "repeatable");
break; 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. * Process the entry point section of the XML file.
* @param parser xml reader * @param parser xml reader
* @param monitor monitor that can be canceled * @param monitor monitor that can be canceled
* @throws AddressFormatException
* @throws CancelledException
*/ */
void read(XmlPullParser parser, TaskMonitor monitor) throws AddressFormatException, void read(XmlPullParser parser, TaskMonitor monitor)
CancelledException { throws AddressFormatException, CancelledException {
XmlElement element = parser.next(); XmlElement element = parser.next();
while (true) { while (true) {
if (monitor.isCancelled()) { if (monitor.isCancelled()) {
@ -103,9 +107,10 @@ class CommentsXmlMgr {
* @param set address set that is either the entire program or a selection * @param set address set that is either the entire program or a selection
* @param monitor monitor that can be canceled * @param monitor monitor that can be canceled
* should be written * 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 ..."); monitor.setMessage("Writing COMMENTS ...");
if (set == null) { if (set == null) {
@ -117,17 +122,15 @@ class CommentsXmlMgr {
CodeUnitIterator iter = listing.getCodeUnitIterator(CodeUnit.COMMENT_PROPERTY, set, true); CodeUnitIterator iter = listing.getCodeUnitIterator(CodeUnit.COMMENT_PROPERTY, set, true);
while (iter.hasNext()) { while (iter.hasNext()) {
if (monitor.isCancelled()) { monitor.checkCancelled();
throw new CancelledException();
}
CodeUnit cu = iter.next(); CodeUnit cu = iter.next();
for (int i = 0; i < COMMENT_TYPES.length; i++) { for (CommentType type : CommentType.values()) {
if (monitor.isCancelled()) { if (monitor.isCancelled()) {
return; return;
} }
String comments = cu.getComment(COMMENT_TYPES[i]); String comments = cu.getComment(type);
if (comments != null) { 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 { try {
String typeStr = element.getAttribute("TYPE"); String typeStr = element.getAttribute("TYPE");
int commentType = getCommentType(typeStr); CommentType commentType = getCommentType(typeStr);
if (commentType < 0) { if (commentType == null) {
log.appendMsg("Unknown comment type: " + typeStr); log.appendMsg("Unknown comment type: " + typeStr);
parser.discardSubTree(element); parser.discardSubTree(element);
return; return;
@ -180,12 +183,15 @@ class CommentsXmlMgr {
writer.writeElement("COMMENT", attrs, comments); writer.writeElement("COMMENT", attrs, comments);
} }
private int getCommentType(String typeStr) { private CommentType getCommentType(String typeStr) {
for (int i = 0; i < COMMENT_TAGS.length; i++) { if (StringUtils.isBlank(typeStr)) {
if (COMMENT_TAGS[i].equals(typeStr)) { return null;
return COMMENT_TYPES[i]; }
for (CommentType type : CommentType.values()) {
if (typeStr.equals(COMMENT_TAGS.get(type))) {
return type;
} }
} }
return -1; // unknown comment return null; // unknown comment
} }
} }

View file

@ -20,6 +20,7 @@ import ghidra.program.model.address.Address;
import ghidra.program.model.listing.CommentType; import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Program;
import ghidra.program.util.*; import ghidra.program.util.*;
import ghidra.util.exception.AssertException;
/** /**
* QuickFix for updating listing comments. * QuickFix for updating listing comments.
@ -80,11 +81,11 @@ public class UpdateCommentQuickFix extends QuickFix {
case POST: case POST:
return new PostCommentFieldLocation(program, address, null, null, 0, 0); return new PostCommentFieldLocation(program, address, null, null, 0, 0);
case PRE: 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: case REPEATABLE:
return new RepeatableCommentFieldLocation(program, address, null, null, 0, 0, 0); return new RepeatableCommentFieldLocation(program, address, null, null, 0, 0, 0);
default: default:
return null; throw new AssertException("Unsupported comment type: " + type.name());
} }
} }

View file

@ -933,6 +933,7 @@ public class ProgramBuilder {
}); });
} }
@Deprecated(forRemoval = true, since = "11.4")
public void createComment(String address, String comment, int commentType) { public void createComment(String address, String comment, int commentType) {
tx(() -> { tx(() -> {
Listing listing = program.getListing(); Listing listing = program.getListing();
@ -940,6 +941,13 @@ public class ProgramBuilder {
}); });
} }
public void createComment(String address, String comment, CommentType commentType) {
tx(() -> {
Listing listing = program.getListing();
listing.setComment(addr(address), commentType, comment);
});
}
public void createFunctionComment(String entryPointAddress, String comment) { public void createFunctionComment(String entryPointAddress, String comment) {
tx(() -> { tx(() -> {
FunctionManager functionManager = program.getFunctionManager(); FunctionManager functionManager = program.getFunctionManager();
@ -1104,10 +1112,9 @@ public class ProgramBuilder {
} }
return tx(() -> { return tx(() -> {
FileBytes fileBytes = FileBytes fileBytes = program.getMemory()
program.getMemory() .createFileBytes("test", 0, size, new ByteArrayInputStream(bytes),
.createFileBytes("test", 0, size, new ByteArrayInputStream(bytes), TaskMonitor.DUMMY);
TaskMonitor.DUMMY);
return fileBytes; return fileBytes;
}); });

View file

@ -319,8 +319,8 @@ public class FlatProgramAPI {
* @param bookmarks true if bookmarks should be cleared * @param bookmarks true if bookmarks should be cleared
* @return true if the address set was successfully cleared * @return true if the address set was successfully cleared
*/ */
public final boolean clearListing(AddressSetView set, boolean instructions, public final boolean clearListing(AddressSetView set, boolean instructions, boolean data,
boolean data, boolean symbols, boolean comments, boolean properties, boolean functions, boolean symbols, boolean comments, boolean properties, boolean functions,
boolean registers, boolean equates, boolean userReferences, boolean analysisReferences, boolean registers, boolean equates, boolean userReferences, boolean analysisReferences,
boolean importReferences, boolean defaultReferences, boolean bookmarks) { boolean importReferences, boolean defaultReferences, boolean bookmarks) {
@ -358,12 +358,10 @@ public class FlatProgramAPI {
long length, boolean overlay) throws Exception { long length, boolean overlay) throws Exception {
if (input == null) { if (input == null) {
return currentProgram.getMemory() return currentProgram.getMemory()
.createUninitializedBlock(name, start, length, .createUninitializedBlock(name, start, length, overlay);
overlay);
} }
return currentProgram.getMemory() return currentProgram.getMemory()
.createInitializedBlock(name, start, input, length, .createInitializedBlock(name, start, input, length, monitor, overlay);
monitor, overlay);
} }
/** /**
@ -379,8 +377,7 @@ public class FlatProgramAPI {
boolean overlay) throws Exception { boolean overlay) throws Exception {
ByteArrayInputStream input = new ByteArrayInputStream(bytes); ByteArrayInputStream input = new ByteArrayInputStream(bytes);
return currentProgram.getMemory() return currentProgram.getMemory()
.createInitializedBlock(name, start, input, bytes.length, .createInitializedBlock(name, start, input, bytes.length, monitor, overlay);
monitor, overlay);
} }
/** /**
@ -534,7 +531,7 @@ public class FlatProgramAPI {
* @return true if the PLATE comment was successfully set * @return true if the PLATE comment was successfully set
*/ */
public final boolean setPlateComment(Address address, String comment) { public final boolean setPlateComment(Address address, String comment) {
SetCommentCmd cmd = new SetCommentCmd(address, CodeUnit.PLATE_COMMENT, comment); SetCommentCmd cmd = new SetCommentCmd(address, CommentType.PLATE, comment);
return cmd.applyTo(currentProgram); return cmd.applyTo(currentProgram);
} }
@ -545,7 +542,7 @@ public class FlatProgramAPI {
* @return true if the PRE comment was successfully set * @return true if the PRE comment was successfully set
*/ */
public final boolean setPreComment(Address address, String comment) { public final boolean setPreComment(Address address, String comment) {
SetCommentCmd cmd = new SetCommentCmd(address, CodeUnit.PRE_COMMENT, comment); SetCommentCmd cmd = new SetCommentCmd(address, CommentType.PRE, comment);
return cmd.applyTo(currentProgram); return cmd.applyTo(currentProgram);
} }
@ -556,7 +553,7 @@ public class FlatProgramAPI {
* @return true if the POST comment was successfully set * @return true if the POST comment was successfully set
*/ */
public final boolean setPostComment(Address address, String comment) { public final boolean setPostComment(Address address, String comment) {
SetCommentCmd cmd = new SetCommentCmd(address, CodeUnit.POST_COMMENT, comment); SetCommentCmd cmd = new SetCommentCmd(address, CommentType.POST, comment);
return cmd.applyTo(currentProgram); return cmd.applyTo(currentProgram);
} }
@ -567,7 +564,7 @@ public class FlatProgramAPI {
* @return true if the EOL comment was successfully set * @return true if the EOL comment was successfully set
*/ */
public final boolean setEOLComment(Address address, String comment) { public final boolean setEOLComment(Address address, String comment) {
SetCommentCmd cmd = new SetCommentCmd(address, CodeUnit.EOL_COMMENT, comment); SetCommentCmd cmd = new SetCommentCmd(address, CommentType.EOL, comment);
return cmd.applyTo(currentProgram); return cmd.applyTo(currentProgram);
} }
@ -578,7 +575,7 @@ public class FlatProgramAPI {
* @return true if the repeatable comment was successfully set * @return true if the repeatable comment was successfully set
*/ */
public final boolean setRepeatableComment(Address address, String comment) { public final boolean setRepeatableComment(Address address, String comment) {
SetCommentCmd cmd = new SetCommentCmd(address, CodeUnit.REPEATABLE_COMMENT, comment); SetCommentCmd cmd = new SetCommentCmd(address, CommentType.REPEATABLE, comment);
return cmd.applyTo(currentProgram); return cmd.applyTo(currentProgram);
} }
@ -593,7 +590,7 @@ public class FlatProgramAPI {
* @see GhidraScript#getPlateCommentAsRendered(Address) * @see GhidraScript#getPlateCommentAsRendered(Address)
*/ */
public final String getPlateComment(Address address) { public final String getPlateComment(Address address) {
return currentProgram.getListing().getComment(CodeUnit.PLATE_COMMENT, address); return currentProgram.getListing().getComment(CommentType.PLATE, address);
} }
/** /**
@ -607,7 +604,7 @@ public class FlatProgramAPI {
* @see GhidraScript#getPreCommentAsRendered(Address) * @see GhidraScript#getPreCommentAsRendered(Address)
*/ */
public final String getPreComment(Address address) { public final String getPreComment(Address address) {
return currentProgram.getListing().getComment(CodeUnit.PRE_COMMENT, address); return currentProgram.getListing().getComment(CommentType.PRE, address);
} }
/** /**
@ -621,7 +618,7 @@ public class FlatProgramAPI {
* @see GhidraScript#getPostCommentAsRendered(Address) * @see GhidraScript#getPostCommentAsRendered(Address)
*/ */
public final String getPostComment(Address address) { public final String getPostComment(Address address) {
return currentProgram.getListing().getComment(CodeUnit.POST_COMMENT, address); return currentProgram.getListing().getComment(CommentType.POST, address);
} }
/** /**
@ -634,7 +631,7 @@ public class FlatProgramAPI {
* @see GhidraScript#getEOLCommentAsRendered(Address) * @see GhidraScript#getEOLCommentAsRendered(Address)
*/ */
public final String getEOLComment(Address address) { public final String getEOLComment(Address address) {
return currentProgram.getListing().getComment(CodeUnit.EOL_COMMENT, address); return currentProgram.getListing().getComment(CommentType.EOL, address);
} }
/** /**
@ -647,7 +644,7 @@ public class FlatProgramAPI {
* @see GhidraScript#getRepeatableCommentAsRendered(Address) * @see GhidraScript#getRepeatableCommentAsRendered(Address)
*/ */
public final String getRepeatableComment(Address address) { public final String getRepeatableComment(Address address) {
return currentProgram.getListing().getComment(CodeUnit.REPEATABLE_COMMENT, address); return currentProgram.getListing().getComment(CommentType.REPEATABLE, address);
} }
/** /**
@ -889,13 +886,13 @@ public class FlatProgramAPI {
Address addr = null; Address addr = null;
monitor.setMessage("Searching plate comments..."); monitor.setMessage("Searching plate comments...");
addr = findComment(CodeUnit.PLATE_COMMENT, text); addr = findComment(CommentType.PLATE, text);
if (addr != null) { if (addr != null) {
return addr; return addr;
} }
monitor.setMessage("Searching pre comments..."); monitor.setMessage("Searching pre comments...");
addr = findComment(CodeUnit.PRE_COMMENT, text); addr = findComment(CommentType.PRE, text);
if (addr != null) { if (addr != null) {
return addr; return addr;
} }
@ -944,19 +941,19 @@ public class FlatProgramAPI {
} }
monitor.setMessage("Searching eol comments..."); monitor.setMessage("Searching eol comments...");
addr = findComment(CodeUnit.EOL_COMMENT, text); addr = findComment(CommentType.EOL, text);
if (addr != null) { if (addr != null) {
return addr; return addr;
} }
monitor.setMessage("Searching repeatable comments..."); monitor.setMessage("Searching repeatable comments...");
addr = findComment(CodeUnit.REPEATABLE_COMMENT, text); addr = findComment(CommentType.REPEATABLE, text);
if (addr != null) { if (addr != null) {
return addr; return addr;
} }
monitor.setMessage("Searching post comments..."); monitor.setMessage("Searching post comments...");
addr = findComment(CodeUnit.POST_COMMENT, text); addr = findComment(CommentType.POST, text);
if (addr != null) { if (addr != null) {
return addr; return addr;
} }
@ -1934,8 +1931,7 @@ public class FlatProgramAPI {
public final Reference addInstructionXref(Address from, Address to, int opIndex, public final Reference addInstructionXref(Address from, Address to, int opIndex,
FlowType type) { FlowType type) {
return currentProgram.getReferenceManager() return currentProgram.getReferenceManager()
.addMemoryReference(from, to, type, .addMemoryReference(from, to, type, SourceType.USER_DEFINED, opIndex);
SourceType.USER_DEFINED, opIndex);
} }
/** /**
@ -2395,8 +2391,7 @@ public class FlatProgramAPI {
*/ */
public final Equate getEquate(Instruction instruction, int operandIndex, long value) { public final Equate getEquate(Instruction instruction, int operandIndex, long value) {
return currentProgram.getEquateTable() return currentProgram.getEquateTable()
.getEquate(instruction.getMinAddress(), operandIndex, .getEquate(instruction.getMinAddress(), operandIndex, value);
value);
} }
/** /**
@ -2407,8 +2402,7 @@ public class FlatProgramAPI {
*/ */
public final List<Equate> getEquates(Instruction instruction, int operandIndex) { public final List<Equate> getEquates(Instruction instruction, int operandIndex) {
return currentProgram.getEquateTable() return currentProgram.getEquateTable()
.getEquates(instruction.getMinAddress(), .getEquates(instruction.getMinAddress(), operandIndex);
operandIndex);
} }
/** /**
@ -2420,8 +2414,7 @@ public class FlatProgramAPI {
Object obj = data.getValue(); Object obj = data.getValue();
if (obj instanceof Scalar) { if (obj instanceof Scalar) {
return currentProgram.getEquateTable() return currentProgram.getEquateTable()
.getEquate(data.getMinAddress(), 0, .getEquate(data.getMinAddress(), 0, ((Scalar) obj).getValue());
((Scalar) obj).getValue());
} }
return null; return null;
} }
@ -2634,7 +2627,7 @@ public class FlatProgramAPI {
return folder; return folder;
} }
private Address findComment(int type, String text) { private Address findComment(CommentType type, String text) {
Listing listing = currentProgram.getListing(); Listing listing = currentProgram.getListing();
Memory memory = currentProgram.getMemory(); Memory memory = currentProgram.getMemory();
AddressIterator iter = listing.getCommentAddressIterator(type, memory, true); AddressIterator iter = listing.getCommentAddressIterator(type, memory, true);

View file

@ -133,7 +133,7 @@ public class CodeUnitFormat {
stringBuffer.append(getOperandRepresentationString(cu, 0)); stringBuffer.append(getOperandRepresentationString(cu, 0));
} }
if (includeEOLcomment) { if (includeEOLcomment) {
String eolComment = cu.getComment(CodeUnit.EOL_COMMENT); String eolComment = cu.getComment(CommentType.EOL);
if (eolComment != null) { if (eolComment != null) {
// fixup annotations // fixup annotations
eolComment = CommentUtils.getDisplayString(eolComment, cu.getProgram()); eolComment = CommentUtils.getDisplayString(eolComment, cu.getProgram());

View file

@ -643,32 +643,32 @@ public class ProgramDiff {
case ProgramDiffFilter.EOL_COMMENT_DIFFS: case ProgramDiffFilter.EOL_COMMENT_DIFFS:
monitorMsg = "Checking End of Line Comment Differences"; monitorMsg = "Checking End of Line Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.EOL_COMMENT, addrs, as = getCommentDiffs(CommentType.EOL, addrs,
new CommentTypeComparator(CodeUnit.EOL_COMMENT), monitor); new CommentTypeComparator(CommentType.EOL), monitor);
break; break;
case ProgramDiffFilter.REPEATABLE_COMMENT_DIFFS: case ProgramDiffFilter.REPEATABLE_COMMENT_DIFFS:
monitorMsg = "Checking Repeatable Comment Differences"; monitorMsg = "Checking Repeatable Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.REPEATABLE_COMMENT, addrs, as = getCommentDiffs(CommentType.REPEATABLE, addrs,
new CommentTypeComparator(CodeUnit.REPEATABLE_COMMENT), monitor); new CommentTypeComparator(CommentType.REPEATABLE), monitor);
break; break;
case ProgramDiffFilter.PRE_COMMENT_DIFFS: case ProgramDiffFilter.PRE_COMMENT_DIFFS:
monitorMsg = "Checking Pre-Comment Differences"; monitorMsg = "Checking Pre-Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.PRE_COMMENT, addrs, as = getCommentDiffs(CommentType.PRE, addrs,
new CommentTypeComparator(CodeUnit.PRE_COMMENT), monitor); new CommentTypeComparator(CommentType.PRE), monitor);
break; break;
case ProgramDiffFilter.POST_COMMENT_DIFFS: case ProgramDiffFilter.POST_COMMENT_DIFFS:
monitorMsg = "Checking Post-Comment Differences"; monitorMsg = "Checking Post-Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.POST_COMMENT, addrs, as = getCommentDiffs(CommentType.POST, addrs,
new CommentTypeComparator(CodeUnit.POST_COMMENT), monitor); new CommentTypeComparator(CommentType.POST), monitor);
break; break;
case ProgramDiffFilter.PLATE_COMMENT_DIFFS: case ProgramDiffFilter.PLATE_COMMENT_DIFFS:
monitorMsg = "Checking Plate Comment Differences"; monitorMsg = "Checking Plate Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.PLATE_COMMENT, addrs, as = getCommentDiffs(CommentType.PLATE, addrs,
new CommentTypeComparator(CodeUnit.PLATE_COMMENT), monitor); new CommentTypeComparator(CommentType.PLATE), monitor);
break; break;
case ProgramDiffFilter.REFERENCE_DIFFS: case ProgramDiffFilter.REFERENCE_DIFFS:
monitorMsg = "Checking Reference Differences"; monitorMsg = "Checking Reference Differences";
@ -926,32 +926,32 @@ public class ProgramDiff {
case ProgramDiffFilter.EOL_COMMENT_DIFFS: case ProgramDiffFilter.EOL_COMMENT_DIFFS:
monitorMsg = "Checking End of Line Comment Differences"; monitorMsg = "Checking End of Line Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.EOL_COMMENT, checkAddressSet, as = getCommentDiffs(CommentType.EOL, checkAddressSet,
new CommentTypeComparator(CodeUnit.EOL_COMMENT), monitor); new CommentTypeComparator(CommentType.EOL), monitor);
break; break;
case ProgramDiffFilter.REPEATABLE_COMMENT_DIFFS: case ProgramDiffFilter.REPEATABLE_COMMENT_DIFFS:
monitorMsg = "Checking Repeatable Comment Differences"; monitorMsg = "Checking Repeatable Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.REPEATABLE_COMMENT, checkAddressSet, as = getCommentDiffs(CommentType.REPEATABLE, checkAddressSet,
new CommentTypeComparator(CodeUnit.REPEATABLE_COMMENT), monitor); new CommentTypeComparator(CommentType.REPEATABLE), monitor);
break; break;
case ProgramDiffFilter.PRE_COMMENT_DIFFS: case ProgramDiffFilter.PRE_COMMENT_DIFFS:
monitorMsg = "Checking Pre-Comment Differences"; monitorMsg = "Checking Pre-Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.PRE_COMMENT, checkAddressSet, as = getCommentDiffs(CommentType.PRE, checkAddressSet,
new CommentTypeComparator(CodeUnit.PRE_COMMENT), monitor); new CommentTypeComparator(CommentType.PRE), monitor);
break; break;
case ProgramDiffFilter.POST_COMMENT_DIFFS: case ProgramDiffFilter.POST_COMMENT_DIFFS:
monitorMsg = "Checking Post-Comment Differences"; monitorMsg = "Checking Post-Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.POST_COMMENT, checkAddressSet, as = getCommentDiffs(CommentType.POST, checkAddressSet,
new CommentTypeComparator(CodeUnit.POST_COMMENT), monitor); new CommentTypeComparator(CommentType.POST), monitor);
break; break;
case ProgramDiffFilter.PLATE_COMMENT_DIFFS: case ProgramDiffFilter.PLATE_COMMENT_DIFFS:
monitorMsg = "Checking Plate Comment Differences"; monitorMsg = "Checking Plate Comment Differences";
monitor.setMessage(monitorMsg); monitor.setMessage(monitorMsg);
as = getCommentDiffs(CodeUnit.PLATE_COMMENT, checkAddressSet, as = getCommentDiffs(CommentType.PLATE, checkAddressSet,
new CommentTypeComparator(CodeUnit.PLATE_COMMENT), monitor); new CommentTypeComparator(CommentType.PLATE), monitor);
break; break;
case ProgramDiffFilter.REFERENCE_DIFFS: case ProgramDiffFilter.REFERENCE_DIFFS:
monitorMsg = "Checking Reference Differences"; monitorMsg = "Checking Reference Differences";
@ -1773,7 +1773,7 @@ public class ProgramDiff {
* Determines the code unit addresses where there are differences of the * Determines the code unit addresses where there are differences of the
* indicated type between program1 and program2. * indicated type between program1 and program2.
* @param cuiType the type of difference on the code unit. These are defined * @param cuiType the type of difference on the code unit. These are defined
* in <CODE>CodeUnit</CODE>. (i.e. CodeUnit.EOL_COMMENT_PROPERTY). * in <CODE>CodeUnit</CODE>. (i.e. CommentType.EOL_PROPERTY).
* @param addressSet the addresses to check for differences. * @param addressSet the addresses to check for differences.
* The addresses in this address set should be derived from program1. * The addresses in this address set should be derived from program1.
* @param c the comparator to use for determining where the differences are. * @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 * Determines the code unit addresses where there are comment differences of the
* indicated type between program1 and program2. * indicated type between program1 and program2.
* @param commentType the type of comment. These are defined * @param commentType the type of comment. These are defined
* in <CODE>CodeUnit</CODE>. (i.e. CodeUnit.EOL_COMMENT). * in <CODE>CodeUnit</CODE>. (i.e. CommentType.EOL).
* @param addressSet the addresses to check for differences. * @param addressSet the addresses to check for differences.
* The addresses in this address set should be derived from program1. * The addresses in this address set should be derived from program1.
* @param c the comparator to use for determining where the differences are. * @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. * The addresses in this address set are derived from program1.
* @throws CancelledException if the user cancelled the Diff. * @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 { CommentTypeComparator c, TaskMonitor monitor) throws CancelledException {
AddressIterator iter1 = listing1.getCommentAddressIterator(commentType, addressSet, true); AddressIterator iter1 = listing1.getCommentAddressIterator(commentType, addressSet, true);
AddressSet addressSet2 = DiffUtility.getCompatibleAddressSet(addressSet, program2); AddressSet addressSet2 = DiffUtility.getCompatibleAddressSet(addressSet, program2);
@ -2638,13 +2638,13 @@ public class ProgramDiff {
private class CommentTypeComparator extends ProgramDiffComparatorImpl<Address> { private class CommentTypeComparator extends ProgramDiffComparatorImpl<Address> {
/** /**
* the type of comment to compare * the type of comment to compare
* <br>CodeUnit.PLATE_COMMENT * <br>CommentType.PLATE
* <br>CodeUnit.PRE_COMMENT * <br>CommentType.PRE
* <br>CodeUnit.EOL_COMMENT * <br>CommentType.EOL
* <br>CodeUnit.REPEATABLE_COMMENT * <br>CommentType.REPEATABLE
* <br>CodeUnit.POST_COMMENT * <br>CommentType.POST
*/ */
int type; CommentType type;
private Listing comparatorListing1; private Listing comparatorListing1;
private Listing comparatorListing2; private Listing comparatorListing2;
@ -2652,7 +2652,7 @@ public class ProgramDiff {
* Generic constructor for comparing program differences. * Generic constructor for comparing program differences.
* @param type the comment type * @param type the comment type
*/ */
private CommentTypeComparator(int type) { private CommentTypeComparator(CommentType type) {
this.type = type; this.type = type;
comparatorListing1 = program1.getListing(); comparatorListing1 = program1.getListing();
comparatorListing2 = program2.getListing(); comparatorListing2 = program2.getListing();

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -1398,19 +1398,19 @@ public class ProgramDiffDetails {
} }
private void addEOLCommentDetails() { private void addEOLCommentDetails() {
hasEolCommentDiffs = addSpecificCommentDetails(CodeUnit.EOL_COMMENT, "EOL-Comment"); hasEolCommentDiffs = addSpecificCommentDetails(CommentType.EOL, "EOL-Comment");
} }
private void addPreCommentDetails() { private void addPreCommentDetails() {
hasPreCommentDiffs = addSpecificCommentDetails(CodeUnit.PRE_COMMENT, "Pre-Comment"); hasPreCommentDiffs = addSpecificCommentDetails(CommentType.PRE, "Pre-Comment");
} }
private void addPostCommentDetails() { private void addPostCommentDetails() {
hasPostCommentDiffs = addSpecificCommentDetails(CodeUnit.POST_COMMENT, "Post-Comment"); hasPostCommentDiffs = addSpecificCommentDetails(CommentType.POST, "Post-Comment");
} }
private void addPlateCommentDetails() { 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() { private void addRepeatableCommentDetails() {
hasRepeatableCommentDiffs = hasRepeatableCommentDiffs =
addSpecificCommentDetails(CodeUnit.REPEATABLE_COMMENT, "Repeatable-Comment"); addSpecificCommentDetails(CommentType.REPEATABLE, "Repeatable-Comment");
} }
/** /**
@ -1490,7 +1490,7 @@ public class ProgramDiffDetails {
return retString; return retString;
} }
private boolean addSpecificCommentDetails(int commentType, String commentName) { private boolean addSpecificCommentDetails(CommentType commentType, String commentName) {
boolean hasCommentDiff = false; boolean hasCommentDiff = false;
try { try {
for (Address p1Address = minP1Address; p1Address for (Address p1Address = minP1Address; p1Address

View file

@ -1546,30 +1546,30 @@ public class ProgramMerge {
} }
String typeStr = "Unknown"; String typeStr = "Unknown";
int cuCommentType; CommentType cuCommentType;
switch (type) { switch (type) {
case ProgramMergeFilter.PLATE_COMMENTS: case ProgramMergeFilter.PLATE_COMMENTS:
typeStr = "Plate"; typeStr = "Plate";
cuCommentType = CodeUnit.PLATE_COMMENT; cuCommentType = CommentType.PLATE;
break; break;
case ProgramMergeFilter.PRE_COMMENTS: case ProgramMergeFilter.PRE_COMMENTS:
typeStr = "Pre"; typeStr = "Pre";
cuCommentType = CodeUnit.PRE_COMMENT; cuCommentType = CommentType.PRE;
break; break;
case ProgramMergeFilter.EOL_COMMENTS: case ProgramMergeFilter.EOL_COMMENTS:
typeStr = "EOL"; typeStr = "EOL";
cuCommentType = CodeUnit.EOL_COMMENT; cuCommentType = CommentType.EOL;
break; break;
case ProgramMergeFilter.REPEATABLE_COMMENTS: case ProgramMergeFilter.REPEATABLE_COMMENTS:
typeStr = "Repeatable"; typeStr = "Repeatable";
cuCommentType = CodeUnit.REPEATABLE_COMMENT; cuCommentType = CommentType.REPEATABLE;
break; break;
case ProgramMergeFilter.POST_COMMENTS: case ProgramMergeFilter.POST_COMMENTS:
typeStr = "Post"; typeStr = "Post";
cuCommentType = CodeUnit.POST_COMMENT; cuCommentType = CommentType.POST;
break; break;
default: default:
throw new AssertException("Unrecognized comment type: " + type); throw new AssertException("Unsupported comment type: " + type);
} }
monitor.setMessage("Applying " + typeStr + " comments..."); monitor.setMessage("Applying " + typeStr + " comments...");
@ -1604,11 +1604,11 @@ public class ProgramMerge {
* <CODE>mergeComments</CODE> merges the comment of the indicated * <CODE>mergeComments</CODE> merges the comment of the indicated
* type in program1 with the comment in program2 at the specified address. * type in program1 with the comment in program2 at the specified address.
* @param commentType comment type to merge (from CodeUnit class). * @param commentType comment type to merge (from CodeUnit class).
* <br>EOL_COMMENT, PRE_COMMENT, POST_COMMENT, REPEATABLE_COMMENT, OR PLATE_COMMENT. * <br>EOL, PRE, POST, REPEATABLE, OR PLATE.
* @param originAddress the address * @param originAddress the address
* This address should be derived from the origin program. * 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); Address resultAddress = originToResultTranslator.getAddress(originAddress);
String resultComment = resultListing.getComment(commentType, resultAddress); String resultComment = resultListing.getComment(commentType, resultAddress);
String origComment = originListing.getComment(commentType, originAddress); String origComment = originListing.getComment(commentType, originAddress);
@ -1620,11 +1620,11 @@ public class ProgramMerge {
* <CODE>replaceComment</CODE> replaces the comment of the indicated * <CODE>replaceComment</CODE> replaces the comment of the indicated
* type in program1 with the comment in program2 at the specified address. * type in program1 with the comment in program2 at the specified address.
* @param commentType comment type to replace (from CodeUnit class). * @param commentType comment type to replace (from CodeUnit class).
* <br>EOL_COMMENT, PRE_COMMENT, POST_COMMENT, REPEATABLE_COMMENT, OR PLATE_COMMENT. * <br>EOL, PRE, POST, REPEATABLE, OR PLATE.
* @param originAddress the address * @param originAddress the address
* This address should be derived from the origin program. * 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); Address resultAddress = originToResultTranslator.getAddress(originAddress);
String origComment = originListing.getComment(commentType, originAddress); String origComment = originListing.getComment(commentType, originAddress);
resultListing.setComment(resultAddress, commentType, origComment); resultListing.setComment(resultAddress, commentType, origComment);

View file

@ -234,7 +234,7 @@ public class ClassicSampleX86ProgramBuilder extends ProgramBuilder {
// //
// Comments // Comments
// //
createComment("0x0100415a", "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); createComment("0x0100415a", "Repeatable Comment", CommentType.REPEATABLE);
// //
// References // References

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -18,7 +18,7 @@ package ghidra.util.table.field;
import ghidra.docking.settings.Settings; import ghidra.docking.settings.Settings;
import ghidra.framework.plugintool.ServiceProvider; import ghidra.framework.plugintool.ServiceProvider;
import ghidra.program.model.address.Address; 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.model.listing.Program;
import ghidra.program.util.*; import ghidra.program.util.*;
@ -26,8 +26,8 @@ import ghidra.program.util.*;
* This table column displays the Label for either the program location or the address * This table column displays the Label for either the program location or the address
* associated with a row in the table. * associated with a row in the table.
*/ */
public class EOLCommentTableColumn extends public class EOLCommentTableColumn
ProgramLocationTableColumnExtensionPoint<ProgramLocation, String> { extends ProgramLocationTableColumnExtensionPoint<ProgramLocation, String> {
@Override @Override
public ProgramLocation getProgramLocation(ProgramLocation rowObject, Settings settings, public ProgramLocation getProgramLocation(ProgramLocation rowObject, Settings settings,
@ -35,7 +35,8 @@ public class EOLCommentTableColumn extends
String comment = getEOLComment(rowObject, program); String comment = getEOLComment(rowObject, program);
if (comment != null) { 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; return rowObject;
} }
@ -58,6 +59,6 @@ public class EOLCommentTableColumn extends
return null; return null;
} }
Address address = location.getAddress(); Address address = location.getAddress();
return program.getListing().getComment(CodeUnit.EOL_COMMENT, address); return program.getListing().getComment(CommentType.EOL, address);
} }
} }

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.Address;
import ghidra.program.model.address.AddressSet; import ghidra.program.model.address.AddressSet;
import ghidra.program.model.data.*; 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.listing.Instruction;
import ghidra.program.model.mem.*; import ghidra.program.model.mem.*;
import ghidra.program.model.symbol.SourceType; import ghidra.program.model.symbol.SourceType;
@ -46,8 +46,8 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
super(); super();
} }
@Test @Test
public void testAddLatestInstr() throws Exception { public void testAddLatestInstr() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -64,12 +64,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
executeMerge(ASK_USER); executeMerge(ASK_USER);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013e1"))); new AddressSet(addr("0x10013d9"), addr("0x10013e1")));
} }
@Test @Test
public void testAddMyInstr() throws Exception { public void testAddMyInstr() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -86,12 +86,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
executeMerge(ASK_USER); executeMerge(ASK_USER);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, myProgram,
addr("0x10013e1"))); new AddressSet(addr("0x10013d9"), addr("0x10013e1")));
} }
@Test @Test
public void testAddLatestData() throws Exception { public void testAddLatestData() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -108,12 +108,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
executeMerge(ASK_USER); executeMerge(ASK_USER);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013da"))); new AddressSet(addr("0x10013d9"), addr("0x10013da")));
} }
@Test @Test
public void testAddMyData() throws Exception { public void testAddMyData() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -130,12 +130,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
executeMerge(ASK_USER); executeMerge(ASK_USER);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, myProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testAddLatestInstrMyDataPickLatest() throws Exception { public void testAddLatestInstrMyDataPickLatest() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -153,12 +153,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_LATEST); chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_LATEST);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testAddLatestInstrMyDataPickMy() throws Exception { public void testAddLatestInstrMyDataPickMy() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -176,12 +176,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_MY); chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_MY);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, myProgram,
addr("0x10013e4"))); new AddressSet(addr("0x10013d9"), addr("0x10013e4")));
} }
@Test @Test
public void testAddLatestInstrMyDataPickOrig() throws Exception { public void testAddLatestInstrMyDataPickOrig() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -199,12 +199,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_ORIGINAL); chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_ORIGINAL);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, originalProgram,
addr("0x10013e4"))); new AddressSet(addr("0x10013d9"), addr("0x10013e4")));
} }
@Test @Test
public void testAddLatestDataMyInstrPickLatest() throws Exception { public void testAddLatestDataMyInstrPickLatest() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -222,14 +222,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_LATEST); chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_LATEST);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013e4"))); new AddressSet(addr("0x10013d9"), addr("0x10013e4")));
} }
@Test @Test
public void testAddLatestDataMyInstrPickMy() throws Exception { public void testAddLatestDataMyInstrPickMy() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
createData(program, "0x10013d9", new DWordDataType()); createData(program, "0x10013d9", new DWordDataType());
@ -245,14 +245,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_MY); chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_MY);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, myProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testAddLatestDataMyInstrPickOrig() throws Exception { public void testAddLatestDataMyInstrPickOrig() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
createData(program, "0x10013d9", new TerminatedStringDataType()); createData(program, "0x10013d9", new TerminatedStringDataType());
@ -268,14 +268,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_ORIGINAL); chooseCodeUnit("0x10013d9", "0x10013e4", KEEP_ORIGINAL);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, originalProgram,
addr("0x10013e4"))); new AddressSet(addr("0x10013d9"), addr("0x10013e4")));
} }
@Test @Test
public void testAddLatestInstrMyInstrPickLatest() throws Exception { public void testAddLatestInstrMyInstrPickLatest() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
disassemble(program, "0x10013d9", "0x10013e1"); disassemble(program, "0x10013d9", "0x10013e1");
@ -291,12 +291,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_LATEST); chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_LATEST);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013e2"))); new AddressSet(addr("0x10013d9"), addr("0x10013e2")));
} }
@Test @Test
public void testAddLatestInstrMyInstrPickMy() throws Exception { public void testAddLatestInstrMyInstrPickMy() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -314,12 +314,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_MY); chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_MY);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, myProgram,
addr("0x10013e2"))); new AddressSet(addr("0x10013d9"), addr("0x10013e2")));
} }
@Test @Test
public void testAddLatestInstrMyInstrPickOrig() throws Exception { public void testAddLatestInstrMyInstrPickOrig() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
@ -337,14 +337,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_ORIGINAL); chooseCodeUnit("0x10013d9", "0x10013e2", KEEP_ORIGINAL);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, originalProgram,
addr("0x10013e2"))); new AddressSet(addr("0x10013d9"), addr("0x10013e2")));
} }
@Test @Test
public void testAddLatestDataMyDataPickLatest() throws Exception { public void testAddLatestDataMyDataPickLatest() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
createData(program, "0x10013d9", new WordDataType()); createData(program, "0x10013d9", new WordDataType());
@ -360,14 +360,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_LATEST); chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_LATEST);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testAddLatestDataMyDataPickMy() throws Exception { public void testAddLatestDataMyDataPickMy() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
createData(program, "0x10013d9", new WordDataType()); createData(program, "0x10013d9", new WordDataType());
@ -383,14 +383,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_MY); chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_MY);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, myProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, myProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testAddLatestDataMyDataPickOrig() throws Exception { public void testAddLatestDataMyDataPickOrig() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
createData(program, "0x10013d9", new WordDataType()); createData(program, "0x10013d9", new WordDataType());
@ -406,12 +406,12 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_ORIGINAL); chooseCodeUnit("0x10013d9", "0x10013dc", KEEP_ORIGINAL);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, originalProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, originalProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testSameInstrLatestMy() throws Exception { public void testSameInstrLatestMy() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
@ -427,14 +427,14 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
executeMerge(ASK_USER); executeMerge(ASK_USER);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013e1"))); new AddressSet(addr("0x10013d9"), addr("0x10013e1")));
} }
@Test @Test
public void testSameDataLatestMy() throws Exception { public void testSameDataLatestMy() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
createData(program, "0x10013d9", new DWordDataType()); createData(program, "0x10013d9", new DWordDataType());
@ -449,34 +449,38 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
executeMerge(ASK_USER); executeMerge(ASK_USER);
waitForMergeCompletion(); waitForMergeCompletion();
assertSameCodeUnits(resultProgram, latestProgram, new AddressSet(addr("0x10013d9"), assertSameCodeUnits(resultProgram, latestProgram,
addr("0x10013dc"))); new AddressSet(addr("0x10013d9"), addr("0x10013dc")));
} }
@Test @Test
public void testMergeCodeUnitsOriginal() throws Exception { public void testMergeCodeUnitsOriginal() throws Exception {
mtf.initialize("notepad", new ProgramModifierListener() { mtf.initialize("notepad", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
try { try {
// Clear Code Units from 1002312 to 1002320 // Clear Code Units from 1002312 to 1002320
program.getListing().clearCodeUnits(addr(program, "0x1002312"), program.getListing()
addr(program, "0x1002320"), false); .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"),
false);
// Clear Code Units from 1002390 to 1002394 // Clear Code Units from 1002390 to 1002394
program.getListing().clearCodeUnits(addr(program, "0x1002390"), program.getListing()
addr(program, "0x1002394"), false); .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"),
false);
// Put a label @ from 10023be-10023c2 to create a conflict with the code unit. // Put a label @ from 10023be-10023c2 to create a conflict with the code unit.
program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", program.getSymbolTable()
SourceType.USER_DEFINED); .createLabel(addr(program, "0x10023be"), "LabelABC",
SourceType.USER_DEFINED);
// Put an Ascii at 10080d0 // Put an Ascii at 10080d0
program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); program.getListing().createData(addr(program, "0x10080d0"), new CharDataType());
// Put a Float at 10080db // 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(); Memory mem = program.getMemory();
MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); MemoryBlock block = mem.getBlock(addr(program, "0x1001000"));
@ -503,17 +507,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
public void modifyPrivate(ProgramDB program) { public void modifyPrivate(ProgramDB program) {
try { try {
// Clear Code Units from 100231d to 1002328 // Clear Code Units from 100231d to 1002328
program.getListing().clearCodeUnits(addr(program, "0x100231d"), program.getListing()
addr(program, "0x1002328"), false); .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"),
assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); false);
assertTrue(!(program.getListing()
.getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction));
// Put a comment @ 1002390-1002394 to create a conflict with the code unit. // Put a comment @ 1002390-1002394 to create a conflict with the code unit.
program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( program.getListing()
CodeUnit.EOL_COMMENT, "EOL comment"); .getCodeUnitAt(addr(program, "0x1002390"))
.setComment(CommentType.EOL, "EOL comment");
// Clear Code Units from 10023be to 10023c2 // Clear Code Units from 10023be to 10023c2
program.getListing().clearCodeUnits(addr(program, "0x10023be"), program.getListing()
addr(program, "0x10023c2"), false); .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"),
false);
// Put a structure at 10080d0 to 10080d3 // Put a structure at 10080d0 to 10080d3
StructureDataType struct = new StructureDataType("Item", 4); StructureDataType struct = new StructureDataType("Item", 4);
@ -524,8 +532,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); program.getListing().createData(addr(program, "0x10080e2"), new WordDataType());
// Clear Code Units from 100652a to 100652a // Clear Code Units from 100652a to 100652a
program.getListing().clearCodeUnits(addr(program, "0x100652a"), program.getListing()
addr(program, "0x100652a"), false); .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"),
false);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
e.printStackTrace(); e.printStackTrace();
@ -556,30 +565,34 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
assertSameCodeUnits(resultProgram, latestProgram, latestAddrs); assertSameCodeUnits(resultProgram, latestProgram, latestAddrs);
} }
@Test @Test
public void testMergeCodeUnitsLatest() throws Exception { public void testMergeCodeUnitsLatest() throws Exception {
mtf.initialize("notepad", new ProgramModifierListener() { mtf.initialize("notepad", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
try { try {
// Clear Code Units from 1002312 to 1002320 // Clear Code Units from 1002312 to 1002320
program.getListing().clearCodeUnits(addr(program, "0x1002312"), program.getListing()
addr(program, "0x1002320"), false); .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"),
false);
// Clear Code Units from 1002390 to 1002394 // Clear Code Units from 1002390 to 1002394
program.getListing().clearCodeUnits(addr(program, "0x1002390"), program.getListing()
addr(program, "0x1002394"), false); .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"),
false);
// Put a label @ from 10023be-10023c2 to create a conflict with the code unit. // Put a label @ from 10023be-10023c2 to create a conflict with the code unit.
program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", program.getSymbolTable()
SourceType.USER_DEFINED); .createLabel(addr(program, "0x10023be"), "LabelABC",
SourceType.USER_DEFINED);
// Put an Ascii at 10080d0 // Put an Ascii at 10080d0
program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); program.getListing().createData(addr(program, "0x10080d0"), new CharDataType());
// Put a Float at 10080db // 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(); Memory mem = program.getMemory();
MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); MemoryBlock block = mem.getBlock(addr(program, "0x1001000"));
@ -606,17 +619,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
public void modifyPrivate(ProgramDB program) { public void modifyPrivate(ProgramDB program) {
try { try {
// Clear Code Units from 100231d to 1002328 // Clear Code Units from 100231d to 1002328
program.getListing().clearCodeUnits(addr(program, "0x100231d"), program.getListing()
addr(program, "0x1002328"), false); .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"),
assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); false);
assertTrue(!(program.getListing()
.getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction));
// Put a comment @ 1002390-1002394 to create a conflict with the code unit. // Put a comment @ 1002390-1002394 to create a conflict with the code unit.
program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( program.getListing()
CodeUnit.EOL_COMMENT, "EOL comment"); .getCodeUnitAt(addr(program, "0x1002390"))
.setComment(CommentType.EOL, "EOL comment");
// Clear Code Units from 10023be to 10023c2 // Clear Code Units from 10023be to 10023c2
program.getListing().clearCodeUnits(addr(program, "0x10023be"), program.getListing()
addr(program, "0x10023c2"), false); .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"),
false);
// Put a structure at 10080d0 to 10080d3 // Put a structure at 10080d0 to 10080d3
StructureDataType struct = new StructureDataType("Item", 4); StructureDataType struct = new StructureDataType("Item", 4);
@ -627,8 +644,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); program.getListing().createData(addr(program, "0x10080e2"), new WordDataType());
// Clear Code Units from 100652a to 100652a // Clear Code Units from 100652a to 100652a
program.getListing().clearCodeUnits(addr(program, "0x100652a"), program.getListing()
addr(program, "0x100652a"), false); .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"),
false);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
@ -654,30 +672,34 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
} }
@Test @Test
public void testMergeCodeUnitsMine() throws Exception { public void testMergeCodeUnitsMine() throws Exception {
mtf.initialize("notepad", new ProgramModifierListener() { mtf.initialize("notepad", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
try { try {
// Clear Code Units from 1002312 to 1002320 // Clear Code Units from 1002312 to 1002320
program.getListing().clearCodeUnits(addr(program, "0x1002312"), program.getListing()
addr(program, "0x1002320"), false); .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"),
false);
// Clear Code Units from 1002390 to 1002394 // Clear Code Units from 1002390 to 1002394
program.getListing().clearCodeUnits(addr(program, "0x1002390"), program.getListing()
addr(program, "0x1002394"), false); .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"),
false);
// Put a label @ from 10023be-10023c2 to create a conflict with the code unit. // Put a label @ from 10023be-10023c2 to create a conflict with the code unit.
program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", program.getSymbolTable()
SourceType.USER_DEFINED); .createLabel(addr(program, "0x10023be"), "LabelABC",
SourceType.USER_DEFINED);
// Put an Ascii at 10080d0 // Put an Ascii at 10080d0
program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); program.getListing().createData(addr(program, "0x10080d0"), new CharDataType());
// Put a Float at 10080db // 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(); Memory mem = program.getMemory();
MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); MemoryBlock block = mem.getBlock(addr(program, "0x1001000"));
@ -704,17 +726,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
public void modifyPrivate(ProgramDB program) { public void modifyPrivate(ProgramDB program) {
try { try {
// Clear Code Units from 100231d to 1002328 // Clear Code Units from 100231d to 1002328
program.getListing().clearCodeUnits(addr(program, "0x100231d"), program.getListing()
addr(program, "0x1002328"), false); .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"),
assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); false);
assertTrue(!(program.getListing()
.getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction));
// Put a comment @ 1002390-1002394 to create a conflict with the code unit. // Put a comment @ 1002390-1002394 to create a conflict with the code unit.
program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( program.getListing()
CodeUnit.EOL_COMMENT, "EOL comment"); .getCodeUnitAt(addr(program, "0x1002390"))
.setComment(CommentType.EOL, "EOL comment");
// Clear Code Units from 10023be to 10023c2 // Clear Code Units from 10023be to 10023c2
program.getListing().clearCodeUnits(addr(program, "0x10023be"), program.getListing()
addr(program, "0x10023c2"), false); .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"),
false);
// Put a structure at 10080d0 to 10080d3 // Put a structure at 10080d0 to 10080d3
StructureDataType struct = new StructureDataType("Item", 4); StructureDataType struct = new StructureDataType("Item", 4);
@ -725,8 +751,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); program.getListing().createData(addr(program, "0x10080e2"), new WordDataType());
// Clear Code Units from 100652a to 100652a // Clear Code Units from 100652a to 100652a
program.getListing().clearCodeUnits(addr(program, "0x100652a"), program.getListing()
addr(program, "0x100652a"), false); .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"),
false);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
e.printStackTrace(); e.printStackTrace();
@ -755,8 +782,8 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
assertSameCodeUnits(resultProgram, latestProgram, latestAddrs); assertSameCodeUnits(resultProgram, latestProgram, latestAddrs);
} }
@Test @Test
public void testMergeCodeUnitsUseForAllPickLatest() throws Exception { public void testMergeCodeUnitsUseForAllPickLatest() throws Exception {
setupUseForAll(); setupUseForAll();
executeMerge(ASK_USER); // auto set is [0100231d, 01002328] [010023be, 010023c2] [010080e2, 010080e3] 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 { private void setupUseForAll() throws Exception {
mtf.initialize("DiffTestPgm1", new ProgramModifierListener() { mtf.initialize("DiffTestPgm1", new ProgramModifierListener() {
@Override @Override
public void modifyLatest(ProgramDB program) { public void modifyLatest(ProgramDB program) {
try { try {
// Clear Code Units from 1002312 to 1002320 // Clear Code Units from 1002312 to 1002320
program.getListing().clearCodeUnits(addr(program, "0x1002312"), program.getListing()
addr(program, "0x1002320"), false); .clearCodeUnits(addr(program, "0x1002312"), addr(program, "0x1002320"),
false);
// Clear Code Units from 1002390 to 1002394 // Clear Code Units from 1002390 to 1002394
program.getListing().clearCodeUnits(addr(program, "0x1002390"), program.getListing()
addr(program, "0x1002394"), false); .clearCodeUnits(addr(program, "0x1002390"), addr(program, "0x1002394"),
false);
// Put a label @ from 10023be-10023c2 to create a conflict with the code unit. // Put a label @ from 10023be-10023c2 to create a conflict with the code unit.
program.getSymbolTable().createLabel(addr(program, "0x10023be"), "LabelABC", program.getSymbolTable()
SourceType.USER_DEFINED); .createLabel(addr(program, "0x10023be"), "LabelABC",
SourceType.USER_DEFINED);
// Put an Ascii at 10080d0 // Put an Ascii at 10080d0
program.getListing().createData(addr(program, "0x10080d0"), new CharDataType()); program.getListing().createData(addr(program, "0x10080d0"), new CharDataType());
// Put a Float at 10080db // 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(); Memory mem = program.getMemory();
MemoryBlock block = mem.getBlock(addr(program, "0x1001000")); MemoryBlock block = mem.getBlock(addr(program, "0x1001000"));
@ -825,17 +856,21 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
public void modifyPrivate(ProgramDB program) { public void modifyPrivate(ProgramDB program) {
try { try {
// Clear Code Units from 100231d to 1002328 // Clear Code Units from 100231d to 1002328
program.getListing().clearCodeUnits(addr(program, "0x100231d"), program.getListing()
addr(program, "0x1002328"), false); .clearCodeUnits(addr(program, "0x100231d"), addr(program, "0x1002328"),
assertTrue(!(program.getListing().getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction)); false);
assertTrue(!(program.getListing()
.getCodeUnitAt(addr(program, "0x1002328")) instanceof Instruction));
// Put a comment @ 1002390-1002394 to create a conflict with the code unit. // Put a comment @ 1002390-1002394 to create a conflict with the code unit.
program.getListing().getCodeUnitAt(addr(program, "0x1002390")).setComment( program.getListing()
CodeUnit.EOL_COMMENT, "EOL comment"); .getCodeUnitAt(addr(program, "0x1002390"))
.setComment(CommentType.EOL, "EOL comment");
// Clear Code Units from 10023be to 10023c2 // Clear Code Units from 10023be to 10023c2
program.getListing().clearCodeUnits(addr(program, "0x10023be"), program.getListing()
addr(program, "0x10023c2"), false); .clearCodeUnits(addr(program, "0x10023be"), addr(program, "0x10023c2"),
false);
// Put a structure at 10080d0 to 10080d3 // Put a structure at 10080d0 to 10080d3
StructureDataType struct = new StructureDataType("Item", 4); StructureDataType struct = new StructureDataType("Item", 4);
@ -846,8 +881,9 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
program.getListing().createData(addr(program, "0x10080e2"), new WordDataType()); program.getListing().createData(addr(program, "0x10080e2"), new WordDataType());
// Clear Code Units from 100652a to 100652a // Clear Code Units from 100652a to 100652a
program.getListing().clearCodeUnits(addr(program, "0x100652a"), program.getListing()
addr(program, "0x100652a"), false); .clearCodeUnits(addr(program, "0x100652a"), addr(program, "0x100652a"),
false);
} }
catch (CodeUnitInsertionException e) { catch (CodeUnitInsertionException e) {
e.printStackTrace(); e.printStackTrace();
@ -856,8 +892,8 @@ public class CodeUnitMergeManager1Test extends AbstractListingMergeManagerTest {
}); });
} }
@Test @Test
public void testMergeCodeUnitsUseForAllPickMine() throws Exception { public void testMergeCodeUnitsUseForAllPickMine() throws Exception {
setupUseForAll(); setupUseForAll();
executeMerge(ASK_USER); executeMerge(ASK_USER);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -77,13 +77,13 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
builder.createLabel("0x31b", "RSTOR()"); builder.createLabel("0x31b", "RSTOR()");
builder.addBytesFallthrough("0x0326"); builder.addBytesFallthrough("0x0326");
builder.createComment("0x0326", "Hey There", CodeUnit.EOL_COMMENT); builder.createComment("0x0326", "Hey There", CommentType.EOL);
builder.createComment("0x0182", "SAVE register 'I'", CodeUnit.EOL_COMMENT); builder.createComment("0x0182", "SAVE register 'I'", CommentType.EOL);
builder.createComment("0x0334", "Set the SP to RAM:ESAV", CodeUnit.EOL_COMMENT); builder.createComment("0x0334", "Set the SP to RAM:ESAV", CommentType.EOL);
builder.createComment("0x0335", "RESTORE register 'DE'", CodeUnit.EOL_COMMENT); builder.createComment("0x0335", "RESTORE register 'DE'", CommentType.EOL);
builder.createComment("0x0336", "RESTORE register 'BC'", CodeUnit.EOL_COMMENT); builder.createComment("0x0336", "RESTORE register 'BC'", CommentType.EOL);
builder.createComment("0x0337", "RESTORE register 'A' and FLAGS", CodeUnit.EOL_COMMENT); builder.createComment("0x0337", "RESTORE register 'A' and FLAGS", CommentType.EOL);
builder.createComment("0x0338", "RESTORE register 'SP'", CodeUnit.EOL_COMMENT); builder.createComment("0x0338", "RESTORE register 'SP'", CommentType.EOL);
builder.createMemoryReference("0x1000", "0x331", RefType.UNCONDITIONAL_JUMP, builder.createMemoryReference("0x1000", "0x331", RefType.UNCONDITIONAL_JUMP,
SourceType.DEFAULT); SourceType.DEFAULT);
@ -197,8 +197,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
int transactionID = programOne.startTransaction("test"); int transactionID = programOne.startTransaction("test");
programOne.getSymbolTable() programOne.getSymbolTable()
.createLabel(addr(programOne, 0x032a), "MyLabel", .createLabel(addr(programOne, 0x032a), "MyLabel", SourceType.USER_DEFINED);
SourceType.USER_DEFINED);
programOne.endTransaction(transactionID, true); programOne.endTransaction(transactionID, true);
goTo(toolTwo, 0x0326); goTo(toolTwo, 0x0326);
@ -389,8 +388,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
// in Browser(1) change default label at 331 to JUNK // in Browser(1) change default label at 331 to JUNK
int transactionID = programOne.startTransaction("test"); int transactionID = programOne.startTransaction("test");
programOne.getSymbolTable() programOne.getSymbolTable()
.createLabel(addr(programOne, 0x0331), "JUNK", .createLabel(addr(programOne, 0x0331), "JUNK", SourceType.USER_DEFINED);
SourceType.USER_DEFINED);
programOne.endTransaction(transactionID, true); programOne.endTransaction(transactionID, true);
// //
// in Browser(1) go to 331 // 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 // in program 2, create a second label, JUNK2, at 0331
int transactionID = programOne.startTransaction("test"); int transactionID = programOne.startTransaction("test");
programOne.getSymbolTable() programOne.getSymbolTable()
.createLabel(addr(programOne, 0x331), "JUNK2", .createLabel(addr(programOne, 0x331), "JUNK2", SourceType.USER_DEFINED);
SourceType.USER_DEFINED);
programOne.endTransaction(transactionID, true); programOne.endTransaction(transactionID, true);
// in Browser(2) select 331 through 334, contains "RSR10" // in Browser(2) select 331 through 334, contains "RSR10"
@ -480,8 +477,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
public void testPasteWhereUserLabelExists() throws Exception { public void testPasteWhereUserLabelExists() throws Exception {
int transactionID = programOne.startTransaction("test"); int transactionID = programOne.startTransaction("test");
programOne.getSymbolTable() programOne.getSymbolTable()
.createLabel(addr(programOne, 0x331), "JUNK2", .createLabel(addr(programOne, 0x331), "JUNK2", SourceType.USER_DEFINED);
SourceType.USER_DEFINED);
programOne.endTransaction(transactionID, true); programOne.endTransaction(transactionID, true);
// in Browser(2) select 331 through 334, contains "RSR10" // in Browser(2) select 331 through 334, contains "RSR10"
@ -538,7 +534,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
// in Browser(1) add a pre comment at 331 // in Browser(1) add a pre comment at 331
CodeUnit cu = programOne.getListing().getCodeUnitAt(addr(programOne, 0x331)); CodeUnit cu = programOne.getListing().getCodeUnitAt(addr(programOne, 0x331));
int transactionID = programOne.startTransaction("test"); int transactionID = programOne.startTransaction("test");
cu.setComment(CodeUnit.PRE_COMMENT, "my pre comment for this test"); cu.setComment(CommentType.PRE, "my pre comment for this test");
programOne.endTransaction(transactionID, true); programOne.endTransaction(transactionID, true);
waitForSwing(); waitForSwing();
@ -572,7 +568,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
// verify pre comment at 331 remains unaffected // verify pre comment at 331 remains unaffected
cu = programOne.getListing().getCodeUnitAt(addr(programOne, 0x331)); cu = programOne.getListing().getCodeUnitAt(addr(programOne, 0x331));
assertEquals("my pre comment for this test", cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals("my pre comment for this test", cu.getComment(CommentType.PRE));
// verify browser field // verify browser field
@ -593,16 +589,14 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
cb.goToField(addr(programOne, 0x0331), LabelFieldFactory.FIELD_NAME, 0, 0); cb.goToField(addr(programOne, 0x0331), LabelFieldFactory.FIELD_NAME, 0, 0);
f = (ListingTextField) cb.getCurrentField(); f = (ListingTextField) cb.getCurrentField();
assertEquals(programOne.getSymbolTable() assertEquals(programOne.getSymbolTable()
.getSymbol("LAB_00000331", addr(programOne, 0x0331), .getSymbol("LAB_00000331", addr(programOne, 0x0331), null)
null)
.getName(), .getName(),
f.getText()); f.getText());
cb.goToField(addr(programOne, 0x031b), LabelFieldFactory.FIELD_NAME, 0, 0); cb.goToField(addr(programOne, 0x031b), LabelFieldFactory.FIELD_NAME, 0, 0);
f = (ListingTextField) cb.getCurrentField(); f = (ListingTextField) cb.getCurrentField();
assertEquals(programOne.getSymbolTable() assertEquals(programOne.getSymbolTable()
.getSymbol("LAB_0000031b", addr(programOne, 0x031b), .getSymbol("LAB_0000031b", addr(programOne, 0x031b), null)
null)
.getName(), .getName(),
f.getText()); f.getText());
@ -629,8 +623,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
int transactionID = programOne.startTransaction("test"); int transactionID = programOne.startTransaction("test");
String name = SymbolUtilities.getDefaultFunctionName(min); String name = SymbolUtilities.getDefaultFunctionName(min);
programOne.getListing() programOne.getListing()
.createFunction(name, min, new AddressSet(min, max), .createFunction(name, min, new AddressSet(min, max), SourceType.USER_DEFINED);
SourceType.USER_DEFINED);
programOne.endTransaction(transactionID, true); programOne.endTransaction(transactionID, true);
programOne.flushEvents(); programOne.flushEvents();
waitForSwing(); waitForSwing();
@ -649,18 +642,18 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
// verify comments are copied // verify comments are copied
CodeUnit cu = listing.getCodeUnitAt(addr(programOne, 0x0320)); CodeUnit cu = listing.getCodeUnitAt(addr(programOne, 0x0320));
assertEquals("My Plate Comment", cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals("My Plate Comment", cu.getComment(CommentType.PLATE));
assertEquals("My Post comment", cu.getComment(CodeUnit.POST_COMMENT)); assertEquals("My Post comment", cu.getComment(CommentType.POST));
cu = listing.getCodeUnitAt(addr(programOne, 0x326)); cu = listing.getCodeUnitAt(addr(programOne, 0x326));
assertEquals("More Plate Comments (1)", cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals("More Plate Comments (1)", cu.getComment(CommentType.PLATE));
assertEquals("More Post comments (1)", cu.getComment(CodeUnit.POST_COMMENT)); assertEquals("More Post comments (1)", cu.getComment(CommentType.POST));
assertEquals("More EOL comments (1)", cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals("More EOL comments (1)", cu.getComment(CommentType.EOL));
cu = listing.getCodeUnitAt(addr(programOne, 0x32a)); cu = listing.getCodeUnitAt(addr(programOne, 0x32a));
assertEquals("More Plate Comments (2)", cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals("More Plate Comments (2)", cu.getComment(CommentType.PLATE));
assertEquals("More Post comments (2)", cu.getComment(CodeUnit.POST_COMMENT)); assertEquals("More Post comments (2)", cu.getComment(CommentType.POST));
assertEquals("More EOL comments (2)", cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals("More EOL comments (2)", cu.getComment(CommentType.EOL));
cb.goToField(addr(programOne, 0x0320), PlateFieldFactory.FIELD_NAME, 0, 0); cb.goToField(addr(programOne, 0x0320), PlateFieldFactory.FIELD_NAME, 0, 0);
ListingTextField f = (ListingTextField) cb.getCurrentField(); ListingTextField f = (ListingTextField) cb.getCurrentField();
@ -708,7 +701,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
Address addr = addr(programOne, 0x334); Address addr = addr(programOne, 0x334);
for (String element : comments) { for (String element : comments) {
CodeUnit cu = listing.getCodeUnitAt(addr); CodeUnit cu = listing.getCodeUnitAt(addr);
assertEquals(element, cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals(element, cu.getComment(CommentType.EOL));
assertTrue(cb.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0)); assertTrue(cb.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0));
ListingTextField f = (ListingTextField) cb.getCurrentField(); ListingTextField f = (ListingTextField) cb.getCurrentField();
assertEquals(element, f.getText()); assertEquals(element, f.getText());
@ -722,8 +715,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
private void copyToolTwoLabels() { private void copyToolTwoLabels() {
ClipboardPlugin plugin = getPlugin(toolTwo, ClipboardPlugin.class); ClipboardPlugin plugin = getPlugin(toolTwo, ClipboardPlugin.class);
ClipboardContentProviderService service = ClipboardContentProviderService service = getClipboardService(plugin);
getClipboardService(plugin);
DockingAction action = getLocalAction(service, "Copy Special", plugin); DockingAction action = getLocalAction(service, "Copy Special", plugin);
assertNotNull(action); assertNotNull(action);
assertEnabled(action, cb2.getProvider()); assertEnabled(action, cb2.getProvider());
@ -791,18 +783,18 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
function.setComment("my function comment"); function.setComment("my function comment");
// add some Plate, Pre, and Post comments within this function. // add some Plate, Pre, and Post comments within this function.
CodeUnit cu = listing.getCodeUnitAt(addr(programTwo, 0x0320)); CodeUnit cu = listing.getCodeUnitAt(addr(programTwo, 0x0320));
cu.setComment(CodeUnit.PLATE_COMMENT, "My Plate Comment"); cu.setComment(CommentType.PLATE, "My Plate Comment");
cu.setComment(CodeUnit.POST_COMMENT, "My Post comment"); cu.setComment(CommentType.POST, "My Post comment");
cu = listing.getCodeUnitAt(addr(programTwo, 0x326)); cu = listing.getCodeUnitAt(addr(programTwo, 0x326));
cu.setComment(CodeUnit.PLATE_COMMENT, "More Plate Comments (1)"); cu.setComment(CommentType.PLATE, "More Plate Comments (1)");
cu.setComment(CodeUnit.POST_COMMENT, "More Post comments (1)"); cu.setComment(CommentType.POST, "More Post comments (1)");
cu.setComment(CodeUnit.EOL_COMMENT, "More EOL comments (1)"); cu.setComment(CommentType.EOL, "More EOL comments (1)");
cu = listing.getCodeUnitAt(addr(programTwo, 0x32a)); cu = listing.getCodeUnitAt(addr(programTwo, 0x32a));
cu.setComment(CodeUnit.PLATE_COMMENT, "More Plate Comments (2)"); cu.setComment(CommentType.PLATE, "More Plate Comments (2)");
cu.setComment(CodeUnit.POST_COMMENT, "More Post comments (2)"); cu.setComment(CommentType.POST, "More Post comments (2)");
cu.setComment(CodeUnit.EOL_COMMENT, "More EOL comments (2)"); cu.setComment(CommentType.EOL, "More EOL comments (2)");
// Edit the label at 0x32d (RSR05) and make it part of a scope // Edit the label at 0x32d (RSR05) and make it part of a scope
Symbol symbol = getUniqueSymbol(programTwo, "RSR05", null); Symbol symbol = getUniqueSymbol(programTwo, "RSR05", null);
@ -826,8 +818,7 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
waitForSwing(); waitForSwing();
} }
private ClipboardContentProviderService getClipboardService( private ClipboardContentProviderService getClipboardService(ClipboardPlugin clipboardPlugin) {
ClipboardPlugin clipboardPlugin) {
Map<?, ?> serviceMap = (Map<?, ?>) getInstanceField("serviceActionMap", clipboardPlugin); Map<?, ?> serviceMap = (Map<?, ?>) getInstanceField("serviceActionMap", clipboardPlugin);
Set<?> keySet = serviceMap.keySet(); Set<?> keySet = serviceMap.keySet();
for (Object name : keySet) { for (Object name : keySet) {
@ -855,10 +846,9 @@ public class CopyPasteCommentsTest extends AbstractProgramBasedTest {
} }
private void assertEnabled(DockingActionIf action, ComponentProvider provider) { private void assertEnabled(DockingActionIf action, ComponentProvider provider) {
boolean isEnabled = boolean isEnabled = runSwing(() -> {
runSwing(() -> { return action.isEnabledForContext(provider.getActionContext(null));
return action.isEnabledForContext(provider.getActionContext(null)); });
});
assertTrue("Action was not enabled when it should be", isEnabled); assertTrue("Action was not enabled when it should be", isEnabled);
} }
} }

View file

@ -87,7 +87,7 @@ public class CopyPasteFunctionInfoTest extends AbstractGhidraHeadedIntegrationTe
builder.createFunction("0x1006420"); builder.createFunction("0x1006420");
builder.createEntryPoint("0x1006420", "entry"); builder.createEntryPoint("0x1006420", "entry");
builder.createFunction("0x1004700"); builder.createFunction("0x1004700");
builder.createComment("0x1006420", "FUNCTION", CodeUnit.PLATE_COMMENT); builder.createComment("0x1006420", "FUNCTION", CommentType.PLATE);
DataType dt = Undefined4DataType.dataType; DataType dt = Undefined4DataType.dataType;
Parameter p = new ParameterImpl(null, dt, builder.getProgram()); 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, builder.createEmptyFunction("BOB", "0x1004260", 1, dt, p, p, p, p, p, p, p, p, p, p, p, p,

View file

@ -595,7 +595,7 @@ public class CodeBrowserOptionsTest extends AbstractGhidraHeadedIntegrationTest
cb.goToField(callAddress, "Bytes", 0, 0); cb.goToField(callAddress, "Bytes", 0, 0);
SetCommentCmd eolCmd = new SetCommentCmd(callAddress, CodeUnit.EOL_COMMENT, SetCommentCmd eolCmd = new SetCommentCmd(callAddress, CommentType.EOL,
"a bb ccc dddd eeeee ffff ggg hhh ii j k ll mmm nnn oooo " + "a bb ccc dddd eeeee ffff ggg hhh ii j k ll mmm nnn oooo " +
"ppppp qqqq rrrr ssss tttt uuuuu vvvvvv wwwww\n\n\n\n" + "ppppp qqqq rrrr ssss tttt uuuuu vvvvvv wwwww\n\n\n\n" +
"AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK LLL MMM NNN OOO PPP QQQ " + "AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK LLL MMM NNN OOO PPP QQQ " +
@ -604,7 +604,7 @@ public class CodeBrowserOptionsTest extends AbstractGhidraHeadedIntegrationTest
"4444 55555 666666 7777777 88888888 999999999 0000000000 1 22 333 4444 55555"); "4444 55555 666666 7777777 88888888 999999999 0000000000 1 22 333 4444 55555");
tool.execute(eolCmd, program); tool.execute(eolCmd, program);
SetCommentCmd repeatCmd = new SetCommentCmd(callAddress, CodeUnit.REPEATABLE_COMMENT, SetCommentCmd repeatCmd = new SetCommentCmd(callAddress, CommentType.REPEATABLE,
"Local repeatable line1.\n" + "\n" + "Line3 of repeatable."); "Local repeatable line1.\n" + "\n" + "Line3 of repeatable.");
tool.execute(repeatCmd, program); tool.execute(repeatCmd, program);
@ -613,7 +613,7 @@ public class CodeBrowserOptionsTest extends AbstractGhidraHeadedIntegrationTest
new CreateFunctionCmd(null, callRefAddress, body, SourceType.USER_DEFINED); new CreateFunctionCmd(null, callRefAddress, body, SourceType.USER_DEFINED);
tool.execute(createFunctionCmd, program); tool.execute(createFunctionCmd, program);
SetCommentCmd callRepeatCmd = new SetCommentCmd(callRefAddress, CodeUnit.REPEATABLE_COMMENT, SetCommentCmd callRepeatCmd = new SetCommentCmd(callRefAddress, CommentType.REPEATABLE,
"\n" + "Function Repeatable line2"); "\n" + "Function Repeatable line2");
tool.execute(callRepeatCmd, program); tool.execute(callRepeatCmd, program);
@ -621,8 +621,8 @@ public class CodeBrowserOptionsTest extends AbstractGhidraHeadedIntegrationTest
SourceType.USER_DEFINED, 0, false); SourceType.USER_DEFINED, 0, false);
tool.execute(addRefCmd, program); tool.execute(addRefCmd, program);
SetCommentCmd commentRefCmd = new SetCommentCmd(otherRefAddress, SetCommentCmd commentRefCmd =
CodeUnit.REPEATABLE_COMMENT, "Mem ref line1.\n" + ""); new SetCommentCmd(otherRefAddress, CommentType.REPEATABLE, "Mem ref line1.\n" + "");
tool.execute(commentRefCmd, program); tool.execute(commentRefCmd, program);
// these values are all DEFAULT, by default; set them in case that changes in the future // these values are all DEFAULT, by default; set them in case that changes in the future
@ -789,8 +789,8 @@ public class CodeBrowserOptionsTest extends AbstractGhidraHeadedIntegrationTest
//--- Verify register variable markup options //--- Verify register variable markup options
Command cmd = new AddRegisterRefCmd(addr("0x1002d0b"), 0, program.getRegister("EDI"), Command<Program> cmd = new AddRegisterRefCmd(addr("0x1002d0b"), 0,
SourceType.USER_DEFINED); program.getRegister("EDI"), SourceType.USER_DEFINED);
applyCmd(program, cmd); applyCmd(program, cmd);
cb.updateNow(); cb.updateNow();

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -61,9 +61,6 @@ import ghidra.util.task.TaskMonitor;
public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest { 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 PRE = "This is a PRE comment.";
private final static String POST = "This is a POST comment."; private final static String POST = "This is a POST comment.";
private final static String EOL = "This is a EOL comment."; private final static String EOL = "This is a EOL comment.";
@ -132,8 +129,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Data subData1 = data.getComponent(0); Data subData1 = data.getComponent(0);
assertEquals(new WordDataType().getName(), subData1.getDataType().getName()); assertEquals(new WordDataType().getName(), subData1.getDataType().getName());
String comment1 = "aaa bbb ccc ddd eee"; String comment1 = "aaa bbb ccc ddd eee";
setAt(addr, CodeUnit.EOL_COMMENT, comment1, "OK"); setAt(addr, CommentType.EOL, comment1, "OK");
assertEquals(comment1, subData1.getComment(CodeUnit.EOL_COMMENT)); assertEquals(comment1, subData1.getComment(CommentType.EOL));
browser.goToField(addr(0x10080a2), "+", 0, 0); browser.goToField(addr(0x10080a2), "+", 0, 0);
@ -146,8 +143,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Data subData = data.getComponent(1).getComponent(0); Data subData = data.getComponent(1).getComponent(0);
assertEquals(new FloatDataType().getName(), subData.getDataType().getName()); assertEquals(new FloatDataType().getName(), subData.getDataType().getName());
String comment = "This is a comment on a structure element."; 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(CodeUnit.EOL_COMMENT)); assertEquals(comment, subData.getComment(CommentType.EOL));
browser.goToField(addr(0x010080a2), EolCommentFieldFactory.FIELD_NAME, 0, 0); browser.goToField(addr(0x010080a2), EolCommentFieldFactory.FIELD_NAME, 0, 0);
assertEquals(comment, browser.getCurrentFieldText()); assertEquals(comment, browser.getCurrentFieldText());
@ -171,11 +168,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
waitForSwing(); waitForSwing();
comment += "\n\nHI, MOM"; comment += "\n\nHI, MOM";
assertEquals(comment, subData.getComment(CodeUnit.EOL_COMMENT)); assertEquals(comment, subData.getComment(CommentType.EOL));
performAction(deleteAction, browser.getProvider(), false); performAction(deleteAction, browser.getProvider(), false);
waitForSwing(); waitForSwing();
assertNull(subData.getComment(CodeUnit.EOL_COMMENT)); assertNull(subData.getComment(CommentType.EOL));
} }
@Test @Test
@ -183,11 +180,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006420); 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); performAction(editAction, browser.getProvider(), false);
waitForSwing(); waitForSwing();
@ -198,7 +195,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
JTabbedPane tab = findComponent(dialog.getComponent(), JTabbedPane.class); JTabbedPane tab = findComponent(dialog.getComponent(), JTabbedPane.class);
assertNotNull(tab); assertNotNull(tab);
assertEquals(element, tab.getSelectedIndex()); assertEquals(type.ordinal(), tab.getSelectedIndex());
pressButtonByText(dialog.getComponent(), "Dismiss", false); pressButtonByText(dialog.getComponent(), "Dismiss", false);
waitForSwing(); waitForSwing();
@ -238,7 +235,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
tool2.firePluginEvent(new OpenProgramPluginEvent("Test", program)); tool2.firePluginEvent(new OpenProgramPluginEvent("Test", program));
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
sendProgramLocation(addr, CodeUnit.EOL_COMMENT); sendProgramLocation(addr, CommentType.EOL);
String comment = "Drag and Drop is a direct manipulation gesture\n" + String comment = "Drag and Drop is a direct manipulation gesture\n" +
"found in many Graphical User Interface\n" + "found in many Graphical User Interface\n" +
@ -246,7 +243,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
"between two entities logically associated with\n" + "between two entities logically associated with\n" +
"presentation elements in the GUI.\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); setFieldWidth(browser, EolCommentFieldFactory.FIELD_NAME, 100);
@ -275,12 +272,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.PRE_COMMENT, PRE, "OK"); setAt(addr, CommentType.PRE, PRE, "OK");
assertEquals(PRE, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(PRE, cu.getComment(CommentType.PRE));
undo(program); undo(program);
assertNull(cu.getComment(CodeUnit.PRE_COMMENT)); assertNull(cu.getComment(CommentType.PRE));
redo(program); redo(program);
assertEquals(PRE, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(PRE, cu.getComment(CommentType.PRE));
browser.goToField(addr, PreCommentFieldFactory.FIELD_NAME, 0, 0); browser.goToField(addr, PreCommentFieldFactory.FIELD_NAME, 0, 0);
assertEquals(PRE, browser.getCurrentFieldText()); assertEquals(PRE, browser.getCurrentFieldText());
} }
@ -290,12 +287,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.POST_COMMENT, POST, "OK"); setAt(addr, CommentType.POST, POST, "OK");
assertEquals(POST, cu.getComment(CodeUnit.POST_COMMENT)); assertEquals(POST, cu.getComment(CommentType.POST));
undo(program); undo(program);
assertNull(cu.getComment(CodeUnit.POST_COMMENT)); assertNull(cu.getComment(CommentType.POST));
redo(program); redo(program);
assertEquals(POST, cu.getComment(CodeUnit.POST_COMMENT)); assertEquals(POST, cu.getComment(CommentType.POST));
browser.goToField(addr, PostCommentFieldFactory.FIELD_NAME, 0, 0); browser.goToField(addr, PostCommentFieldFactory.FIELD_NAME, 0, 0);
assertEquals(POST, browser.getCurrentFieldText()); assertEquals(POST, browser.getCurrentFieldText());
} }
@ -305,12 +302,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.EOL_COMMENT, EOL, "OK"); setAt(addr, CommentType.EOL, EOL, "OK");
assertEquals(EOL, cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals(EOL, cu.getComment(CommentType.EOL));
undo(program); undo(program);
assertNull(cu.getComment(CodeUnit.EOL_COMMENT)); assertNull(cu.getComment(CommentType.EOL));
redo(program); redo(program);
assertEquals(EOL, cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals(EOL, cu.getComment(CommentType.EOL));
browser.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0); browser.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0);
assertEquals(EOL, browser.getCurrentFieldText()); assertEquals(EOL, browser.getCurrentFieldText());
} }
@ -321,12 +318,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
resetFormatOptions(browser); resetFormatOptions(browser);
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.PLATE_COMMENT, PLATE, "OK"); setAt(addr, CommentType.PLATE, PLATE, "OK");
assertEquals(PLATE, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(PLATE, cu.getComment(CommentType.PLATE));
undo(program); undo(program);
assertNull(cu.getComment(CodeUnit.PLATE_COMMENT)); assertNull(cu.getComment(CommentType.PLATE));
redo(program); redo(program);
assertEquals(PLATE, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(PLATE, cu.getComment(CommentType.PLATE));
browser.goToField(addr, PlateFieldFactory.FIELD_NAME, 0, 0); browser.goToField(addr, PlateFieldFactory.FIELD_NAME, 0, 0);
//allow for the "*" that get added to the plate //allow for the "*" that get added to the plate
assertEquals(65, browser.getCurrentFieldText().indexOf(PLATE)); assertEquals(65, browser.getCurrentFieldText().indexOf(PLATE));
@ -337,12 +334,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.REPEATABLE_COMMENT, REPEAT, "OK"); setAt(addr, CommentType.REPEATABLE, REPEAT, "OK");
assertEquals(REPEAT, cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertEquals(REPEAT, cu.getComment(CommentType.REPEATABLE));
undo(program); undo(program);
assertNull(cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertNull(cu.getComment(CommentType.REPEATABLE));
redo(program); redo(program);
assertEquals(REPEAT, cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertEquals(REPEAT, cu.getComment(CommentType.REPEATABLE));
browser.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0); browser.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0);
assertEquals(REPEAT, browser.getCurrentFieldText()); assertEquals(REPEAT, browser.getCurrentFieldText());
} }
@ -354,8 +351,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
CodeUnit cu = program.getListing().getCodeUnitAt(addr); 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"; 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(CodeUnit.REPEATABLE_COMMENT)); assertEquals(longComment, cu.getComment(CommentType.REPEATABLE));
// this fails when excepting // this fails when excepting
assertTrue(browser.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0)); assertTrue(browser.goToField(addr, EolCommentFieldFactory.FIELD_NAME, 0, 0));
@ -367,33 +364,33 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.PRE_COMMENT, PRE, "OK"); setAt(addr, CommentType.PRE, PRE, "OK");
setAt(addr, CodeUnit.POST_COMMENT, POST, "OK"); setAt(addr, CommentType.POST, POST, "OK");
setAt(addr, CodeUnit.EOL_COMMENT, EOL, "OK"); setAt(addr, CommentType.EOL, EOL, "OK");
setAt(addr, CodeUnit.PLATE_COMMENT, PLATE, "OK"); setAt(addr, CommentType.PLATE, PLATE, "OK");
setAt(addr, CodeUnit.REPEATABLE_COMMENT, REPEAT, "OK"); setAt(addr, CommentType.REPEATABLE, REPEAT, "OK");
assertEquals(PRE, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(PRE, cu.getComment(CommentType.PRE));
assertEquals(POST, cu.getComment(CodeUnit.POST_COMMENT)); assertEquals(POST, cu.getComment(CommentType.POST));
assertEquals(EOL, cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals(EOL, cu.getComment(CommentType.EOL));
assertEquals(PLATE, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(PLATE, cu.getComment(CommentType.PLATE));
assertEquals(REPEAT, cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertEquals(REPEAT, cu.getComment(CommentType.REPEATABLE));
undo(program, 5); undo(program, 5);
assertNull(cu.getComment(CodeUnit.PRE_COMMENT)); assertNull(cu.getComment(CommentType.PRE));
assertNull(cu.getComment(CodeUnit.POST_COMMENT)); assertNull(cu.getComment(CommentType.POST));
assertNull(cu.getComment(CodeUnit.EOL_COMMENT)); assertNull(cu.getComment(CommentType.EOL));
assertNull(cu.getComment(CodeUnit.PLATE_COMMENT)); assertNull(cu.getComment(CommentType.PLATE));
assertNull(cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertNull(cu.getComment(CommentType.REPEATABLE));
redo(program, 5); redo(program, 5);
assertEquals(PRE, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(PRE, cu.getComment(CommentType.PRE));
assertEquals(POST, cu.getComment(CodeUnit.POST_COMMENT)); assertEquals(POST, cu.getComment(CommentType.POST));
assertEquals(EOL, cu.getComment(CodeUnit.EOL_COMMENT)); assertEquals(EOL, cu.getComment(CommentType.EOL));
assertEquals(PLATE, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(PLATE, cu.getComment(CommentType.PLATE));
assertEquals(REPEAT, cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertEquals(REPEAT, cu.getComment(CommentType.REPEATABLE));
} }
@Test @Test
@ -401,12 +398,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006000); Address addr = addr(0x01006000);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); 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); final CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class);
assertNotNull(commentsDialog); assertNotNull(commentsDialog);
pressButtonByText(commentsDialog.getComponent(), "Dismiss", false); pressButtonByText(commentsDialog.getComponent(), "Dismiss", false);
waitForSwing(); waitForSwing();
assertEquals("Bla bla bla", cu.getComment(CodeUnit.REPEATABLE_COMMENT)); assertEquals("Bla bla bla", cu.getComment(CommentType.REPEATABLE));
assertTrue(!commentsDialog.isVisible()); assertTrue(!commentsDialog.isVisible());
} }
@ -415,12 +412,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0xf0001300); Address addr = addr(0xf0001300);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.PRE_COMMENT, PRE, "OK"); setAt(addr, CommentType.PRE, PRE, "OK");
setAt(addr, CodeUnit.PRE_COMMENT, PRE_U, "OK"); setAt(addr, CommentType.PRE, PRE_U, "OK");
undo(program); undo(program);
assertEquals(PRE, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(PRE, cu.getComment(CommentType.PRE));
redo(program); redo(program);
assertEquals(PRE_U, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(PRE_U, cu.getComment(CommentType.PRE));
} }
@Test @Test
@ -428,7 +425,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006000); Address addr = addr(0x01006000);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); 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); CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class);
OptionDialog saveDialog = waitForDialogComponent(OptionDialog.class); OptionDialog saveDialog = waitForDialogComponent(OptionDialog.class);
assertNotNull(saveDialog); assertNotNull(saveDialog);
@ -439,7 +436,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
pressButton(button, false); pressButton(button, false);
waitForSwing(); waitForSwing();
assertEquals("Bla bla bla", cu.getComment(CodeUnit.POST_COMMENT)); assertEquals("Bla bla bla", cu.getComment(CommentType.POST));
assertFalse(commentsDialog.isVisible()); assertFalse(commentsDialog.isVisible());
} }
@ -448,7 +445,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006000); Address addr = addr(0x01006000);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); 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); CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class);
assertNotNull(commentsDialog); assertNotNull(commentsDialog);
OptionDialog saveDialog = waitForDialogComponent(OptionDialog.class); OptionDialog saveDialog = waitForDialogComponent(OptionDialog.class);
@ -460,7 +457,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
pressButton(button, false); pressButton(button, false);
waitForSwing(); waitForSwing();
assertNull(cu.getComment(CodeUnit.POST_COMMENT)); assertNull(cu.getComment(CommentType.POST));
assertFalse(commentsDialog.isVisible()); assertFalse(commentsDialog.isVisible());
} }
@ -469,7 +466,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x01006000); Address addr = addr(0x01006000);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); 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); CommentsDialog commentsDialog = waitForDialogComponent(CommentsDialog.class);
assertNotNull(commentsDialog); assertNotNull(commentsDialog);
@ -482,7 +479,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
pressButton(button, false); pressButton(button, false);
waitForSwing(); waitForSwing();
assertNull(cu.getComment(CodeUnit.POST_COMMENT)); assertNull(cu.getComment(CommentType.POST));
assertTrue(commentsDialog.isVisible()); assertTrue(commentsDialog.isVisible());
close(commentsDialog); close(commentsDialog);
@ -493,14 +490,14 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0xf0000250); Address addr = addr(0xf0000250);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.PLATE_COMMENT, PLATE, "OK"); setAt(addr, CommentType.PLATE, PLATE, "OK");
assertEquals(PLATE, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(PLATE, cu.getComment(CommentType.PLATE));
removeAt(addr, CodeUnit.PLATE_COMMENT); removeAt(addr, CommentType.PLATE);
assertNull(cu.getComment(CodeUnit.PLATE_COMMENT)); assertNull(cu.getComment(CommentType.PLATE));
undo(program); undo(program);
assertEquals(PLATE, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(PLATE, cu.getComment(CommentType.PLATE));
redo(program); redo(program);
assertNull(cu.getComment(CodeUnit.PLATE_COMMENT)); assertNull(cu.getComment(CommentType.PLATE));
} }
@Test @Test
@ -508,11 +505,10 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
openX86ProgramInTool(); openX86ProgramInTool();
Address addr = addr(0x0100bbbb); Address addr = addr(0x0100bbbb);
setAt(addr, CodeUnit.EOL_COMMENT, EOL, "OK"); setAt(addr, CommentType.EOL, EOL, "OK");
setAt(addr, CodeUnit.EOL_COMMENT, EOL_U, "OK"); setAt(addr, CommentType.EOL, EOL_U, "OK");
CommentHistory[] history = CommentHistory[] history = program.getListing().getCommentHistory(addr, CommentType.EOL);
program.getListing().getCommentHistory(addr, CodeUnit.EOL_COMMENT);
assertEquals(2, history.length); assertEquals(2, history.length);
for (int i = 0; i < history.length; i++) { for (int i = 0; i < history.length; i++) {
@ -542,8 +538,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
String comment = buffer.toString(); String comment = buffer.toString();
Address addr = addr(0x01006000); Address addr = addr(0x01006000);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
setAt(addr, CodeUnit.PRE_COMMENT, comment, "OK"); setAt(addr, CommentType.PRE, comment, "OK");
assertEquals(comment, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(comment, cu.getComment(CommentType.PRE));
} }
@Test @Test
@ -555,7 +551,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
String comment = "This is a comment with address " + commentAddress + " in it."; String comment = "This is a comment with address " + commentAddress + " in it.";
CommentsDialog dialog = editComment(addr(0x01006990)); CommentsDialog dialog = editComment(addr(0x01006990));
JTextArea commentTextArea = getTextArea(dialog, CodeUnit.EOL_COMMENT); JTextArea commentTextArea = getTextArea(dialog, CommentType.EOL);
runSwing(() -> { runSwing(() -> {
commentTextArea.setText(comment); commentTextArea.setText(comment);
@ -585,8 +581,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr); CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr);
String comment = "This is a comment DAT_01008094 with a label in it."; 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(CodeUnit.PRE_COMMENT)); assertEquals(comment, cu.getComment(CommentType.PRE));
browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23);
click(browser, 2); click(browser, 2);
@ -602,8 +598,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr); CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr);
String comment = "This is a comment 01008094 with an address in it."; 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(CodeUnit.PRE_COMMENT)); assertEquals(comment, cu.getComment(CommentType.PRE));
browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23);
click(browser, 2); click(browser, 2);
@ -622,7 +618,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Address srcAddr = addr(0x01006990); Address srcAddr = addr(0x01006990);
String comment = "This is a comment {@sym DAT_01008094} with an annotation in it."; 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); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23);
click(browser, 2); click(browser, 2);
@ -638,7 +634,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Address srcAddr = addr(0x01006990); Address srcAddr = addr(0x01006990);
String comment = "This is a comment {@sym Deadpool::Bob} with an annotation in it."; 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); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 20);
click(browser, 2); click(browser, 2);
@ -654,7 +650,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Address srcAddr = addr(0x01006990); Address srcAddr = addr(0x01006990);
String comment = "This is a symbol {@program Test@Deadpool::Bob} annotation."; 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); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 23);
click(browser, 2); click(browser, 2);
@ -677,8 +673,8 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr); CodeUnit cu = program.getListing().getCodeUnitAt(srcAddr);
String comment = "This is a comment DAT_* with a wildcard in it."; 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(CodeUnit.PRE_COMMENT)); assertEquals(comment, cu.getComment(CommentType.PRE));
browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 19); browser.goToField(srcAddr, PreCommentFieldFactory.FIELD_NAME, 0, 19);
click(browser, 2); click(browser, 2);
@ -709,7 +705,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
AddressSpace extmemSpace = af.getAddressSpace("EXTMEM"); AddressSpace extmemSpace = af.getAddressSpace("EXTMEM");
Address addr = extmemSpace.getAddress(0); 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); browser.goToField(addr, PlateFieldFactory.FIELD_NAME, 1, 22);
click(browser, 2); click(browser, 2);
@ -723,11 +719,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
Address addr = addr(0x01006420); Address addr = addr(0x01006420);
CodeUnit cu = program.getListing().getCodeUnitAt(addr); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
String tabComment = "abcd\tdefg\n\t1\t2\t3\t4"; 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 // space comment is exactly the same; i.e. make sure that no tab conversion happens
String spaceComment = "abcd\tdefg\n\t1\t2\t3\t4"; String spaceComment = "abcd\tdefg\n\t1\t2\t3\t4";
assertEquals(spaceComment, cu.getComment(CodeUnit.PLATE_COMMENT)); assertEquals(spaceComment, cu.getComment(CommentType.PLATE));
} }
/* /*
@ -790,12 +786,12 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
String illegal = "null\0 comment"; String illegal = "null\0 comment";
String legal = "null comment"; String legal = "null comment";
setAt(addr, CodeUnit.PRE_COMMENT, illegal, "OK"); setAt(addr, CommentType.PRE, illegal, "OK");
assertEquals(legal, cu.getComment(CodeUnit.PRE_COMMENT)); assertEquals(legal, cu.getComment(CommentType.PRE));
} }
private void setAt(Address addr, int commentType, String comment, String nameOfButtonToClick) private void setAt(Address addr, CommentType commentType, String comment,
throws Exception { String nameOfButtonToClick) throws Exception {
CommentsDialog dialog = editComment(addr); CommentsDialog dialog = editComment(addr);
assertEquals("Set Comment(s) at Address " + addr.toString(), dialog.getTitle()); assertEquals("Set Comment(s) at Address " + addr.toString(), dialog.getTitle());
@ -817,7 +813,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
return waitForDialogComponent(CommentsDialog.class); return waitForDialogComponent(CommentsDialog.class);
} }
private JTextArea getTextArea(CommentsDialog dialog, int commentType) { private JTextArea getTextArea(CommentsDialog dialog, CommentType commentType) {
runSwing(() -> dialog.setCommentType(commentType)); runSwing(() -> dialog.setCommentType(commentType));
waitForSwing(); waitForSwing();
@ -829,7 +825,7 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
return textArea; return textArea;
} }
private void removeAt(Address addr, int commentType) throws Exception { private void removeAt(Address addr, CommentType commentType) throws Exception {
sendProgramLocation(addr, commentType); sendProgramLocation(addr, commentType);
performAction(deleteAction, browser.getProvider(), false); performAction(deleteAction, browser.getProvider(), false);
waitForSwing(); waitForSwing();
@ -839,11 +835,11 @@ public class CommentsPluginTest extends AbstractGhidraHeadedIntegrationTest {
return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset); 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); CodeUnit cu = program.getListing().getCodeUnitAt(addr);
String[] comment = cu.getCommentAsArray(type); 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 EolCommentFieldLocation(program, addr, null, comment, 0, 0, 0)
: new CommentFieldLocation(program, addr, null, comment, type, 0, 0); : new CommentFieldLocation(program, addr, null, comment, type, 0, 0);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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.app.services.ProgramManager;
import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.address.*; 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.model.listing.Program;
import ghidra.test.*; import ghidra.test.*;
@ -79,11 +79,11 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest
ClassicSampleX86ProgramBuilder builder = new ClassicSampleX86ProgramBuilder(); ClassicSampleX86ProgramBuilder builder = new ClassicSampleX86ProgramBuilder();
program = builder.getProgram(); program = builder.getProgram();
builder.createComment("01006420", "test EOL comment", CodeUnit.EOL_COMMENT); builder.createComment("01006420", "test EOL comment", CommentType.EOL);
builder.createComment("01008004", "test Pre comment", CodeUnit.PRE_COMMENT); builder.createComment("01008004", "test Pre comment", CommentType.PRE);
builder.createComment("0100b2b", "test Post comment", CodeUnit.POST_COMMENT); builder.createComment("0100b2b", "test Post comment", CommentType.POST);
builder.createComment("010018a0", "test Plate comment", CodeUnit.PLATE_COMMENT); builder.createComment("010018a0", "test Plate comment", CommentType.PLATE);
builder.createComment("010018cf", "test Repeatable comment", CodeUnit.REPEATABLE_COMMENT); builder.createComment("010018cf", "test Repeatable comment", CommentType.REPEATABLE);
ProgramManager pm = tool.getService(ProgramManager.class); ProgramManager pm = tool.getService(ProgramManager.class);
pm.openProgram(program.getDomainFile()); pm.openProgram(program.getDomainFile());
@ -144,7 +144,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest
assertEquals(5, numComments); assertEquals(5, numComments);
addComment(addr("0x01001000"), CodeUnit.EOL_COMMENT, "Added EOL Comment"); addComment(addr("0x01001000"), CommentType.EOL, "Added EOL Comment");
assertRowCount(6); assertRowCount(6);
@ -169,7 +169,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest
assertEquals("test EOL comment", getTableComment(rowIndex)); assertEquals("test EOL comment", getTableComment(rowIndex));
// Then set the comment to a different value // 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 // Test to see if the changed comment is in the table
assertEquals("Changed EOL Comment", getTableComment(rowIndex)); assertEquals("Changed EOL Comment", getTableComment(rowIndex));
@ -193,7 +193,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest
loadProgram("notepad"); 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()); int id = program.startTransaction(testName.getMethodName());
try { try {
program.getListing().setComment(addr, commentType, comment); program.getListing().setComment(addr, commentType, comment);
@ -230,7 +230,7 @@ public class CommentWindowPluginTest extends AbstractGhidraHeadedIntegrationTest
return commentTable.getValueAt(rowIndex, CommentTableModel.COMMENT_COL).toString(); 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()); int id = program.startTransaction(testName.getMethodName());
try { try {
program.getListing().setComment(addr, commentType, comment); program.getListing().setComment(addr, commentType, comment);

View file

@ -567,8 +567,7 @@ public class ClearTest extends AbstractGhidraHeadedIntegrationTest {
public void testClearComments() throws Exception { public void testClearComments() throws Exception {
assertTrue(cb.goToField(addr("0x10022cc"), "Bytes", 0, 4)); assertTrue(cb.goToField(addr("0x10022cc"), "Bytes", 0, 4));
SetCommentCmd cmd = SetCommentCmd cmd = new SetCommentCmd(addr("0x10022cc"), CommentType.EOL, "my comment");
new SetCommentCmd(addr("0x10022cc"), CodeUnit.EOL_COMMENT, "my comment");
applyCmd(program, cmd); applyCmd(program, cmd);
performAction(clearWithOptionsAction, cb.getProvider(), false); performAction(clearWithOptionsAction, cb.getProvider(), false);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -41,7 +41,7 @@ import ghidra.framework.model.*;
import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.PluginTool;
import ghidra.program.database.ProgramBuilder; import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.address.Address; 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.model.listing.Program;
import ghidra.program.model.symbol.SourceType; import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.symbol.SymbolTable; import ghidra.program.model.symbol.SymbolTable;
@ -383,8 +383,8 @@ public class MultiTabPluginTest extends AbstractGhidraHeadedIntegrationTest {
String newName = "myNewLogin"; String newName = "myNewLogin";
renameProgramFile(p, newName); renameProgramFile(p, newName);
ArrayList<DomainObjectChangeRecord> changeRecs = new ArrayList<>(); ArrayList<DomainObjectChangeRecord> changeRecs = new ArrayList<>();
changeRecs.add( changeRecs
new DomainObjectChangeRecord(DomainObjectEvent.RENAMED, oldName, p.getName())); .add(new DomainObjectChangeRecord(DomainObjectEvent.RENAMED, oldName, p.getName()));
DomainObjectChangedEvent ev = new DomainObjectChangedEvent(p, changeRecs); DomainObjectChangedEvent ev = new DomainObjectChangedEvent(p, changeRecs);
runSwing(() -> env.getPlugin(MultiTabPlugin.class).domainObjectChanged(ev)); runSwing(() -> env.getPlugin(MultiTabPlugin.class).domainObjectChanged(ev));
@ -589,7 +589,7 @@ public class MultiTabPluginTest extends AbstractGhidraHeadedIntegrationTest {
try { try {
p.getListing() p.getListing()
.setComment(p.getAddressFactory().getAddress("01000000"), .setComment(p.getAddressFactory().getAddress("01000000"),
CodeUnit.REPEATABLE_COMMENT, "This is a simple comment change."); CommentType.REPEATABLE, "This is a simple comment change.");
} }
finally { finally {
p.endTransaction(transactionID, true); p.endTransaction(transactionID, true);

View file

@ -4,9 +4,9 @@
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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 FIND_DIALOG_TITLE = "Enter Search String";
private static final String REPLACE_DIALOG_TITLE = "Enter Replace 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 static final int SCRIPT_TIMEOUT = 100000;
private TestEnv env; private TestEnv env;
@ -65,19 +64,18 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
builder = new ToyProgramBuilder("ReplaceCommentTest", true, this); builder = new ToyProgramBuilder("ReplaceCommentTest", true, this);
builder.createMemory(".text", "0x1001000", 0x4000); builder.createMemory(".text", "0x1001000", 0x4000);
builder.createComment("0x01001000", "EOL Comment", CodeUnit.EOL_COMMENT); builder.createComment("0x01001000", "EOL Comment", CommentType.EOL);
builder.createComment("0x01001100", "Pre Comment", CodeUnit.PRE_COMMENT); builder.createComment("0x01001100", "Pre Comment", CommentType.PRE);
builder.createComment("0x01001200", "Post Comment", CodeUnit.POST_COMMENT); builder.createComment("0x01001200", "Post Comment", CommentType.POST);
builder.createComment("0x01001300", "Plate Comment", CodeUnit.PLATE_COMMENT); builder.createComment("0x01001300", "Plate Comment", CommentType.PLATE);
builder.createComment("0x01001400", "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); builder.createComment("0x01001400", "Repeatable Comment", CommentType.REPEATABLE);
builder.createComment("0x01001500", "EOL Comment Repeated", CodeUnit.EOL_COMMENT); builder.createComment("0x01001500", "EOL Comment Repeated", CommentType.EOL);
builder.createComment("0x01001600", "EOL Comment Repeated", CodeUnit.EOL_COMMENT); builder.createComment("0x01001600", "EOL Comment Repeated", CommentType.EOL);
builder.createComment("0x01001700", "Generic Comment Repeated", CodeUnit.EOL_COMMENT); builder.createComment("0x01001700", "Generic Comment Repeated", CommentType.EOL);
builder.createComment("0x01001800", "Generic Comment Repeated", CodeUnit.PRE_COMMENT); builder.createComment("0x01001800", "Generic Comment Repeated", CommentType.PRE);
builder.createComment("0x01001900", "Generic Comment Repeated", CodeUnit.POST_COMMENT); builder.createComment("0x01001900", "Generic Comment Repeated", CommentType.POST);
builder.createComment("0x01002000", "Generic Comment Repeated", CodeUnit.PLATE_COMMENT); builder.createComment("0x01002000", "Generic Comment Repeated", CommentType.PLATE);
builder.createComment("0x01002100", "Generic Comment Repeated", builder.createComment("0x01002100", "Generic Comment Repeated", CommentType.REPEATABLE);
CodeUnit.REPEATABLE_COMMENT);
return builder.getProgram(); return builder.getProgram();
} }
@ -92,13 +90,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001000, "EOL Comment", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001000, "EOL Comment", CommentType.EOL);
respondToDialog("EOL Comment", FIND_DIALOG_TITLE); respondToDialog("EOL Comment", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001000, "New Value", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001000, "New Value", CommentType.EOL);
} }
@Test @Test
@ -106,13 +104,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001100, "Pre Comment", CodeUnit.PRE_COMMENT); assertCommentEquals(0x01001100, "Pre Comment", CommentType.PRE);
respondToDialog("Pre Comment", FIND_DIALOG_TITLE); respondToDialog("Pre Comment", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001100, "New Value", CodeUnit.PRE_COMMENT); assertCommentEquals(0x01001100, "New Value", CommentType.PRE);
} }
@Test @Test
@ -120,13 +118,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001200, "Post Comment", CodeUnit.POST_COMMENT); assertCommentEquals(0x01001200, "Post Comment", CommentType.POST);
respondToDialog("Post Comment", FIND_DIALOG_TITLE); respondToDialog("Post Comment", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001200, "New Value", CodeUnit.POST_COMMENT); assertCommentEquals(0x01001200, "New Value", CommentType.POST);
} }
@Test @Test
@ -134,13 +132,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001300, "Plate Comment", CodeUnit.PLATE_COMMENT); assertCommentEquals(0x01001300, "Plate Comment", CommentType.PLATE);
respondToDialog("Plate Comment", FIND_DIALOG_TITLE); respondToDialog("Plate Comment", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001300, "New Value", CodeUnit.PLATE_COMMENT); assertCommentEquals(0x01001300, "New Value", CommentType.PLATE);
} }
@Test @Test
@ -148,13 +146,13 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001400, "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); assertCommentEquals(0x01001400, "Repeatable Comment", CommentType.REPEATABLE);
respondToDialog("Repeatable Comment", FIND_DIALOG_TITLE); respondToDialog("Repeatable Comment", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001400, "New Value", CodeUnit.REPEATABLE_COMMENT); assertCommentEquals(0x01001400, "New Value", CommentType.REPEATABLE);
} }
@Test @Test
@ -162,15 +160,15 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001500, "EOL Comment Repeated", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001500, "EOL Comment Repeated", CommentType.EOL);
assertCommentEquals(0x01001600, "EOL Comment Repeated", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001600, "EOL Comment Repeated", CommentType.EOL);
respondToDialog("EOL Comment Repeated", FIND_DIALOG_TITLE); respondToDialog("EOL Comment Repeated", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001500, "New Value", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001500, "New Value", CommentType.EOL);
assertCommentEquals(0x01001600, "New Value", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001600, "New Value", CommentType.EOL);
} }
@Test @Test
@ -178,21 +176,21 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001700, "Generic Comment Repeated", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001700, "Generic Comment Repeated", CommentType.EOL);
assertCommentEquals(0x01001800, "Generic Comment Repeated", CodeUnit.PRE_COMMENT); assertCommentEquals(0x01001800, "Generic Comment Repeated", CommentType.PRE);
assertCommentEquals(0x01001900, "Generic Comment Repeated", CodeUnit.POST_COMMENT); assertCommentEquals(0x01001900, "Generic Comment Repeated", CommentType.POST);
assertCommentEquals(0x01002000, "Generic Comment Repeated", CodeUnit.PLATE_COMMENT); assertCommentEquals(0x01002000, "Generic Comment Repeated", CommentType.PLATE);
assertCommentEquals(0x01002100, "Generic Comment Repeated", CodeUnit.REPEATABLE_COMMENT); assertCommentEquals(0x01002100, "Generic Comment Repeated", CommentType.REPEATABLE);
respondToDialog("Generic Comment Repeated", FIND_DIALOG_TITLE); respondToDialog("Generic Comment Repeated", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001700, "New Value", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001700, "New Value", CommentType.EOL);
assertCommentEquals(0x01001800, "New Value", CodeUnit.PRE_COMMENT); assertCommentEquals(0x01001800, "New Value", CommentType.PRE);
assertCommentEquals(0x01001900, "New Value", CodeUnit.POST_COMMENT); assertCommentEquals(0x01001900, "New Value", CommentType.POST);
assertCommentEquals(0x01002000, "New Value", CodeUnit.PLATE_COMMENT); assertCommentEquals(0x01002000, "New Value", CommentType.PLATE);
assertCommentEquals(0x01002100, "New Value", CodeUnit.REPEATABLE_COMMENT); assertCommentEquals(0x01002100, "New Value", CommentType.REPEATABLE);
} }
@Test @Test
@ -203,7 +201,7 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
respondToDialog("This Value Does Not Exist", FIND_DIALOG_TITLE); respondToDialog("This Value Does Not Exist", FIND_DIALOG_TITLE);
respondToDialog("New Value", REPLACE_DIALOG_TITLE); respondToDialog("New Value", REPLACE_DIALOG_TITLE);
assertCommentDoesNotExists("New Value"); assertCommentDoesNotExist("New Value");
} }
@Test @Test
@ -211,21 +209,21 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
ScriptTaskListener scriptID = env.runScript(script); ScriptTaskListener scriptID = env.runScript(script);
assertNotNull(scriptID); assertNotNull(scriptID);
assertCommentEquals(0x01001000, "EOL Comment", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001000, "EOL Comment", CommentType.EOL);
assertCommentEquals(0x01001100, "Pre Comment", CodeUnit.PRE_COMMENT); assertCommentEquals(0x01001100, "Pre Comment", CommentType.PRE);
assertCommentEquals(0x01001200, "Post Comment", CodeUnit.POST_COMMENT); assertCommentEquals(0x01001200, "Post Comment", CommentType.POST);
assertCommentEquals(0x01001300, "Plate Comment", CodeUnit.PLATE_COMMENT); assertCommentEquals(0x01001300, "Plate Comment", CommentType.PLATE);
assertCommentEquals(0x01001400, "Repeatable Comment", CodeUnit.REPEATABLE_COMMENT); assertCommentEquals(0x01001400, "Repeatable Comment", CommentType.REPEATABLE);
respondToDialog("Comment", FIND_DIALOG_TITLE); respondToDialog("Comment", FIND_DIALOG_TITLE);
respondToDialog("Test", REPLACE_DIALOG_TITLE); respondToDialog("Test", REPLACE_DIALOG_TITLE);
waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT); waitForScriptCompletion(scriptID, SCRIPT_TIMEOUT);
assertCommentEquals(0x01001000, "EOL Test", CodeUnit.EOL_COMMENT); assertCommentEquals(0x01001000, "EOL Test", CommentType.EOL);
assertCommentEquals(0x01001100, "Pre Test", CodeUnit.PRE_COMMENT); assertCommentEquals(0x01001100, "Pre Test", CommentType.PRE);
assertCommentEquals(0x01001200, "Post Test", CodeUnit.POST_COMMENT); assertCommentEquals(0x01001200, "Post Test", CommentType.POST);
assertCommentEquals(0x01001300, "Plate Test", CodeUnit.PLATE_COMMENT); assertCommentEquals(0x01001300, "Plate Test", CommentType.PLATE);
assertCommentEquals(0x01001400, "Repeatable Test", CodeUnit.REPEATABLE_COMMENT); assertCommentEquals(0x01001400, "Repeatable Test", CommentType.REPEATABLE);
} }
private void respondToDialog(String response, String titleValue) { private void respondToDialog(String response, String titleValue) {
@ -235,21 +233,22 @@ public class FindAndReplaceCommentScriptTest extends AbstractGhidraHeadedIntegra
pressButtonByText(askStringDialog, "OK"); 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); Address address = program.getMinAddress().getNewAddress(commentAddress);
String existingComment = listing.getComment(commentType, address); String existingComment = listing.getComment(commentType, address);
assertEquals(commentValue, existingComment); assertEquals(commentValue, existingComment);
} }
private void assertCommentDoesNotExists(String comment) { private void assertCommentDoesNotExist(String comment) {
Memory memory = program.getMemory(); Memory memory = program.getMemory();
Iterator<Address> addressIterator = listing.getCommentAddressIterator(memory, true); Iterator<Address> addressIterator = listing.getCommentAddressIterator(memory, true);
boolean commentExists = false; boolean commentExists = false;
while (addressIterator.hasNext()) { while (addressIterator.hasNext()) {
Address address = addressIterator.next(); Address address = addressIterator.next();
for (int i : COMMENT_TYPES) { for (CommentType type : CommentType.values()) {
String foundComment = listing.getComment(i, address); String foundComment = listing.getComment(type, address);
if (foundComment != null && foundComment.equals(comment)) { if (foundComment != null && foundComment.equals(comment)) {
commentExists = true; commentExists = true;
} }

View file

@ -100,7 +100,7 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
builder.disassemble("0x10029bd", 0xe, true); builder.disassemble("0x10029bd", 0xe, true);
builder.createLabel("0x01001068", "CreateDCW"); builder.createLabel("0x01001068", "CreateDCW");
builder.createComment("0x01001068", "CreateDCW", CodeUnit.EOL_COMMENT); builder.createComment("0x01001068", "CreateDCW", CommentType.EOL);
builder.createLabel("0x010010b4", "CreateFileW"); builder.createLabel("0x010010b4", "CreateFileW");
builder.createLabel("0x010012bc", "CreateWindowExW"); builder.createLabel("0x010012bc", "CreateWindowExW");
@ -119,8 +119,8 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
// dt.add(new BooleanDataType(), "likesCheese", null); // dt.add(new BooleanDataType(), "likesCheese", null);
// dt.add(new PointerDataType(dt), "next", null); // dt.add(new PointerDataType(dt), "next", null);
builder.createComment("0x01006642", "EOL comment", CodeUnit.EOL_COMMENT); builder.createComment("0x01006642", "EOL comment", CommentType.EOL);
builder.createComment("0x01006648", "EOL comment", CodeUnit.EOL_COMMENT); builder.createComment("0x01006648", "EOL comment", CommentType.EOL);
return builder.getProgram(); return builder.getProgram();
} }
@ -280,9 +280,9 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
listing.createData(addr(0x01006890), floatDt); listing.createData(addr(0x01006890), floatDt);
Data data = listing.getDataAt(addr(0x0100688c)); Data data = listing.getDataAt(addr(0x0100688c));
data.setComment(CodeUnit.EOL_COMMENT, "this is a float data type"); data.setComment(CommentType.EOL, "this is a float data type");
data = listing.getDataAt(addr(0x01006890)); data = listing.getDataAt(addr(0x01006890));
data.setComment(CodeUnit.EOL_COMMENT, "this is another float data type"); data.setComment(CommentType.EOL, "this is another float data type");
} }
finally { finally {
@ -357,9 +357,9 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
listing.createData(addr(0x01006890), floatDt); listing.createData(addr(0x01006890), floatDt);
Data data = listing.getDataAt(addr(0x0100688c)); Data data = listing.getDataAt(addr(0x0100688c));
data.setComment(CodeUnit.EOL_COMMENT, "this is a float data type"); data.setComment(CommentType.EOL, "this is a float data type");
data = listing.getDataAt(addr(0x01006890)); data = listing.getDataAt(addr(0x01006890));
data.setComment(CodeUnit.EOL_COMMENT, "this is another float data type"); data.setComment(CommentType.EOL, "this is another float data type");
} }
finally { finally {
@ -445,9 +445,9 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
listing.createData(addr(0x01006890), floatDt); listing.createData(addr(0x01006890), floatDt);
Data data = listing.getDataAt(addr(0x0100688c)); Data data = listing.getDataAt(addr(0x0100688c));
data.setComment(CodeUnit.EOL_COMMENT, "this is a float data type"); data.setComment(CommentType.EOL, "this is a float data type");
data = listing.getDataAt(addr(0x01006890)); data = listing.getDataAt(addr(0x01006890));
data.setComment(CodeUnit.EOL_COMMENT, "this is another float data type"); data.setComment(CommentType.EOL, "this is another float data type");
} }
finally { finally {
@ -789,7 +789,7 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
} }
else if (location instanceof EolCommentFieldLocation) { else if (location instanceof EolCommentFieldLocation) {
EolCommentFieldLocation eLoc = (EolCommentFieldLocation) location; EolCommentFieldLocation eLoc = (EolCommentFieldLocation) location;
assertEquals(CodeUnit.EOL_COMMENT, eLoc.getCommentType()); assertEquals(CommentType.EOL, eLoc.getCommentType());
String[] comment = eLoc.getComment(); String[] comment = eLoc.getComment();
for (String element : comment) { for (String element : comment) {
if (element.indexOf(text) >= 0) { if (element.indexOf(text) >= 0) {
@ -801,7 +801,7 @@ public class ListingDisplaySearcherTest extends AbstractGhidraHeadedIntegrationT
} }
else if (location instanceof AutomaticCommentFieldLocation) { else if (location instanceof AutomaticCommentFieldLocation) {
AutomaticCommentFieldLocation eLoc = (AutomaticCommentFieldLocation) location; AutomaticCommentFieldLocation eLoc = (AutomaticCommentFieldLocation) location;
assertEquals(CodeUnit.EOL_COMMENT, eLoc.getCommentType()); assertEquals(CommentType.EOL, eLoc.getCommentType());
String[] comment = eLoc.getComment(); String[] comment = eLoc.getComment();
for (String element : comment) { for (String element : comment) {
if (element.indexOf(text) >= 0) { if (element.indexOf(text) >= 0) {

View file

@ -114,7 +114,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
builder.createMemory(".debug_data", Long.toHexString(0xF0001300), 0x1C); builder.createMemory(".debug_data", Long.toHexString(0xF0001300), 0x1C);
builder.createOverlayMemory("otherOverlay", "OTHER:0", 100); 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 //create and disassemble a function
builder.setBytes("0x0100415a", 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" + "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); param, param);
builder.createComment("otherOverlay:4", "This is a comment in the other overlay", builder.createComment("otherOverlay:4", "This is a comment in the other overlay",
CodeUnit.EOL_COMMENT); CommentType.EOL);
return builder.getProgram(); return builder.getProgram();
} }
@ -376,17 +376,17 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
CodeUnit cu = listing.getCodeUnitAt(getAddr(0x0100416f)); CodeUnit cu = listing.getCodeUnitAt(getAddr(0x0100416f));
int transactionID = program.startTransaction("test"); int transactionID = program.startTransaction("test");
cu.setComment(CodeUnit.EOL_COMMENT, "call sscanf"); cu.setComment(CommentType.EOL, "call sscanf");
cu = listing.getCodeUnitAt(getAddr(0x01004178)); cu = listing.getCodeUnitAt(getAddr(0x01004178));
cu.setComment(CodeUnit.REPEATABLE_COMMENT, "make a reference to sscanf"); cu.setComment(CommentType.REPEATABLE, "make a reference to sscanf");
cu = listing.getCodeUnitAt(getAddr(0x01004192)); cu = listing.getCodeUnitAt(getAddr(0x01004192));
cu.setComment(CodeUnit.PLATE_COMMENT, "another ref to sscanf"); cu.setComment(CommentType.PLATE, "another ref to sscanf");
cu.setComment(CodeUnit.POST_COMMENT, "sscanf in a post comment"); cu.setComment(CommentType.POST, "sscanf in a post comment");
cu = listing.getCodeUnitAt(getAddr(0x0100467b)); cu = listing.getCodeUnitAt(getAddr(0x0100467b));
cu.setComment(CodeUnit.PRE_COMMENT, "call sscanf here"); cu.setComment(CommentType.PRE, "call sscanf here");
program.endTransaction(transactionID, true); program.endTransaction(transactionID, true);
@ -403,7 +403,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
ProgramLocation loc = cbPlugin.getCurrentLocation(); ProgramLocation loc = cbPlugin.getCurrentLocation();
assertEquals(getAddr(0x0100416f), loc.getAddress()); assertEquals(getAddr(0x0100416f), loc.getAddress());
assertTrue(loc instanceof CommentFieldLocation); assertTrue(loc instanceof CommentFieldLocation);
assertEquals(CodeUnit.EOL_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(CommentType.EOL, ((CommentFieldLocation) loc).getCommentType());
JButton searchButton = (JButton) findButton(dialog.getComponent(), "Next"); JButton searchButton = (JButton) findButton(dialog.getComponent(), "Next");
pressButton(searchButton); pressButton(searchButton);
@ -412,7 +412,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
loc = cbPlugin.getCurrentLocation(); loc = cbPlugin.getCurrentLocation();
assertEquals(getAddr(0x01004178), loc.getAddress()); assertEquals(getAddr(0x01004178), loc.getAddress());
assertTrue(loc instanceof CommentFieldLocation); assertTrue(loc instanceof CommentFieldLocation);
assertEquals(CodeUnit.REPEATABLE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(CommentType.REPEATABLE, ((CommentFieldLocation) loc).getCommentType());
pressButton(searchButton); pressButton(searchButton);
waitForSearchTasks(dialog); waitForSearchTasks(dialog);
@ -422,7 +422,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
assertTrue(loc instanceof CommentFieldLocation); assertTrue(loc instanceof CommentFieldLocation);
assertEquals("Search result not placed at the matching character position", 15, assertEquals("Search result not placed at the matching character position", 15,
loc.getCharOffset()); loc.getCharOffset());
assertEquals(CodeUnit.PLATE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(CommentType.PLATE, ((CommentFieldLocation) loc).getCommentType());
pressButton(searchButton); pressButton(searchButton);
waitForSearchTasks(dialog); waitForSearchTasks(dialog);
@ -430,7 +430,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
loc = cbPlugin.getCurrentLocation(); loc = cbPlugin.getCurrentLocation();
assertEquals(getAddr(0x01004192), loc.getAddress()); assertEquals(getAddr(0x01004192), loc.getAddress());
assertTrue(loc instanceof CommentFieldLocation); assertTrue(loc instanceof CommentFieldLocation);
assertEquals(CodeUnit.POST_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(CommentType.POST, ((CommentFieldLocation) loc).getCommentType());
pressButton(searchButton); pressButton(searchButton);
waitForSearchTasks(dialog); waitForSearchTasks(dialog);
@ -443,7 +443,7 @@ public class SearchTextPlugin1Test extends AbstractGhidraHeadedIntegrationTest {
loc = cbPlugin.getCurrentLocation(); loc = cbPlugin.getCurrentLocation();
assertEquals(getAddr(0x0100415a), loc.getAddress()); assertEquals(getAddr(0x0100415a), loc.getAddress());
assertTrue(loc instanceof CommentFieldLocation); assertTrue(loc instanceof CommentFieldLocation);
assertEquals(CodeUnit.PRE_COMMENT, ((CommentFieldLocation) loc).getCommentType()); assertEquals(CommentType.PRE, ((CommentFieldLocation) loc).getCommentType());
} }
private void programLocationChange2(String buttonText) throws Exception { private void programLocationChange2(String buttonText) throws Exception {

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