ghidra.program.model.data.PointerDataType Java Examples

The following examples show how to use ghidra.program.model.data.PointerDataType. 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: IPCAnalyzer.java    From Ghidra-Switch-Loader with ISC License 7 votes vote down vote up
protected int createPointer(Program program, Address address)
{
    Data d = program.getListing().getDataAt(address);
    
    if (d == null) 
    {
        try 
        {
            d = program.getListing().createData(address, PointerDataType.dataType, 8);
        } 
        catch (CodeUnitInsertionException | DataTypeConflictException e) 
        {
            Msg.error(this, String.format("Failed to create pointer at 0x%X", address.getOffset()), e);
        }
    }
    
    return d.getLength();
}
 
Example #2
Source File: GoTypesAnalyzer.java    From gotools with MIT License 6 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView addressSetView, TaskMonitor taskMonitor,
    MessageLog messageLog) throws CancelledException {
  StructureDataType s = new StructureDataType("GoString", 0);
  s.add(new QWordDataType(), "len", null);
  s.add(new Pointer64DataType(new CharDataType()), "str", null);
  program.getDataTypeManager().addDataType(s, DataTypeConflictHandler.KEEP_HANDLER);

  StructureDataType sl = new StructureDataType("GoSlice", 0);
  sl.add(new PointerDataType(), 8, "data", null);
  sl.add(new QWordDataType(), "len", null);
  sl.add(new QWordDataType(), "cap", null);

  program.getDataTypeManager().addDataType(sl, DataTypeConflictHandler.KEEP_HANDLER);
  return false;
}
 
Example #3
Source File: FunctionManagerTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetReferencedFunction() throws Exception {

	createFunction("foo", addr(100), new AddressSet(addr(100), addr(200)));
	createFunction("foo1", addr(250), new AddressSet(addr(250), addr(350)));
	Function foo2 = createFunction("foo2", addr(201), new AddressSet(addr(201), addr(249)));

	Function fum = program.getExternalManager().addExtLocation("lib", "fum", null,
		SourceType.USER_DEFINED).createFunction();

	program.getMemory().setInt(addr(50), 201);
	program.getListing().createData(addr(50), PointerDataType.dataType);
	assertEquals(foo2, program.getFunctionManager().getReferencedFunction(addr(50)));

	program.getReferenceManager().addExternalReference(addr(50), 0,
		program.getExternalManager().getExternalLocation(fum.getSymbol()),
		SourceType.USER_DEFINED, RefType.DATA);

	assertEquals(fum, program.getFunctionManager().getReferencedFunction(addr(50)));

}
 
Example #4
Source File: ListingPanelTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private ProgramDB buildProgram() throws Exception {
	ProgramBuilder builder = new ProgramBuilder("notepad", ProgramBuilder._X86, this);

	builder.createMemory(".text", "0x1001000", 0x6600);
	builder.createMemory(".data", "0x1008000", 0x600);
	builder.createMemory(".data", "0x1008600", 0x1344);
	builder.createMemory(".rsrc", "0x100a000", 0x5400);
	builder.applyDataType("0x1001000", PointerDataType.dataType, 4);
	builder.setBytes("0x1001008", "01 02 03 04");
	builder.createMemoryReference("1001100", "1001008", RefType.READ, SourceType.DEFAULT);
	builder.createLabel("0x1001008", "ADVAPI32.dll_RegQueryValueExW");
	builder.createExternalReference("0x1001008", "ADVAPI32.dll", "RegQueryValueExW", 0);

	builder.setBytes("1004772", "bf 00 01 00 00", true);
	builder.createMemoryReference("1004700", "1004777", RefType.DATA, SourceType.DEFAULT);
	return builder.getProgram();
}
 
Example #5
Source File: ArmOffcutReferenceTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

	builder = new ProgramBuilder("Test", ProgramBuilder._ARM);
	builder.setBytes("0023303a", functionBytes);
	builder.disassembleArm("0023303a", functionBytes.length(), true);

	builder.setBytes("0045b390", addressTableBytes);
	builder.applyDataType("0045b390", new PointerDataType(), 7);

	program = builder.getProgram();

	env = new TestEnv();
	tool = env.showTool(program);
	tool.addPlugin(CodeBrowserPlugin.class.getName());
	cb = env.getPlugin(CodeBrowserPlugin.class);
}
 
