Java Code Examples for ghidra.program.model.address.Address#equals()

The following examples show how to use ghidra.program.model.address.Address#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FunctionNameMarkupType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Stringable getCurrentDestinationValue(VTAssociation association,
		Address destinationAddress) {
	Address expectedDestinationAddress = association.getDestinationAddress();
	if (expectedDestinationAddress.equals(destinationAddress)) {
		Function function = getDestinationFunction(association);
		if (function == null) {
			return null;
		}
		String functionName = function.getName();
		Namespace namespace = function.getParentNamespace();
		Program program = getDestinationProgram(association);
		Address address = association.getDestinationAddress();
		SymbolTable symbolTable = program.getSymbolTable();
		Symbol symbol = symbolTable.getSymbol(functionName, address, namespace);
		return new FunctionNameStringable(symbol);
	}
	return null;
}
 
Example 2
Source File: EmuX86DeobfuscateExampleScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Perform processing for the various breakpoints.
 * @param addr current execute address where emulation has been suspended
 * @throws Exception if an error occurs
 */
private void processBreakpoint(Address addr) throws Exception {

	if (addr.equals(deobfuscateCall)) {
		lastDeobfuscateArg0 = emuHelper.readRegister("RDI").longValue();
	}

	else if (addr.equals(deobfuscateReturn)) {
		long deobfuscateReturnValue = emuHelper.readRegister("RAX").longValue();
		String str = "deobfuscate(src=0x" + Long.toHexString(lastDeobfuscateArg0) + ") -> \"" +
			emuHelper.readNullTerminatedString(getAddress(deobfuscateReturnValue), 32) + "\"";
		String comment = getPreComment(deobfuscateReturn);
		if (comment == null) {
			comment = "";
		}
		else {
			comment += "\n";
		}
		comment += str;
		println("Updated pre-comment at " + deobfuscateReturn);
		setPreComment(deobfuscateReturn, comment);
	}
}
 
Example 3
Source File: MySwitchAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addReference(PcodeOp flowOp, Address toAddr) {
	
	Address flowFrom = flowOp.getSeqnum().getTarget();
	Instruction fromInstr = listing.getInstructionAt(flowFrom);
	
	for (Reference ref : fromInstr.getReferencesFrom()) {
		if (toAddr.equals(ref.getToAddress())) {
			return;
		}
	}
	
	FlowType ftype = fromInstr.getFlowType();
	
	fromInstr.addMnemonicReference(toAddr, ftype, SourceType.ANALYSIS);
}
 
Example 4
Source File: SleighDebugLogger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public ParserContext getParserContext(Address instructionAddress)
		throws UnknownContextException, MemoryAccessException {
	if (instructionAddress.equals(buf.getAddress())) {
		return getParserContext();
	}
	append("Warning! ignored request for instruction context at " + instructionAddress);
	return null;
}
 
Example 5
Source File: SymbolDatabaseAdapterV2.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.program.database.symbol.SymbolDatabaseAdapter#getSymbolIDs(ghidra.program.model.address.Address)
 */
@Override
long[] getSymbolIDs(Address addr) throws IOException {
	long key = addrMap.getKey(addr, false);
	if (key == AddressMap.INVALID_ADDRESS_KEY && !addr.equals(Address.NO_ADDRESS)) {
		return new long[0];
	}
	return symbolTable.findRecords(new LongField(key), SYMBOL_ADDR_COL);
}
 
Example 6
Source File: RefListV0.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
synchronized ReferenceDB getRef(Address refAddress, int opIndex) {
	ReferenceIterator it = getRefs();
	while (it.hasNext()) {
		Reference ref = it.next();
		if (ref.getOperandIndex() == opIndex) {
			Address addr = isFrom ? ref.getToAddress() : ref.getFromAddress();
			if (refAddress.equals(addr)) {
				return (ReferenceDB) ref;
			}
		}
	}
	return null;

}
 
Example 7
Source File: Rtti1Model.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean refersToRtti0(Address rtti0Address) {

	Address referredToAddress;
	try {
		referredToAddress = getRtti0Address();
	}
	catch (InvalidDataTypeException e) {
		return false;
	}
	return rtti0Address.equals(referredToAddress);
}
 
