Java Code Examples for ghidra.program.model.symbol.Reference#getToAddress()

The following examples show how to use ghidra.program.model.symbol.Reference#getToAddress() . 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: InstructionPcodeOverride.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Address getOverridingReference(RefType type) {
	if (!type.isOverride()) {
		return null;
	}
	Address overrideAddress = null;
	for (Reference ref : primaryOverridingReferences) {
		if (ref.getReferenceType().equals(type)) {
			if (overrideAddress == null) {
				overrideAddress = ref.getToAddress();
			}
			else {
				return null; //only allow one primary reference of each type
			}
		}
	}
	return overrideAddress;
}
 
Example 2
Source File: MnemonicFieldFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address getReferenceAddress(CodeUnit cu) {

		Program program = cu.getProgram();

		if (cu instanceof Data) {
			if (((Data) cu).getNumComponents() != 0) {
				return null; // outer composite/array type should ignore reference from component
			}
		}

		ReferenceManager referenceManager = program.getReferenceManager();
		Reference[] referencesFrom = referenceManager.getReferencesFrom(cu.getMinAddress());
		for (Reference reference : referencesFrom) {
			if (reference.isMemoryReference()) {
				return reference.getToAddress();
			}
		}

		return null;
	}
 
Example 3
Source File: CallTreePlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 *  
 * Apparently, we create fake function markup for external functions.  Thus, there is no
 * real function at that address and our plugin has to do some work to find out where
 * we 'hang' references to the external function, which is itself a Function.  These 
 * fake function will usually just be a pointer to another function.
 * 
 * @param function the function to resolve; if it is not null, then it will be used
 * @param address the address for which to find a function
 * @return either the given function if non-null, or a function being referenced from the
 *         given address.
 */
Function resolveFunction(Function function, Address address) {
	if (function != null) {
		return function;
	}

	// maybe we point to another function?
	FunctionManager functionManager = currentProgram.getFunctionManager();
	ReferenceManager referenceManager = currentProgram.getReferenceManager();
	Reference[] references = referenceManager.getReferencesFrom(address);
	for (Reference reference : references) {
		Address toAddress = reference.getToAddress();
		Function toFunction = functionManager.getFunctionAt(toAddress);
		if (toFunction != null) {
			return toFunction;
		}
	}

	return null;
}
 
Example 4
Source File: SelectForwardRefsAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private ProgramSelection getSelection(Program program, AddressSetView addressSetView) {
	AddressSet addressSet = new AddressSet();

	CodeUnitIterator iter = program.getListing().getCodeUnits(addressSetView, true);

	while (iter.hasNext()) {
		CodeUnit cu = iter.next();
		Reference[] memRef = cu.getReferencesFrom();
		for (Reference element : memRef) {
			Address addr = element.getToAddress();
			if (addr.isMemoryAddress()) {
				addressSet.addRange(addr, addr);
			}

		}
	}
	return new ProgramSelection(addressSet);
}
 
Example 5
Source File: InstructionPcodeOverride.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * This constructor caches the primary and overriding "from" references of {@code instr}.  
 * This cache is never updated; the assumption is that this object is short-lived 
 * (duration of {@link PcodeEmit})  
 * @param instr the instruction
 */
public InstructionPcodeOverride(Instruction instr) {
	this.instr = instr;

	primaryOverridingReferences = new ArrayList<>();
	for (Reference ref : instr.getReferencesFrom()) {
		if (!ref.isPrimary() || !ref.getToAddress().isMemoryAddress()) {
			continue;
		}
		RefType type = ref.getReferenceType();
		if (type.isOverride()) {
			primaryOverridingReferences.add(ref);
		}
		else if (type.isCall() && primaryCallAddress == null) {
			primaryCallAddress = ref.getToAddress();
		}
	}
}
 
Example 6
Source File: FindPotentialDecompilerProblems.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean isValidCallReference(Reference ref) {
	if (!ref.getReferenceType().isCall()) {
		return false;
	}
	if (ref.getToAddress() == null) {
		return false;
	}
	if (currentProgram.getFunctionManager().getFunctionAt(ref.getToAddress()) != null) {
		return true;
	}
	return false;

}
 