Example #6
Source File: PseudoDisassembler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Interpret the bytes at a location in memory as an address
 * and return the address.  This routine assumes that the bytes
 * needed to create the address are the same size as the bytes
 * needed to represent the toAddr.  So this is somewhat generic.
 * 
 * @param toAddr location of the bytes in memory
 * 
 * @return the address value
 */
public Address getIndirectAddr(Address toAddr) {
	Data data =
		applyDataType(toAddr, PointerDataType.getPointer(null, toAddr.getPointerSize()));

	if (data == null) {
		return null;
	}
	Object objVal = data.getValue();
	if (!(objVal instanceof Address)) {
		return null;
	}
	Address ptrAddr = (Address) objVal;

	return ptrAddr;
}
 
Example #7
Source File: StringTable_BE_Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void openProgram() throws Exception {
	// make big endian program
	ToyProgramBuilder builder = new ToyProgramBuilder("TestGhidraSearches", true);
	builder.createMemory("test", "0x0", 1000);

	// create bytes for string at 100
	builder.setBytes("0x100", "61, 62, 63, 64, 65, 66, 67, 68");

	// create defined string at 200
	builder.createEncodedString("200", "abcdefghij", StandardCharsets.US_ASCII, false);

	// create conflict at 300
	builder.setBytes("0x300", "61, 62, 63, 64, 65, 66, 67");
	builder.applyDataType("0x300", new PointerDataType());
	builder.applyDataType("0x304", new PointerDataType());

	// create a unicode
	builder.setBytes("0x400", "00, 61, 00, 62, 00, 63, 00, 64, 00, 65, 00, 66, 00");
	program = builder.getProgram();
	ProgramManager pm = tool.getService(ProgramManager.class);
	pm.openProgram(program.getDomainFile());
}
 
Example #8
Source File: PefLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processTermSymbol(ContainerHeader header, Program program,
		ImportStateCache importState, MessageLog log, TaskMonitor monitor) {
	SymbolTable symbolTable = program.getSymbolTable();

	LoaderInfoHeader loader = header.getLoader();

	int termSectionIndex = loader.getTermSection();
	if (termSectionIndex != -1) {
		SectionHeader termSection = header.getSections().get(termSectionIndex);
		MemoryBlock termBlock = importState.getMemoryBlockForSection(termSection);
		Address address = termBlock.getStart().add(loader.getTermOffset());
		try {
			symbolTable.createLabel(address, PefConstants.TERM, SourceType.IMPORTED);
			CreateDataCmd cmd = new CreateDataCmd(address, new PointerDataType());
			cmd.applyTo(program);
		}
		catch (Exception e) {
			log.appendException(e);
		}
	}
}
 
Example #9
Source File: PefLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processInitSymbol(ContainerHeader header, Program program,
		ImportStateCache importState, MessageLog log, TaskMonitor monitor) {
	SymbolTable symbolTable = program.getSymbolTable();

	LoaderInfoHeader loader = header.getLoader();

	int initSectionIndex = loader.getInitSection();
	if (initSectionIndex != -1) {
		SectionHeader initSection = header.getSections().get(initSectionIndex);
		MemoryBlock initBlock = importState.getMemoryBlockForSection(initSection);
		Address address = initBlock.getStart().add(loader.getInitOffset());
		try {
			symbolTable.createLabel(address, PefConstants.INIT, SourceType.IMPORTED);
			CreateDataCmd cmd = new CreateDataCmd(address, new PointerDataType());
			cmd.applyTo(program);
		}
		catch (Exception e) {
			log.appendException(e);
		}
	}
}
 
Example #10
Source File: PefLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * TODO determine how to correctly identify TOC location
 */
