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

The following examples show how to use ghidra.program.model.address.Address#isExternalAddress() . 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: EditFunctionTagsAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Overridden to only allow this menu option when clicking in a function.
 * Note that we do not allow external functions to have tags.
 * 
 * @param context the listing context
 * @return
 */
@Override
protected boolean isEnabledForContext(ListingActionContext context) {

	if (context.hasSelection() || context.getAddress() == null) {
		return false;
	}

	if (context.getLocation().getAddress().isExternalAddress()) {
		return false;
	}

	Address funcAddress = getFunctionAddress(context.getLocation());
	if (funcAddress == null) {
		return false;
	}

	return !funcAddress.isExternalAddress();
}
 
Example 2
Source File: PreviewTableCellData.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getCodeUnitPreview(CodeUnitFormat format) {
	Address addr = location.getAddress();
	if (addr.isExternalAddress()) {
		Symbol s = program.getSymbolTable().getPrimarySymbol(addr);
		if (s != null) {
			ExternalLocation extLoc = program.getExternalManager().getExternalLocation(s);
			DataType dt = extLoc.getDataType();
			if (dt == null) {
				dt = DataType.DEFAULT;
			}
			return dt.getMnemonic(dt.getDefaultSettings());
		}
	}

	CodeUnit cu = program.getListing().getCodeUnitAt(addr);
	return getFormatedCodeUnitPreview(cu);
}
 
Example 3
Source File: SymbolType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValidParent(Program program, Namespace parent, Address symbolAddr,
		boolean isExternalSymbol) {
	if (symbolAddr.isExternalAddress() != parent.isExternal()) {
		return false;
	}
	if (parent.getID() != Namespace.GLOBAL_NAMESPACE_ID &&
		program != parent.getSymbol().getProgram()) {
		return false;
	}
	// FUNCTION can not be contained within a function
	while (parent.getID() != Namespace.GLOBAL_NAMESPACE_ID) {
		if (parent instanceof Function) {
			return false;
		}
		parent = parent.getParentNamespace();
	}
	return true;
}
 
Example 4
Source File: OperandFieldMouseHandler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean checkExternalReference(Navigatable navigatable, CodeUnit codeUnit,
		OperandFieldLocation loc, GoToService goToService) {

	Address refAddr = loc.getRefAddress();
	if (refAddr == null || !refAddr.isExternalAddress()) {
		return checkExternalThunkFunctionReference(navigatable, codeUnit, loc, goToService);
	}

	Program program = codeUnit.getProgram();
	Symbol s = program.getSymbolTable().getPrimarySymbol(refAddr);
	if (s == null) {
		return false;
	}

	ExternalLocation extLoc = program.getExternalManager().getExternalLocation(s);
	return goToService.goToExternalLocation(extLoc, true);
}
 
Example 5
Source File: GoToHelper.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Program findProgramContaining(Program currentProgram, Address addr) {
	if (addr.isExternalAddress()) {
		return currentProgram; // only consider current program for external address
	}
	ProgramManager service = tool.getService(ProgramManager.class);
	if (service != null) {
		return service.getProgram(addr);
	}
	else if (currentProgram != null && currentProgram.getMemory().contains(addr)) {
		return currentProgram;
	}
	return null;
}
 
Example 6
Source File: BigRefListV0.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private ReferenceDB getRef(Record rec) {
	long symbolID = -1;
	long addr = rec.getLongValue(ADDRESS_COL);

	RefListFlagsV0 flags = new RefListFlagsV0(rec.getByteValue(FLAGS_COL));
	RefType refType = RefTypeFactory.get(rec.getByteValue(TYPE_COL));
	byte opIndex = rec.getByteValue(OPINDEX_COL);

	SourceType source = flags.getSource();

	long offsetOrShift = 0;

	if (flags.hasSymbolID()) {
		symbolID = rec.getLongValue(SYMBOL_ID_COL);
	}
	Address from = isFrom ? address : addrMap.decodeAddress(addr);
	Address to = isFrom ? addrMap.decodeAddress(addr) : address;
	if (flags.isOffsetRef() || flags.isShiftRef()) {
		offsetOrShift = rec.getLongValue(OFFSET_COL);
		if (flags.isShiftRef()) {
			return new ShiftedReferenceDB(program, from, to, refType, opIndex, source,
				flags.isPrimary(), symbolID, (int) offsetOrShift);
		}
		return new OffsetReferenceDB(program, from, to, refType, opIndex, source,
			flags.isPrimary(), symbolID, offsetOrShift);
	}
	else if (to.isExternalAddress()) {
		return new ExternalReferenceDB(program, from, to, refType, opIndex, source);
	}
	else if (from.equals(Address.EXT_FROM_ADDRESS)) {
		return new EntryPointReferenceDB(from, to, refType, opIndex, source, flags.isPrimary(),
			symbolID);
	}
	else if (to.isStackAddress()) {
		return new StackReferenceDB(program, from, to, refType, opIndex, source,
			flags.isPrimary(), symbolID);
	}
	return new MemReferenceDB(program, from, to, refType, opIndex, source, flags.isPrimary(),
		symbolID);
}
 
