ghidra.program.model.listing.Data Java Examples

The following examples show how to use ghidra.program.model.listing.Data. 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: PortableExecutableBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processStringTable(Address address) throws Exception {
	Data dwordData = createDWord(address);

	createFragment("StringTable", dwordData.getMinAddress(), dwordData.getLength());

	int usedBytes = dwordData.getLength();
	int totalBytes = getInt(address);

	Address stringAddress = address.add(4);

	while (usedBytes < totalBytes) {
		if (monitor.isCancelled()) {
			break;
		}

		Data stringData = createAsciiString(stringAddress);
		setEOLComment(stringAddress, "");
		createFragment("StringTable", stringData.getMinAddress(), stringData.getLength());

		usedBytes += stringData.getLength();

		stringAddress = stringAddress.add(stringData.getLength());
	}
}
 
Example #3
Source File: NSDictionary.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Data objectData, Program program, TaskMonitor monitor)
		throws CancelledException {
	ReferenceManager referenceManager = program.getReferenceManager();
	for (int i = 0; i < objectData.getNumComponents(); ++i) {
		monitor.checkCanceled();
		Data component = objectData.getComponent(i);
		if (component.getFieldName().startsWith("key") ||
			component.getFieldName().startsWith("value")) {
			long value = getValue(component);
			String name = BinaryPropertyListUtil.generateName(value);
			Symbol symbol = SymbolUtilities.getLabelOrFunctionSymbol(program, name,
				err -> Msg.error(this, err));
			if (symbol != null) {
				referenceManager.addMemoryReference(component.getMinAddress(),
					symbol.getAddress(), RefType.DATA, SourceType.ANALYSIS, 0);
			}
		}
	}
}
 
Example #4
Source File: ApplyDataTypeToBrowserTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCycleOnDefaultDts() throws Exception {
	CodeViewerProvider codeViewerProvider = positionListingCursorAtAddress("004027d0");
	waitForSwing();

	DockingActionIf chooseDataTypeAction = getAction(dataPlugin, "Choose Data Type");
	assertNotNull(chooseDataTypeAction);
	performAction(chooseDataTypeAction, codeViewerProvider, false);

	chooseInDialog("_person");

	Data data = program.getListing().getDataAt(addr("004027d0"));
	ProgramDataTypeManager dataTypeManager = program.getDataTypeManager();
	DataType dataType = dataTypeManager.getDataType(new CategoryPath("/"), "_person");
	assertEquals(dataType, data.getDataType());
	assertEquals(addr("004027f8"), data.getMaxAddress());
}
 
Example #5
Source File: ApplyDataTypeToBrowserTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testLastUsedOnDefinedDtsAnswerYes() throws Exception {
	ProgramDataTypeManager dataTypeManager = program.getDataTypeManager();
	DataType dataType = dataTypeManager.getDataType(new CategoryPath("/"), "_person");
	plugin.setRecentlyUsed(dataType);

	createData("004027d1", new ByteDataType());
	CodeViewerProvider codeViewerProvider = positionListingCursorAtAddress("004027d0");
	waitForSwing();

	DockingActionIf chooseDataTypeAction = getAction(dataPlugin, "Recently Used");
	assertNotNull(chooseDataTypeAction);
	performAction(chooseDataTypeAction, codeViewerProvider, false);

	waitForSwing();

	JDialog dialog = waitForJDialog(tool.getToolFrame(), "Data Conflict", 2000);
	assertNotNull(dialog);

	pressButtonByText(dialog, "Yes");
	waitForSwing();

	Data data = program.getListing().getDataAt(addr("004027d0"));
	assertEquals(dataType, data.getDataType());
	assertEquals(addr("004027f8"), data.getMaxAddress());
}
 
Example #6
Source File: StringTableProviderTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakePascalString() {
	StringTableOptions options = (StringTableOptions) getInstanceField("options", provider);
	options.setRequirePascal(true);
	model.reload();
	waitForTableModel(model);

	DockingAction makeStringAction =
		(DockingAction) getInstanceField("makeStringAction", provider);

	Address address = addr(0x400);

	Data data = program.getListing().getDataAt(address);
	assertEquals(DefaultDataType.class, data.getDataType().getClass());

	selectRows(address);		// string localtime is here
	performAction(makeStringAction, true);

	data = program.getListing().getDataAt(address);

	assertEquals(PascalUnicodeDataType.class, data.getDataType().getClass());
	assertEquals("abcdef", data.getValue());
}
 
