Java Code Examples for ghidra.program.model.mem.Memory#getBlock()

The following examples show how to use ghidra.program.model.mem.Memory#getBlock() . 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: MemoryBlockHelper.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
private void addUniqueSection(String name, long addressOffset, long offset, long length, boolean read, boolean write, boolean execute)
{
    Memory memory = this.program.getMemory();
    Address startAddr = this.program.getImageBase().add(addressOffset);
    Address endAddr = startAddr.add(length);
    String newBlockName = name;
    int nameCounter = 0;
    
    while (memory.getBlock(newBlockName) != null)
    {
        nameCounter++;
        newBlockName = name + "." + nameCounter; 
    }
    
    Msg.info(this, "Adding unique section " + newBlockName + " from " + startAddr.toString() + " to " + endAddr.toString());
    this.addSection(newBlockName, offset, offset, length, read, write, execute);
}
 
Example 2
Source File: MemorySectionResolver.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getUniqueSectionName(String baseName) {
	if (baseName != null) {
		baseName = baseName.trim();
		if (baseName.length() == 0) {
			baseName = "NO-NAME";
		}
	}
	else {
		baseName = "NO-NAME";
	}
	Memory mem = program.getMemory();
	String name = baseName;
	int index = 0;
	while (mem.getBlock(name) != null) {
		name = baseName + "-" + (++index);
	}
	return name;
}
 
Example 3
Source File: MemorySectionResolver.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getUniqueSectionChunkName(MemorySection section, Memory memory,
		int preferredIndex) {
	String sectionName = section.getSectionName();
	int index = preferredIndex;
	while (true) {
		String name = sectionName;
		if (index >= 0) {
			name += "." + index;
		}
		if (memory.getBlock(name) == null) {
			return name;
		}
		if (index <= 0) {
			index = 1;
		}
		else {
			index += 1;
		}
	}
}
 
Example 4
Source File: IPCAnalyzer.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) throws CancelledException 
{
    Memory memory = program.getMemory();
    MemoryBlock text = memory.getBlock(".text");
    MemoryBlock rodata = memory.getBlock(".rodata");
    MemoryBlock data = memory.getBlock(".data");
    ElfCompatibilityProvider elfCompatProvider = new ElfCompatibilityProvider(program, false);
    
    Msg.info(this, "Beginning IPC analysis...");
    
    if (text == null || rodata == null || data == null)
        return true;
    
    try
    {
        List<Address> vtAddrs = this.locateIpcVtables(program, elfCompatProvider);
        List<IPCVTableEntry> vtEntries = this.createVTableEntries(program, elfCompatProvider, vtAddrs);
        HashBiMap<Address, Address> sTableProcessFuncMap = this.locateSTables(program, elfCompatProvider);
        Multimap<Address, IPCTrace> processFuncTraces = this.emulateProcessFunctions(program, monitor, sTableProcessFuncMap.values());
        HashBiMap<Address, IPCVTableEntry> procFuncVtMap = this.matchVtables(vtEntries, sTableProcessFuncMap.values(), processFuncTraces);
        this.markupIpc(program, monitor, vtEntries, sTableProcessFuncMap, processFuncTraces, procFuncVtMap);
    }
    catch (Exception e)
    {
        Msg.error(this, "Failed to analyze binary IPC.", e);
        return false;
    }
    
    return true;
}
 
Example 5
Source File: ObjectiveC1_Utilities.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the address is THUMB code.
 */
public static boolean isThumb(Program program, Address address) {
	Processor ARM = Processor.findOrPossiblyCreateProcessor("ARM");
	if (program.getLanguage().getProcessor().equals(ARM)) {
		Memory memory = program.getMemory();
		MemoryBlock block = memory.getBlock(address);
		if (block != null && block.isExecute()) {
			return (address.getOffset() % 2) != 0;
		}
	}
	return false;
}
 
