Java Code Examples for ghidra.program.model.listing.Data#getComponent()

The following examples show how to use ghidra.program.model.listing.Data#getComponent() . 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: ChangeDataSettingsScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void run() throws Exception {
	Data data = getDataAt(currentAddress);
	if (data == null) {
	    println("No data exists.");
	    return;
	}
	int componentCount = data.getNumComponents();
	if (componentCount == 0) {
	    println("Data does not have any sub-components.");
	    return;
	}
	for (int i = 0 ; i < componentCount ; ++i) {
		Data component = data.getComponent( i );
		if ( component == null ) {
			break; // something bad and unexpected has happened
		}
		SettingsDefinition [] settings = component.getDataType().getSettingsDefinitions();
		for (int j = 0; j < settings.length; j++) {
            if (settings[j] instanceof FormatSettingsDefinition) {
                FormatSettingsDefinition format = (FormatSettingsDefinition)settings[j];
                format.setChoice(component, FormatSettingsDefinition.DECIMAL);
            }
        }
	}
}
 
Example 2
Source File: FixArrayStructReferencesScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected void run() throws Exception {
	Data data = getDataAt(currentAddress);
	if (data == null) {
		printerr("no data at " + currentAddress);
		return;
	}
	if (!data.isArray()) {
		printerr("data at " + currentAddress + " is not an array");
		return;
	}
	CodeManager codeManager = ((ProgramDB) currentProgram).getCodeManager();
	int numComponents = data.getNumComponents();
	monitor.setMessage("updating data references in array");
	monitor.initialize(numComponents);
	for (int ii = 0; ii < numComponents; ++ii) {
		if (monitor.isCancelled()) {
			printerr("cancelled");
			return;
		}
		monitor.incrementProgress(1);
		Data component = data.getComponent(ii);
		codeManager.updateDataReferences(component);
	}
}
 
Example 3
Source File: NSArray.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 4
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 5
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 6
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 7
Source File: CreateStructureInStructureCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
DataType initializeStructureData( Program program, Structure localStructure ){
    
    Data data = program.getListing().getDataContaining( 
        getStructureAddress() );           
    Data comp1 = data.getComponent( fromPath );
    Data comp2 = data.getComponent(toPath);
    int dataLength = (comp2.getParentOffset() + comp2.getLength())
        - comp1.getParentOffset();
    
    DataType parentDataType = comp1.getParent().getBaseDataType();        
    if ( !(parentDataType instanceof Structure) ){
        throw new IllegalArgumentException(
            "Data not in a structure");
    }        
    Structure originalStructure = (Structure) parentDataType;        
    
    // clear and initialize the original structure and then get the new
    // data
    clearStruct(originalStructure, comp1.getParentOffset(), dataLength );
    originalStructure.replace(comp1.getComponentIndex(), 
        localStructure, localStructure.getLength());
    comp1 = data.getComponent( fromPath );
    
    return comp1.getDataType();
}
 
Example 8
Source File: ObjectiveC2_ClassAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void processMessageReferences(ObjectiveC2_State state, BinaryReader reader)
		throws Exception {
	state.monitor.setMessage("Objective-C 2.0 Message References...");

	MemoryBlock block =
		state.program.getMemory().getBlock(ObjectiveC2_Constants.OBJC2_MESSAGE_REFS);
	if (block == null) {
		return;
	}
	ObjectiveC1_Utilities.clear(state, block);

	long count = block.getSize() / ObjectiveC2_MessageReference.SIZEOF(state);

	state.monitor.initialize((int) count);

	Address address = block.getStart();

	for (int i = 0; i < count; ++i) {
		if (state.monitor.isCancelled()) {
			break;
		}
		state.monitor.setProgress(i);
		reader.setPointerIndex(address.getOffset());
		ObjectiveC2_MessageReference messageRef =
			new ObjectiveC2_MessageReference(state, reader);
		DataType dt = messageRef.toDataType();
		Data messageRefData = state.program.getListing().createData(address, dt);
		Data selData = messageRefData.getComponent(1);
		Object selAddress = selData.getValue();
		Data selStringData = state.program.getListing().getDataAt((Address) selAddress);
		Object selString = selStringData.getValue();
		ObjectiveC1_Utilities.createSymbol(state.program, null, selString + "_" +
			ObjectiveC2_MessageReference.NAME, address);
		address = address.add(dt.getLength());
	}
}
 
Example 9
Source File: OpenCloseFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Computes if the given data is the last component at its level.
 */