Example #7
Source File: ApplyDataTypeToBrowserTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testChooseDataTypeOnDefaultDts() throws Exception {
	CodeViewerProvider codeViewerProvider = positionListingCursorAtAddress("004027d0");
	waitForSwing();

	DockingActionIf chooseDataTypeAction = getAction(dataPlugin, "Choose Data Type");
	assertNotNull(chooseDataTypeAction);
	performAction(chooseDataTypeAction, codeViewerProvider, false);

	chooseInDialog("_person");

	Data data = program.getListing().getDataAt(addr("004027d0"));
	ProgramDataTypeManager dataTypeManager = program.getDataTypeManager();
	DataType dataType = dataTypeManager.getDataType(new CategoryPath("/"), "_person");
	assertEquals(dataType, data.getDataType());
	assertEquals(addr("004027f8"), data.getMaxAddress());
}
 
Example #8
Source File: NSSet.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Data objectData, Program program, TaskMonitor monitor)
		throws CancelledException {
	ReferenceManager referenceManager = program.getReferenceManager();
	for (int i = 0; i < objectData.getNumComponents(); ++i) {
		monitor.checkCanceled();
		Data component = objectData.getComponent(i);
		if (component.getFieldName().startsWith("value")) {
			long value = getValue(component);
			String name = BinaryPropertyListUtil.generateName(value);
			Symbol symbol = SymbolUtilities.getLabelOrFunctionSymbol(program, name,
				err -> Msg.error(this, err));
			if (symbol != null) {
				referenceManager.addMemoryReference(component.getMinAddress(),
					symbol.getAddress(), RefType.DATA, SourceType.ANALYSIS, 0);
			}
		}
	}
}
 
Example #9
Source File: ArrayTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayDataSettings() throws Exception {
	ArrayDataType dataType = new ArrayDataType(new ByteDataType(), 10, 1);
	assertEquals(5, dataType.getSettingsDefinitions().length);

	Array array = (Array) dataMgr.resolve(dataType, null);
	assertEquals(5, array.getSettingsDefinitions().length);

	listing.createData(addr(0x100), array, 0);
	Data data = listing.getDataAt(addr(0x100));
	assertEquals(5, data.getDataType().getSettingsDefinitions().length);

	assertArrayEquals(new ByteDataType().getSettingsDefinitions(),
		data.getDataType().getSettingsDefinitions());

}
 
Example #10
Source File: ArrayTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayDataSettingsInAStructure() throws Exception {
	ArrayDataType arrayDataType = new ArrayDataType(new ByteDataType(), 10, 1);
	StructureDataType structDataType = new StructureDataType("TestStruct", 0);
	structDataType.add(new FloatDataType());
	structDataType.add(arrayDataType);

	Structure structDB = (Structure) dataMgr.resolve(structDataType, null);
	DataTypeComponent component = structDB.getComponent(1);
	DataType dataType = component.getDataType();
	assertEquals(5, dataType.getSettingsDefinitions().length);

	listing.createData(addr(0x100), structDB, 0);
	Data data = listing.getDataAt(addr(0x100));
	Data subData = data.getComponent(1);
	SettingsDefinition[] settingsDefinitions = subData.getDataType().getSettingsDefinitions();

	assertArrayEquals(new ByteDataType().getSettingsDefinitions(), settingsDefinitions);

}
 
