ghidra.program.model.listing.CodeUnit Java Examples

The following examples show how to use ghidra.program.model.listing.CodeUnit. 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: ByteCountProgramLocationBasedTableColumn.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Integer getValue(ProgramLocation rowObject, Settings settings, Program program,
		ServiceProvider serviceProvider) throws IllegalArgumentException {

	CodeUnit cu = program.getListing().getCodeUnitContaining(rowObject.getAddress());
	if (cu == null) { // can happen for 'SpecialAddress'es
		return 0;
	}

	try {
		return cu.getBytes().length;
	}
	catch (MemoryAccessException e) {
		return 0;
	}
}
 
Example #2
Source File: FindEmptySpaceScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected void addLabelAndExportSym(Address matchAddr, long len, String stem, String tag,
		String optComment) {
	String label = stem + "_" + matchAddr + "_" + len;
	label = label.replaceAll(":", "_");
	String comment = "{@exportsym " + tag + " " + optComment + "}";
	CodeUnit cd = currentProgram.getListing().getCodeUnitAt(matchAddr);
	if (cd == null) {
		return;
	}
	AddLabelCmd lcmd = new AddLabelCmd(matchAddr, label, false, SourceType.USER_DEFINED);
	lcmd.applyTo(currentProgram);
	String commentThere = cd.getComment(CodeUnit.EOL_COMMENT);
	if (commentThere != null) {
		comment = commentThere + "\n" + comment;
	}
	cd.setComment(CodeUnit.EOL_COMMENT, comment);
}
 
Example #3
Source File: DisplayableEolTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testReferenceToOffcutStringData() throws Exception {

	Address dataStartAddress = addr("0x1001234");
	Address offcutAddress = dataStartAddress.add(2);
	Command cmd =
		new AddMemRefCmd(addr("0x1001000"), offcutAddress, SourceType.USER_DEFINED, 0, true);
	applyCmd(cmd);

	Listing listing = program.getListing();
	CodeUnit cu = listing.getCodeUnitAt(addr("0x1001000"));

	// with this at false, all of the string will be rendered
	boolean useAbbreviatedComments = false;

	DisplayableEol displayableEol =
		new DisplayableEol(cu, true, true, true, false, 5, useAbbreviatedComments);

	String[] comments = displayableEol.getAutomaticComment();
	assertEquals(1, comments.length);
	assertEquals("= \"one.two\"", comments[0]);
}
 
Example #4
Source File: ExternalDisassemblyFieldFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public ListingField getField(ProxyObj<?> proxy, int varWidth) {
	if (!enabled) {
		return null;
	}
	Object obj = proxy.getObject();
	if (!(obj instanceof CodeUnit)) {
		return null;
	}
	CodeUnit cu = (CodeUnit) obj;

	try {
		String disassembly = getDisassemblyText(cu);
		if (disassembly == null) {
			return null;
		}
		AttributedString text = new AttributedString(disassembly, Color.black, getMetrics());
		FieldElement fieldElement = new TextFieldElement(text, 0, 0);
		return ListingTextField.createSingleLineTextField(this, proxy, fieldElement,
			startX + varWidth, width, hlProvider);
	}
	catch (Exception e) {
		return getErrorText(proxy, varWidth, e);
	}
}
 
Example #5
Source File: ReferencesPluginScreenShots.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testStackRefPanel() {
	goToListing(0x0401008);

	CodeUnit cu = program.getListing().getCodeUnitAt(addr(0x401008));
	ReferencesPlugin plugin = getPlugin(tool, ReferencesPlugin.class);
	final EditReferenceDialog dialog = new EditReferenceDialog(plugin);
	dialog.initDialog(cu, 0, 0, null);
	runSwing(() -> {
		JRadioButton choiceButton = (JRadioButton) getInstanceField("stackRefChoice", dialog);
		invokeInstanceMethod("refChoiceActivated", dialog,
			new Class<?>[] { JRadioButton.class }, new Object[] { choiceButton });
	}, true);
	showDialogWithoutBlocking(tool, dialog);

	JPanel panel = (JPanel) getInstanceField("stackRefPanel", dialog);
	Rectangle bounds = panel.getBounds();
	bounds.height = bounds.height / 2;
	bounds = SwingUtilities.convertRectangle(panel.getParent(), bounds, null);
	captureDialog();
	takeSnippet(bounds);
}
 
