ghidra.program.model.util.CodeUnitInsertionException Java Examples

The following examples show how to use ghidra.program.model.util.CodeUnitInsertionException. 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: GenericRefernenceBaseRelocationFixupHandler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean handleGenerically64(Program program, Relocation relocation,
		Address oldImageBase, Address newImageBase) throws MemoryAccessException,
		CodeUnitInsertionException {
	long diff = newImageBase.subtract(oldImageBase);

	Address address = relocation.getAddress();
	Memory memory = program.getMemory();
	long value = memory.getLong(address);
	long newValue = value + diff;

	Address candiateRelocationValue = newImageBase.getNewAddress(newValue);
	if (hasMatchingReference(program, address, candiateRelocationValue)) {
		return process64BitRelocation(program, relocation, oldImageBase, newImageBase);
	}

	return false;
}
 
Example #3
Source File: COMDescriptorDataDirectory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		IOException, MemoryAccessException {

	monitor.setMessage("[" + program.getName() + "]: com descriptor(s)...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);
	DataType dt = header.toDataType();
	PeUtils.createData(program, addr, dt, log);

	if (hasParsed) {
		header.markup(program, isBinary, monitor, log, ntHeader);
	}
}
 
Example #4
Source File: SecurityDataDirectory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		DataTypeConflictException, IOException {

	if (!isBinary) {//certificates are never mapped into running program...
		return;
	}

	monitor.setMessage(program.getName()+": security data...");

	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	Address addr = space.getAddress(virtualAddress);//NOTE: virtualAddress is only a binary offset inside file!!!

	createDirectoryBookmark(program, addr);

	program.getListing().clearCodeUnits(addr, addr, false);

	for (SecurityCertificate cert : certificates) {
		DataType dt = cert.toDataType();
		program.getListing().createData(addr, dt);
		addr = addr.add(dt.getLength());
	}
}
 
Example #5
Source File: DyldCacheAccelerateInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupDependencies(Program program, Address accelerateInfoAddr,
		TaskMonitor monitor, MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD dependencies...");
	monitor.initialize(1);
	try {
		Address addr = accelerateInfoAddr.add(depListOffset);
		DataType dt = new ArrayDataType(WORD, depListCount, WORD.getLength());
		DataUtilities.createData(program, addr, dt, -1, false,
			DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
		program.getListing().setComment(addr, CodeUnit.EOL_COMMENT, "dependencies");
		monitor.incrementProgress(1);
	}
	catch (CodeUnitInsertionException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(),
			"Failed to markup dependences.");
	}
}
 
Example #6
Source File: FlatProgramAPI.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Create an ASCII string at the specified address.
 * @param address
 * @param length length of string (a value of 0 or negative will force use
 * of dynamic null terminated string)
 * @return string data created
 * @throws CodeUnitInsertionException
 * @throws DataTypeConflictException
 */
public final Data createAsciiString(Address address, int length)
		throws CodeUnitInsertionException {
	Listing listing = currentProgram.getListing();
	DataType dt = StringDataType.dataType;
	if (length <= 0) {
		dt = TerminatedStringDataType.dataType;
		length = -1;
	}
	Data d = listing.getDefinedDataAt(address);
	if (d != null) {
		if (d.getDataType().isEquivalent(dt) || (length > 0 && length != d.getLength())) {
			throw new CodeUnitInsertionException("Data conflict at address " + address);
		}
	}
	else {
		d = listing.createData(address, dt, length);
	}
	return d;
}
 
Example #7
Source File: DyldCacheAccelerateInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupAcceleratorDof(Program program, Address accelerateInfoAddr,
		TaskMonitor monitor, MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD DOF sections...");
	monitor.initialize(acceleratorDofList.size());
	try {
		Address addr = accelerateInfoAddr.add(dofSectionsOffset);
		for (DyldCacheAcceleratorDof dof : acceleratorDofList) {
			Data d = DataUtilities.createData(program, addr, dof.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(),
			"Failed to markup dyld_cache_accelerator_dof.");
	}
}
 
Example #8
Source File: DyldCacheAccelerateInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupImageInfoExtra(Program program, Address accelerateInfoAddr,
		TaskMonitor monitor, MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD image info extras...");
	monitor.initialize(imageInfoExtraList.size());
	try {
		Address addr = accelerateInfoAddr.add(imagesExtrasOffset);
		for (DyldCacheImageInfoExtra imageInfoExtra : imageInfoExtraList) {
			Data d = DataUtilities.createData(program, addr, imageInfoExtra.toDataType(), -1,
				false, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(),
			"Failed to markup dyld_cache_image_info_extra.");
	}
}
 
Example #9
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupAcceleratorInfo(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD accelerator info...");
	monitor.initialize(1);
	try {
		if (accelerateInfo != null) {
			Address addr = space.getAddress(accelerateInfoAddr);
			DataUtilities.createData(program, addr, accelerateInfo.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			accelerateInfo.markup(program, addr, monitor, log);
		}
		monitor.incrementProgress(1);
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup dyld_cache_accelerator_info.");
	}
}
 
Example #10
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupBranchPools(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD branch pool addresses...");
	monitor.initialize(branchPoolList.size());
	try {
		Address addr = fileOffsetToAddr(branchPoolsOffset, program, space);
		for (Long element : branchPoolList) {
			Data d = DataUtilities.createData(program, addr, Pointer64DataType.dataType,
				Pointer64DataType.dataType.getLength(), false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup branch pool addresses.");
	}
}
 
Example #11
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupSlideInfo(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD slide info...");
	monitor.initialize(1);
	try {
		if (slideInfo != null) {
			Address addr = fileOffsetToAddr(slideInfoOffset, program, space);
			DataUtilities.createData(program, addr, slideInfo.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
		}
		monitor.incrementProgress(1);
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup dyld_cache_slide_info.");
	}
}
 
Example #12
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupImageInfo(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD image info...");
	monitor.initialize(imageInfoList.size());
	try {
		Address addr = fileOffsetToAddr(imagesOffset, program, space);
		for (DyldCacheImageInfo imageInfo : imageInfoList) {
			Data d = DataUtilities.createData(program, addr, imageInfo.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			program.getListing().setComment(addr, CodeUnit.EOL_COMMENT, imageInfo.getPath());
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup dyld_cache_image_info.");
	}
}
 
Example #13
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupMappingInfo(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD mapping info...");
	monitor.initialize(mappingInfoList.size());
	try {
		Address addr = fileOffsetToAddr(mappingOffset, program, space);
		for (DyldCacheMappingInfo mappingInfo : mappingInfoList) {
			Data d = DataUtilities.createData(program, addr, mappingInfo.toDataType(), -1,
				false, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup dyld_cache_mapping_info.");
	}
}
 
Example #14
Source File: DyldCacheLocalSymbolsInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupLocalSymbols(Program program, Address localSymbolsInfoAddr,
		TaskMonitor monitor, MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD local symbol entries...");
	monitor.initialize(entriesCount);
	try {
		Address addr = localSymbolsInfoAddr.add(entriesOffset);
		for (DyldCacheLocalSymbolsEntry localSymbolsEntry : localSymbolsEntryList) {
			Data d = DataUtilities.createData(program, addr, localSymbolsEntry.toDataType(), -1,
				false, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(),
			"Failed to markup dyld_cache_local_symbols_entry.");
	}
}
 
Example #15
Source File: DyldCacheLocalSymbolsInfo.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupNList(Program program, Address localSymbolsInfoAddr, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD nlist symbol table...");
	monitor.initialize(nlistCount);
	try {
		Address addr = localSymbolsInfoAddr.add(nlistOffset);
		for (NList nlist : nlistList) {
			Data d = DataUtilities.createData(program, addr, nlist.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			addr = addr.add(d.getLength());
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(), "Failed to markup nlist.");
	}
}
 
Example #16
Source File: RelocationFixupHandler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected boolean process32BitRelocation(Program program, Relocation relocation,
		Address oldImageBase, Address newImageBase) throws MemoryAccessException,
		CodeUnitInsertionException {
	long diff = newImageBase.subtract(oldImageBase);

	Address address = relocation.getAddress();
	Memory memory = program.getMemory();
	int value = memory.getInt(address);
	int newValue = (int) (value + diff);

	InstructionStasher instructionStasher = new InstructionStasher(program, address);

	memory.setInt(address, newValue);

	instructionStasher.restore();

	return true;
}
 
Example #17
Source File: DyldCacheHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void markupLocalSymbolsInfo(Program program, AddressSpace space, TaskMonitor monitor,
		MessageLog log) throws CancelledException {
	monitor.setMessage("Marking up DYLD local symbols info...");
	monitor.initialize(1);
	try {
		if (localSymbolsInfo != null) {
			Address addr = fileOffsetToAddr(localSymbolsOffset, program, space);
			DataUtilities.createData(program, addr, localSymbolsInfo.toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
			localSymbolsInfo.markup(program, addr, monitor, log);
		}
		monitor.incrementProgress(1);
	}
	catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
		log.appendMsg(DyldCacheHeader.class.getSimpleName(),
			"Failed to markup dyld_cache_local_symbols_info.");
	}
}
 
Example #18
Source File: PCodeTestControlBlock.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Find Main TestInfo structure within memory and return instance of PCodeTestControlBlock
 * @param program
 * @param testFile original binary test file
 * @param restrictedSet a restricted set to be searched for control structures
 * @param cachedProgramPath program path within program file cache
 * @param testInfoStruct TestInfo structure definition
 * @param groupInfoStruct GroupInfo structure definition
 * @param applyStruct create structure Data within program if true
 * @param testResults test results storage object
 * @return instance of PCodeTestControlBlock
 * @throws InvalidControlBlockException
 * @throws CodeUnitInsertionException
 */
static PCodeTestControlBlock getMainControlBlock(Program program, PCodeTestFile testFile,
		AddressSetView restrictedSet, String cachedProgramPath, Structure testInfoStruct,
		Structure groupInfoStruct, boolean applyStruct, PCodeTestResults testResults)
		throws InvalidControlBlockException, CodeUnitInsertionException {

	PCodeTestControlBlock.testInfoStruct = testInfoStruct;
	PCodeTestControlBlock.groupInfoStruct = groupInfoStruct;

	Memory memory = program.getMemory();
	byte[] magicBytes = getCharArrayBytes(program, MAIN_CONTROL_BLOCK_MAGIC);

	Address startOfControlBlock = findBytes(memory, restrictedSet, magicBytes);
	if (startOfControlBlock == null) {
		throw new InvalidControlBlockException("TestInfo structure not found");
	}

	return new PCodeTestControlBlock(program, restrictedSet, startOfControlBlock, testFile,
		cachedProgramPath, applyStruct, testResults);
}
 
Example #19
Source File: VTMatchAcceptTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Data setData(DataType dataType, int dtLength, Address address, Program program)
		throws CodeUnitInsertionException, DataTypeConflictException {

	Listing listing = program.getListing();
	Data data = null;
	boolean commit = false;
	int transaction = program.startTransaction("Test - Set Data");
	try {
		data = listing.createData(address, dataType, dtLength);
		commit = true;
	}
	finally {
		program.endTransaction(transaction, commit);
	}
	return data;
}
 
Example #20
Source File: ElfDefaultGotPltMarkup.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Data createPointer(Address addr, boolean keepRefWhenValid)
		throws CodeUnitInsertionException {

	MemoryBlock block = memory.getBlock(addr);
	if (block == null || !block.isInitialized()) {
		return null;
	}
	int pointerSize = program.getDataTypeManager().getDataOrganization().getPointerSize();
	Pointer pointer = PointerDataType.dataType;
	if (elf.is32Bit() && pointerSize != 4) {
		pointer = Pointer32DataType.dataType;
	}
	else if (elf.is64Bit() && pointerSize != 8) {
		pointer = Pointer64DataType.dataType;
	}
	Data data = listing.getDataAt(addr);
	if (data == null || !pointer.isEquivalent(data.getDataType())) {
		if (data != null) {
			listing.clearCodeUnits(addr, addr.add(pointerSize - 1), false);
		}
		data = listing.createData(addr, pointer);
	}
	Address refAddr = (Address) data.getValue();
	if (keepRefWhenValid) {
		if (memory.contains(refAddr)) {
			return data;
		}
		Symbol syms[] = program.getSymbolTable().getSymbols(refAddr);
		if (syms != null && syms.length > 0 && syms[0].getSource() != SourceType.DEFAULT) {
			return data;
		}
	}
	removeMemRefs(data);
	return data;
}
 
Example #21
Source File: ImageCor20Header.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		IOException, MemoryAccessException {

	if (!metadata.hasParsedCorrectly()) {
		return;
	}

	metadata.markup(program, isBinary, monitor, log, ntHeader);

	if (entryPointToken > 0) { // DLL's won't have an entry point
		try {
			if ((flags &
				ImageCor20Flags.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT) == ImageCor20Flags.COMIMAGE_FLAGS_NATIVE_ENTRYPOINT) {
				// Add new symbol for the native entry point
				program.getSymbolTable().addExternalEntryPoint(
					program.getImageBase().add(entryPointToken));
			}
			else {
				// Add a new symbol for the .NET entry point
				CliStreamMetadata stream =
					(CliStreamMetadata) metadata.getMetadataRoot().getStreamHeader(
						CliStreamMetadata.getName()).getStream();
				CliMethodDefRow row = (CliMethodDefRow) stream.getTable(
					(entryPointToken & 0xff000000) >> 24).getRow(entryPointToken & 0x00ffffff);
				program.getSymbolTable().addExternalEntryPoint(
					program.getImageBase().add(row.RVA));
			}
		}
		catch (Exception e) {
			log.appendException(e);
		}
	}
}
 
Example #22
Source File: ExceptionDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		DataTypeConflictException, IOException {
	monitor.setMessage(program.getName()+": exceptions...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);
}
 
Example #23
Source File: CodeUnitMerger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * <CODE>performMergeData</CODE> merges the indicated defined data
 * into the merge program. The bytes in the merge program are not affected
 * by this method.
 *
 * @param data the defined data to be merged
 * @param copyBytes whether or not bytes should be copied.
 * @throws CodeUnitInsertionException if the defined data can't be created
 * in the merge program.
 */
private void performMergeData(Data data, boolean copyBytes)
		throws CodeUnitInsertionException, MemoryAccessException {
	Address minAddress = data.getMinAddress();
	Address maxAddress = data.getMaxAddress();
	Program fromPgm = data.getProgram();
	DataType dt = data.getDataType();
	DataTypeManager fromDTM = fromPgm.getDataTypeManager();
	long dtID = fromDTM.getID(dt);
	if (!(dt instanceof BuiltInDataType)) {
		dt = (dt != DataType.DEFAULT) ? getResultDataType(dtID, fromPgm) : DataType.DEFAULT;
	}
	boolean hasNewData = false;
	Listing resultListing = resultPgm.getListing();

	if (copyBytes && !resultUninitSet.intersects(minAddress, maxAddress)) {
		ProgramMemoryUtil.copyBytesInRanges(resultPgm, fromPgm, minAddress, maxAddress);
	}
	if (!(dt.equals(DataType.DEFAULT))) {
		DataType tmpDt = dt;
		resultListing.createData(minAddress, tmpDt, data.getLength());
		hasNewData = true;
	}
	if (hasNewData) {
		Data newData = resultListing.getDataAt(minAddress);
		String[] settingNames = data.getNames();
		for (String settingName : settingNames) {
			Object obj = data.getValue(settingName);
			if (obj != null) {
				newData.setValue(settingName, obj);
			}
		}
	}
}
 
Example #24
Source File: ResourceDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void markupDirectory(ResourceDirectory directory, Address directoryAddr,
		Address resourceBase, Program program, boolean isBinary, TaskMonitor monitor,
		MessageLog log) throws IOException, DuplicateNameException, CodeUnitInsertionException {

	PeUtils.createData(program, directoryAddr, directory.toDataType(), log);
	directoryAddr = directoryAddr.add(ResourceDirectory.SIZEOF);

	List<ResourceDirectoryEntry> entries = directory.getEntries();
	for (ResourceDirectoryEntry entry : entries) {
		if (monitor.isCancelled()) {
			return;
		}

		PeUtils.createData(program, directoryAddr, entry.toDataType(), log);
		directoryAddr = directoryAddr.add(ResourceDirectoryEntry.SIZEOF);

		ResourceDirectory subDirectory = entry.getSubDirectory();
		if (subDirectory != null) {
			Address subDirectoryAddr = resourceBase.add(entry.getOffsetToDirectory());
			markupDirectory(subDirectory, subDirectoryAddr, resourceBase, program, isBinary,
				monitor, log);
		}

		ResourceDataEntry data = entry.getData();
		if (data != null) {
			Address dataAddr = resourceBase.add(entry.getOffsetToData());
			PeUtils.createData(program, dataAddr, data.toDataType(), log);
		}

		ResourceDirectoryStringU string = entry.getDirectoryString();
		if (string != null && string.getLength() > 0) {
			Address strAddr = resourceBase.add(entry.getNameOffset() & 0x7fffffff);
			PeUtils.createData(program, strAddr, string.toDataType(), log);
		}
	}
}
 
Example #25
Source File: CodeUnitMerger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * <CODE>performMergeInstruction</CODE> merges the indicated instruction
 * into the result program. The bytes are also moved from the program
 * if they differ. The flow override and fallthrough override will be set
 * the same in the result program's instruction as they are in the instruction
 * that is passed to this method.
 *
 * @param instruction the instruction to be merged
 * @param copyBytes whether or not bytes should be copied if turned into
 * an instruction.
 * @throws CodeUnitInsertionException if the instruction can't be created
 * in the merge program.
 *
 * @throws MemoryAccessException if bytes can't be copied.
 */
private void performMergeInstruction(Instruction instruction, boolean copyBytes)
		throws CodeUnitInsertionException, MemoryAccessException {
	Address minAddress = instruction.getMinAddress();
	Address maxAddress = instruction.getMaxAddress();
	Program fromPgm = instruction.getProgram();
	// Code unit should already be cleared where this instruction needs to go.
	Listing resultListing = resultPgm.getListing();

	// Copy the bytes if requested.
	if (copyBytes && !resultUninitSet.intersects(minAddress, maxAddress)) {
		ProgramMemoryUtil.copyBytesInRanges(resultPgm, fromPgm, minAddress, maxAddress);
	}

	Instruction inst = resultListing.createInstruction(minAddress, instruction.getPrototype(),
		new DumbMemBufferImpl(resultPgm.getMemory(), minAddress),
		new ProgramProcessorContext(resultPgm.getProgramContext(), minAddress));

	// Set the fallthrough override if necessary.
	if (instruction.isFallThroughOverridden()) {
		// override the fallthrough the same as it is in the one being merged.
		inst.setFallThrough(instruction.getFallThrough());
	}

	// Set the flow override if necessary.
	if (instruction.getFlowOverride() != FlowOverride.NONE) {
		inst.setFlowOverride(instruction.getFlowOverride());
	}
}
 
Example #26
Source File: BoundImportDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException {

   	monitor.setMessage(program.getName()+": bound import(s)...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);

	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();

	for (BoundImportDescriptor descriptor : descriptors) {
           if (monitor.isCancelled()) {
               return;
           }
           DataType dt = descriptor.toDataType();
		PeUtils.createData(program, addr, dt, log);
           addr = addr.add(dt.getLength());

           long namePtr = descriptor.getOffsetModuleName()+virtualAddress;
           Address nameAddr = space.getAddress(va(namePtr, isBinary));
           createTerminatedString(program, nameAddr, false, log);
       }

	BoundImportDescriptor terminator = new BoundImportDescriptor();
	PeUtils.createData(program, addr, terminator.toDataType(), log);
   }
 
Example #27
Source File: ImportAddressTableDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws CodeUnitInsertionException, MemoryAccessException {

	monitor.setMessage(program.getName()+": IAT...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);
}
 
Example #28
Source File: ConvertCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean applyDataSettings(Data data)
		throws CodeUnitInsertionException, DataTypeConflictException {

	DataType dt = data.getBaseDataType();
	Settings settings = data;
	Settings defaultSettings = dt.getDefaultSettings();
	if (!(Scalar.class.equals(data.getValueClass())) ||
		!(dt instanceof AbstractIntegerDataType)) {
		msg = "Unsupported data type for convert: " + data.getDataType().getDisplayName();
		return false;
	}

	int formatChoice = action.getFormatChoice();

	// Only change data-type when decimal signed/unsigned mode differs from data type
	// since other formats are always unsigned regardless of data type
	if (formatChoice == FormatSettingsDefinition.DECIMAL) {
		AbstractIntegerDataType numDt = (AbstractIntegerDataType) dt;
		if (action.isSignedChoice()) {
			if (!numDt.isSigned()) {
				DataType signedDataType = numDt.getOppositeSignednessDataType();
				createData(data, signedDataType);
			}
		}
		else if (numDt.isSigned()) {
			DataType unsignedDataType = numDt.getOppositeSignednessDataType();
			createData(data, unsignedDataType);
		}
	}

	if (FormatSettingsDefinition.DEF.getChoice(defaultSettings) == formatChoice) {
		FormatSettingsDefinition.DEF.clear(settings);
	}
	else {
		FormatSettingsDefinition.DEF.setChoice(settings, formatChoice);
	}

	return true;
}
 
Example #29
Source File: CreateDataBackgroundCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void createData(Address start, Address end, DataType dataType, Program p,
		TaskMonitor monitor)
		throws AddressOverflowException, CodeUnitInsertionException, DataTypeConflictException {

	Listing listing = p.getListing();
	listing.clearCodeUnits(start, end, false);
	int length = (int) end.subtract(start) + 1;
	while (start.compareTo(end) <= 0) {
		if (monitor.isCancelled()) {
			return;
		}

		Data d = listing.createData(start, dataType, length);
		int dataLen = d.getLength();
		start = start.addNoWrap(dataLen);
		length -= dataLen;
		bytesApplied += dataLen;

		monitor.setProgress(bytesApplied);
		if (++numDataCreated % 10000 == 0) {
			monitor.setMessage("Created " + numDataCreated);

			// Allow the Swing thread a chance to paint components that may require
			// a DB lock.
			Swing.allowSwingToProcessEvents();
		}
	}
}
 
Example #30
Source File: DebugDataDirectory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		DataTypeConflictException, IOException {

	monitor.setMessage(program.getName()+": debug...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);

	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();

	DebugDirectory [] ddarr = parser.getDebugDirectories();
	for (DebugDirectory dd : ddarr) {
		PeUtils.createData(program, addr, dd.toDataType(), log);
		addr = addr.add(DebugDirectory.IMAGE_SIZEOF_DEBUG_DIRECTORY);

		Address dataAddr = getDataAddress(dd, isBinary, space, ntHeader);
		if (dataAddr != null) {
			boolean success = createFragment(program, "Debug Data", dataAddr, dataAddr.add(dd.getSizeOfData()));
			if (!success) {
				log.appendMsg("Unable to create fragment: Debug Data");
			}
		}
	}

	markupDebigMisc(program, isBinary, log, space);
	markupDebugCodeView(program, isBinary, log, space);
}