Example 8
Source File: RefListV0.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
synchronized boolean setPrimary(Reference ref, boolean isPrimary) throws IOException {
	int opIndex = ref.getOperandIndex();
	Address changeAddr = isFrom ? ref.getToAddress() : ref.getFromAddress();

	Reference[] result = new Reference[1];
	int pos = 0;
	int newPos = 0;
	for (int i = 0; i < numRefs; i++) {
		newPos = decode(refData, pos, result);
		Reference r = result[0];
		if (r.getOperandIndex() == opIndex) {
			Address addr = isFrom ? r.getToAddress() : r.getFromAddress();
			if (changeAddr.equals(addr)) {
				if (isPrimary == r.isPrimary()) {
					return false; // change not required
				}
				boolean isOffset = false;
				boolean isShifted = false;
				long offsetOrShift = 0;
				if (r.isMemoryReference()) {
					isOffset = ((MemReferenceDB) r).isOffset();
					isShifted = ((MemReferenceDB) r).isShifted();
					offsetOrShift = ((MemReferenceDB) r).getOffsetOrShift();
				}

				byte[] bytes =
					encode(r.getFromAddress(), r.getToAddress(), r.getReferenceType(),
						r.getSource(), r.getOperandIndex(), r.getSymbolID(), isPrimary,
						isOffset, isShifted, offsetOrShift);

				System.arraycopy(bytes, 0, refData, pos, bytes.length);
				updateRecord();
				return true;
			}
		}
		pos = newPos;
	}
	return false;
}
 
Example 9
Source File: StructureMemberLocationDescriptor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean isAddressInDataPath(Address address) {
	if (address == null) {
		return false;
	}
	for (Data component : dataPathList) {
		Address componentAddress = component.getMinAddress();
		if (address.equals(componentAddress)) {
			return true;
		}
	}

	return false;
}
 
Example 10
Source File: AddressInputDialog.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean stopCellEditing() {
	ListSelectionModel columnSelectionModel = table.getColumnModel().getSelectionModel();
	columnSelectionModel.setValueIsAdjusting(true);
	int columnAnchor = columnSelectionModel.getAnchorSelectionIndex();
	int columnLead = columnSelectionModel.getLeadSelectionIndex();

	dialog.close();

	Address newAddress = null;
	if (dialog instanceof DialogProvider) {
		newAddress = ((DialogProvider) dialog).getAddress();
	}
	if (newAddress == null) {
		// user must have cancelled
		fireEditingCanceled();
		return true;
	}

	if (newAddress.equals(address)) {
		fireEditingCanceled();
		return true;
	}

	address = newAddress;
	fireEditingStopped();

	columnSelectionModel.setAnchorSelectionIndex(columnAnchor);
	columnSelectionModel.setLeadSelectionIndex(columnLead);
	columnSelectionModel.setValueIsAdjusting(false);

	return true;
}
 
Example 11
Source File: CodeBlockCache.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Get the cached block whose first entry-point is addr. 
 * This method is slightly more efficient than getBlockWithEntryAt,
 * however, it should only be used when the cached block has exactly
 * one entry-point.
 * @return the block with an entry-point address of addr, or null of
 * the block was not found.
 */
CodeBlock getBlockAt(Address addr){
    Object[] blocks = getObjects(addr);
    for (int i=0; i < blocks.length; i++) {
        CodeBlock block = (CodeBlock) blocks[i];
        Address startAddr = block.getFirstStartAddress();
        if (startAddr.equals(addr)) {
            return block;
        }
    }
    return null;
}
 
Example 12
Source File: FindReferencesToAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isAddToPopup(ListingActionContext context) {
	if (!super.isAddToPopup(context)) {
		return false;
	}

	LocationDescriptor descriptor = getDescriptor(context);
	if (descriptor == null) {
		return false;
	}

	if (!(descriptor instanceof AddressLocationDescriptor)) {
		return true;
	}

	AddressLocationDescriptor addressDescriptor = (AddressLocationDescriptor) descriptor;
	Address homeAddress = addressDescriptor.getHomeAddress();
	Address actionAddress = context.getAddress();
	if (actionAddress.equals(homeAddress)) {
		// A bit of guilty knowledge here: this is handled by another action, the
		// FindReferencesToAddressAction. For that situation, we don't want two actions 
		// appearing in the popup menu.
		return false;
	}

	return true;
}
 
