ghidra.program.model.data.DataType Java Examples

The following examples show how to use ghidra.program.model.data.DataType. 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: CreateFunctionThunkTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * This tests the forcing of a function to be a thunk with CreateThunkFunctionCmd
 * Tests that the Function start analyzer will create a thunk given the thunk tag on a matching function
 * That the MIPS BE language has a thunking pattern.
 * That the MIPS 64/32 hybrid with sign extension of registers still gets found as a thunk.
 * That the thunking function can be found with out the constant reference analyzer
 * 
 */
@Test
public void testDelayMips6432SlotThunk() throws Exception {

	builder = new ProgramBuilder("thunk", ProgramBuilder._MIPS_6432);

	builder.setBytes("0x466050", "3c 0f 00 47  8d f9 72 24  03 20 00 08  25 f8 72 24");
	builder.setBytes("0x477224", "00 47 99 c0");
	builder.createEmptyFunction("chdir", "0x4799c0", 1, DataType.VOID);
	builder.disassemble("0x466050", 27, true);

	builder.createFunction("0x466050");

	program = builder.getProgram();

	analyze();

	Function isThunk = program.getFunctionManager().getFunctionAt(builder.addr(0x466050));
	assertEquals(true, isThunk.isThunk());
	assertEquals("chdir", isThunk.getName());
}
 
Example #2
Source File: CompositeDBAdapterV0.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public Record translateRecord(Record oldRec) {
	if (oldRec == null) {
		return null;
	}
	Record rec = CompositeDBAdapter.COMPOSITE_SCHEMA.createRecord(oldRec.getKey());
	rec.setString(COMPOSITE_NAME_COL, oldRec.getString(V0_COMPOSITE_NAME_COL));
	rec.setString(COMPOSITE_COMMENT_COL, oldRec.getString(V0_COMPOSITE_COMMENT_COL));
	rec.setBooleanValue(COMPOSITE_IS_UNION_COL,
		oldRec.getBooleanValue(V0_COMPOSITE_IS_UNION_COL));
	rec.setLongValue(COMPOSITE_CAT_COL, oldRec.getLongValue(V0_COMPOSITE_CAT_COL));
	rec.setIntValue(COMPOSITE_LENGTH_COL, oldRec.getIntValue(V0_COMPOSITE_LENGTH_COL));
	rec.setIntValue(COMPOSITE_NUM_COMPONENTS_COL,
		oldRec.getIntValue(V0_COMPOSITE_NUM_COMPONENTS_COL));
	rec.setLongValue(COMPOSITE_SOURCE_ARCHIVE_ID_COL, DataTypeManager.LOCAL_ARCHIVE_KEY);
	rec.setLongValue(COMPOSITE_UNIVERSAL_DT_ID, UniversalIdGenerator.nextID().getValue());
	rec.setLongValue(COMPOSITE_SOURCE_SYNC_TIME_COL, DataType.NO_SOURCE_SYNC_TIME);
	rec.setLongValue(COMPOSITE_LAST_CHANGE_TIME_COL, DataType.NO_LAST_CHANGE_TIME);
	rec.setIntValue(COMPOSITE_INTERNAL_ALIGNMENT_COL, CompositeDBAdapter.UNALIGNED);
	rec.setIntValue(COMPOSITE_EXTERNAL_ALIGNMENT_COL, CompositeDBAdapter.DEFAULT_ALIGNED);
	return rec;
}
 
Example #3
Source File: DefaultPdbMember.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected WrappedDataType getDataType() throws CancelledException {
	WrappedDataType wrappedDt = dataTypeParser.findDataType(getDataTypeName());
	if (wrappedDt != null && isBitField) {
		if (wrappedDt.isZeroLengthArray()) {
			return null;
		}
		PdbBitField bitFieldDt;
		try {
			DataType baseDataType =
				wrappedDt.getDataType().clone(dataTypeParser.getProgramDataTypeManager());
			bitFieldDt = new PdbBitField(baseDataType, bitFieldSize,
				bitFieldOffset >= 0 ? bitFieldOffset : 0);
		}
		catch (InvalidDataTypeException e) {
			Msg.error(this, "PDB parse error: " + e.getMessage());
			return null;
		}
		wrappedDt = new WrappedDataType(bitFieldDt, false, false);
	}
	return wrappedDt;
}
 
Example #4
Source File: ExternalManagerDB.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Get the default name for an external function or code symbol
 * @param sym
 * @return default name
 */