private void processTocSymbol(ContainerHeader header, Program program,
		ImportStateCache importState, MessageLog log, TaskMonitor monitor) {
	SymbolTable symbolTable = program.getSymbolTable();
	List<SectionHeader> sections = header.getSections();
	if (sections.size() < 2) {
		return;
	}
	SectionHeader dataSection = sections.get(1);
	if (!dataSection.isWrite()) {//is not a data section...
		return;
	}
	Address tocAddress = importState.getTocAddress();
	if (tocAddress == null) {
		MemoryBlock dataBlock = importState.getMemoryBlockForSection(dataSection);
		tocAddress = dataBlock.getStart();
	}
	try {
		symbolTable.createLabel(tocAddress, PefConstants.TOC, SourceType.IMPORTED);
		CreateDataCmd cmd = new CreateDataCmd(tocAddress, new PointerDataType());
		cmd.applyTo(program);
	}
	catch (Exception e) {
		log.appendException(e);
	}
}
 
Example #11
Source File: RelocationState.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the fixup address to the contents stored at address,
 * then creates a pointer at address.
 * @param address the address to fixup
 * @param fixupAddress the value to use in fixup
 * @param log message log for recording errors
 */
public void fixupMemory(Address address, Address fixupAddress, MessageLog log) {
	relocateMemoryAt(address, (int) fixupAddress.getOffset(), log);
	try {
		program.getListing().createData(address, new PointerDataType(), 4);
	}
	catch (Exception e) {
		log.appendException(e);
	}
}
 
Example #12
Source File: CallTreePluginTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallTreeForExternalFicticiousFunction() {
	// 
	// 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.
	//

	// Setup external call linkage, 2000 -> PTR@10100 -> GDI32.DLL:LineTo
	String addrString = "10100";
	applyCmd(program, new CreateDataCmd(addr(addrString), true, PointerDataType.dataType));
	applyCmd(program,
		new CreateExternalFunctionCmd("GDI32.DLL", "LineTo", null, SourceType.IMPORTED));
	applyCmd(program, new SetExternalRefCmd(addr(addrString), 0, "GDI32.DLL", "LineTo", null,
		RefType.DATA, SourceType.IMPORTED));
	applyCmd(program, new AddMemRefCmd(addr("2000"), addr(addrString), RefType.INDIRECTION,
		SourceType.ANALYSIS, 0));
	applyCmd(program, new SetExternalRefCmd(addr("2000"), Reference.MNEMONIC, "GDI32.DLL",
		"LineTo", null, RefType.COMPUTED_CALL, SourceType.ANALYSIS));

	setProviderFunction(addrString);

	waitForTree(incomingTree);
	GTreeNode rootNode = getRootNode(incomingTree);
	List<GTreeNode> children = rootNode.getChildren();
	assertTrue("Incoming tree does not have callers as expected for function: " + addrString,
		children.size() > 0);
}
 
Example #13
Source File: PefLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createPointer(Program program, Address start, MessageLog log) {
	try {
		program.getListing().createData(start, new PointerDataType(), 4);
	}
	catch (Exception e) {
		log.appendMsg(e.getMessage());
	}
}
 
Example #14
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
protected int createPointer(Address address) throws CodeUnitInsertionException, DataTypeConflictException
{
    NXOAdapter adapter = this.nxo.getAdapter();
    Data d = this.program.getListing().getDataAt(address);
    
    if (d == null || !PointerDataType.dataType.isEquivalent(d.getDataType())) 
    {
        d = this.program.getListing().createData(address, PointerDataType.dataType, adapter.getOffsetSize());
    }
    
    return d.getLength();
}
 
Example #15
Source File: ObjectiveC1_Protocol.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public DataType toDataType() throws DuplicateNameException, IOException {
	StructureDataType struct = new StructureDataType(NAME, 0);
	struct.setCategoryPath(ObjectiveC1_Constants.CATEGORY_PATH);
	struct.add(DWORD, "isa", null);
	struct.add(PointerDataType.getPointer(ASCII, _state.pointerSize), "name", null);
	struct.add(PointerDataType.getPointer(ObjectiveC1_ProtocolList.toGenericDataType(_state), _state.pointerSize), "protocolList", null);
	struct.add(PointerDataType.getPointer(ObjectiveC1_ProtocolMethodList.toGenericDataType(_state), _state.pointerSize), "instanceMethods", null);
	struct.add(PointerDataType.getPointer(ObjectiveC1_ProtocolMethodList.toGenericDataType(_state), _state.pointerSize), "classMethods", null);
	return struct;
}
 