Example 6
Source File: PropertyManagerPluginScreenShots.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();

	// create some properties
	int id = program.startTransaction("test");
	PropertyMapManager pm = program.getUsrPropertyManager();
	pm.createIntPropertyMap("Foo Property");
	IntPropertyMap map1 = pm.createIntPropertyMap("Bar Property");
	Memory memory = program.getMemory();
	MemoryBlock block = memory.getBlock(".text");
	Address addr = block.getStart();
	for (int i = 0; i < 5000; i++) {
		map1.add(addr, i);
		addr = addr.add(10);
	}

	program.endTransaction(id, true);
	loadPlugin(PropertyManagerPlugin.class);
	showProvider(PropertyManagerProvider.class);
	PropertyManagerProvider provider = getProvider(PropertyManagerProvider.class);
	goToListing(0x00401082);
	final JTable table = (JTable) getInstanceField("table", provider);
	runSwing(new Runnable() {

		@Override
		public void run() {
			table.setRowSelectionInterval(0, 0);
		}
	});
}
 
Example 7
Source File: ObjectiveC2_ClassAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void setDataAndRefBlocksReadOnly(ObjectiveC2_State state) {
	Memory memory = state.program.getMemory();
	MemoryBlock dataBlock = memory.getBlock(ObjectiveC2_Constants.OBJC2_DATA);
	if (dataBlock != null) {
		dataBlock.setWrite(false);
	}

	MemoryBlock classRefsBlock = memory.getBlock(ObjectiveC2_Constants.OBJC2_CLASS_REFS);
	if (classRefsBlock != null) {
		classRefsBlock.setWrite(false);
	}

	MemoryBlock messageRefsBlock = memory.getBlock(ObjectiveC2_Constants.OBJC2_MESSAGE_REFS);
	if (messageRefsBlock != null) {
		messageRefsBlock.setWrite(false);
	}

	MemoryBlock selectorRefsBlock = memory.getBlock(ObjectiveC2_Constants.OBJC2_SELECTOR_REFS);
	if (selectorRefsBlock != null) {
		selectorRefsBlock.setWrite(false);
	}

	MemoryBlock superRefsBlock = memory.getBlock(ObjectiveC2_Constants.OBJC2_SUPER_REFS);
	if (superRefsBlock != null) {
		superRefsBlock.setWrite(false);
	}

	MemoryBlock protocolRefsBlock = memory.getBlock(ObjectiveC2_Constants.OBJC2_PROTOCOL_REFS);
	if (protocolRefsBlock != null) {
		protocolRefsBlock.setWrite(false);
	}
}
 
Example 8
Source File: ArmSymbolAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) {
	monitor.setMessage("ARM/Thumb symbol analyzer");

	Memory memory = program.getMemory();

	// Get and iterate over symbols
	SymbolIterator it = program.getSymbolTable().getPrimarySymbolIterator(set, true);
	while (it.hasNext() && !monitor.isCancelled()) {
		Symbol primarySymbol = it.next();
		Address address = primarySymbol.getAddress();
		if (!address.isMemoryAddress()) {
			continue;
		}

		MemoryBlock block = memory.getBlock(address);
		if (block == null || !block.isExecute()) {
			continue;
		}

		// Check if last bit is set to indicate Thumb
		if ((address.getOffset() & 0x01) != 0x01) {
			continue;
		}

		Address newAddress = address.subtract(1L);

		moveFunction(program, address, newAddress);

		moveSymbols(program, address, newAddress);

		updateEntryPoint(program, address, newAddress);

		setTModeRegister(program, newAddress);

	}
	return true;
}
 
Example 9
Source File: MemoryTypeProgramLocationBasedTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public MemoryBlock getValue(ProgramLocation rowObject, Settings settings, Program program,
		ServiceProvider serviceProvider) throws IllegalArgumentException {
	Memory memory = program.getMemory();
	MemoryBlock block = memory.getBlock(rowObject.getAddress());
	return block;
}
 
Example 10
Source File: RttiUtil.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the number of vf addresses in the vf table that begins at the specified base 
 * address.
 * @param program the program whose memory is providing their addresses
 * @param vfTableBaseAddress the base address in the program for the vf table
 * @return the number of virtual function addresses in the vf table
 */