Example 7
Source File: PlateFieldFactoryTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testLinesBeforeLabels() throws Exception {

	setIntOption(PlateFieldFactory.LINES_BEFORE_LABELS_OPTION, 3);
	Listing listing = program.getListing();
	SymbolIterator symIter = program.getSymbolTable().getSymbolIterator();
	while (symIter.hasNext()) {
		Symbol symbol = symIter.next();
		Address addr = symbol.getAddress();
		if (addr.isExternalAddress()) {
			continue;
		}

		CodeUnit cu = listing.getCodeUnitAt(addr);
		String[] plates = cu.getCommentAsArray(CodeUnit.PLATE_COMMENT);
		assertTrue("Failed to navigate to plate field at address: " + cu.getMinAddress(),
			cb.goToField(cu.getMinAddress(), PlateFieldFactory.FIELD_NAME, 1, 1));
		ListingTextField tf = (ListingTextField) cb.getCurrentField();
		if (plates == null || plates.length == 0) {
			assertEquals(3, tf.getNumRows());
		}
		else {
			assertEquals(plates.length + 5, tf.getNumRows());
		}
	}

}
 
Example 8
Source File: EditExternalReferencePanel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(CodeUnit fromCu, Reference ref) {
	isValidState = false;
	this.fromCodeUnit = fromCu;

	Program program = fromCu.getProgram();

	Address toAddr = ref.getToAddress();
	if (!toAddr.isExternalAddress()) {
		throw new IllegalArgumentException("Expected external reference");
	}
	this.editRef = (ExternalReference) ref;
	ExternalLocation extLoc = editRef.getExternalLocation();

	populateExternalNames();
	String name = extLoc.getLibraryName();
	extLibName.setSelectedItem(name);
	extProgNameChanged();

	updateExtLibPath();

	extLabel.setText(extLoc.getLabel());
	extAddr.setAddressFactory(program.getAddressFactory());
	Address addr = extLoc.getAddress();
	if (addr != null) {
		extAddr.setAddress(addr);
	}
	else {
		extAddr.clear();
	}

	extLibName.requestFocus();

	isValidState = true;
}
 
Example 9
Source File: BlockGraphTask.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String getVertexId(CodeBlock bb) {
	// vertex has attributes of Name       = Label
	//                          Address    = address of blocks start
	//                          VertexType = flow type of vertex
	Address addr = bb.getFirstStartAddress();
	if (addr.isExternalAddress()) {
		Symbol s = bb.getModel().getProgram().getSymbolTable().getPrimarySymbol(addr);
		return s.getName(true);
	}
	return addr.toString();
}
 
Example 10
Source File: GoToPluginTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveRestoreState() throws Exception {
	int maxEntries = plugin.getMaximumGotoEntries();

	loadProgram("x86.exe");
	Memory memory = program.getMemory();

	int count = 0;
	SymbolIterator iter = program.getSymbolTable().getAllSymbols(true);
	while (iter.hasNext() && count < 30) {
		Symbol symbol = iter.next();
		Address addr = symbol.getAddress();
		if ((addr.isMemoryAddress() && !memory.contains(addr)) || addr.isExternalAddress()) {
			continue;
		}
		setText(symbol.getName());
		performOkCallback();
		++count;
	}

	SaveState saveState = new SaveState("test");
	plugin.writeDataState(saveState);

	plugin.readDataState(saveState);

	GhidraComboBox<?> combo = findComponent(dialog, GhidraComboBox.class);
	assertNotNull(combo);
	assertEquals(maxEntries, combo.getModel().getSize());
}
 