private boolean computeIsLast(Data data) {
	Data parent = data.getParent();
	if (parent != null) {
		Data d2 = parent.getComponent(parent.getNumComponents() - 1);
		if (d2 == data) {
			return true;
		}
	}
	return false;
}
 
Example 10
Source File: SubDataFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Data getComponent(Data data, int[] path) {
	for (int element : path) {
		Data d = data.getComponent(element);
		if (d == null) {
			return data;
		}
		data = d;
	}
	return data;
}
 
Example 11
Source File: ProgramStructureProviderContext.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public ProgramStructureProviderContext(Program program, ProgramLocation loc) {
	this.program = program;

	int dataPath[] = loc.getComponentPath();
	Data data = program.getListing().getDefinedDataContaining(loc.getAddress());
	data = data.getComponent(dataPath);
	this.addr = data.getMinAddress();
	myoffset = data.getParentOffset();
	data = data.getParent();
	struct = (Structure) data.getDataType();
}
 
Example 12
Source File: BTreeAnnotationScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void changeEndianSettings(Data data) throws Exception {
	for (int i = 0; i < data.getNumComponents(); ++i) {
		Data component = data.getComponent(i);
		SettingsDefinition[] settings = component.getDataType().getSettingsDefinitions();
		for (int j = 0; j < settings.length; ++j) {
			if (settings[j] instanceof EndianSettingsDefinition) {
				EndianSettingsDefinition setting = (EndianSettingsDefinition) settings[j];
				setting.setBigEndian(component, false);
			}
		}
	}
}
 
Example 13
Source File: DataDB.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.program.model.listing.Data#getComponent(int[])
 */
@Override
public Data getComponent(int[] componentPath) {
	lock.acquire();
	try {
		if (componentPath == null || componentPath.length <= level) {
			return this;
		}
		Data component = getComponent(componentPath[level]);
		return (component == null ? null : component.getComponent(componentPath));
	}
	finally {
		lock.release();
	}
}
 
Example 14
Source File: PseudoData.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Data getComponent(int[] componentPath) {
	if (componentPath == null || componentPath.length <= level) {
		return this;
	}
	Data component = getComponent(componentPath[level]);
	return (component == null ? null : component.getComponent(componentPath));
}
 
Example 15
Source File: CreateDataInStructureBackgroundCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
	 * 
	 * @see ghidra.framework.cmd.BackgroundCommand#applyTo(ghidra.framework.model.DomainObject, ghidra.util.task.TaskMonitor)
	 */
	@Override
	public boolean applyTo(DomainObject obj, TaskMonitor monitor) {

		Program program = (Program) obj;
		Data data = program.getListing().getDefinedDataContaining(addr);
		Data startData = data.getComponent(startPath);
		if (startData == null) {
			setStatusMsg("Component data not found");
			return false;
		}

		Data parent = startData.getParent();
		DataType parentDataType = parent.getBaseDataType();

		if (!(parentDataType instanceof Structure)) {
			setStatusMsg("Range based operation only supported within Structures");
			return false;
		}

		DataType existingDT = startData.getDataType();
		int startIndex = startData.getComponentIndex();
		Data lastComp = parent.getComponentAt(
			(int) (startData.getMinAddress().subtract(parent.getMinAddress()) + length - 1));
		int endIndex = lastComp.getComponentIndex();

		Structure struct = (Structure) parentDataType;

		// TODO: Is looking at the first component data-type (existingDT) the right thing to do for a selection ??

		if (newDataType instanceof FactoryDataType) {
			setStatusMsg("Factory data-type not allowed in structure: " + newDataType.getName());
			return false;
		}

		newDataType = newDataType.clone(program.getDataTypeManager());
		newDataType =
			DataUtilities.reconcileAppliedDataType(existingDT, newDataType, stackPointers);

		if (newDataType instanceof Dynamic && !((Dynamic) newDataType).canSpecifyLength()) {
			setStatusMsg(
				"Non-sizable Dynamic data-type not allowed in structure: " + newDataType.getName());
			return false;
		}

		for (int i = endIndex; i >= startIndex; i--) {
			struct.clearComponent(i);
		}

		if (newDataType != DataType.DEFAULT) {
			int index = startIndex;
			int numCreated = 0;
			while (length > 0) {
				try {
//			        MemBuffer memBuf = new ProgramStructureProviderContext(program,addr, 
//    	    	    					struct, struct.getComponent(index).getOffset());
					DataTypeInstance dti =
						DataTypeInstance.getDataTypeInstance(newDataType, length);
					if (dti == null || dti.getLength() > length) {
						break;
					}
					DataTypeComponent dtc =
						struct.replace(index, dti.getDataType(), dti.getLength());
					length -= dtc.getLength();
					numCreated++;
					index++;
				}

				catch (Exception e) {
					setStatusMsg(e.getMessage());
					return false;
				}
			}
			if (numCreated == 0) {
				setStatusMsg("Not enough space");
				return false;
			}
		}
		return true;
	}
 