Example #6
Source File: CommentMerger.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private int getCodeUnitCommentType(int programMergeCommentType) {
	switch (programMergeCommentType) {
		case ProgramMergeFilter.PLATE_COMMENTS:
			return CodeUnit.PLATE_COMMENT;
		case ProgramMergeFilter.PRE_COMMENTS:
			return CodeUnit.PRE_COMMENT;
		case ProgramMergeFilter.EOL_COMMENTS:
			return CodeUnit.EOL_COMMENT;
		case ProgramMergeFilter.REPEATABLE_COMMENTS:
			return CodeUnit.REPEATABLE_COMMENT;
		case ProgramMergeFilter.POST_COMMENTS:
			return CodeUnit.POST_COMMENT;
		default:
			return -1;
	}
}
 
Example #7
Source File: CommentsDialog.java    From ghidra with Apache License 2.0 6 votes vote down vote up
void setCommentType(int type) {
	switch (type) {
		case CodeUnit.EOL_COMMENT:
			tab.setSelectedIndex(0);
			break;
		case CodeUnit.PRE_COMMENT:
			tab.setSelectedIndex(1);
			break;
		case CodeUnit.POST_COMMENT:
			tab.setSelectedIndex(2);
			break;
		case CodeUnit.PLATE_COMMENT:
			tab.setSelectedIndex(3);
			break;
		case CodeUnit.REPEATABLE_COMMENT:
			tab.setSelectedIndex(4);
			break;
	}
}
 
Example #8
Source File: EditReferenceDialog.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public void initDialog(CodeUnit cu, int opIndex, int subIndex, Reference ref) {

		initializing = true;

		instrPanel.setCodeUnitLocation(cu, opIndex, subIndex, ref != null);

		if (ref != null) {
			configureEditReference(cu, ref);
		}
		else {
			configureAddReference(opIndex, subIndex);
		}

		initializing = false;
		activeRefPanel.requestFocus();
	}
 
Example #9
Source File: InstructionPanel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Set the code unit location.
 * @param cu code unit
 * @param loc location
 * @param opIndex operand index
 * @param showBlockID ID for what to show for the block name in the
 * operand
 */
void setCodeUnitLocation(CodeUnit cu, int opIndex, int subIndex, boolean locked) {
	if (cu != null) {
		this.locked = locked;
		addressLabel.setText(cu.getMinAddress().toString());
		memory = cu.getProgram().getMemory();
		cuFormat.addChangeListener(this);
	}
	else {
		cuFormat.removeChangeListener(this);
		this.locked = false;
		addressLabel.setText("");
		memory = null;
	}
	currentCodeUnit = cu;
	activeIndex = ReferenceManager.MNEMONIC - 1; // force updateLabels to work
	updateLabels(opIndex, subIndex);
	updateDropTargets(cu != null ? cu.getNumOperands() : -1);
}
 