Example 13
Source File: VTMatchApplyTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testApplyWithSomeMarkupItemsAlreadyApplied() throws Exception {

	Address sourceAddress = addr("0x01002cf5", sourceProgram);
	Address destinationAddress = addr("0x01002cf5", destinationProgram);

	VTMatch match = createMatchSetWithOneMatch(session, sourceAddress, destinationAddress);

	// force known values for the test
	Address labelAddress = addr("0x01002d06", sourceProgram);
	Symbol sourceSymbol1 = addLabel(labelAddress, sourceProgram);
	Symbol destinationSymbol1 = addLabel(labelAddress, destinationProgram);

	// symbol/comment choices
	ToolOptions options = controller.getOptions();
	options.setEnum(VTOptionDefines.LABELS, LabelChoices.REPLACE_ALL);
	options.setEnum(VTOptionDefines.END_OF_LINE_COMMENT, CommentChoices.APPEND_TO_EXISTING);

	// symbol/comment choices
	String sourceComment = "Hi mom replace";
	String destinationComment = "Hi dad replace";
	Address commentAddress = addr("0x01002d06", sourceProgram);
	setComment(sourceProgram, commentAddress, CodeUnit.EOL_COMMENT, sourceComment);
	setComment(destinationProgram, commentAddress, CodeUnit.EOL_COMMENT, destinationComment);

	MatchInfo matchInfo = controller.getMatchInfo(match);
	Collection<VTMarkupItem> markupItems =
		matchInfo.getAppliableMarkupItems(TaskMonitorAdapter.DUMMY_MONITOR);

	List<VTMarkupItem> itemsToApply = new ArrayList<>();
	for (VTMarkupItem item : markupItems) {
		Address itemSourceAddress = item.getSourceAddress();
		if (commentAddress.equals(itemSourceAddress) &&
			(item.getMarkupType() instanceof CommentMarkupType)) {
			itemsToApply.add(item);
			break;
		}
	}

	//
	// Apply only one item now (our comment item)
	//
	ApplyMarkupItemTask markupTask =
		new ApplyMarkupItemTask(controller.getSession(), itemsToApply, options);
	runTask(markupTask);

	String expectedComment = destinationComment + "\n" + sourceComment;
	Listing destinationListing = destinationProgram.getListing();
	String comment = destinationListing.getComment(CodeUnit.EOL_COMMENT, commentAddress);
	assertEquals("Comment was not applied", expectedComment, comment);

	//
	// Now call the match apply task and make sure the remaining item is applied
	//
	List<VTMatch> matches = new ArrayList<>();
	matches.add(match);
	ApplyMatchTask task = new ApplyMatchTask(controller, matches);
	runTask(task);

	// make sure these symbols are still applied (from earlier)
	Symbol expectedSymbol = sourceSymbol1;
	SymbolTable symbolTable = destinationProgram.getSymbolTable();
	Symbol[] newSymbols = symbolTable.getSymbols(labelAddress);
	Symbol[] expectedSymbols = new Symbol[] { expectedSymbol };
	assertTrue("New symbol does not match the source symbol",
		SystemUtilities.isArrayEqual(expectedSymbols, newSymbols));

	expectedComment = destinationComment + "\n" + sourceComment;
	destinationListing = destinationProgram.getListing();
	comment = destinationListing.getComment(CodeUnit.EOL_COMMENT, commentAddress);
	assertEquals("Comment was not applied", expectedComment, comment);

	//
	// Now test the unapply
	//
	ClearMatchTask unapplyTask = new ClearMatchTask(controller, matches);
	runTask(unapplyTask);
	newSymbols = symbolTable.getSymbols(labelAddress);
	expectedSymbols = new Symbol[] { destinationSymbol1 };
	assertTrue("New symbol does not match the source symbol",
		SystemUtilities.isArrayEqual(expectedSymbols, newSymbols));

	comment = destinationListing.getComment(CodeUnit.EOL_COMMENT, commentAddress);
	assertEquals("Comment was not unpplied", destinationComment, comment);
}
 
Example 14
Source File: AddressCorrelationTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Check that the expected comment markup was created and it has the expected destination address.
 * @param desiredCommentMarkupType the comment markup type we are checking
 * @param sourceAddressString the source address of the markup
 * @param comment the expected comment
 * @param destinationAddressString the expected destination address for the markup
 */