Example 11
Source File: AbstractReferenceHover.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public JComponent getHoverComponent(Program program, ProgramLocation programLocation,
		FieldLocation fieldLocation, Field field) {

	initializeLazily();
	if (!enabled || programLocation == null || panel == null) {
		return null;
	}

	Address refAddr = programLocation.getRefAddress();
	if (refAddr != null && refAddr.isExternalAddress()) {
		return createExternalToolTipComponent(program, refAddr);
	}

	previewLocation =
		getPreviewLocation(program, programLocation, programLocation.getRefAddress());
	if (previewLocation == null) {
		return null;
	}

	panel.setProgram(program); // the program must be set in order for the goto to work
	boolean validLocation = panel.goTo(previewLocation);
	if (validLocation) {
		Rectangle bounds = panel.getBounds();
		bounds.x = WINDOW_OFFSET;
		bounds.y = WINDOW_OFFSET;
		panel.setBounds(bounds);
		return panel;
	}
	panel.setProgram(null);

	// At this point we have a program location, but we could not go there.  This can happen
	// if the location is not in memory.
	return createOutOfMemoryToolTipComponent(previewLocation);
}
 
Example 12
Source File: SymbolType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidSourceType(SourceType sourceType, Address symbolAddress) {
	if (sourceType != SourceType.DEFAULT) {
		return true;
	}
	return symbolAddress.isExternalAddress();
}
 
Example 13
Source File: SymbolType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidParent(Program program, Namespace parent, Address symbolAddr,
		boolean isExternalSymbol) {
	boolean externalParent = parent.isExternal();
	if (symbolAddr.isExternalAddress() != externalParent) {
		return false;
	}
	if (parent.getID() != Namespace.GLOBAL_NAMESPACE_ID &&
		program != parent.getSymbol().getProgram()) {
		return false;
	}
	// CODE symbol may not have an external function parent
	return !(parent instanceof Function) || !externalParent;
}
 
Example 14
Source File: EditReferenceDialog.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void configureEditReference(CodeUnit cu, Reference ref) {
	setTitle("Edit Reference");
	setHelpLocation(EDIT_HELP);

	applyButton.setText("Update");

	memRefChoice.setEnabled(false);
	extRefChoice.setEnabled(false);
	stackRefChoice.setEnabled(false);
	regRefChoice.setEnabled(false);

	Address toAddress = ref.getToAddress();
	if (toAddress.isRegisterAddress() || cu.getProgram().getRegister(toAddress) != null) {
		regRefPanel.initialize(cu, ref);
		regRefChoice.setSelected(true);
		regRefChoice.setEnabled(true);
		if (toAddress.isMemoryAddress()) {
			memRefPanel.initialize(cu, ref);
			memRefChoice.setEnabled(true);
		}
	}
	else if (toAddress.isStackAddress()) {
		stackRefPanel.initialize(cu, ref);
		stackRefChoice.setSelected(true);
		stackRefChoice.setEnabled(true);
	}
	else if (toAddress.isMemoryAddress()) {
		memRefPanel.initialize(cu, ref);
		memRefChoice.setSelected(true);
		memRefChoice.setEnabled(true);
	}
	else if (toAddress.isExternalAddress()) {
		extRefPanel.initialize(cu, ref);
		extRefChoice.setSelected(true);
		extRefChoice.setEnabled(true);
	}
	else {
		throw new AssertException("Unknown address type");
	}
}
 
Example 15
Source File: SymbolType.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValidAddress(Program program, Address symbolAddress) {
	return symbolAddress.isMemoryAddress() || symbolAddress.isExternalAddress();
}
 
Example 16
Source File: DecompilePlugin.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Process the plugin event; delegates the processing to the
 * byte block.
 */
@Override
public void processEvent(PluginEvent event) {
	if (event instanceof ProgramClosedPluginEvent) {
		Program program = ((ProgramClosedPluginEvent) event).getProgram();
		programClosed(program);
		return;
	}
	if (connectedProvider == null) {
		return;
	}

	if (event instanceof ProgramActivatedPluginEvent) {
		currentProgram = ((ProgramActivatedPluginEvent) event).getActiveProgram();
		connectedProvider.doSetProgram(currentProgram);
	}
	else if (event instanceof ProgramLocationPluginEvent) {
		ProgramLocation location = ((ProgramLocationPluginEvent) event).getLocation();
		Address address = location.getAddress();
		if (address.isExternalAddress()) {
			return;
		}
		if (currentProgram != null) {
			Listing listing = currentProgram.getListing();
			CodeUnit codeUnit = listing.getCodeUnitContaining(address);
			if (codeUnit instanceof Data) {
				return;
			}
		}
		currentLocation = location;
		// delay location change to allow immediate location changes to
		// settle down.  This happens when switching program tabs in
		// code browser which produces multiple location changes
		delayedLocationUpdateMgr.updateLater();
	}
	else if (event instanceof ProgramSelectionPluginEvent) {
		currentSelection = ((ProgramSelectionPluginEvent) event).getSelection();
		connectedProvider.setSelection(currentSelection);
	}

}
 