static int getVfTableCount(Program program, Address vfTableBaseAddress) {

	Memory memory = program.getMemory();
	MemoryBlock textBlock = memory.getBlock(".text");
	AddressSetView initializedAddresses = memory.getLoadedAndInitializedAddressSet();
	PseudoDisassembler pseudoDisassembler = new PseudoDisassembler(program);

	// Create pointers starting at the address until reaching a 0 pointer.
	// Terminate the possible table at any entry containing a cross reference that 
	// is beyond the first table entry and don't include it.
	int tableSize = 0;
	Address currentVfPointerAddress = vfTableBaseAddress;
	int defaultPointerSize = program.getDefaultPointerSize();
	while (true) {
		Address referencedAddress = getAbsoluteAddress(program, currentVfPointerAddress);
		if (referencedAddress == null) {
			break; // Cannot get a virtual function address.
		}
		if (referencedAddress.getOffset() == 0) {
			break; // Encountered 0 entry.
		}
		if (!initializedAddresses.contains(referencedAddress)) {
			break; // Not pointing to initialized memory.
		}
		if ((textBlock != null) ? !textBlock.equals(memory.getBlock(referencedAddress))
				: false) {
			break; // Not pointing to text section.
		}
		if (!pseudoDisassembler.isValidSubroutine(referencedAddress, true)) {
			break; // Not pointing to possible function.
		}

		tableSize++; // Count this entry in the table.

		// Advance to the next table entry address.
		currentVfPointerAddress = currentVfPointerAddress.add(defaultPointerSize);
	}
	return tableSize;
}
 
Example 11
Source File: ObjectiveC2_DecompilerMessageAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean isFunctionInTextSection(Program program, Function function) {
	if (function == null) {
		return false;
	}
	Address address = function.getEntryPoint();
	Memory memory = program.getMemory();
	MemoryBlock block = memory.getBlock(address);
	if (block.getName().equals("__text")) {
		return true;
	}
	return false;
}
 
Example 12
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;
}
 
Example 13
Source File: DiffOverlayApplyTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
   public void testShowHideDiffApplySettings() throws Exception {
	ClassicSampleX86ProgramBuilder builder = new ClassicSampleX86ProgramBuilder();
	builder.createMemory(".data", "0x2001000", 1000);

	Program p1 = builder.getProgram();
	assertTrue(p1.getAddressFactory() instanceof ProgramAddressFactory);
	assertEquals(2, p1.getAddressFactory().getNumAddressSpaces()); // ram, OTHER

	int id1 = p1.startTransaction("");
	Memory memory1 = p1.getMemory();
	MemoryBlock dataBlock1 = memory1.getBlock(".data");
	MemoryBlock overlayBlock1 =
		memory1.createInitializedBlock("OVL1", dataBlock1.getStart(), 0x20L, (byte) 0,
			TaskMonitorAdapter.DUMMY_MONITOR, true);
	assertEquals(3, p1.getAddressFactory().getNumAddressSpaces()); // ram, OTHER, OVL1

	AddressSet addressSet1 = new AddressSet(overlayBlock1.getStart(), overlayBlock1.getEnd());
	byte[] bytes1 =
		{ 'a', 'p', 'p', 'l', 'e', (byte) 0, 'o', 'r', 'a', 'n', 'g', 'e', (byte) 0 };
	memory1.setBytes(overlayBlock1.getStart(), bytes1);

	Listing listing1 = p1.getListing();
	Address overlayAddress1 = overlayBlock1.getStart();
	listing1.createData(overlayAddress1, new TerminatedStringDataType());
	overlayAddress1 = overlayAddress1.add(6);
	listing1.createData(overlayAddress1, new TerminatedStringDataType());

	p1.endTransaction(id1, true);

	ClassicSampleX86ProgramBuilder builder2 = new ClassicSampleX86ProgramBuilder();
	builder2.createMemory(".data", "0x2001000", 1000);
	Program p2 = builder2.getProgram();
	assertTrue(p2.getAddressFactory() instanceof ProgramAddressFactory);
	assertEquals(2, p2.getAddressFactory().getNumAddressSpaces());

	int id2 = p2.startTransaction("");
	Memory memory2 = p2.getMemory();
	MemoryBlock dataBlock2 = memory2.getBlock(".data");
	MemoryBlock overlayBlock2 =
		memory2.createInitializedBlock("OVL1", dataBlock2.getStart(), 0x20L, (byte) 0,
			TaskMonitorAdapter.DUMMY_MONITOR, true);
	assertEquals(3, p2.getAddressFactory().getNumAddressSpaces());

	AddressSet addressSet2 = DiffUtility.getCompatibleAddressSet(addressSet1, p2);
	byte[] bytes2 =
		{ 'd', 'o', 'b', 'e', 'r', 'm', 'a', 'n', (byte) 0, 'p', 'o', 'o', 'd', 'l', 'e',
			(byte) 0 };
	memory2.setBytes(overlayBlock2.getStart(), bytes2);

	Listing listing2 = p2.getListing();
	Address overlayAddress2 = overlayBlock2.getStart();
	listing2.createData(overlayAddress2, new TerminatedStringDataType());
	overlayAddress2 = overlayAddress2.add(9);
	listing2.createData(overlayAddress2, new TerminatedStringDataType());

	p2.endTransaction(id2, true);

	openProgram(p1);

	openDiff(p2);
	setDiffSelection(addressSet2);
	apply();

	Listing listing = p1.getListing();
	MemoryBlock overlayBlock = p1.getMemory().getBlock("OVL1");
	Address overlayAddress = overlayBlock.getStart();
	Data dataAt = listing.getDataAt(overlayAddress);
	assertNotNull(dataAt);
	assertEquals("doberman", dataAt.getValue());

	overlayAddress = overlayBlock.getStart().add(9);
	dataAt = listing.getDataAt(overlayAddress);
	assertNotNull(dataAt);
	assertEquals("poodle", dataAt.getValue());
}
 