private void checkCommentMarkup(VTMarkupType desiredCommentMarkupType,
		String sourceAddressString, String comment, String destinationAddressString) {
	Address srcAddress = addr(sourceAddressString, sourceProgram);
	Address destAddress =
		destinationAddressString.equals("NO_ADDRESS") ? Address.NO_ADDRESS : addr(
			destinationAddressString, destinationProgram);

	Collection<VTMarkupItem> appliableMarkupItems =
		controller.getMatchInfo(testMatch).getAppliableMarkupItems(TaskMonitor.DUMMY); // Initialize the cache.

	for (VTMarkupItem vtMarkupItem : appliableMarkupItems) {
		VTMarkupType markupType = vtMarkupItem.getMarkupType();
		if (markupType != desiredCommentMarkupType) {
			continue; // Not the right markup type.
		}
		Address markupSrcAddress = vtMarkupItem.getSourceAddress();
		if (!markupSrcAddress.equals(srcAddress)) {
			continue; // Not the right source address.
		}

		// Check the comment.
		Stringable sourceValue = vtMarkupItem.getSourceValue();
		String displayString = sourceValue.getDisplayString();
		assertEquals(comment, displayString);

		// Check destination address
		Address markupDestAddress = vtMarkupItem.getDestinationAddress();
		if (markupDestAddress == null) {
			markupDestAddress = Address.NO_ADDRESS;
		}
		boolean isNoAddress =
			markupDestAddress == null || markupDestAddress == Address.NO_ADDRESS;
		if (destAddress == Address.NO_ADDRESS) {
			assertTrue("Unexpected destination address of NO_ADDRESS for " +
				vtMarkupItem.getMarkupType().getDisplayName() + " markup @ " +
				vtMarkupItem.getSourceAddress().toString() + ".", isNoAddress);
			return;
		}
		assertTrue("Unexpected destination address of " + markupDestAddress.toString() +
			" when expecting " + destAddress.toString() + " for " +
			vtMarkupItem.getMarkupType().getDisplayName() + " markup @ " +
			vtMarkupItem.getSourceAddress().toString() + ".",
			markupDestAddress.equals(destAddress));
		return;
	}
}
 
Example 15
Source File: EmuX86DeobfuscateExampleScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected void run() throws Exception {

	String format =
		currentProgram.getOptions(Program.PROGRAM_INFO).getString("Executable Format", null);

	if (currentProgram == null || !currentProgram.getName().startsWith(PROGRAM_NAME) ||
		!"x86:LE:64:default".equals(currentProgram.getLanguageID().toString()) ||
		!ElfLoader.ELF_NAME.equals(format)) {

		printerr(
			"This emulation example script is specifically intended to be executed against the\n" +
				PROGRAM_NAME +
				" program whose source is contained within the GhidraClass exercise files\n" +
				"(see docs/GhidraClass/ExerciseFiles/Emulation/" + PROGRAM_NAME + ".c).\n" +
				"This program should be compiled using gcc for x86 64-bit, imported into your project, \n" +
				"analyzed and open as the active program before running ths script.");
		return;
	}

	// Identify function to be emulated
	mainFunctionEntry = getSymbolAddress("main");

	// Obtain entry instruction in order to establish initial processor context
	Instruction entryInstr = getInstructionAt(mainFunctionEntry);
	if (entryInstr == null) {
		printerr("Instruction not found at main entry point: " + mainFunctionEntry);
		return;
	}

	// Identify important symbol addresses
	// NOTE: If the sample is recompiled the following addresses may need to be adjusted
	Instruction callSite = getCalledFromInstruction("deobfuscate");
	if (callSite == null) {
		printerr("Instruction not found at call site for: deobfuscate");
		return;
	}

	deobfuscateCall = callSite.getAddress();
	deobfuscateReturn = callSite.getFallThrough(); // instruction address immediately after deobfuscate call

	// Remove prior pre-comment
	setPreComment(deobfuscateReturn, null);

	// Establish emulation helper
	emuHelper = new EmulatorHelper(currentProgram);
	try {

		// Initialize stack pointer (not used by this example)
		long stackOffset =
			(entryInstr.getAddress().getAddressSpace().getMaxAddress().getOffset() >>> 1) -
				0x7fff;
		emuHelper.writeRegister(emuHelper.getStackPointerRegister(), stackOffset);

		// Setup breakpoints
		emuHelper.setBreakpoint(deobfuscateCall);
		emuHelper.setBreakpoint(deobfuscateReturn);

		// Set controlled return location so we can identify return from emulated function
		controlledReturnAddr = getAddress(CONTROLLED_RETURN_OFFSET);
		emuHelper.writeStackValue(0, 8, CONTROLLED_RETURN_OFFSET);
		emuHelper.setBreakpoint(controlledReturnAddr);

		Msg.debug(this, "EMU starting at " + mainFunctionEntry);

		// Execution loop until return from function or error occurs
		while (!monitor.isCancelled()) {
			boolean success =
				(emuHelper.getEmulateExecutionState() == EmulateExecutionState.BREAKPOINT)
						? emuHelper.run(monitor)
						: emuHelper.run(mainFunctionEntry, entryInstr, monitor);
			Address executionAddress = emuHelper.getExecutionAddress();
			if (monitor.isCancelled()) {
				println("Emulation cancelled");
				return;
			}
			if (executionAddress.equals(controlledReturnAddr)) {
				println("Returned from function");
				return;
			}
			if (!success) {
				String lastError = emuHelper.getLastError();
				printerr("Emulation Error: " + lastError);
				return;
			}
			processBreakpoint(executionAddress);
		}
	}
	finally {
		// cleanup resources and release hold on currentProgram
		emuHelper.dispose();
	}
}
 