public static String getDefaultExternalName(SymbolDB sym) {
	SymbolType type = sym.getSymbolType();
	if ((type != SymbolType.LABEL && type != SymbolType.FUNCTION) || !sym.isExternal()) {
		throw new AssertException();
	}
	ExternalData3 externalData3 = ExternalLocationDB.getExternalData3(sym);
	Address addr = externalData3.getAddress(sym.getProgram().getAddressFactory());
	if (addr == null) {
		throw new AssertException("External should not be default without memory address");
	}
	if (type == SymbolType.FUNCTION) {
		return SymbolUtilities.getDefaultExternalFunctionName(addr);
	}
	long dataTypeID = sym.getSymbolData1();
	DataType dt =
		(dataTypeID < 0) ? null : sym.getProgram().getDataTypeManager().getDataType(dataTypeID);
	return SymbolUtilities.getDefaultExternalName(addr, dt);
}
 
Example #5
Source File: ParameterDB.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public DataType getDataType() {
	DataType dt = getFormalDataType();
	VariableStorage varStorage = getVariableStorage();
	if (varStorage.isForcedIndirect()) {
		Program program = function.getProgram();
		DataTypeManager dtm = program.getDataTypeManager();
		int ptrSize = varStorage.size();
		if (ptrSize != dtm.getDataOrganization().getPointerSize()) {
			dt = dtm.getPointer(dt, ptrSize);
		}
		else {
			dt = dtm.getPointer(dt);
		}
	}
	return dt;
}
 
Example #6
Source File: PortableExecutableBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processSections(NTHeader nt)
		throws Exception, DuplicateNameException, InvalidInputException {
	FileHeader fh = nt.getFileHeader();
	SectionHeader[] sections = fh.getSectionHeaders();
	int index = fh.getPointerToSections();
	for (SectionHeader section : sections) {
		DataType sectionDT = section.toDataType();
		Address sectionStartAddr = toAddr(index);
		createData(sectionStartAddr, sectionDT);
		createFragment(sectionDT.getName(), sectionStartAddr, sectionDT.getLength());

		setPlateComment(sectionStartAddr, section.toString());

		index += SectionHeader.IMAGE_SIZEOF_SECTION_HEADER;

		if (section.getPointerToRawData() == 0 || section.getSizeOfRawData() == 0) {
			continue;
		}

		Address dataStartAddr = toAddr(section.getPointerToRawData());
		currentProgram.getSymbolTable().createLabel(dataStartAddr, section.getName(),
			SourceType.IMPORTED);
		createFragment(section.getName() + "_DATA", dataStartAddr,
			section.getSizeOfRawData());
	}
}
 
Example #7
Source File: DataTypeLocationDescriptor.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean functionContainsDataType(Address functionAddress) {
	FunctionManager functionManager = program.getFunctionManager();
	Function function = functionManager.getFunctionAt(functionAddress);
	DataType currentDataType = getDataType();
	if (function != null) {
		List<Variable> allVariables = ReferenceUtils.getVariables(function, true);
		for (Variable variable : allVariables) {
			DataType variableDataType = variable.getDataType();
			if (ReferenceUtils.getBaseDataType(variableDataType).isEquivalent(
				currentDataType)) {
				return true;
			}
		}

		DataType returnType = function.getReturnType();
		if (ReferenceUtils.getBaseDataType(returnType).isEquivalent(currentDataType)) {
			return true;
		}
	}

	return false;
}
 
Example #8
Source File: PreviewTableCellData.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getCodeUnitPreview(CodeUnitFormat format) {
	Address addr = location.getAddress();
	if (addr.isExternalAddress()) {
		Symbol s = program.getSymbolTable().getPrimarySymbol(addr);
		if (s != null) {
			ExternalLocation extLoc = program.getExternalManager().getExternalLocation(s);
			DataType dt = extLoc.getDataType();
			if (dt == null) {
				dt = DataType.DEFAULT;
			}
			return dt.getMnemonic(dt.getDefaultSettings());
		}
	}

	CodeUnit cu = program.getListing().getCodeUnitAt(addr);
	return getFormatedCodeUnitPreview(cu);
}
 