Example #11
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 #12
Source File: StringTableProviderTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakeStringWithLabel() {
	JCheckBox autoLabelCheckbox = (JCheckBox) getInstanceField("autoLabelCheckbox", provider);
	setCheckbox(autoLabelCheckbox, true);

	DockingAction makeStringAction =
		(DockingAction) getInstanceField("makeStringAction", provider);

	Address address = addr(0x100);

	Data data = program.getListing().getDataAt(address);
	assertEquals(DefaultDataType.class, data.getDataType().getClass());
	assertNull(program.getSymbolTable().getPrimarySymbol(address));

	selectRows(address);		// string localtime is here
	performAction(makeStringAction, true);

	data = program.getListing().getDataAt(address);

	assertEquals(StringDataType.class, data.getDataType().getClass());
	assertEquals("abcdefgh", data.getValue());
	assertEquals("s_abcdefgh", program.getSymbolTable().getPrimarySymbol(address).getName());
}
 
Example #13
Source File: ApplyDataTypeToBrowserTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testChooseDataTypeWhereDoesNotFit() throws Exception {
	CodeViewerProvider codeViewerProvider = positionListingCursorAtAddress("004027e0");
	waitForSwing();

	DockingActionIf chooseDataTypeAction = getAction(dataPlugin, "Choose Data Type");
	assertNotNull(chooseDataTypeAction);
	performAction(chooseDataTypeAction, codeViewerProvider, false);

	DialogComponentProvider dialog =
		chooseInDialog("_person", "_person doesn't fit within 32 bytes, need 41 bytes");

	Data data = program.getListing().getDataAt(addr("004027d0"));
	assertEquals(DataType.DEFAULT, data.getDataType());
	assertEquals(addr("004027d0"), data.getMaxAddress());

	pressButtonByText(dialog, "Cancel");
	waitForSwing();
}
 
Example #14
Source File: ApplyDataTypeToBrowserTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateArrayOnDefaultDts() throws Exception {
	CodeViewerProvider codeViewerProvider = positionListingCursorAtAddress("004027d0");
	waitForSwing();

	DockingActionIf chooseDataTypeAction = getAction(dataPlugin, "Define Array");
	assertNotNull(chooseDataTypeAction);
	performAction(chooseDataTypeAction, codeViewerProvider, false);

	waitForSwing();

	JDialog dialog = waitForJDialog(tool.getToolFrame(), "Create undefined[]", 2000);
	assertNotNull(dialog);
	JTextField tf = findComponent(dialog, JTextField.class);
	triggerText(tf, "48");
	waitForSwing();

	pressButtonByText(dialog, "OK");
	waitForSwing();

	Data data = program.getListing().getDataAt(addr("004027d0"));
	ProgramDataTypeManager dataTypeManager = program.getDataTypeManager();
	DataType dataType = dataTypeManager.getDataType(new CategoryPath("/"), "undefined[48]");
	assertEquals(dataType, data.getDataType());
	assertEquals(addr("004027ff"), data.getMaxAddress());
}
 
Example #15
Source File: StringTableProviderTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakeStringThatBumpsIntoDefinedTruncateAllowed() throws Exception {
	JCheckBox truncationCheckbox =
		(JCheckBox) getInstanceField("allowTruncationCheckbox", provider);
	setCheckbox(truncationCheckbox, true);

	DockingAction makeStringAction =
		(DockingAction) getInstanceField("makeStringAction", provider);

	Address address = addr(0x100);
	createDataAt(address.add(4));

	Data data = program.getListing().getDataAt(address);
	assertEquals(DefaultDataType.class, data.getDataType().getClass());

	selectRows(address);		// string abcdefgh is here

	performAction(makeStringAction, true);

	data = program.getListing().getDataAt(address);

	assertEquals(StringDataType.class, data.getDataType().getClass());
	assertEquals("abcd", data.getValue());
}
 
Example #16
Source File: ViewStringsProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public List<ProgramLocation> getSelectedDataLocationList(Predicate<Data> filter) {
	List<ProgramLocation> result = new ArrayList<>();
	int[] selectedRows = table.getSelectedRows();
	for (int row : selectedRows) {
		ProgramLocation location = stringModel.getRowObject(row);
		Data data = DataUtilities.getDataAtLocation(location);
		if (passesFilter(data, filter)) {
			result.add(location);
		}
	}
	return result;
}
 