Example 16
Source File: ProgramDatabaseFieldSearcher.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public boolean hasMatch( Address address ) {
	if (!address.equals(currentAddress)) {
		return false;
	}
	return !matchesForCurrentAddress.isEmpty();
}
 
Example 17
Source File: VTDualListingHighlightProvider.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Color getMarkupBackgroundColor(int cursorTextOffset, VTMarkupItem vtMarkupItem,
		int startIndex, int endIndex) {
	Color highlightColor = null;
	Address sourceAddress = vtMarkupItem.getSourceAddress();
	Address destinationAddress = vtMarkupItem.getDestinationAddress();
	VTMarkupItemStatus status = vtMarkupItem.getStatus();
	if (status == VTMarkupItemStatus.DONT_CARE) {
		highlightColor = IGNORED_MARKUP_COLOR;
	}
	else if (status == VTMarkupItemStatus.DONT_KNOW) {
		highlightColor = IGNORED_MARKUP_COLOR;
	}
	else if (status == VTMarkupItemStatus.REJECTED) {
		highlightColor = REJECTED_MARKUP_COLOR;
	}
	else if (status == VTMarkupItemStatus.CONFLICT) {
		highlightColor = CONFLICT_MARKUP_COLOR;
	}
	else if (destinationAddress == null || destinationAddress == Address.NO_ADDRESS) {
		highlightColor = NO_ADDRESS_MARKUP_COLOR;
	}
	else if (status == VTMarkupItemStatus.UNAPPLIED) {
		highlightColor = UNAPPLIED_MARKUP_COLOR;
	}
	else if (status.isUnappliable()) {
		highlightColor = APPLIED_MARKUP_COLOR;
	}
	else if (status == VTMarkupItemStatus.FAILED_APPLY) {
		highlightColor = FAILED_MARKUP_COLOR;
	}
	else if (status == VTMarkupItemStatus.SAME) {
		highlightColor = SAME_MARKUP_COLOR;
	}
	else {
		return null;
	}
	if (currentMarkupItem != null) {
		VTMarkupType currentMarkupType = currentMarkupItem.getMarkupType();
		VTMarkupType markupType = vtMarkupItem.getMarkupType();
		Address currentSourceAddress = currentMarkupItem.getSourceAddress();
		boolean inCurrentMarkup =
			(currentMarkupType == markupType) && currentSourceAddress.equals(sourceAddress);
		if (inCurrentMarkup) {
			// Set the highlight color to be a bit darker than normal.  Color.darker() returns
			// a color that is too dark, so use this custom function instead.
			highlightColor = shade(highlightColor, 0.85);
		}
	}
	return highlightColor;
}
 
Example 18
Source File: RefListV0.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private int decode(byte[] data, int offset, Reference[] result) {
	long symbolID = -1;
	long addr = getLong(data, offset);
	offset += 8;
	RefListFlagsV0 flags = new RefListFlagsV0(data[offset++]);
	RefType refType = RefTypeFactory.get(data[offset++]);
	byte opIndex = data[offset++];

	SourceType source = flags.getSource();

	long offsetOrShift = 0;

	if (flags.hasSymbolID()) {
		symbolID = getLong(data, offset);
		offset += 8;
	}
	Address from = isFrom ? address : addrMap.decodeAddress(addr);
	Address to = isFrom ? addrMap.decodeAddress(addr) : address;
	if (flags.isOffsetRef() || flags.isShiftRef()) {
		offsetOrShift = getLong(data, offset);
		offset += 8;
		if (flags.isShiftRef()) {
			result[0] =
				new ShiftedReferenceDB(program, from, to, refType, opIndex, source,
					flags.isPrimary(), symbolID, (int) offsetOrShift);
		}
		else {
			result[0] =
				new OffsetReferenceDB(program, from, to, refType, opIndex, source,
					flags.isPrimary(), symbolID, offsetOrShift);
		}
	}
	else if (to.isExternalAddress()) {
		result[0] = new ExternalReferenceDB(program, from, to, refType, opIndex, source);
	}
	else if (from.equals(Address.EXT_FROM_ADDRESS)) {
		result[0] =
			new EntryPointReferenceDB(from, to, refType, opIndex, source, flags.isPrimary(),
				symbolID);
	}
	else if (to.isStackAddress()) {
		result[0] =
			new StackReferenceDB(program, from, to, refType, opIndex, source,
				flags.isPrimary(), symbolID);
	}
	else {
		result[0] =
			new MemReferenceDB(program, from, to, refType, opIndex, source, flags.isPrimary(),
				symbolID);
	}
	return offset;
}
 