Example #9
Source File: ParameterInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
String convertToString() {

		DataTypeManager dataTypeMananger = getProgram().getDataTypeManager();
		DataType dt = getDataType();

		StringBuffer buffy = new StringBuffer();
		buffy.append(getClass().getSimpleName()).append(Stringable.DELIMITER);
		buffy.append(Long.toString(dataTypeMananger.getUniversalID().getValue())).append(
			Stringable.DELIMITER);
		buffy.append(Long.toString(dataTypeMananger.getID(dt))).append(Stringable.DELIMITER);
		buffy.append(dt.getName()).append(Stringable.DELIMITER);
		buffy.append(Integer.toString(getOrdinal())).append(Stringable.DELIMITER);
		buffy.append(getName()).append(Stringable.DELIMITER);
		buffy.append(getSource().name()).append(Stringable.DELIMITER);
		buffy.append(getComment()).append(Stringable.DELIMITER);
		buffy.append(getVariableStorage().getSerializationString());
		return buffy.toString();
	}
 
Example #10
Source File: CompareFunctionsTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private ProgramBuilder buildTestProgram1() throws Exception {
	ProgramBuilder builder = new ProgramBuilder("TestPgm1", ProgramBuilder._TOY_BE);
	builder.createMemory(".text", "0x1001000", 0x6600);
	builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent

	// functions 
	DataType dt = new ByteDataType();
	Parameter p = new ParameterImpl(null, dt, builder.getProgram());
	foo = builder.createEmptyFunction("Foo", "10018cf", 10, null, p);
	bar = builder.createEmptyFunction("Bar", "100299e", 130, null, p, p, p);
	junk = builder.createEmptyFunction("Junk", "1002cf5", 15, null, p, p, p, p, p);
	stuff = builder.createEmptyFunction("Stuff", "1003100", 20, null, p, p);

	program1 = builder.getProgram();
	AbstractGenericTest.setInstanceField("recordChanges", program1, Boolean.TRUE);
	return builder;
}
 
Example #11
Source File: FindReferencesToDataTypeAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void updateMenuName(DataType type) {

		if (type == null) {
			return; // not sure if this can happen
		}

		String typeName = type.getName();
		String menuName = "Find Uses of " + typeName;

		String fieldName = getDataTypeField();
		if (fieldName != null) {
			menuName += '.' + fieldName;
		}

		MenuData data = getPopupMenuData().cloneData();
		data.setMenuPath(new String[] { LocationReferencesService.MENU_GROUP, menuName });
		setPopupMenuData(data);
	}
 
Example #12
Source File: UnsignedLeb128DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public DataType clone(DataTypeManager dtm) {
	if (dtm == getDataTypeManager()) {
		return this;
	}
	return new UnsignedLeb128DataType(dtm);
}
 
Example #13
Source File: ApplyStackVariables.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private DataType getDataType(PdbXmlMember member, MessageLog log) throws CancelledException {
	WrappedDataType wrappedDataType = pdbParser.findDataType(member.memberDataTypeName);
	if (wrappedDataType == null) {
		log.appendMsg("PDB", "Failed to resolve data type for " + member.kind + ": " +
			member.memberDataTypeName);
		return null;
	}
	if (wrappedDataType.isZeroLengthArray()) {
		log.appendMsg("PDB", "Zero length array not supported for for " + member.kind + ": " +
			member.memberDataTypeName);
		return null;
	}
	return wrappedDataType.getDataType();
}
 
Example #14
Source File: ConstantPoolIntegerInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public DataType toDataType() throws DuplicateNameException, IOException {
	String name = "CONSTANT_Integer_info";
	Structure structure = new StructureDataType( name, 0 );
	structure.add(  BYTE,   "tag", null );
	structure.add( DWORD, "bytes", null );
	return structure;
}
 
Example #15
Source File: ConstantPoolInterfaceMethodReferenceInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public DataType toDataType() throws DuplicateNameException, IOException {
	StructureDataType structure = (StructureDataType) super.toDataType();
	try {
		structure.setName("CONSTANT_InterfaceMethodref_info");
	}
	catch (InvalidNameException e) {
		throw new IOException(e);
	}
	return structure;
}
 
Example #16
Source File: ArrayValuesFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String getDisplayValue(Data data, boolean addDelimeter) {
	DataType dt = data.getDataType();
	int minLength = data.getLength() * 3 + 1;  // this just seems a decent minimum size
	StringBuffer buf = new StringBuffer(dt.getRepresentation(data, data, data.getLength()));
	if (buf.length() < minLength) {
		for (int i = buf.length(); i < minLength; i++) {
			buf.insert(0, ' ');
		}
	}
	if (addDelimeter) {
		buf.append(',');
	}
	return buf.toString();
}
 