Example 7
Source File: FidProgramSeeker.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public static ArrayList<Function> getChildren(Function function,boolean followThunks) {
		Program program = function.getProgram();
		FunctionManager functionManager = program.getFunctionManager();
		ReferenceManager referenceManager = program.getReferenceManager();
		HashSet<Address> alreadyDone = new HashSet<Address>();
		ArrayList<Function> funcList = new ArrayList<Function>();
		AddressIterator referenceIterator =
				referenceManager.getReferenceSourceIterator(function.getBody(), true);
		for (Address address : referenceIterator) {
//			monitor.checkCanceled();
			Reference[] referencesFrom = referenceManager.getReferencesFrom(address);
			for (Reference reference : referencesFrom) {
				Address toAddress = reference.getToAddress();
				if (reference.getReferenceType().isCall() && !alreadyDone.contains(toAddress)) {
					Function child = functionManager.getFunctionContaining(toAddress);
					if (child != null) {
						if (followThunks && child.isThunk()) {
							child = child.getThunkedFunction(true);
						}
						funcList.add(child);
						alreadyDone.add(toAddress);
					}
				}
			}
		}
		return funcList;
	}
 
Example 8
Source File: SetStackDepthChangeAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Address getFunctionCallAddress(Instruction instr) {
	if ((instr != null) && instr.getFlowType().isCall()) {
		Program program = instr.getProgram();
		FunctionManager functionMgr = program.getFunctionManager();
		Reference[] refs =
			program.getReferenceManager().getReferencesFrom(instr.getMinAddress());
		for (Reference ref : refs) {
			Address toAddr = ref.getToAddress();
			if (functionMgr.getFunctionAt(toAddr) != null) {
				return toAddr;
			}
		}
	}
	return null;
}
 
Example 9
Source File: FindPotentialDecompilerProblems.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the address of first function called by {@code func}.  That is, the returned {@link Address}
 * is the target of the call instruction with the least address within the body of {@code func}. 
 * @param func the {@link Function} to search for calls
 * @return the {@link Address} of the first called function, or {@code Address.NO_ADDRESS} if
 * no calls are found.
 */
private Address getFirstCalledFunction(Function func) {

	//could be issues if func's body has addresses that are before the entry point of
	//func - see the comment in getFirstFuncWithVar
	ReferenceIterator refIter =
		func.getProgram().getReferenceManager().getReferenceIterator(func.getEntryPoint());

	Address maxAddr = func.getBody().getMaxAddress();

	for (Reference ref : CollectionUtils.asIterable(refIter)) {
		// check whether we are at an address not in the function
		// only necessary in case func consists of non-contiguous blocks
		// TODO: handle tail-call elimination
		if (!func.getBody().contains(ref.getFromAddress())) {
			continue;
		}

		// return the first call for the function
		if (isValidCallReference(ref)) {
			return ref.getToAddress();
		}
		// The references are sorted by their "from" addresses, so if this condition is true, 
		// we've searched all the references from the body of func and haven't found anything.
		// So, stop looking.
		if (ref.getFromAddress().compareTo(maxAddr) > 0) {
			return Address.NO_ADDRESS;
		}
	}
	//in case there are no references with "from" addresses after the body of func
	return Address.NO_ADDRESS;
}
 
Example 10
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 11
Source File: VTSubToolManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Address getFunctionOrDataStartAddress(Address address) {
	if (address == null) {
		return null;
	}
	Program program = getVTProgram();
	if (program == null) {
		return null;
	}
	Function function = program.getFunctionManager().getFunctionContaining(address);
	if (function == null) {
		Data data = program.getListing().getDataContaining(address);
		if (data == null) {
			return null;
		}
		if (data.isPointer()) {
			// follow external reference (handle external linkage location)
			Reference ref = data.getPrimaryReference(0);
			if (ref != null && ref.isExternalReference()) {
				return ref.getToAddress();
			}
		}
		return data.getAddress();
	}
	else if (function.isThunk()) {
		// follow thunk (handle internal/external linkage location)
		function = function.getThunkedFunction(true);
	}
	return function.getEntryPoint();
}
 
