Java Code Examples for ghidra.program.model.address.AddressSpace#getAddress()

The following examples show how to use ghidra.program.model.address.AddressSpace#getAddress() . 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: InjectPayloadDexRange.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public PcodeOp[] getPcode(Program program, InjectContext con) {
	if (con.inputlist.size() != 2) {
		return null;			// Error
	}
	// The first Varnode must be a constant specifying the number of parameters
	int numParams = (int) con.inputlist.get(0).getOffset();
	// The second Varnode must be the first register to be moved
	long fromOffset = con.inputlist.get(1).getOffset();
	// Base of designated input registers
	long toOffset = InjectPayloadDexParameters.INPUT_REGISTER_START;
	AddressSpace registerSpace = program.getAddressFactory().getAddressSpace("register");
	PcodeOp[] resOps = new PcodeOp[numParams];
	for (int i = 0; i < numParams; ++i) {
		Address fromAddr = registerSpace.getAddress(fromOffset);
		Address toAddr = registerSpace.getAddress(toOffset);
		fromOffset += 4;
		toOffset += 4;
		PcodeOp op = new PcodeOp(con.baseAddr, i, PcodeOp.COPY);
		op.setInput(new Varnode(fromAddr, 4), 0);
		op.setOutput(new Varnode(toAddr, 4));
		resOps[i] = op;
	}
	return resOps;
}
 
Example 2
Source File: SleighDebugLogger.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void dumpFinalGlobalSets() throws MemoryAccessException {
	SleighParserContext protoContext = prototype.getParserContext(buf, context);
	ParserWalker walker = new ParserWalker(protoContext);
	Iterator<ContextSet> contextCommits = protoContext.getContextCommits();
	while (contextCommits.hasNext()) {
		ContextSet set = contextCommits.next();
		walker.subTreeState(set.point);
		FixedHandle hand = new FixedHandle();
		// FIXME: review after Chris has checked the SleighParserContext.applyCommits method
		set.sym.getFixedHandle(hand, walker);
		// TODO: this is a hack. Addresses that are computed end up in the
		// constant space and we must factor-in the wordsize.
		long offset = hand.offset_offset;
		AddressSpace curSpace = buf.getAddress().getAddressSpace();
		if (hand.space.getType() == AddressSpace.TYPE_CONSTANT) {
			offset = offset * curSpace.getAddressableUnitSize();
		}
		Address address = curSpace.getAddress(offset);
		dumpGlobalSet(set.point, set.num, set.mask, set.value, address);
	}
}
 
Example 3
Source File: DebugDataDirectory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address getDataAddress(DebugDirectory dd, boolean isBinary,
					AddressSpace space, NTHeader ntHeader) {

	long ptr = 0;
	if (isBinary) {
		ptr = dd.getPointerToRawData();
        if (ptr != 0 && !ntHeader.checkPointer(ptr)) {
        	Msg.error(this, "Invalid pointer "+Long.toHexString(ptr));
        	return null;
        }
	}
	else {
		ptr = dd.getAddressOfRawData();
	}
	if (ptr != 0) {
		if (isBinary) {
			return space.getAddress(ptr);
		}
		return space.getAddress(ptr + ntHeader.getOptionalHeader().getImageBase());
	}
	return null;
}
 
Example 4
Source File: AddBlockModelTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateOverlayBlock2() throws Exception {

	model.setBlockName(".test");
	model.setStartAddress(getAddr(0x01001000));
	model.setLength(100);
	model.setBlockType(MemoryBlockType.DEFAULT);
	model.setOverlay(true);
	model.setInitializedType(InitializedType.INITIALIZED_FROM_VALUE);
	model.setInitialValue(0xa);
	assertTrue(model.execute());
	MemoryBlock block = null;
	AddressSpace[] spaces = program.getAddressFactory().getAddressSpaces();
	AddressSpace ovSpace = null;
	for (AddressSpace space : spaces) {
		if (space.isOverlaySpace()) {
			ovSpace = space;
			Address blockAddr = space.getAddress(0x1001000);
			block = program.getMemory().getBlock(blockAddr);
			break;
		}
	}
	assertNotNull(block);
	assertEquals((byte) 0xa, block.getByte(ovSpace.getAddress(0x1001000)));
}
 
Example 5
Source File: AddressMapDBTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
   public void testStackAddress() {
	AddressSpace stackSpace = p.getAddressFactory().getStackSpace();
	Address a = stackSpace.getAddress(0);
	long key = addrMap.getKey(a, false);
	assertEquals(0x4000000000000000l, key);
	Address b = addrMap.decodeAddress(key);
	assertEquals(a, b);

	a = stackSpace.getAddress(10);
	key = addrMap.getKey(a, false);
	assertEquals(0x400000000000000al, key);
	b = addrMap.decodeAddress(key);
	assertEquals(a, b);
}
 