Example #17
Source File: HighSymbol.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a symbol that is not attached to a function model. The symbol is given
 * a name, data-type, and other basic attributes.  Mappings must be attached separately.
 * @param uniqueId is the id to associate with the new symbol
 * @param nm is the given name
 * @param tp is the given data-type
 * @param tlock is true if the symbol is type locked
 * @param nlock is true if the symbol is name locked
 * @param manage is a PcodeDataTypeManager to facilitate XML marshaling
 */
protected HighSymbol(long uniqueId, String nm, DataType tp, boolean tlock, boolean nlock,
		PcodeDataTypeManager manage) {
	function = null;
	dtmanage = manage;
	name = nm;
	type = tp;
	namelock = nlock;
	typelock = tlock;
	id = uniqueId;
	category = -1;
	categoryIndex = -1;
}
 
Example #18
Source File: PortableExecutableBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void processNTHeader(DOSHeader dos, NTHeader nt)
		throws DuplicateNameException, IOException, Exception {
	DataType ntDT = nt.toDataType();
	Address ntStartAddr = toAddr(dos.e_lfanew());
	Address ntEndAddr = ntStartAddr.add(ntDT.getLength());
	clearListing(ntStartAddr, ntEndAddr);//sometimes overlaps DOS header to packing
	createData(ntStartAddr, ntDT);
	createFragment(ntDT.getName(), ntStartAddr, ntDT.getLength());
}
 
Example #19
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 #20
Source File: FunctionReturnTypeLocationDescriptor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected DataType getSourceDataType() {
	FunctionManager functionManager = program.getFunctionManager();
	FunctionReturnTypeFieldLocation location = (FunctionReturnTypeFieldLocation) getLocation();
	Function function = functionManager.getFunctionContaining(location.getFunctionAddress());
	return function.getReturnType();
}
 
Example #21
Source File: CopyPasteFunctionInfoTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Program buildNotepad(String name) throws Exception {
	ToyProgramBuilder builder = new ToyProgramBuilder(name, true, ProgramBuilder._TOY);
	builder.createMemory("test1", "0x01001000", 0x8000);
	builder.createEntryPoint("0x1006420", "entry");
	DataType dt = DataType.DEFAULT;
	Parameter p = new ParameterImpl(null, dt, builder.getProgram());
	builder.createEmptyFunction("ghidra", "0x1004600", 1, dt, p, p, p, p, p, p, p, p, p, p, p,
		p, p);
	return builder.getProgram();
}
 
Example #22
Source File: ApplyDataTypes.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Perform parsing and caching of composite types 
 * @param monitor task monitor
 * @throws CancelledException if task cancelled
 */
void buildDataTypes(TaskMonitor monitor) throws CancelledException {

	monitor.setMessage("Order PDB datatypes... ");

	List<CompositeDefinition> verticesInPostOrder =
		getCompositeDefinitionsInPostDependencyOrder(monitor);

	monitor.setMessage("Building PDB datatypes... ");

	for (CompositeDefinition compositeDefinition : verticesInPostOrder) {
		monitor.checkCanceled();

		// namespace qualified name used for cache lookups
		DataType cachedDataType = pdbParser.getCachedDataType(compositeDefinition.name);
		SymbolPath symbolPath = new SymbolPath(compositeDefinition.name);
		if (!(cachedDataType instanceof Composite) ||
			!cachedDataType.getCategoryPath().equals(
				pdbParser.getCategory(symbolPath.getParent(), true)) ||
			!pdbParser.isCorrectKind(cachedDataType, compositeDefinition.kind)) {
			log.appendMsg("PDB", "Conflicting data type name: " + compositeDefinition.name);
			continue;
		}
		Composite composite = (Composite) cachedDataType;
		PdbUtil.clearComponents(composite);

		if (!DefaultCompositeMember.applyDataTypeMembers(composite, compositeDefinition.isClass,
			compositeDefinition.length, getNormalMembersOnly(compositeDefinition),
			msg -> Msg.warn(this, msg), monitor)) {
			PdbUtil.clearComponents(composite);
		}

	}
}
 
Example #23
Source File: AbstractFindReferencesDataTypeAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionContext context) {

	FindAppliedDataTypesService service = tool.getService(FindAppliedDataTypesService.class);
	if (service == null) {
		Msg.showError(this, null, "Missing Plugin",
			"The FindAppliedDataTypesService is not installed.\n" +
				"Please add the plugin implementing this service.");
		return;
	}

	DataType dataType = getDataType(context);
	DataType baseDataType = ReferenceUtils.getBaseDataType(dataType);
	String field = getDataTypeField();

	// sanity check - should not happen
	if (field != null && !(baseDataType instanceof Composite)) {
		Msg.error(this, "Somehow have a field without a Composite parent--searching " +
			"only for the parent type '" + dataType + "'; field '" + field + "'");
		Swing.runLater(() -> service.findAndDisplayAppliedDataTypeAddresses(dataType));
		return;
	}

	if (field == null) {
		Swing.runLater(() -> service.findAndDisplayAppliedDataTypeAddresses(dataType));
	}
	else {
		Swing.runLater(() -> service.findAndDisplayAppliedDataTypeAddresses(
			(Composite) baseDataType, field));
	}
}
 