Example #10
Source File: CommentHistoryDialog.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private JPanel buildMainPanel() {
	JPanel mainPanel = new JPanel(new BorderLayout());
	tabbedPane = new JTabbedPane();
	mainPanel.add(tabbedPane);
	
	eolPanel = new CommentHistoryPanel(CodeUnit.EOL_COMMENT);
	prePanel = new CommentHistoryPanel(CodeUnit.PRE_COMMENT);
	postPanel = new CommentHistoryPanel(CodeUnit.POST_COMMENT);
	platePanel = new CommentHistoryPanel(CodeUnit.PLATE_COMMENT);
	repeatablePanel = new CommentHistoryPanel(CodeUnit.REPEATABLE_COMMENT);

	JScrollPane sp = new JScrollPane(eolPanel);
	JViewport vp = sp.getViewport();
	Dimension d = vp.getPreferredSize();
	sp.getViewport().setPreferredSize(new Dimension(500, d.height*7));
	tabbedPane.addTab("  EOL Comment    ",sp);
	tabbedPane.addTab("  Pre Comment    ",new JScrollPane(prePanel));
	tabbedPane.addTab("  Post Comment   ",new JScrollPane(postPanel));
	tabbedPane.addTab("  Plate Comment  ",new JScrollPane(platePanel));
	tabbedPane.addTab("  Repeatable Comment  ", new JScrollPane(repeatablePanel));
	
	tabbedPane.addChangeListener(this);
	return mainPanel;
}
 
Example #11
Source File: MemoryBlockStartFieldFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Overridden to ensure that we return a {@link MemoryBlockStartFieldLocation} instance.
 * 
 * @see ghidra.app.util.viewer.field.FieldFactory#getProgramLocation(int, int, ghidra.app.util.viewer.field.ListingField)
 */
@Override
public ProgramLocation getProgramLocation(int row, int col, ListingField bf) {

	Object proxyObject = bf.getProxy().getObject();
	if (!(proxyObject instanceof CodeUnit)) {
		return null;
	}
	CodeUnit cu = (CodeUnit) proxyObject;

	String[] comments;
	List<AttributedString> attributedStrings = createBlockStartText(cu);
	if (attributedStrings == null) {
		comments = new String[0];
	}
	else {
		comments = new String[attributedStrings.size()];
		for (int i = 0; i < comments.length; i++) {
			comments[i] = attributedStrings.get(i).getText();
		}
	}

	return new MemoryBlockStartFieldLocation(cu.getProgram(), cu.getMinAddress(), null, row,
		col, comments, 0);
}
 
Example #12
Source File: ListingDiffHighlightProvider.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Highlight[] getHighlights(String text, Object obj,
		Class<? extends FieldFactory> fieldFactoryClass, int cursorTextOffset) {

	Highlight[] highlights = EMPTY_HIGHLIGHT;

	if (obj instanceof CodeUnit) {
		CodeUnit codeUnit = (CodeUnit) obj;
		if (fieldFactoryClass == BytesFieldFactory.class) {
			highlights = getByteDiffHighlights(text, codeUnit, cursorTextOffset);
		}
		else if (fieldFactoryClass == MnemonicFieldFactory.class) {
			highlights = getMnemonicDiffHighlights(text, codeUnit, cursorTextOffset);
		}
		else if (fieldFactoryClass == OperandFieldFactory.class) {
			highlights = getOperandDiffHighlights(text, codeUnit, cursorTextOffset);
		}
	}
	return highlights;
}
 
Example #13
Source File: ExactBytesFunctionHasher.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected long hash(TaskMonitor monitor, ArrayList<CodeUnit> units, int byteCount)
		throws MemoryAccessException, CancelledException {
	byte[] buffer = new byte[byteCount];
	int offset = 0;
	for (CodeUnit codeUnit : units) {
		monitor.checkCanceled();

		try {
			codeUnit.getBytesInCodeUnit(buffer, offset);
		}
		catch (MemoryAccessException e) {
			Msg.warn(this, "Could not get code unit bvtes at " + codeUnit.getAddress());
		}
		offset += codeUnit.getLength();
	}
	if (offset != byteCount) {
		throw new IllegalStateException("did NOT use all the codeUnit buffer bytes");
	}
	synchronized (digest) {
		digest.reset();
		digest.update(buffer, monitor);
		return digest.digestLong();
	}
}
 