Example 17
Source File: SimpleSourceReferenceIterator.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
     * Count and queue all source references flowing from this block.
     * All Calls to this block, and all external FlowType block references
     * to this block are counted.
     * 
     * @param block code block to get the number of source references to.
     * @param blockRefQueue the CodeBlockReference queue, may be null
     * @param followIndirectFlows indirect references will only be included if true
     * @param monitor task monitor which allows user to cancel operation.
     * @throws CancelledException if the monitor cancels the operation.
     */
    private static int getSources(CodeBlock block, LinkedList<CodeBlockReferenceImpl> blockRefQueue, 
    	boolean followIndirectFlows, TaskMonitor monitor) throws CancelledException {
    	
    	if (block == null) {
            return 0;
        }     
        
        CodeBlockModel m = block.getModel();
		if (!(m instanceof SimpleBlockModel))
			throw new IllegalArgumentException();	
		SimpleBlockModel model = (SimpleBlockModel) m;
		
        Address start = block.getMinAddress();
        if (start == null)
        	return 0;
        	
        int count = 0;
		Listing listing = model.getListing();
		Instruction instr = listing.getInstructionAt(start);
		
        // get the references from the symbol table.
        ReferenceManager refMgr = model.getProgram().getReferenceManager();
        Address[] entryPts = block.getStartAddresses();

		// Check references to all entry points - very special case to have more than one
    	for (int n = 0; n < entryPts.length; n++) {
     		ReferenceIterator iter = refMgr.getReferencesTo(entryPts[n]);
    		while (iter.hasNext()) {
    			Reference ref = iter.next();
    			RefType refType = ref.getReferenceType();
    			
    			if (monitor != null && monitor.isCancelled())
					throw new CancelledException();
    			
    			// Handle FlowType reference 
    			if (refType.isFlow()) {
    				queueDestReference(
    					blockRefQueue,
    					block, 
            			entryPts[n],
            			ref.getFromAddress(),
            			(FlowType)refType,
            			monitor);
            		++count;
    			}
    			
    			// Handle possible indirection
    			else if (followIndirectFlows && (instr != null || start.isExternalAddress())) {
        			int cnt = followIndirection(blockRefQueue, block, ref, monitor);
//        			if (cnt == 0) {
//        				// Could not resolve indirection - include ref as invalid flow
//        				queueDestReference(
//        					blockRefQueue,
//        					block, 
//                			entryPts[n],
//                			refs[i].getFromAddress(),
//                			FlowType.INVALID);
//                		cnt = 1;
//        			}
        			count += cnt;        
				}
    		}
    	}

        // Get single fall-from address for instruction block		
 		if (instr != null) {
 			Address fallAddr = instr.getFallFrom();
 			if (fallAddr != null) {
 				queueDestReference(
					blockRefQueue,
					block, 
        			start,
        			fallAddr,
        			RefType.FALL_THROUGH,
        			monitor);
        		++count;
 			}
 		}
        return count;
    }
 
Example 18
Source File: GoToHelper.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public boolean goTo(final Navigatable navigatable, ProgramLocation loc, Program program) {
		if (loc == null || loc.getAddress() == null) {
			return false;
		}
		if (program == null) {
			program = findGoToProgram(navigatable.getProgram(), loc.getAddress());
		}
		if (program == null) {
			return false;
		}

		Address addr = loc.getAddress();
		if (addr.isExternalAddress()) {
			Symbol externalSym = program.getSymbolTable().getPrimarySymbol(addr);
			if (externalSym == null) {
				return false;
			}
			ExternalLocation externalLoc =
				program.getExternalManager().getExternalLocation(externalSym);

			// TODO - this seems like a mistake to always pass 'false' here; please doc why we
			//        wish to ignore the user options for when to navigate to external programs
			return goToExternalLinkage(navigatable, externalLoc, false);
		}

		Memory memory = program.getMemory();
		if (!memory.contains(addr)) {
			tool.setStatusInfo("Address not found in program memory: " + addr);
			return false;
		}

		saveLocation(navigatable);

		if (!navigatable.goTo(program, loc)) {
			return false;
		}

// If we want the goto to request focus then we will need to add a new parameter - you don't always
//       	want to request focus.
//       	// sometimes this gets call directly after creating a new provider window.  Need to
//       	// request focus in an invokeLater to give WindowManager a chance to create the component
//       	// hierarchy tree.
//       	SwingUtilities.invokeLater(new Runnable() {
//			public void run() {
//		       	navigatable.requestFocus();
//			}
//		});

		saveLocation(navigatable);

		return true;
	}
 