Example 12
Source File: LocationDescriptor.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected boolean refersToAddress(Reference reference, Address address) {
	Address toAddress = reference.getToAddress();
	return toAddress.equals(address);
}
 
Example 13
Source File: FindPotentialDecompilerProblems.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the target of the first (in address order) call in the body of {@code func}
 * which takes {@code vn} as a parameter.
 * @param func {@link Function} whose body to search for calls
 * @param vn {@link Varnode} representing required parameter
 * @return entry point of first function called by {@code func} which uses {@code vn}
 * as a parameter, or {@code Address.NO_ADDRESS} if no such function found.
 */
private Address getFirstFuncWithVar(Function func, Varnode vn) {
	Address variableAddr = vn.getAddress();
	if (variableAddr == null) {
		return Address.NO_ADDRESS;
	}

	// Note: this handles some cases where functions consist of non-contiguous blocks,
	// but since we start at the entry point we might miss things if part of the body of
	// the function is before the entry point (in address order)
	ReferenceIterator refIter =
		func.getProgram().getReferenceManager().getReferenceIterator(func.getEntryPoint());

	Address maxAddr = func.getBody().getMaxAddress();

	// return the first call to a function which takes vn as an argument
	for (Reference ref : CollectionUtils.asIterable(refIter)) {
		// check whether we are at an address not in the function
		// only necessary in case func consists of non-contiguous blocks
		// TODO: handle tail-call elimination
		if (!func.getBody().contains(ref.getFromAddress())) {
			continue;
		}
		if (isValidCallReference(ref)) {
			Function calledFunc =
				currentProgram.getFunctionManager().getFunctionAt(ref.getToAddress());
			Parameter[] params = calledFunc.getParameters();
			for (Parameter param : params) {
				Address addr = param.getMinAddress();
				if (addr != null && addr.equals(variableAddr)) {
					return ref.getToAddress();
				}
			}
		}
		// The references are sorted by their "from" addresses, so if this condition is true, 
		// we've searched all the references from the body of func and haven't found anything.
		// So, stop looking.
		if (ref.getFromAddress().compareTo(maxAddr) > 0) {
			return Address.NO_ADDRESS;
		}
	}
	//in case there are no references with "from" addresses after the body of func
	return Address.NO_ADDRESS;
}
 
Example 14
Source File: CallDepthChangeInfo.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * @param instr
 */
private int getCallPurge(Instruction instr) {

	// see if there is an override at this address
	Integer override = overrideMap.get(instr.getMinAddress());
	if (override != null) {
		return override.intValue();
	}

	FlowType fType = instr.getFlowType();
	Address[] flows;
	if (fType.isComputed()) {
		Reference refs[] = instr.getReferencesFrom();
		flows = new Address[refs.length];
		for (int ri = 0; ri < refs.length; ri++) {
			Data data = program.getListing().getDataAt(refs[ri].getToAddress());
			if (data != null && data.isPointer()) {
				Reference pointerRef = data.getPrimaryReference(0);
				if (pointerRef != null) {
					flows[ri] = pointerRef.getToAddress();
				}
			}
		}
	}
	else {
		flows = instr.getFlows();
	}

	// try to find a call destination that the stack frame is known
	for (Address flow : flows) {
		if (flow == null) {
			continue;
		}
		Function func = program.getListing().getFunctionAt(flow);
		if (func != null) {
			int purge = func.getStackPurgeSize();
			if (func.isStackPurgeSizeValid() && purge != Function.UNKNOWN_STACK_DEPTH_CHANGE &&
				purge != Function.INVALID_STACK_DEPTH_CHANGE) {
				return purge;
			}
		}
	}

	return getDefaultStackDepthChange(Function.UNKNOWN_STACK_DEPTH_CHANGE);
}
 