Example 14
Source File: SampleProgramTreePlugin.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean applyTo(DomainObject obj, TaskMonitor monitor) {
	Program program = (Program) obj;

	listing = program.getListing();

	createDefaultTreeView(program, programTreeName);

	Memory mem = program.getMemory();

	ProgramModule root_module = listing.getRootModule(programTreeName);

	AddressSet set = new AddressSet(mem);

	try {
		root_module.createModule("Fragments");
	}
	catch (DuplicateNameException e) {
		// don't care???
	}
	ProgramModule frags = listing.getModule(programTreeName, "Fragments");

	long startCount = set.getNumAddresses();
	monitor.initialize(startCount);
	while (!monitor.isCancelled() && !set.isEmpty()) {
		MemoryBlock block = mem.getBlock(set.getMinAddress());
		Address start = block.getStart();
		Address end = block.getEnd();

		set.deleteRange(block.getStart(), block.getEnd());

		long numLeft = set.getNumAddresses();
		monitor.setProgress(startCount - numLeft);

		String mod_name = block.getName();

		monitor.setMessage("Module " + start + " : " + mod_name);

		ProgramModule mod = make_module(mod_name, frags);
		makeFragment(start, end, "frag_" + fragment_count, mod);
		fragment_count++;
	}

	return true;
}
 