Example 16
Source File: CreateStructureAction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void createStructureInStructure(Program program, InteriorSelection sel) {
	PluginTool tool = plugin.getTool();
	ProgramLocation from = sel.getFrom();
	ProgramLocation to = sel.getTo();
	Data data = program.getListing().getDataContaining(from.getAddress());
	Data comp = null;
	if (data != null) {
		comp = data.getComponent(from.getComponentPath());
	}

	if (comp == null) {
		tool.setStatusInfo("Create Structure Failed! No data at " + from.getAddress());
		return;
	}

	DataType parentDataType = comp.getParent().getBaseDataType();
	if (!(parentDataType instanceof Structure)) {
		tool.setStatusInfo("Cannot create structure here");
		return;
	}

	Address newStructureAddress = from.getAddress();
	int[] fromPath = from.getComponentPath();
	int[] toPath = to.getComponentPath();
	Structure tempStructure = null;
	try {
		tempStructure = StructureFactory.createStructureDataTypeInStrucuture(program,
			newStructureAddress, fromPath, toPath);
	}
	catch (Exception exc) {
		tool.setStatusInfo("Create structure failed: " + exc.getMessage());
		return;
	}

	Structure userChoice =
		createStructureDialog.showCreateStructureDialog(program, tempStructure);

	if (userChoice != null) {
		CreateStructureInStructureCmd cmd = new CreateStructureInStructureCmd(userChoice,
			newStructureAddress, fromPath, toPath);

		if (!tool.execute(cmd, program)) {
			tool.setStatusInfo(cmd.getStatusMsg());
		}
		else {
			plugin.updateRecentlyUsed(cmd.getNewDataType());
		}
	}
}
 
Example 17
Source File: CreateDataInStructureCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
	 * @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject)
	 */
	@Override
	public boolean applyTo(DomainObject obj) {
		Program program = (Program) obj;
		Data data = program.getListing().getDefinedDataContaining(addr);
		Data dataComp = data.getComponent(componentPath);
		if (dataComp == null) {
			msg = "Component data not found";
			return false;
		}

		DataType parentDataType = dataComp.getParent().getBaseDataType();

		if (!(parentDataType instanceof Composite)) {
			msg = "Invalid command usage";
			return false;
		}

		if (newDataType instanceof FactoryDataType) {
			msg = "Factory data-type not allowed in structure or union: " + newDataType.getName();
			return false;
		}

		DataType existingDT = dataComp.getDataType();
		int index = dataComp.getComponentIndex();

		newDataType =
			DataUtilities.reconcileAppliedDataType(existingDT, newDataType, stackPointers);

		if (newDataType instanceof Dynamic) {
			msg = "Dynamically sized data-type not allowed: " + newDataType.getName();
			return false;
		}

		// Ensure that dynamically sized types adjust to the data type manager
		newDataType = program.getDataTypeManager().resolve(newDataType, null);

		try {
			if (parentDataType instanceof Structure) {
				Structure struct = (Structure) parentDataType;
				if (newDataType == DataType.DEFAULT) {
					struct.clearComponent(index);
				}
				else {
//			        MemBuffer memBuf = new ProgramStructureProviderContext(program,addr, 
//	    	        					struct, dataComp.getParentOffset());
					DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(newDataType, -1);
					struct.replace(index, dti.getDataType(), dti.getLength());
				}
			}
			else if (parentDataType instanceof Union) {
				Union union = (Union) parentDataType;
				DataTypeComponent comp = union.getComponent(index);
				String comment = comp.getComment();
				String fieldName = comp.getFieldName();
				union.insert(index, newDataType);
				union.delete(index + 1);
				comp = union.getComponent(index);
				comp.setComment(comment);
				comp.setFieldName(fieldName);
			}

		}
		catch (Exception e) {
			msg = e.getMessage();
			return false;
		}
		return true;
	}