Example #24
Source File: DataAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public DataAction(String name, String group, DataType dataType, FunctionPlugin plugin) {
	super(name, plugin.getName(), KeyBindingType.SHARED);
	this.group = group;
	this.plugin = plugin;
	this.dataType = dataType;

	setPopupMenu(plugin.getDataActionMenuName(null), true);
	setHelpLocation(new HelpLocation(plugin.getName(), "DataType"));

	initKeyStroke(getDefaultKeyStroke());
}
 
Example #25
Source File: EquateSymbol.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public EquateSymbol(long uniqueId, int conv, long val, HighFunction func, Address addr,
		long hash) {
	super(uniqueId, "", DataType.DEFAULT, func);
	category = 1;
	value = val;
	convert = conv;
	DynamicEntry entry = new DynamicEntry(this, addr, hash);
	addMapEntry(entry);
}
 
Example #26
Source File: DwarfDecoderFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public DataType getDataType(Program program) {
	int ptrSize = getDecodeSize(program);
	switch (ptrSize) {
		case 2:
			return WORD_DATA_TYPE;
		case 4:
			return DWORD_DATA_TYPE;
		case 8:
			return QWORD_DATA_TYPE;
	}
	throw new IllegalStateException("Don't have a type for " + ptrSize + "-byte pointers");
}
 
Example #27
Source File: StackEditorEnablementTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testLastComponentSelectedEnablement() throws Exception {
	init(SIMPLE_STACK);

	// Check enablement on last component selected.
	runSwing(() -> model.setSelection(new int[] { model.getNumComponents() - 1 }));
	int numBytes = getModel().getMaxReplaceLength(model.getNumComponents() - 1);
	for (int i = 0; i < actions.length; i++) {
		if (actions[i] instanceof FavoritesAction) {
			FavoritesAction fav = (FavoritesAction) actions[i];
			DataType favDt = fav.getDataType();
			int len = favDt.getLength();
			boolean enabled = ((len <= numBytes) && ((favDt instanceof Pointer) || (len > 0)));
			checkEnablement(actions[i], enabled);
		}
		else if ((actions[i] instanceof CycleGroupAction) ||
			(actions[i] instanceof HexNumbersAction) ||
			(actions[i] instanceof ShowComponentPathAction) ||
			(actions[i] instanceof EditFieldAction) || (actions[i] instanceof ClearAction) ||
			(actions[i] instanceof DeleteAction) || (actions[i] instanceof ArrayAction) ||
			(actions[i] instanceof PointerAction)) {
			checkEnablement(actions[i], true);
		}
		else {
			checkEnablement(actions[i], false);
		}
	}
}
 
Example #28
Source File: ResourceDirectory.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.add(DWORD, "Characteristics",      null);
	struct.add(DWORD, "TimeDateStamp",        null);
	struct.add( WORD, "MajorVersion",         null);
	struct.add( WORD, "MinorVersion",         null);
	struct.add( WORD, "NumberOfNamedEntries", null);
	struct.add( WORD, "NumberOfIdEntries",    null);
	struct.setCategoryPath(new CategoryPath("/PE"));
	return struct;
}
 
Example #29
Source File: DefaultDataTypeHTMLRepresentation.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private TextLine buildHeader(DataType dataType) {
	if (dataType instanceof Array) {
		Array array = (Array) dataType;
		return new TextLine(getArrayDescription(array));
	}

	String description = dataType.getDescription();
	if (description == null || description.length() == 0) {
		return new TextLine(dataType.getName());
	}
	return new TextLine(description);
}
 
Example #30
Source File: SymbolManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Address getUpgradedVariableAddress(Address storageAddr, long dataTypeId)
		throws InvalidInputException, IOException {
	// Let the variable do the work
	DataType dt = getDataType(dataTypeId);
	Variable var = new LocalVariableImpl(null, 0, dt, storageAddr, program);
	return variableStorageMgr.getVariableStorageAddress(var.getVariableStorage(), true);
}