Example 6
Source File: SymbolUtilities2Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseDynamicName() {
	assertEquals(addr(0x100),
		SymbolUtilities.parseDynamicName(program.getAddressFactory(), "LAB_CODE_0100"));
	assertEquals(addr(0x100),
		SymbolUtilities.parseDynamicName(program.getAddressFactory(), "s_foo_CODE_0100"));
	AddressSpace intmemSpace = program.getAddressFactory().getAddressSpace("INTMEM");
	Address address = intmemSpace.getAddress(0x5);
	assertEquals(address,
		SymbolUtilities.parseDynamicName(program.getAddressFactory(), "BYTE_05h_INTMEM_0005"));
}
 
Example 7
Source File: DexAnalysisState.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the Address for every method in the list and add an entry to -methodMap-
 * @param defaultAddressSpace is the AddressSpace all encoded offsets are relative to
 * @param methodList is the list of encoded methods
 */
private void installMethodList(AddressSpace defaultAddressSpace,
		List<EncodedMethod> methodList) {
	for (EncodedMethod encodedMethod : methodList) {
		Address methodAddress = defaultAddressSpace.getAddress(
			DexUtil.METHOD_ADDRESS + encodedMethod.getCodeOffset());
		methodMap.put(methodAddress, encodedMethod);
	}
}
 
Example 8
Source File: TLSDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		DataTypeConflictException, IOException {

	monitor.setMessage(program.getName()+": TLS...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);
	PeUtils.createData(program, addr, tls.toDataType(), log);

	// Markup TLS callback functions
	if (tls.getAddressOfCallBacks() != 0) {
		AddressSpace space = program.getImageBase().getAddressSpace();
		DataType pointerDataType = PointerDataType.dataType.clone(program.getDataTypeManager());
		try {
			for (int i = 0; i < 20; i++) { // cap # of TLS callbacks as a precaution (1 is the norm)
				Address nextCallbackPtrAddr = space.getAddress(
					tls.getAddressOfCallBacks() + i * pointerDataType.getLength());
				Address nextCallbackAddr = PointerDataType.getAddressValue(
					new DumbMemBufferImpl(program.getMemory(), nextCallbackPtrAddr),
					pointerDataType.getLength(), space);
				if (nextCallbackAddr.getOffset() == 0) {
					break;
				}
				PeUtils.createData(program, nextCallbackPtrAddr, pointerDataType, log);
				program.getSymbolTable().createLabel(nextCallbackAddr, "tls_callback_" + i,
					SourceType.IMPORTED);
				program.getSymbolTable().addExternalEntryPoint(nextCallbackAddr);
			}
		}
		catch (InvalidInputException e) {
			log.appendMsg("TLS", "Failed to markup TLS callback functions: " + e.getMessage());
		}
	}
}
 
Example 9
Source File: AndroidElfRelocationOffset.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	Scalar s = (Scalar) super.getValue(buf, settings, length);
	if (s == null) {
		return null;
	}
	// assume pointer into physical space associated with buf
	AddressSpace space = buf.getAddress().getAddressSpace().getPhysicalSpace();
	return space.getAddress(s.getUnsignedValue() + baseOffset);
}
 
Example 10
Source File: OmfSegmentHeader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @param language is the Program language for this binary
 * @return the starting Address for this segment
 */
public Address getAddress(Language language) {
	AddressSpace addrSpace;

	if (isCode) {
		addrSpace = language.getDefaultSpace();
	} else {
		addrSpace = language.getDefaultDataSpace();
	}
	return addrSpace.getAddress(vma);		
}
 
Example 11
Source File: AddressMapDBTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
   public void testStackAddressNegative() {
	AddressSpace stackSpace = p.getAddressFactory().getStackSpace();
	Address a = stackSpace.getAddress(-1);
	long key = addrMap.getKey(a, false);
	assertEquals(0x40000000ffffffffl, key);
	Address b = addrMap.decodeAddress(key);
	assertEquals(a, b);

}
 
Example 12
Source File: CreateArrayInStructureCmdTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address addr(long offset) {
	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	return space.getAddress(offset);
}
 