Example #14
Source File: ReferenceManagerTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
   public void testRemoveExternalReferences() throws Exception {

	refMgr.addExternalReference(addr(100), "foo.dll", "ABC", null, SourceType.USER_DEFINED, 0,
		RefType.DATA);
	CodeUnit cu = listing.getCodeUnitAt(addr(100));
	Reference ref = cu.getExternalReference(0);
	assertNotNull(ref);
	Reference[] refs = refMgr.getReferencesFrom(addr(100));
	assertEquals(1, refs.length);

	refMgr.delete(ref);

	assertNull(cu.getExternalReference(0));
	refs = refMgr.getReferencesFrom(addr(100));
	assertEquals(0, refs.length);
}
 
Example #15
Source File: MemoryMapProvider1Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testGoToAddress() {
	Rectangle rect = table.getCellRect(2, MemoryMapModel.START, true);
	clickMouse(table, 1, rect.x, rect.y, 1, 0);
	CodeBrowserPlugin cb = env.getPlugin(CodeBrowserPlugin.class);
	assertEquals(getAddr(0x0100a000), cb.getCurrentAddress());

	rect = table.getCellRect(3, MemoryMapModel.END, true);
	clickMouse(table, 1, rect.x, rect.y, 1, 0);
	String str = (String) model.getValueAt(3, MemoryMapModel.END);
	Address endAddr = AddressEvaluator.evaluate(program, str);

	// the cursor should be on the address that contains the last byte of the range, which
	// happens to be a member of a structure that we opened
	CodeUnit cu = program.getListing().getCodeUnitContaining(endAddr);
	assertTrue(cu.contains(cb.getCurrentAddress()));
}
 
Example #16
Source File: AddressFieldFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public ProgramLocation getProgramLocation(int row, int col, ListingField lf) {
	Object obj = lf.getProxy().getObject();
	if (!(obj instanceof CodeUnit)) {
		return null;
	}
	CodeUnit cu = (CodeUnit) obj;

	Address addr = cu.getMinAddress();

	int[] cpath = null;
	if (cu instanceof Data) {
		cpath = ((Data) cu).getComponentPath();
	}

	return new AddressFieldLocation(cu.getProgram(), addr, cpath, addr.toString(), col);
}
 
Example #17
Source File: DeleteSpacePropertyScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
   public void run() throws Exception {
	
	PropertyMapManager propMgr = currentProgram.getUsrPropertyManager();
	IntPropertyMap map = propMgr.getIntPropertyMap(CodeUnit.SPACE_PROPERTY);
	if (map != null) {
		AddressIterator iter = map.getPropertyIterator();
		ArrayList<Address> list = new ArrayList<Address>();
		while(iter.hasNext()) {
			list.add(iter.next());
		}
		String str = list.size() > 1? " addresses." : " address.";
		println("Removed space property from "+ list.size() + str);
		for (int i=0; i<list.size(); i++) {
			Address addr = list.get(i);
			map.remove(addr);
		}
	}
	else {
		println("No space properties were found.");
	}
}
 
Example #18
Source File: LSDAHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address createTTypeOffset(Address addr) {
	String comment = "(LSDA) TType Offset";

	DwarfEHDecoder decoder = DwarfDecoderFactory.getDecoder(ttypeEncoding);
	if (decoder.getDataFormat() == DwarfEHDataDecodeFormat.DW_EH_PE_omit) {
		ttypeOffset = 0;
		return addr;
	}

	UnsignedLeb128DataType uleb = UnsignedLeb128DataType.dataType;
	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);

	int encodedLen = uleb.getLength(buf, -1);

	Object actionObj = uleb.getValue(buf, uleb.getDefaultSettings(), encodedLen);

	// this offset it based from *here*..
	ttypeOffset = (int) ((Scalar) actionObj).getUnsignedValue() + curSize;

	createAndCommentData(program, addr, uleb, comment, CodeUnit.EOL_COMMENT);

	return addr.add(encodedLen);
}
 