Example 19
Source File: RefListV0.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
synchronized boolean setSymbolID(Reference ref, long symbolID) throws IOException {
	int opIndex = ref.getOperandIndex();
	Address changeAddr = isFrom ? ref.getToAddress() : ref.getFromAddress();

	Reference[] result = new Reference[1];
	int pos = 0;
	int newPos = 0;
	for (int i = 0; i < numRefs; i++) {
		newPos = decode(refData, pos, result);
		Reference r = result[0];
		if (r.getOperandIndex() == opIndex) {
			Address addr = isFrom ? r.getToAddress() : r.getFromAddress();
			if (changeAddr.equals(addr)) {
				boolean isPrimary = ref.isPrimary();
				boolean isOffset = false;
				boolean isShifted = false;
				long offsetOrShift = 0;
				if (r.isMemoryReference()) {
					isOffset = ((MemReferenceDB) r).isOffset();
					isShifted = ((MemReferenceDB) r).isShifted();
					offsetOrShift = ((MemReferenceDB) r).getOffsetOrShift();
				}

				byte[] bytes =
					encode(r.getFromAddress(), r.getToAddress(), r.getReferenceType(),
						r.getSource(), r.getOperandIndex(), symbolID, isPrimary, isOffset,
						isShifted, offsetOrShift);

				if (bytes.length == newPos - pos) {
					System.arraycopy(bytes, 0, refData, pos, bytes.length);
				}
				else {
					byte[] newData = new byte[refData.length - (newPos - pos) + bytes.length];
					System.arraycopy(refData, 0, newData, 0, pos);
					System.arraycopy(bytes, 0, newData, pos, bytes.length);
					System.arraycopy(refData, newPos, newData, pos + bytes.length,
						refData.length - newPos);
					refData = newData;
				}
				updateRecord();
				return true;
			}
		}
		pos = newPos;
	}
	return false;
}
 
Example 20
Source File: MarkupItemImpl.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void unapply() throws VersionTrackingApplyException {
	Address destinationAddress = markupItemStorage.getDestinationAddress(); // Save destination address before reset.
	VTMarkupItemStatus oldStatus = markupItemStorage.getStatus();
	markupType.unapplyMarkup(this);
	markupItemStorage.setStatus(UNAPPLIED);

	markupItemStorage = maybeReset();

	VTMarkupItemStatus newStatus = markupItemStorage.getStatus();
	if (oldStatus != newStatus) {
		// the only way these to stati are the same is if you unapply an unapplied
		fireMarkupItemStatusChanged(oldStatus, newStatus);
	}

	// isUnapplyingItems makes sure only the first markup item will try
	// to remove all other items of this type and address.
	if (isUnApplyingItems) {
		return;
	}

	// Unapply other items of this markup type at the same address as this.
	try {
		isUnApplyingItems = true;

		// Reset each markup item that is the same markup type and destination address.
		VTAssociation association = markupItemStorage.getAssociation();
		Collection<VTMarkupItem> markupItems;
		try {
			markupItems = association.getMarkupItems(TaskMonitorAdapter.DUMMY_MONITOR);
			for (VTMarkupItem currentMarkupItem : markupItems) {
				if (currentMarkupItem == this) {
					continue;
				}
				if ((currentMarkupItem.getMarkupType() == markupType) &&
					currentMarkupItem.canUnapply()) {
					Address itemDestination = currentMarkupItem.getDestinationAddress();
					if (destinationAddress.equals(itemDestination)) {
						currentMarkupItem.unapply();
					}
				}
			}
		}
		catch (CancelledException e) {
			// can't happen--dummy monitor
		}
	}
	finally {
		isUnApplyingItems = false;
	}
	hasSameValues = null;
}