Java Code Examples for ghidra.app.util.MemoryBlockUtils#createInitializedBlock()

The following examples show how to use ghidra.app.util.MemoryBlockUtils#createInitializedBlock() . 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: ApploaderProgramBuilder.java    From Ghidra-GameCube-Loader with Apache License 2.0 6 votes vote down vote up
protected void load(ByteProvider provider)
		throws AddressOutOfBoundsException {
	this.baseAddress = 0x80000000L;
	this.addressSpace = program.getAddressFactory().getDefaultAddressSpace();
	
	try {
		this.program.setImageBase(addressSpace.getAddress(this.baseAddress), true);
		
		// Create Apploader section.
		MemoryBlockUtils.createInitializedBlock(this.program, false, "Apploader", addressSpace.getAddress(0x81200000), provider.getInputStream(ApploaderHeader.HEADER_SIZE),
				header.GetSize(), "", null, true, true, true, null, monitor);
		
		// Create trailer section.
		MemoryBlockUtils.createInitializedBlock(this.program, false, "Trailer", addressSpace.getAddress(0x81200000 + header.GetSize()),
				provider.getInputStream(ApploaderHeader.HEADER_SIZE + header.GetSize()), header.GetTrailerSize(), "", null, true, true, true, null, monitor);
	}
	catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: MemoryBlockHelper.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
public void addSection(String name, long addressOffset, long offset, long length, boolean read, boolean write, boolean execute)
{
    try
    {
        FileBytes fileBytes = MemoryBlockUtils.createFileBytes(this.program, this.byteProvider, offset, length, this.monitor);
        MemoryBlockUtils.createInitializedBlock(this.program, false, name, this.program.getImageBase().add(addressOffset), fileBytes, 0, length, "", null, read, write, execute, this.log);
    }
    catch (Exception e)
    {
        Msg.error(this, "Failed to add section " + name, e);
    }
    
    this.flushLog();
}
 
Example 3
Source File: MIPS_ElfRelocationHandler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Flush the section GOT table to a new %got memory block
 */
private void createGot() {
	if (lastSectionGotEntryAddress == null) {
		return;
	}
	int size = (int) lastSectionGotEntryAddress.subtract(sectionGotAddress) + 1;
	String sectionName = relocationTable.getSectionToBeRelocated().getNameAsString();
	String blockName = getSectionGotName();
	try {
		MemoryBlock block = MemoryBlockUtils.createInitializedBlock(program, false,
			blockName, sectionGotAddress, size, "GOT for " + sectionName + " section",
			"MIPS-Elf Loader", true, false, false, loadHelper.getLog());
		DataConverter converter =
			program.getMemory().isBigEndian() ? BigEndianDataConverter.INSTANCE
					: LittleEndianDataConverter.INSTANCE;
		for (long symbolValue : gotMap.keySet()) {
			Address addr = gotMap.get(symbolValue);
			byte[] bytes;
			if (program.getDefaultPointerSize() == 4) {
				bytes = converter.getBytes((int) symbolValue);
			}
			else {
				bytes = converter.getBytes(symbolValue);
			}
			block.putBytes(addr, bytes);
			loadHelper.createData(addr, PointerDataType.dataType);
		}
	}
	catch (MemoryAccessException e) {
		throw new AssertException(e); // unexpected
	}
}
 
Example 4
Source File: MergeTwoProgramsScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void mergeMemory( Program currProgram, Program otherProgram ) throws Exception {
	monitor.setMessage( "Merging memory..." );
	Memory otherMemory = otherProgram.getMemory();
	MemoryBlock[] otherBlocks = otherMemory.getBlocks();
	MessageLog log = new MessageLog();
	for (MemoryBlock otherBlock : otherBlocks) {
		if (monitor.isCancelled()) {
			break;
		}
		if (otherBlock.getType() != MemoryBlockType.DEFAULT) {
			printerr("Unhandled memory block type: " + otherBlock.getName());
			continue;
		}
		if (otherBlock.isInitialized()) {
			MemoryBlockUtils.createInitializedBlock(currProgram, false, otherBlock.getName(),
				otherBlock.getStart(), otherBlock.getData(), otherBlock.getSize(),
				otherBlock.getComment(), otherBlock.getSourceName(), otherBlock.isRead(),
				otherBlock.isWrite(), otherBlock.isExecute(), log, monitor);
		}
		else {
			MemoryBlockUtils.createUninitializedBlock(currProgram, false, otherBlock.getName(),
				otherBlock.getStart(), otherBlock.getSize(), otherBlock.getComment(),
				otherBlock.getSourceName(), otherBlock.isRead(), otherBlock.isWrite(),
				otherBlock.isExecute(), log);
		}
	}
}
 
Example 5
Source File: CoffLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private MemoryBlock createInitializedBlock(ByteProvider provider, Program program,
		FileBytes fileBytes, TaskMonitor monitor, MessageLog log, final Language language,
		int sectionNumber, CoffSectionHeader section, final int sectionSize,
		Address sectionAddr, boolean isOverlay) throws AddressOverflowException, IOException {

	String name = section.getName();
	if (isOverlay) {
		name += "-" + sectionNumber;
	}
	MemoryBlock block = null;
	try {
		if (section.isProcessedBytes(language)) {
			try (InputStream dataStream = section.getRawDataStream(provider, language)) {
				block = MemoryBlockUtils.createInitializedBlock(program, isOverlay, name,
					sectionAddr, dataStream, sectionSize,
					"PhysAddr:0x" + Integer.toHexString(section.getPhysicalAddress()) + " " +
						"Size:0x" + Integer.toHexString(sectionSize) + " " + "Flags:0x" +
						Integer.toHexString(section.getFlags()),
					null/*source*/, section.isReadable(), section.isWritable(),
					section.isExecutable(), log, monitor);
			}
		}
		else {
			block = MemoryBlockUtils.createInitializedBlock(program, isOverlay, name,
				sectionAddr, fileBytes, section.getPointerToRawData(), sectionSize,
				"PhysAddr:0x" + Integer.toHexString(section.getPhysicalAddress()) + " " +
					"Size:0x" + Integer.toHexString(sectionSize) + " " + "Flags:0x" +
					Integer.toHexString(section.getFlags()),
				null/*source*/, section.isReadable(), section.isWritable(),
				section.isExecutable(), log);
		}
	}
	catch (RuntimeException e) {
		log.appendMsg(
			"Unable to create non-loaded block " + section + ". No memory block was created.");
		log.appendException(e);
	}
	return block;
}
 
Example 6
Source File: ElfProgramBuilder.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected MemoryBlock createInitializedBlock(MemoryLoadable loadable, boolean isOverlay,
		String name, Address start, long fileOffset, long dataLength, String comment, boolean r,
		boolean w, boolean x, TaskMonitor monitor)
		throws IOException, AddressOverflowException, CancelledException {

	// TODO: MemoryBlockUtil poorly and inconsistently handles duplicate name errors (can throw RuntimeException).
	// Are we immune from such errors? If not, how should they be handled?

	long revisedLength = checkBlockLimit(name, dataLength, true);

	if (start.isNonLoadedMemoryAddress()) {
		r = false;
		w = false;
		x = false;
	}

	Msg.debug(this,
		"Loading block " + name + " at " + start + " from file offset " + fileOffset);

	long endOffset = fileOffset + revisedLength - 1;
	if (endOffset >= fileBytes.getSize()) {
		revisedLength = fileBytes.getSize() - fileOffset;
		log("Truncating block load for " + name + " which exceeds file length");
	}

	String blockComment = comment;
	if (dataLength != revisedLength) {
		blockComment += " (section truncated)";
	}

	if (elf.getLoadAdapter().hasFilteredLoadInputStream(this, loadable, start)) {
		// block is unable to map directly to file bytes - load from input stream
		try (InputStream dataInput =
			getInitializedBlockInputStream(loadable, start, fileOffset, revisedLength)) {
			return MemoryBlockUtils.createInitializedBlock(program, isOverlay, name, start,
				dataInput, revisedLength, blockComment, BLOCK_SOURCE_NAME, r, w, x, log,
				monitor);
		}
	}

	// create block using direct mapping to file bytes
	return MemoryBlockUtils.createInitializedBlock(program, isOverlay, name, start, fileBytes,
		fileOffset, revisedLength, blockComment, BLOCK_SOURCE_NAME, r, w, x, log);
}
 
Example 7
Source File: PefLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processSections(ContainerHeader header, Program program, FileBytes fileBytes,
		ImportStateCache importState, MessageLog log, TaskMonitor monitor)
		throws AddressOverflowException, IOException {

	List<SectionHeader> sections = header.getSections();
	for (SectionHeader section : sections) {
		if (monitor.isCancelled()) {
			return;
		}

		Address start = getSectionAddressAligned(section, program);

		monitor.setMessage("Creating section at 0x" + start + "...");

		if (!section.getSectionKind().isInstantiated()) {
			continue;
		}

		if (section.getSectionKind() == SectionKind.PackedData) {
			byte[] unpackedData = section.getUnpackedData(monitor);
			ByteArrayInputStream is = new ByteArrayInputStream(unpackedData);
			MemoryBlockUtils.createInitializedBlock(program, false, section.getName(), start,
				is, unpackedData.length, section.getSectionKind().toString(), null,
				section.isRead(), section.isWrite(), section.isExecute(), log, monitor);
		}
		else {
			MemoryBlockUtils.createInitializedBlock(program, false, section.getName(), start,
				fileBytes, section.getContainerOffset(), section.getUnpackedLength(),
				section.getSectionKind().toString(), null, section.isRead(), section.isWrite(),
				section.isExecute(), log);
		}

		importState.setMemoryBlockForSection(section, program.getMemory().getBlock(start));

		if (section.getUnpackedLength() < section.getTotalLength()) {
			start = start.add(section.getUnpackedLength());

			MemoryBlockUtils.createUninitializedBlock(program, false, section.getName(), start,
				section.getTotalLength() - section.getUnpackedLength(),
				section.getSectionKind().toString(), null, section.isRead(), section.isWrite(),
				section.isExecute(), log);
		}
	}
}
 
Example 8
Source File: OmfLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
	 * Run through the OMF segments an produce Ghidra memory blocks.
	 * Most segments cause an initialized block to be created, but if a segment
	 * consists only of a string of zero bytes, as described by a compact LIDATA record,
	 * an uninitialized block is created.
	 * @param reader is a reader for the underlying file
	 * @param header is the OMF file header
	 * @param program is the Program
	 * @param mbu is the block creation utility
	 * @param monitor is checked for cancellation
	 * @param log receives error messages
	 * @throws AddressOverflowException if the underlying data stream causes an address to wrap
	 * @throws IOException for problems accessing the OMF file through the reader
	 */
	private void processSegmentHeaders(BinaryReader reader, OmfFileHeader header, Program program,
			TaskMonitor monitor, MessageLog log) throws AddressOverflowException, IOException {
		monitor.setMessage("Process segments...");

		final Language language = program.getLanguage();

		ArrayList<OmfSegmentHeader> segments = header.getSegments();
//		int sectionNumber = 0;
		for (OmfSegmentHeader segment : segments) {
//			++sectionNumber;
			if (monitor.isCancelled()) {
				break;
			}

			//		if (segment.hasIteratedData() && segment.hasEnumeratedData())
			//			throw new IOException("OMF segment has both iterated and enumerated data blocks");
			MemoryBlock block = null;

			final long segmentSize = segment.getSegmentLength();

			Address segmentAddr = segment.getAddress(language);

			if (segmentSize == 0) {
				// don't create a block...just log that we've seen the segment
				block = program.getMemory().getBlock(segmentAddr);
				log.appendMsg("Empty Segment: " + segment.getName());
			}
			else if (segment.hasNonZeroData()) {
				block = MemoryBlockUtils.createInitializedBlock(program, false, segment.getName(),
					segmentAddr, segment.getRawDataStream(reader, log), segmentSize,
					"Address:0x" + Long.toHexString(segmentAddr.getOffset()) + " " + "Size:0x" +
						Long.toHexString(segmentSize),
					null/*source*/, segment.isReadable(), segment.isWritable(),
					segment.isExecutable(), log, monitor);
				if (block != null) {
					log.appendMsg(
						"Created Initialized Block: " + segment.getName() + " @ " + segmentAddr);
				}
			}
			else {
				block = MemoryBlockUtils.createUninitializedBlock(program, false, segment.getName(),
					segmentAddr, segmentSize,
					"Address:0x" + Long.toHexString(segmentAddr.getOffset()) + " " + "Size:0x" +
						Long.toHexString(segmentSize),
					null/*source*/, segment.isReadable(), segment.isWritable(),
					segment.isExecutable(), log);
				if (block != null) {
					log.appendMsg(
						"Created Uninitialized Block: " + segment.getName() + " @ " + segmentAddr);
				}
			}
		}
	}