Example #19
Source File: ListingDiffHighlightProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Highlight[] getOperandDiffHighlights(String text, CodeUnit codeUnit,
		int cursorTextOffset) {
	Address minAddress = codeUnit.getMinAddress();
	AddressSetView unmatchedDiffs = (isListing1) ? listingDiff.getListing1UnmatchedCode()
			: listingDiff.getListing2UnmatchedCode();
	if (unmatchedDiffs.contains(minAddress)) {
		return EMPTY_HIGHLIGHT;
	}
	Color operandDiffsBackgroundColor = comparisonOptions.getOperandDiffsBackgroundColor();
	AddressSetView codeUnitDiffs = (isListing1) ? listingDiff.getListing1CodeUnitDiffs()
			: listingDiff.getListing2CodeUnitDiffs();
	// Get intersection of Code Unit Diff addresses and this code unit's addresses
	AddressSet diffSet = new AddressSet(codeUnit.getMinAddress(), codeUnit.getMaxAddress());
	diffSet = diffSet.intersect(codeUnitDiffs);
	if (!diffSet.isEmpty()) {
		CodeUnit matchingCodeUnit = listingDiff.getMatchingCodeUnit(codeUnit, isListing1);
		if (listingDiff.doesEntireOperandSetDiffer(codeUnit, matchingCodeUnit)) {
			return entireTextHighlight(text, cursorTextOffset, operandDiffsBackgroundColor);
		}
		Pair[] pairs = getOperandPairs(text, codeUnit);
		int numOperands = codeUnit.getNumOperands();
		if (pairs.length != numOperands) {
			return entireTextHighlight(text, cursorTextOffset, operandDiffsBackgroundColor);
		}
		int[] diffOpIndices = listingDiff.getOperandsThatDiffer(codeUnit, matchingCodeUnit);
		ArrayList<Highlight> highlights = new ArrayList<>();
		for (int diffOpIndex : diffOpIndices) {
			// Highlight each operand that differs.
			highlights.add(new Highlight(pairs[diffOpIndex].start, pairs[diffOpIndex].end,
				operandDiffsBackgroundColor));
		}
		return highlights.toArray(new Highlight[highlights.size()]);
	}
	return EMPTY_HIGHLIGHT;
}
 
Example #20
Source File: ReferenceManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
   public void testRemoveAllExtRefsInRange() throws Exception {
	refMgr.addExternalReference(addr(100), "io.dll", "label", null, SourceType.USER_DEFINED, 0,
		RefType.DATA);

	refMgr.addExternalReference(addr(100), "io.dll", "label1", null, SourceType.USER_DEFINED,
		0, RefType.DATA);
	refMgr.addExternalReference(addr(110), "io.dll", "label2", null, SourceType.USER_DEFINED,
		0, RefType.DATA);
	refMgr.addExternalReference(addr(120), "io.dll", "label3", null, SourceType.USER_DEFINED,
		0, RefType.DATA);
	refMgr.addExternalReference(addr(130), "io.dll", "label4", null, SourceType.USER_DEFINED,
		0, RefType.DATA);

	refMgr.addExternalReference(addr(1000), "io.dll", "label5", null, SourceType.USER_DEFINED,
		0, RefType.DATA);

	refMgr.removeAllReferencesFrom(addr(0), addr(500));

	CodeUnit cu = listing.getCodeUnitAt(addr(100));
	assertNull(cu.getExternalReference(0));

	cu = listing.getCodeUnitAt(addr(110));
	assertNull(cu.getExternalReference(0));

	cu = listing.getCodeUnitAt(addr(120));
	assertNull(cu.getExternalReference(0));

	cu = listing.getCodeUnitAt(addr(130));
	assertNull(cu.getExternalReference(0));

	cu = listing.getCodeUnitAt(addr(1000));
	assertNotNull(cu.getExternalReference(0));
}
 
Example #21
Source File: LSDAHeader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Address createTTypeEncoding(Address addr) throws MemoryAccessException {
	String comment = "(LSDA) TType Encoding";

	ttypeEncoding = GccAnalysisUtils.readByte(program, addr);

	createAndCommentData(program, addr, new DwarfEncodingModeDataType(), comment,
		CodeUnit.EOL_COMMENT);

	curSize += BYTE_LEN;
	return addr.add(BYTE_LEN);
}
 