Example #17
Source File: SettingsTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsEmptyInstanceSettings() throws Exception {
	listing.createData(addr(10), new ByteDataType(), 1);
	Data data = listing.getDataAt(addr(10));

	data.setString("color", "red");
	data.setLong("someLongValue", 10);
	data.setByteArray("bytes", new byte[] { 0, 1, 2 });
	data.setString("endian", "big Endian");

	assertTrue(!data.isEmpty());
	data.clearAllSettings();

	assertTrue(data.isEmpty());
}
 
Example #18
Source File: ViewStringsProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean passesFilter(Data data, Predicate<Data> filter) {
	if (data == null) {
		return false;
	}
	if (filter == null) {
		return true;
	}
	return filter.test(data);
}
 
Example #19
Source File: VxWorksSymTab_Finder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void clearString(Address addr) throws Exception {
	Data data;
	Instruction inst;

	// Clear the string, breaking on the terminating null character
	while (getByte(addr) != 0) {
		data = getDataContaining(addr);
		if (data != null) {
			removeDataAt(data.getAddress());
		}
		inst = getInstructionContaining(addr);
		if (inst != null) {
			removeInstructionAt(inst.getAddress());
		}

		addr = addr.add(1);
	}

	// Now clear at string's terminating null character
	data = getDataContaining(addr);
	if (data != null) {
		removeDataAt(data.getAddress());
	}
	inst = getInstructionContaining(addr);
	if (inst != null) {
		removeInstructionAt(inst.getAddress());
	}
}
 
Example #20
Source File: SettingsTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testClearSetting() throws Exception {
	listing.createData(addr(10), new ByteDataType(), 1);
	Data data = listing.getDataAt(addr(10));
	ByteDataType dt = (ByteDataType) data.getDataType();
	Settings defaultSettings = dt.getDefaultSettings();
	defaultSettings.setString("color", "red");
	defaultSettings.setLong("someLongValue", 10);
	defaultSettings.setByteArray("bytes", new byte[] { 0, 1, 2 });

	defaultSettings.clearSetting("color");
	assertNull(defaultSettings.getString("color"));
}
 
Example #21
Source File: MnemonicLocationDescriptor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected DataType getBaseDataType() {
	Data data = getData(getLocation());
	if (data != null) {
		return ReferenceUtils.getBaseDataType(data.getDataType());
	}
	return null;
}
 
Example #22
Source File: LabelDataScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	listing = currentProgram.getListing();
	memory = currentProgram.getMemory();
	symbolTable = currentProgram.getSymbolTable();

	monitor.setMessage("Labeling referenced data...");
	Data data = getFirstData();
	while ((data != null) && (!monitor.isCancelled())) {
		if (!data.isPointer() &&
			(!data.getBaseDataType().getName().toLowerCase().contains("string")) &&
			(!data.getBaseDataType().getName().toLowerCase().contains("unicode"))) {
			Symbol sym = symbolTable.getPrimarySymbol(data.getMinAddress());
			if ((sym != null) && ((sym.getSource() == SourceType.DEFAULT) ||
				(sym.getSource() == SourceType.ANALYSIS))) {
				String newLabel =
					data.getDefaultLabelPrefix(null) + "_" +
						SymbolUtilities.replaceInvalidChars(
							data.getDefaultValueRepresentation(), false) +
						"_" + data.getMinAddress().toString();
				Symbol newSym = symbolTable.createLabel(data.getMinAddress(), newLabel,
					SourceType.ANALYSIS);
				println(data.getMinAddress().toString() + " " + newLabel);
				if (!newSym.isPrimary()) {
					newSym.setPrimary();
				}

			}
		}
		data = getDataAfter(data);
	}
}
 
Example #23
Source File: ArrayTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplyArray() throws Exception {
	Array array =
		(Array) dataMgr.resolve(new ArrayDataType(struct, 5, struct.getLength()), null);

	listing.createData(addr(0x100), array, 0);

	Data data = listing.getDataAt(addr(0x100));
	assertNotNull(data);
	assertTrue(data.getDataType() instanceof Array);
	assertEquals(addr(0x100 + array.getLength() - 1), data.getMaxAddress());
}
 