Example 19
Source File: SubroutineDestReferenceIterator.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
   * Count and queue all destination references flowing out of this subroutine (block).
   * All Calls from this block, and all external FlowType block references
   * from this block are counted.
   * 
   * @param block code block to get the number of destination references from.
   * @param blockRefQueue the CodeBlockReference queue, may be null
   * @param includeExternals external references will be included if true
   * @param monitor task monitor
   */
  private static int getDestinations(CodeBlock block, List<CodeBlockReference> blockRefQueue, TaskMonitor monitor) throws CancelledException {
  	
  	if (block == null || block.getMinAddress() == null) {
          return 0;
      }

      int count = 0;

CodeBlockModel model = block.getModel();
boolean includeExternals = model.externalsIncluded();

      // Iterate over all basic blocks within specified block
      CodeBlockIterator bblockIter = (model.getBasicBlockModel()).getCodeBlocksContaining(block, monitor);
      while (bblockIter.hasNext()) {

	// Get next basic block
	CodeBlock bblock = bblockIter.next();
	
	// Get basic block destinations
	CodeBlockReferenceIterator bbDestIter = bblock.getDestinations(monitor);
	while (bbDestIter.hasNext()) {
		CodeBlockReference bbDestRef = bbDestIter.next();
		FlowType refFlowType = bbDestRef.getFlowType();
		Address destAddr = bbDestRef.getReference();
		boolean addBlockRef = false;
		if (destAddr.isExternalAddress()) {
			if (includeExternals) {
				// Add all forward external references to queue if includeExternals
				addBlockRef = true;
			}
		}
		else if (refFlowType.isCall()) {
			// Add all forward CALL references to queue
			addBlockRef = true;
              }
              else if (refFlowType.isJump() || refFlowType.isFallthrough()) {		
              	// Add forward external JUMP and FALL-THROUGH references to queue
              	if (!block.contains(destAddr)) {
              		addBlockRef = true;
                  }
              }
		if (addBlockRef) {
			queueDestReferences(blockRefQueue,
								block, 
								bbDestRef.getReferent(), 
								destAddr, 
								refFlowType);
			count++;
		}
	}			
      }
return count;
  }
 
Example 20
Source File: AddressBasedLocation.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private static String buildStringRepresentation(Program program, Address address,
		Reference reference, ShowBlockName showBlockName) {
	if (address == null) {
		return "<NULL>";
	}
	if (address.getAddressSpace().getType() == AddressSpace.TYPE_NONE) {
		return ""; // NO_ADDRESS or EXT_FROM_ADDRESS not rendered
	}
	if (address.isExternalAddress()) {
		return getExternalAddressRepresentation(program, address);
	}
	if (address.isVariableAddress()) {
		return getVariableAddressRepresentation();
	}
	if (address.isStackAddress()) {
		return getStackAddressRepresentation(address);
	}
	if (address.isConstantAddress()) {
		return getConstantAddressRepresentation(address);
	}
	if (address.isRegisterAddress()) {
		return getRegisterAddressRepresentation(program, address);
	}

	// Handle all other spaces (e.g., memory, other, overlays, hash, etc.)
	String addrStr;
	if (reference != null && reference.isOffsetReference()) {
		OffsetReference offsetRef = (OffsetReference) reference;
		long offset = offsetRef.getOffset();
		boolean neg = (offset < 0);
		Address baseAddr = offsetRef.getBaseAddress();
		addrStr = baseAddr.toString() + (neg ? "-" : "+") + "0x" +
			Long.toHexString(neg ? -offset : offset);
	}
	else if (reference != null && reference.isShiftedReference()) {
		// TODO: unsure of rendering which has never really been addressed
		// TODO: shifted references have never addressed concerns related to
		// addressable unit size
		ShiftedReference shiftedRef = (ShiftedReference) reference;
		StringBuilder buf = new StringBuilder();
		buf.append(address.toString());
		buf.append("(0x");
		buf.append(Long.toHexString(shiftedRef.getValue()));
		buf.append("<<");
		buf.append(Long.toString(shiftedRef.getShift()));
		buf.append(")");
		addrStr = buf.toString();
	}
	else {
		addrStr = address.toString();
	}

	if (showBlockName != ShowBlockName.NEVER) {
		Memory mem = program.getMemory();
		MemoryBlock toBlock = mem.getBlock(address);
		if (toBlock != null && showBlockName == ShowBlockName.NON_LOCAL && reference != null &&
			toBlock.equals(mem.getBlock(reference.getFromAddress()))) {
			toBlock = null;
		}
		if (toBlock != null) {
			addrStr = toBlock.getName() + "::" + addrStr;
		}
	}

	return addrStr;
}