Example #22
Source File: X64DbgExport.java    From GhidraX64Dbg with MIT License 5 votes vote down vote up
/**
 * Adds comments labels to the X64 database. Does not retrieve plate comments
 * and pre/post comments as X64 does not really support them.
 */
public void populateComments() {

	Listing listing = currentProgram.getListing();

	for (Address commentedAddress : listing.getCommentAddressIterator(currentProgram.getMemory(), true)) {

		CodeUnit cu = listing.getCodeUnitAt(commentedAddress);

		// Skip empty code units or empty comment
		if (cu == null) {
			continue;
		}

		String comment;
		String start = "0x" + Long.toHexString(commentedAddress.subtract(imageBase));

		// Process EOL comments
		comment = cu.getComment(CodeUnit.EOL_COMMENT);
		if (comment != null && comment.length() != 0) {
			this.comments.add(new X64Label(start, comment));
		}

		// Process repeatable comments
		comment = cu.getComment(CodeUnit.REPEATABLE_COMMENT);
		if (cu.getComment(CodeUnit.REPEATABLE_COMMENT) != null) {
			this.comments.add(new X64Label(start, comment));
		}
	}
}
 
Example #23
Source File: InstructionContext.java    From dragondance with GNU General Public License v3.0 5 votes vote down vote up
public InstructionContext(Instruction inst, CodeUnit cu, InstructionInfo info) {
	this.instruction = inst;
	this.codeUnit = cu;
	
	if (info == null) {
		info = new InstructionInfo(null,inst.getAddress().getOffset(),cu.getLength(),0);
	}
	
	this.info = info;
}
 
Example #24
Source File: FieldNameFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean acceptsType(int category, Class<?> proxyObjectClass) {
	if (!CodeUnit.class.isAssignableFrom(proxyObjectClass)) {
		return false;
	}
	return (category == FieldFormatModel.OPEN_DATA || category == FieldFormatModel.ARRAY);
}
 
Example #25
Source File: GnuDemanglerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testDemangleTypeInfo() throws Exception {

	String mangled = "_ZTIN6AP_HAL3HAL9CallbacksE";

	program.startTransaction("markup...");
	program.getMemory().setInt(addr("01001000"), 0x1001010);

	SymbolTable symbolTable = program.getSymbolTable();
	symbolTable.createLabel(addr("01001000"), mangled, SourceType.IMPORTED);

	GnuDemangler demangler = new GnuDemangler();
	DemangledObject obj = demangler.demangle(mangled);
	assertNotNull(obj);

	//assertEquals("typeinfo for AP_HAL::HAL::Callbacks", obj.getSignature(false));

	assertTrue(
		obj.applyTo(program, addr("01001000"), new GnuDemanglerOptions(), TaskMonitor.DUMMY));

	Symbol s = symbolTable.getPrimarySymbol(addr("01001000"));
	assertNotNull(s);
	assertEquals("typeinfo", s.getName());
	assertEquals("AP_HAL::HAL::Callbacks", s.getParentNamespace().getName(true));

	assertEquals("typeinfo for AP_HAL::HAL::Callbacks",
		program.getListing().getComment(CodeUnit.PLATE_COMMENT, addr("01001000")));

	Data d = program.getListing().getDefinedDataAt(addr("01001000"));
	assertNotNull(d);
	assertTrue(d.isPointer());
}
 
Example #26
Source File: ProgramMemoryUtil.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Checks a programs memory for direct references to the CodeUnit indicated.
 * Direct references are only found at addresses that match the indicated alignment. 
 * @param program the program whose memory is to be checked.
 * @param alignment direct references are to only be found at the indicated alignment in memory.
 * @param codeUnit the code unit to to search for references to.
 * @param monitor a task monitor for progress or to allow canceling.
 * @return list of addresses referring directly to the toAddress.
 */