Example 13
Source File: MemoryMapProvider2Test.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddOverlayBlockInitialized() throws Exception {
	DockingActionIf action = getAction(plugin, "Add Block");
	performAction(action, false);

	// find the dialog for the add
	AddBlockDialog d = waitForDialogComponent(tool.getToolFrame(), AddBlockDialog.class, 2000);
	final GhidraComboBox<?> comboBox = findComponent(d.getComponent(), GhidraComboBox.class);

	final JTextField nameField =
		(JTextField) findComponentByName(d.getComponent(), "Block Name");
	final RegisterField lengthField =
		(RegisterField) findComponentByName(d.getComponent(), "Length");
	final JTextField commentField =
		(JTextField) findComponentByName(d.getComponent(), "Comment");
	final JCheckBox readCB = (JCheckBox) findComponentByName(d.getComponent(), "Read");
	final JCheckBox writeCB = (JCheckBox) findComponentByName(d.getComponent(), "Write");
	final JCheckBox executeCB = (JCheckBox) findComponentByName(d.getComponent(), "Execute");
	final JCheckBox overlayCB = (JCheckBox) findComponentByName(d.getComponent(), "Overlay");
	final JRadioButton initializedRB =
		(JRadioButton) findComponentByName(d.getComponent(), "Initialized");
	final RegisterField initialValue =
		(RegisterField) findComponentByName(d.getComponent(), "Initial Value");
	final AddressInput addrField =
		(AddressInput) findComponentByName(d.getComponent(), "Source Addr");
	assertNotNull(addrField);
	assertTrue(!addrField.isShowing());

	final JButton okButton = findButton(d.getComponent(), "OK");

	SwingUtilities.invokeAndWait(() -> {
		comboBox.setSelectedItem(MemoryBlockType.DEFAULT);
		overlayCB.setSelected(true);
		overlayCB.getActionListeners()[0].actionPerformed(null);
		nameField.setText(".test");
		lengthField.setText("0x100");
		commentField.setText("this is a block test");
		initialValue.setText("0xa");
	});

	SwingUtilities.invokeAndWait(() -> {
		pressButton(executeCB);
	});

	int x = 1;
	int y = 1;
	clickMouse(initializedRB, 1, x, y, 1, 0);

	assertTrue(okButton.isEnabled());
	assertTrue(readCB.isSelected());
	assertTrue(writeCB.isSelected());
	assertTrue(executeCB.isSelected());

	SwingUtilities.invokeAndWait(() -> okButton.getActionListeners()[0].actionPerformed(null));
	program.flushEvents();
	waitForPostedSwingRunnables();

	MemoryBlock block = null;
	AddressSpace[] spaces = program.getAddressFactory().getAddressSpaces();
	for (AddressSpace space : spaces) {
		if (space.isOverlaySpace()) {
			Address blockAddr = space.getAddress(0);
			block = memory.getBlock(blockAddr);
			break;
		}
	}

	assertNotNull(block);
	MemoryBlock[] blocks = program.getMemory().getBlocks();
	int row = blocks.length - 1;
	assertEquals(".test", model.getValueAt(row, MemoryMapModel.NAME));
	assertEquals("00000000", model.getValueAt(row, MemoryMapModel.START));
	assertEquals(".test::00000000", block.getStart().toString());
	assertEquals("000000ff", model.getValueAt(row, MemoryMapModel.END));
	assertEquals(".test::000000ff", block.getEnd().toString());
	assertEquals("0x100", model.getValueAt(row, MemoryMapModel.LENGTH));
	assertEquals(Boolean.TRUE, model.getValueAt(row, MemoryMapModel.READ));
	assertEquals(Boolean.TRUE, model.getValueAt(row, MemoryMapModel.WRITE));
	assertEquals(Boolean.TRUE, model.getValueAt(row, MemoryMapModel.EXECUTE));
	assertEquals(Boolean.TRUE, model.getValueAt(row, MemoryMapModel.OVERLAY));
	assertEquals(
		MemoryBlockType.DEFAULT.toString(),
		model.getValueAt(row, MemoryMapModel.BLOCK_TYPE));
	assertEquals(Boolean.TRUE, model.getValueAt(row, MemoryMapModel.INIT));
	assertEquals("", model.getValueAt(row, MemoryMapModel.SOURCE));
	assertEquals("this is a block test", model.getValueAt(row, MemoryMapModel.COMMENT));

	assertEquals(0xa, memory.getByte(block.getStart()));
}
 
Example 14
Source File: CreateArrayCmdTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address addr(long offset) {
	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	return space.getAddress(offset);
}
 
Example 15
Source File: SecurityDataDirectory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * virtualAddress is always a binary offset
 */