Example #16
Source File: ObjectiveC1_ProtocolMethod.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public DataType toDataType() throws DuplicateNameException, IOException {
	StructureDataType struct = new StructureDataType(NAME, 0);
	struct.setCategoryPath(ObjectiveC1_Constants.CATEGORY_PATH);
	struct.add(PointerDataType.getPointer(ASCII, _state.pointerSize), "name", null);
	struct.add(PointerDataType.getPointer(ASCII, _state.pointerSize), "types", null);
	return struct;
}
 
Example #17
Source File: iOS_KextStubFixupAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void markupNonLazySymbolPointerSection(Program program, MemoryBlock block,
		TaskMonitor monitor) {
	ReferenceManager referenceManager = program.getReferenceManager();
	Listing listing = program.getListing();
	listing.clearCodeUnits(block.getStart(), block.getEnd(), false);
	Address address = block.getStart();
	while (!monitor.isCancelled()) {
		if (address.compareTo(block.getEnd()) > 0) {
			break;
		}
		int length;
		try {
			Data data = listing.createData(address, new PointerDataType());
			Reference[] references = data.getReferencesFrom();
			for (Reference reference : references) {
				if (monitor.isCancelled()) {
					break;
				}
				referenceManager.delete(reference);
			}
			length = data.getLength();
		}
		catch (Exception e) {
			return;
		}
		address = address.add(length);
	}
}
 
Example #18
Source File: MIPS_ElfRelocationHandler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Flush the section GOT table to a new %got memory block
 */
private void createGot() {
	if (lastSectionGotEntryAddress == null) {
		return;
	}
	int size = (int) lastSectionGotEntryAddress.subtract(sectionGotAddress) + 1;
	String sectionName = relocationTable.getSectionToBeRelocated().getNameAsString();
	String blockName = getSectionGotName();
	try {
		MemoryBlock block = MemoryBlockUtils.createInitializedBlock(program, false,
			blockName, sectionGotAddress, size, "GOT for " + sectionName + " section",
			"MIPS-Elf Loader", true, false, false, loadHelper.getLog());
		DataConverter converter =
			program.getMemory().isBigEndian() ? BigEndianDataConverter.INSTANCE
					: LittleEndianDataConverter.INSTANCE;
		for (long symbolValue : gotMap.keySet()) {
			Address addr = gotMap.get(symbolValue);
			byte[] bytes;
			if (program.getDefaultPointerSize() == 4) {
				bytes = converter.getBytes((int) symbolValue);
			}
			else {
				bytes = converter.getBytes(symbolValue);
			}
			block.putBytes(addr, bytes);
			loadHelper.createData(addr, PointerDataType.dataType);
		}
	}
	catch (MemoryAccessException e) {
		throw new AssertException(e); // unexpected
	}
}
 
Example #19
Source File: DataTypeArchiveDB.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private boolean isValidDefaultpointerSize(int pointerSize) {
	return pointerSize > 0 && pointerSize <= PointerDataType.MAX_POINTER_SIZE_BYTES;
}
 
Example #20
Source File: PowerPC64_ElfExtension.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Symbol markupDescriptorEntry(Address entryAddr, boolean isGlobal,
		ElfLoadHelper elfLoadHelper) {
	Program program = elfLoadHelper.getProgram();

	// markup function descriptor (3 elements, 24-bytes)
	Data refPtr = elfLoadHelper.createData(entryAddr, PointerDataType.dataType);
	Data tocPtr = elfLoadHelper.createData(entryAddr.add(program.getDefaultPointerSize()),
		PointerDataType.dataType);
	// TODO: uncertain what 3rd procedure descriptor element represents
	elfLoadHelper.createData(entryAddr.add(2 * program.getDefaultPointerSize()),
		QWordDataType.dataType);

	if (refPtr == null || tocPtr == null) {
		Msg.error(this, "Failed to process PPC64 descriptor at " + entryAddr);
		return null;
	}

	Address refAddr = (Address) refPtr.getValue();
	if (refAddr == null || program.getMemory().getBlock(refAddr) == null) {
		return null;
	}

	Function function = program.getListing().getFunctionAt(refAddr);
	if (function == null) {
		// Check for potential pointer table (unsure a non-function would be referenced by OPD section)
		Relocation reloc = program.getRelocationTable().getRelocation(refAddr);
		if (reloc != null &&
			reloc.getType() == PowerPC64_ElfRelocationConstants.R_PPC64_RELATIVE) {
			return program.getSymbolTable().getPrimarySymbol(refAddr);
		}

		// Otherwise, create function at OPD referenced location
		function = elfLoadHelper.createOneByteFunction(null, refAddr, isGlobal);
	}

	// set r2 to TOC base for each function
	Address tocAddr = (Address) tocPtr.getValue();
	if (tocAddr != null) {
		Register r2reg = program.getRegister("r2");
		RegisterValue tocValue = new RegisterValue(r2reg, tocAddr.getOffsetAsBigInteger());
		try {
			program.getProgramContext().setRegisterValue(refAddr, refAddr, tocValue);
		}
		catch (ContextChangeException e) {
			throw new AssertException(e);
		}
	}
	return function.getSymbol();
}
 