public static List<Address> findDirectReferencesCodeUnit(Program program, int alignment,
		CodeUnit codeUnit, TaskMonitor monitor) {

	if (monitor == null) {
		monitor = TaskMonitorAdapter.DUMMY_MONITOR;
	}

	AddressSet toAddressSet =
		new AddressSet((codeUnit.getMinAddress()), codeUnit.getMaxAddress());

	List<ReferenceAddressPair> directReferenceList = new ArrayList<>();
	List<Address> results = new ArrayList<>();

	try {
		ProgramMemoryUtil.loadDirectReferenceList(program, alignment,
			toAddressSet.getMinAddress(), toAddressSet, directReferenceList, monitor);
	}
	catch (CancelledException e) {
		return Collections.emptyList();
	}

	for (ReferenceAddressPair rap : directReferenceList) {
		if (monitor.isCancelled()) {
			return null;
		}
		Address fromAddr = rap.getSource();
		if (!results.contains(fromAddr)) {
			results.add(fromAddr);
		}
	}

	return results;
}
 
Example #27
Source File: ApplyLineNumbers.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void applyTo(TaskMonitor monitor, MessageLog log) {
	while (xmlParser.hasNext()) {
		if (monitor.isCancelled()) {
			return;
		}
		XmlElement elem = xmlParser.peek();
		if (elem.isEnd() && elem.getName().equals("function")) {
			break;
		}
		elem = xmlParser.next();//line number start tag
		String sourcefileName = elem.getAttribute("source_file");

		int start = XmlUtilities.parseInt(elem.getAttribute("start"));
		int addr = XmlUtilities.parseInt(elem.getAttribute("addr"));
		Address address = PdbUtil.reladdr(program, addr);
		// The following line was changed from getCodeUnitAt(address) to
		// getCodeUnitContaining(address) in order to fix an issue where the PDB associates
		// a line number with base part of an instruction instead of the prefix part of an
		// instruction.  In particular, Microsoft emits a "REP RET" (f3 c3) sequence, where
		// the "REP" is an instruction prefix, in order to avoid a branch prediction penalty
		// for AMD processors.  However, Microsoft associates the line number of the
		// instruction with the address of the "RET" (c3) instead of with the address of the
		// "REP" (f3) portion (beginning) of the instruction.
		CodeUnit cu = program.getListing().getCodeUnitContaining(address);
		if (cu == null) {
			log.appendMsg("PDB",
				"Could not apply source code line number (no code unit found at " + address +
					")");
		}
		else {
			cu.setProperty("Source Path", sourcefileName);
			cu.setProperty("Source File", new File(sourcefileName).getName());
			cu.setProperty("Source Line", start);
		}
		//String comment = sourcefile.getName()+":"+start;
		//setComment(CodeUnit.PRE_COMMENT, program.getListing(), address, comment);
		elem = xmlParser.next();//line number end tag
	}
}
 
Example #28
Source File: SpaceFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.app.util.viewer.field.FieldFactory#acceptsType(int, java.lang.Class)
 */
@Override
public boolean acceptsType(int category, Class<?> proxyObjectClass) {
	if (!CodeUnit.class.isAssignableFrom(proxyObjectClass)) {
		return false;
	}
	return (category == FieldFormatModel.INSTRUCTION_OR_DATA);
}
 
Example #29
Source File: NewExt4Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean setPlateComment( Program program, Address address, String comment ) {
	SetCommentCmd cmd = new SetCommentCmd( address, CodeUnit.PLATE_COMMENT, comment );
	if ( program.getMemory( ).contains( address ) ) {
		return cmd.applyTo( program );
	}
	if ( program2 != null && program2.getMemory( ).contains( address ) ) {
		return cmd.applyTo( program2 );
	}
	throw new RuntimeException( "Cannot set plate comment, neither program contains that address." );
}
 
Example #30
Source File: NextPreviousLabelAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Address getAddressOfPreviousCodeUnit(Program program, Address address) {
	CodeUnit cu = program.getListing().getCodeUnitBefore(address);
	if (cu == null) {
		return null;
	}
	return cu.getAddress();
}