Example 15
Source File: DexHeaderFormatAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean analyze(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws Exception {

	Address startAddress = toAddr(program, 0x0);

	if (getDataAt(program, startAddress) != null) {
		log.appendMsg("data already exists.");
		return true;
	}

	Memory memory = program.getMemory();
	MemoryBlock block = memory.getBlock(startAddress);
	block.setRead(true);
	block.setWrite(false);
	block.setExecute(false);

	DexAnalysisState analysisState = DexAnalysisState.getState(program);
	DexHeader header = analysisState.getHeader();
	processHeader(program, header);

	createInitialFragments(program, header, monitor);

	BasicCompilerSpec.enableJavaLanguageDecompilation(program);
	createNamespaces(program, header, monitor, log);
	processMap(program, header, monitor, log);
	processStrings(program, header, monitor, log);
	processTypes(program, header, monitor, log);
	processPrototypes(program, header, monitor, log);
	processFields(program, header, monitor, log);
	processMethods(program, header, monitor, log);
	processClassDefs(program, header, monitor, log);
	createProgramDataTypes(program, header, monitor, log);

	createMethods(program, header, monitor, log);

	monitor.setMessage("DEX: cleaning up tree");
	removeEmptyFragments(program);

	return true;
}
 
Example 16
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Get a LabelString object which corresponds to the specified memory
 * reference from the specified code unit. Format options are considered
 * when generating label.
 * 
 * @param fromCodeUnit code unit
 * @param ref memory reference
 * @return LabelString representation object
 */
private Object getMemoryReferenceLabel(CodeUnit fromCodeUnit, Reference ref) {

	Program program = fromCodeUnit.getProgram();
	Address toAddress = ref.getToAddress();

	boolean withBlockName = false;
	MemoryBlock refBlock = null;

	if (toAddress.isMemoryAddress()) {
		Memory mem = program.getMemory();
		refBlock = mem.getBlock(toAddress);
		if (options.showBlockName == ShowBlockName.ALWAYS) {
			withBlockName = true;
		}
		else if (options.showBlockName == ShowBlockName.NON_LOCAL) {
			MemoryBlock block = mem.getBlock(fromCodeUnit.getMinAddress());
			withBlockName = (block != refBlock);
		}
	}

	String result;
	Symbol toSymbol = program.getSymbolTable().getSymbol(ref);
	if (toSymbol != null) {
		result = getSymbolLabelString(program, toSymbol, fromCodeUnit.getMinAddress());
	}
	else {
		result = toAddress.toString();
	}

	result = addBlockName(program, toAddress, result, refBlock, withBlockName);
	LabelType labelType = (toSymbol != null && toSymbol.isExternal()) ? LabelString.EXTERNAL
			: LabelString.CODE_LABEL;
	LabelString label = new LabelString(result, labelType);

	// Apply extended pointer markup if needed
	RefType referenceType = ref.getReferenceType();
	if (options.followReferencedPointers &&
		(referenceType.isIndirect() || ref.getReferenceType() == RefType.READ)) {
		LabelString extLabel = getExtendedPointerReferenceMarkup(program, ref);
		if (extLabel != null) {
			OperandRepresentationList list = new OperandRepresentationList();
			//list.add(label);
			list.add(EXTENDED_INDIRECT_REFERENCE_DELIMITER);
			list.add(extLabel);
			return list;
		}
	}

	return label;
}
 
Example 17
Source File: X86_32_ElfExtension.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Handle the case where GOT entry offset are computed based upon EBX.  
 * This implementation replaces the old "magic map" which had previously been used.
 * @param elfLoadHelper
 * @param monitor
 * @throws CancelledException
 */
private void processX86Plt(ElfLoadHelper elfLoadHelper, TaskMonitor monitor) throws CancelledException {
	
	// TODO: Does 64-bit have a similar mechanism?

	// TODO: Would be better to use only dynamic table entries since sections may be stripped -
	// the unresolved issue is to determine the length of the PLT area without a section
	
	ElfHeader elfHeader = elfLoadHelper.getElfHeader();
	ElfSectionHeader pltSection = elfHeader.getSection(ElfSectionHeaderConstants.dot_plt);
	if (pltSection == null || !pltSection.isExecutable()) {
		return;
	}
	
	ElfDynamicTable dynamicTable = elfHeader.getDynamicTable();
	if (dynamicTable == null || !dynamicTable.containsDynamicValue(ElfDynamicType.DT_PLTGOT)) {
		return; // avoid NotFoundException which causes issues for importer
	}
	
	Program program = elfLoadHelper.getProgram();
	Memory memory = program.getMemory();
	
	// MemoryBlock pltBlock = getBlockPLT(pltSection);
	MemoryBlock pltBlock = memory.getBlock(pltSection.getNameAsString());
	// TODO: This is a band-aid since there are many PLT implementations and this assumes only one.
	if (pltBlock == null || pltBlock.getSize() <= ElfConstants.PLT_ENTRY_SIZE) {
		return;
	}

	// Paint pltgot base over .plt section to allow thunks to be resolved during analysis
	Register ebxReg = program.getRegister("EBX");
	try {
		long pltgotOffset = elfHeader.adjustAddressForPrelink(dynamicTable.getDynamicValue(
				ElfDynamicType.DT_PLTGOT));
		pltgotOffset = elfLoadHelper.getDefaultAddress(pltgotOffset).getOffset(); // adjusted for image base
		RegisterValue pltgotValue = new RegisterValue(ebxReg, BigInteger.valueOf(pltgotOffset));
		program.getProgramContext().setRegisterValue(pltBlock.getStart(), pltBlock.getEnd(), pltgotValue);
	} catch (NotFoundException | ContextChangeException e) {
		throw new AssertException("unexpected", e);
	}

}
 
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: DisassembledViewPluginTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the plugins response to 
 * {@link ghidra.app.events.ProgramLocationPluginEvent}s.  This plugin is
 * driven off of these events.
 * 
 * @throws Exception If there is a problem opening the program.
 */
@Test
public void testProcessingOnLocationChanged() throws Exception {
	openProgram("notepad");

	// get the list hiding inside of the component provider
	JList list = (JList) getInstanceField("contentList", componentProvider);

	// sanity check
	assertEquals("The component provider has data when it is not visible.", 0,
		list.getModel().getSize());

	// show the plugin and make sure it is visible before we continue
	tool.showComponentProvider(componentProvider, true);
	waitForPostedSwingRunnables();

	ListModel modelOne = list.getModel();

	// now the list should have data, as it will populate itself off of the
	// current program location of the plugin
	assertTrue("The component provider does not have data when it " + "should.",
		(modelOne.getSize() != 0));

	// make sure we process the event in order to show the user the 
	// preview
	CodeBrowserPlugin cbPlugin = getPlugin(tool, CodeBrowserPlugin.class);

	// scroll the display and force a new selection
	pageDown(cbPlugin.getFieldPanel());
	simulateButtonPress(cbPlugin);
	waitForPostedSwingRunnables();

	// get the data
	ListModel modelTwo = list.getModel();

	boolean sameData = compareListData(modelOne, modelTwo);
	assertTrue("The contents of the two lists are the same when they " + "should not be.",
		!sameData);

	// make sure no work is done when we are not visible
	tool.showComponentProvider(componentProvider, false);
	waitForPostedSwingRunnables();

	assertEquals("The component provider has data when it is not visible.", 0,
		list.getModel().getSize());

	// show the plugin so that it will get the program location change 
	// data
	tool.showComponentProvider(componentProvider, true);
	waitForPostedSwingRunnables();

	// test that sending a bad address will not return any results or 
	// throw any exceptions
	Memory memory = program.getMemory();
	MemoryBlock textBlock = memory.getBlock(".text");
	Address endAddress = textBlock.getEnd();

	// creating a program location based upon the end address should result
	// in only one item in the disassembled list
	ProgramLocation location = new ProgramLocation(program, endAddress);

	// call the locationChanged() method
	invokeInstanceMethod("locationChanged", plugin, new Class[] { ProgramLocation.class },
		new Object[] { location });

	assertTrue(
		"The plugin's display list has more than 1 element when " +
			"at the end address of a memory block.  List size: " + list.getModel().getSize(),
		(list.getModel().getSize() == 1));

	Listing listing = program.getListing();
	CodeUnit codeUnit = listing.getCodeUnitAt(endAddress);
	Address invalidAddress = endAddress.addNoWrap(codeUnit.getLength());
	ProgramLocation newLocation = new ProgramLocation(program, invalidAddress);

	invokeInstanceMethod("locationChanged", plugin, new Class[] { ProgramLocation.class },
		new Object[] { newLocation });

	assertEquals("The plugin's display list has data when there is an " +
		"invalid address at the current program location.", list.getModel().getSize(), 0);
}
 
Example 20
Source File: MemoryRangeDiff.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor. <CODE>MemoryRangeDiff</CODE> determines the types of differences 
 * between two memory blocks.
 * @param memory1 the first program's memory
 * @param memory2 the second program's memory
 * @param range the address range where the two programs differ
 */
public MemoryRangeDiff(Memory memory1, Memory memory2, AddressRange range) {
	super(memory1.getBlock(range.getMinAddress()), memory2.getBlock(range.getMinAddress()));
	this.memory1 = memory1;
	this.memory2 = memory2;
	this.range = range;
}