Example #24
Source File: UnionLocationDescriptor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected DataType getSourceDataType() {
	Data data = getData(getLocation());
	Data parentData = getParent(data);
	DataType dataType = parentData.getDataType();
	if (!(dataType instanceof Union)) {
		throw new AssertException("A Union is required for this LocationDescriptor");
	}
	union = (Union) dataType;
	return dataType;
}
 
Example #25
Source File: PCodeTestAbstractControlBlock.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Check for a Data pointer at the specified address and return the referenced
 * address.
 * @param addr address of stored pointer
 * @return pointer referenced address or null if no pointer found
 */
protected Address readDefinedDataPointer(Address addr) {
	Data data = program.getListing().getDefinedDataAt(addr);
	if (data == null || !(data.getDataType() instanceof Pointer)) {
		return null;
	}
	return (Address) data.getValue();
}
 
Example #26
Source File: BTreeAnnotationScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Data createBTreeHeaderRecord(Program program, BTreeHeaderRecord headerRecord, int offset)
		throws Exception {
	Address address = toAddr(offset);
	DataType dataType = headerRecord.toDataType();
	Data data = createData(address, dataType);
	createFragment(dataType.getName(), data.getMinAddress(), data.getLength());
	return data;
}
 
Example #27
Source File: BTreeAnnotationScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	Address address = currentProgram.getMinAddress();

	ByteProvider provider = new MemoryByteProvider(currentProgram.getMemory(), address);

	BinaryReader reader = new BinaryReader(provider, false);

	BTreeRootNodeDescriptor root = new BTreeRootNodeDescriptor(reader);

	markupRecordOffsets(currentProgram, root, 0, root);

	Data headerNodeData = createBTreeNode(currentProgram, root, 0);

	Data headerRecordData =
		createBTreeHeaderRecord(currentProgram, root.getHeaderRecord(),
			headerNodeData.getLength());

	Data userDataRecordData =
		createUserDataRecord(currentProgram, root.getUserDataRecord(),
			headerNodeData.getLength() + headerRecordData.getLength());

	Data mapRecordData =
		createMapRecord(currentProgram, root.getMapRecord(), headerNodeData.getLength() +
			headerRecordData.getLength() + userDataRecordData.getLength());

	if (mapRecordData == null) {
		printerr("mapRecordData == null ????");
	}

	processNodes(currentProgram, root);
}
 
Example #28
Source File: NewExt4Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected Data createData( Program program, Address address, DataType datatype ) throws Exception {
	if ( program.getMemory( ).contains( address ) ) {
		return super.createData( program, address, datatype );
	}
	if ( program2 != null && program2.getMemory( ).contains( address ) ) {
		return super.createData( program2, address, datatype );
	}
	throw new RuntimeException( "Cannot create data, neither program contains that address." );
}
 
Example #29
Source File: Img3Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean analysisWorkerCallback(Program program, Object workerContext, TaskMonitor monitor)
		throws Exception, CancelledException {
	Address address = program.getMinAddress();

	ByteProvider provider = new MemoryByteProvider(program.getMemory(), address);
	BinaryReader reader = new BinaryReader(provider, true);

	Img3 header = new Img3(reader);

	if (!header.getMagic().equals(Img3Constants.IMG3_SIGNATURE)) {
		return false;
	}

	DataType headerDataType = header.toDataType();

	Data headerData = createData(program, address, headerDataType);

	createFragment(program, headerDataType.getName(), headerData.getMinAddress(),
		headerData.getMaxAddress().add(1));

	Address tagAddress = headerData.getMaxAddress().add(1);
	applyTags(program, header, tagAddress, monitor);

	changeDataSettings(program, monitor);

	removeEmptyFragments(program);
	return true;
}
 
Example #30
Source File: CollapseAllDataAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void actionPerformed(ProgramLocationActionContext context) {
	ListingModel model = getModel();
	ProgramSelection selection = context.getSelection();
	if (selection != null && !selection.isEmpty()) {
		TaskLauncher.launchModal("Collapse Data In Selection",
			monitor -> model.closeAllData(selection, monitor));
		return;
	}

	ProgramLocation location = context.getLocation();
	Data data = getTopLevelComponentData(location);
	TaskLauncher.launchModal("Collapse Data", monitor -> model.closeAllData(data, monitor));
}