Example 15
Source File: OutgoingReferenceEndpoint.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public OutgoingReferenceEndpoint(Reference r, boolean isOffcut) {
	super(r, r.getToAddress(), r.getReferenceType(), isOffcut, r.getSource());
}
 
Example 16
Source File: ReferenceToReferenceAddressPairTableRowMapper.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public ReferenceAddressPair map( Reference rowObject, Program program,
        ServiceProvider serviceProvider ) {
    return new ReferenceAddressPair( rowObject.getFromAddress(), rowObject.getToAddress() );
}
 
Example 17
Source File: ArmThumbFunctionTableScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void 
   run() throws Exception 
   { 
      Register tmode = currentProgram.getProgramContext().getRegister("TMode"); 
      Listing lst = currentProgram.getListing(); 
      if (currentSelection != null) 
      { 
         AddressIterator addrIter = currentSelection.getAddresses(true); 
         
         while (addrIter.hasNext()) 
         { 
            Address currAddr = addrIter.next(); 
            // Only look at dword-aligned boundaries for function pointers 
            if ((currAddr.getOffset() & 3) != 0) 
            { 
               continue; 
            } 
            // Skip over entries with value 0 (null pointers) 
            long dstOffset = getInt(currAddr); 
            if (dstOffset == 0) 
            { 
               continue; 
            } 
            // Clear any defined data before applying our new type 
            if (!lst.isUndefined(currAddr,currAddr.add(3))) 
            { 
               clearListing(currAddr, currAddr.add(3)); 
            } 
            // Apply a pointer data type 
            createData(currAddr, new Pointer32DataType()); 
            // Now check out what we're pointing to 
            Reference ref = getReferencesFrom(currAddr)[0]; 
            Address refAddr = ref.getToAddress(); 
            if (!currentProgram.getMemory().contains(refAddr)) 
            { 
               continue; 
            } 
            // Decide whether this is a pointer to an ARM or Thumb function 
            BigInteger tmodeValue; 
            if ((dstOffset & 1) == 1) 
            { 
               refAddr = refAddr.subtract(1); 
               tmodeValue = BigInteger.ONE; 
            } 
            else 
            { 
               // ARM function pointers should always be dword-aligned 
               if ((dstOffset & 3) != 0) 
               { 
                  println("Warning: Invalid function pointer to " + refAddr); 
                  continue; 
               } 
               tmodeValue = BigInteger.ZERO; 
            } 
             
            // Check current TMode at referenced address 
            BigInteger currVal = 
               currentProgram.getProgramContext().getValue(tmode, refAddr, false); 
            if (currVal == null) 
            { 
               currVal = BigInteger.ZERO; 
            } 
            // If the TMode isn't set correctly, fix it here 
            if (currVal.compareTo(tmodeValue) != 0) 
            { 
               currentProgram.getProgramContext().setValue( 
                     tmode, 
                     refAddr, 
                     refAddr, 
                     tmodeValue); 
               // if TMode was wrong but there is code here, 
               // clear the flow so we can disassemble it in the right mode 
               if (!lst.isUndefined(refAddr, refAddr)) 
               { 
                  ClearFlowAndRepairCmd cmd = new ClearFlowAndRepairCmd(refAddr, true, true, false); 
                  runCommand(cmd); 
               } 
            } 
            if (lst.isUndefined(refAddr, refAddr)) 
            { 
               disassemble(refAddr); 
            } 
            if (lst.getFunctionAt(refAddr) == null) 
            { 
               createFunction(refAddr, null); 
            } 
         } 
      }    
   }
 
Example 18
Source File: SetPrimaryRefCmd.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a command for setting whether or not a reference is the primary reference.
 * If isPrimary is true, any other reference that was primary at that 
 * address will no longer be primary.
 * @param ref the reference
 * @param isPrimary true to make the reference primary, false to make it non-primary
 */
public SetPrimaryRefCmd(Reference ref, boolean isPrimary) {
    this (ref.getFromAddress(), ref.getOperandIndex(), ref.getToAddress(), isPrimary);
}