public Address getMarkupAddress(Program program, boolean isBinary) {
	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	return space.getAddress( virtualAddress);
}
 
Example 16
Source File: CreateDataInStructureBackgroundCmdTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address addr(long offset) {
	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	return space.getAddress(offset);
}
 
Example 17
Source File: MoveBlockModelTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address getAddr(Program p, String spaceName, int offset) {
	AddressSpace space = p.getAddressFactory().getAddressSpace(spaceName);
	return space.getAddress(offset);
}
 
Example 18
Source File: IPCAnalyzer.java    From Ghidra-Switch-Loader with ISC License 4 votes vote down vote up
protected HashBiMap<Address, Address> locateSTables(Program program, ElfCompatibilityProvider elfProvider)
{
    HashBiMap<Address, Address> out = HashBiMap.create();
    List<Pair<Long, Long>> candidates = new ArrayList<>();
    AddressSpace aSpace = program.getAddressFactory().getDefaultAddressSpace();
    Address baseAddr = program.getImageBase();
    Memory mem = program.getMemory();
    
    for (NXRelocation reloc : elfProvider.getRelocations()) 
    {
        if (reloc.addend > 0)
            candidates.add(new Pair(baseAddr.getOffset() + reloc.addend, baseAddr.getOffset() + reloc.offset));
    }
    
    candidates.sort((a, b) -> a.first.compareTo(b.first));
    
    
    // 5.x: match on the "SFCI" constant used in the template of s_Table
    //   MOV  W?, #0x4653
    //   MOVK W?, #0x4943, LSL#16
    long movMask  = 0x5288CAL;
    long movkMask = 0x72A928L;
    
    MemoryBlock text = mem.getBlock(".text"); // Text is one of the few blocks that isn't split
    
    try
    {
        for (long off = text.getStart().getOffset(); off < text.getEnd().getOffset(); off += 0x4)
        {
            long val1 = (elfProvider.getReader().readUnsignedInt(off) & 0xFFFFFF00L) >> 8;
            long val2 = (elfProvider.getReader().readUnsignedInt(off + 0x4) & 0xFFFFFF00L) >> 8;
            
            // Match on a sequence of MOV, MOVK
            if (val1 == movMask && val2 == movkMask)
            {
                long processFuncOffset = 0;
                long sTableOffset = 0;
                
                // Find the candidate after our offset, then pick the one before that
                for (Pair<Long, Long> candidate : candidates)
                {
                    if (candidate.first > off)
                        break;
                    
                    processFuncOffset = candidate.first;
                    sTableOffset = candidate.second;
                }
                
                long pRetOff;
                
                // Make sure our SFCI offset is within the process function by matching on the
                // RET instruction
                for (pRetOff = processFuncOffset; pRetOff < text.getEnd().getOffset(); pRetOff += 0x4)
                {
                    long rval = elfProvider.getReader().readUnsignedInt(pRetOff);
                    
                    // RET
                    if (rval == 0xD65F03C0L)
                        break;
                }
                
                if (pRetOff > off)
                {
                    Address stAddr = aSpace.getAddress(sTableOffset);
                    Address pFuncAddr = aSpace.getAddress(processFuncOffset);
                    out.put(stAddr, pFuncAddr);
                }
            }
        }
    }
    catch (IOException e)
    {
        Msg.error(this, "Failed to locate s_Tables", e);
    }
    
    return out;
}
 
Example 19
Source File: CoffSectionHeader.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Convert address offset to an Address in the specified space (defined by pspec).
 * If pspec does not specify a default data space, the default language space is used.
 * @param language
 * @param offset address offset (word offset assumed).
 * @param space address space
 * @return address object
 */
public static Address getAddress(Language language, long offset, AddressSpace space) {
	return space.getAddress(offset * getOffsetUnitSize(language, null));
}
 
Example 20
Source File: CoffSectionHeader.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Convert address offset to an Address object.  The default data space (defined by pspec)
 * will be used if section is null or corresponds to a data section.  The language default
 * space (defined by slaspec) will be used for all non-data sections.  If pspec does not 
 * specify a default data space, the default language space is used.
 * @param language
 * @param offset address offset (byte offset assumed if section is null or is not explicitly
 * byte aligned, otherwise word offset assumed).
 * @param section section which contains the specified offset or null (data space assumed)
 * @return address object
 */
public static Address getAddress(Language language, long offset, CoffSectionHeader section) {
	boolean isData = section == null || section.isData();
	AddressSpace space = isData ? language.getDefaultDataSpace() : language.getDefaultSpace();
	return space.getAddress(offset * getOffsetUnitSize(language, section));
}