Example #21
Source File: PowerPC64_ElfExtension.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processPpc64v2PltPointerTable(ElfLoadHelper elfLoadHelper, TaskMonitor monitor)
		throws CancelledException {

	ElfHeader elf = elfLoadHelper.getElfHeader();
	ElfSectionHeader pltSection = elf.getSection(ElfSectionHeaderConstants.dot_plt);
	if (pltSection == null) {
		return;
	}
	Program program = elfLoadHelper.getProgram();
	MemoryBlock pltBlock = program.getMemory().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;
	}
	if (pltSection.isExecutable()) {
		return;
	}

	// set pltBlock read-only to permit decompiler simplification
	pltBlock.setWrite(false);

	if (getPpc64ABIVersion(elf) != 2) {
		// TODO: add support for other PLT implementations
		return;
	}

	// TODO: Uncertain

	Address addr = pltBlock.getStart().add(ElfConstants.PLT_ENTRY_SIZE);
	try {
		while (addr.compareTo(pltBlock.getEnd()) < 0) {
			monitor.checkCanceled();
			if (elfLoadHelper.createData(addr, PointerDataType.dataType) == null) {
				break; // stop early if failed to create a pointer
			}
			addr = addr.addNoWrap(8);
		}
	}
	catch (AddressOverflowException e) {
		// ignore
	}

}
 
Example #22
Source File: FindFunctionsUsingTOCinPEFScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
	public void run() throws Exception {
		listing = currentProgram.getListing();
		symbolTable = currentProgram.getSymbolTable();

		// Find .toc symbol
		Symbol toc = SymbolUtilities.getExpectedLabelOrFunctionSymbol(currentProgram, ".toc",
			err -> Msg.error(this, err));
		if (toc == null) {
			return;
		}
		Address tocAddress = toc.getAddress();

		// Get direct refs to .toc
		monitor.setMessage("Finding references to .toc");
		FindReferencesTableModel refs =
			new FindReferencesTableModel(tocAddress, state.getTool(), currentProgram);
		while (refs.isBusy()) {
			if (monitor.isCancelled()) {
				break;
			}
		}

		// Loop through refs to find functions
		for (int i = 0; i < refs.getRowCount(); ++i) {
			monitor.setMessage("Finding functions");
			if (monitor.isCancelled()) {
				break;
			}

			// Make them pointers to .toc
			Address refAddr = refs.getAddress(i);
			listing.clearCodeUnits(refAddr, refAddr, false);
			listing.createData(refAddr, new PointerDataType());

			// Make previous code unit (addr-addrSize) a pointer
			Address codeAddr = refAddr.subtract(addrSize);
			listing.clearCodeUnits(codeAddr, codeAddr, false);
			CreateDataCmd cmd = new CreateDataCmd(codeAddr, new PointerDataType());
			cmd.applyTo(currentProgram);
// 	 		listing.createData(codeAddr, new PointerDataType());

			currentProgram.flushEvents();
		}

		popup("Script complete.\n\nNote:  Auto analyzer may still be running.\n" +
			"(Depending on the size of the binary, analysis may take a while...see Ghidra's progress bar.)");

	}