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

The following examples show how to use ghidra.app.util.MemoryBlockUtils#createUninitializedBlock() . 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: ElfProgramBuilder.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected MemoryBlock createUninitializedBlock(MemoryLoadable loadable, boolean isOverlay,
		String name, Address start, long dataLength, String comment, boolean r, boolean w,
		boolean x) 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, false);

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

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

	return MemoryBlockUtils.createUninitializedBlock(program, isOverlay, name, start,
		revisedLength, comment, BLOCK_SOURCE_NAME, r, w, x, log);
}
 
Example 2
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 3
Source File: SystemMemorySections.java    From Ghidra-GameCube-Loader with Apache License 2.0 5 votes vote down vote up
public static void Create(Program program) {
	var addressSpace = program.getAddressFactory().getDefaultAddressSpace();
	
	// Create globals section first
	MemoryBlockUtils.createUninitializedBlock(program, false, "OS Globals", addressSpace.getAddress(0x80000000), 0x3100, "Operating System Globals", null, true, true, false, null);
	
	// Now create hardware registers
	var cp = MemoryBlockUtils.createUninitializedBlock(program, false, "CP", addressSpace.getAddress(0xCC000000), 0x80, "Command Processor Register", null, true, true, false, null);
	cp.setVolatile(true);

	var pe = MemoryBlockUtils.createUninitializedBlock(program, false, "PE", addressSpace.getAddress(0xCC001000), 0x100, "Pixel Engine Register", null, true, true, false, null);
	pe.setVolatile(true);
	
	var vi = MemoryBlockUtils.createUninitializedBlock(program, false, "VI", addressSpace.getAddress(0xCC002000), 0x100, "Video Interface Register", null, true, true, false, null);
	vi.setVolatile(true);
	
	var pi = MemoryBlockUtils.createUninitializedBlock(program, false, "PI", addressSpace.getAddress(0xCC003000), 0x100, "Processor Interface Register", null, true, true, false, null);
	pi.setVolatile(true);
	
	var mi = MemoryBlockUtils.createUninitializedBlock(program, false, "MI", addressSpace.getAddress(0xCC004000), 0x80, "Memory Interface Register", null, true, true, false, null);
	mi.setVolatile(true);
	
	var dsp = MemoryBlockUtils.createUninitializedBlock(program, false, "DSP", addressSpace.getAddress(0xCC005000), 0x200, "Digital Signal Processor Register", null, true, true, false, null);
	dsp.setVolatile(true);
	
	var di = MemoryBlockUtils.createUninitializedBlock(program, false, "DI", addressSpace.getAddress(0xCC006000), 0x40, "DVD Interface Reigster", null, true, true, false, null);
	di.setVolatile(true);
	
	var si = MemoryBlockUtils.createUninitializedBlock(program, false, "SI", addressSpace.getAddress(0xCC006400), 0x100, "Serial Interface Reigster", null, true, true, false, null);
	si.setVolatile(true);
	
	var exi = MemoryBlockUtils.createUninitializedBlock(program, false, "EXI", addressSpace.getAddress(0xCC006800), 0x40, "External Interface Reigster", null, true, true, false, null);
	exi.setVolatile(true);
	
	var ai = MemoryBlockUtils.createUninitializedBlock(program, false, "AI", addressSpace.getAddress(0xCC006C00), 0x40, "Audio Interface Reigster", null, true, true, false, null);
	ai.setVolatile(true);
	
	var gxfifo = MemoryBlockUtils.createUninitializedBlock(program, false, "GXFIFO", addressSpace.getAddress(0xCC008000), 0x8, "Graphics FIFO Reigster", null, true, true, false, null);
	gxfifo.setVolatile(true);
}
 
Example 4
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 4 votes vote down vote up
public void load(TaskMonitor monitor)
{
    NXOAdapter adapter = this.nxo.getAdapter();
    ByteProvider memoryProvider = adapter.getMemoryProvider();
    this.aSpace = program.getAddressFactory().getDefaultAddressSpace();
    
    try 
    {
        this.memBlockHelper = new MemoryBlockHelper(monitor, this.program, memoryProvider);
        
        NXOSection text = adapter.getSection(NXOSectionType.TEXT);
        NXOSection rodata = adapter.getSection(NXOSectionType.RODATA);
        NXOSection data = adapter.getSection(NXOSectionType.DATA);
        
        if (adapter.getDynamicSize() == 0)
        {
            // We can't create .dynamic, so work with what we've got.
            return;
        }
        
        this.memBlockHelper.addSection(".dynamic", adapter.getDynamicOffset(), adapter.getDynamicOffset(), adapter.getDynamicSize(), true, true, false);

        // Create dynamic sections
        this.tryCreateDynBlock(".dynstr", ElfDynamicType.DT_STRTAB, ElfDynamicType.DT_STRSZ);
        this.tryCreateDynBlock(".init_array", ElfDynamicType.DT_INIT_ARRAY, ElfDynamicType.DT_INIT_ARRAYSZ);
        this.tryCreateDynBlock(".fini_array", ElfDynamicType.DT_FINI_ARRAY, ElfDynamicType.DT_FINI_ARRAYSZ);
        this.tryCreateDynBlock(".rela.dyn", ElfDynamicType.DT_RELA, ElfDynamicType.DT_RELASZ);
        this.tryCreateDynBlock(".rel.dyn", ElfDynamicType.DT_REL, ElfDynamicType.DT_RELSZ);
        
        if (adapter.isAarch32())
        {
            this.tryCreateDynBlock(".rel.plt", ElfDynamicType.DT_JMPREL, ElfDynamicType.DT_PLTRELSZ);
        }
        else
        {
            this.tryCreateDynBlock(".rela.plt", ElfDynamicType.DT_JMPREL, ElfDynamicType.DT_PLTRELSZ);
        }

        this.tryCreateDynBlockWithRange(".hash", ElfDynamicType.DT_HASH, ElfDynamicType.DT_GNU_HASH);
        this.tryCreateDynBlockWithRange(".gnu.hash", ElfDynamicType.DT_GNU_HASH, ElfDynamicType.DT_SYMTAB);
        
        if (adapter.getSymbolTable(this.program) != null)
        {
            Msg.info(this, String.format("String table offset %X, base addr %X", adapter.getSymbolTable(this.program).getFileOffset(), this.nxo.getBaseAddress()));
            this.memBlockHelper.addSection(".dynsym", adapter.getSymbolTable(this.program).getFileOffset() - this.nxo.getBaseAddress(), adapter.getSymbolTable(this.program).getFileOffset() - this.nxo.getBaseAddress(), adapter.getSymbolTable(this.program).getLength(), true, false, false);
        }
        
        this.setupRelocations();
        this.createGlobalOffsetTable();
        
        this.memBlockHelper.addFillerSection(".text", text.getOffset(), text.getSize(), true, false, true);
        this.memBlockHelper.addFillerSection(".rodata", rodata.getOffset(), rodata.getSize(), true, false, false);
        this.memBlockHelper.addFillerSection(".data", data.getOffset(), data.getSize(), true, true, false);
        
        this.setupStringTable();
        this.setupSymbolTable();
        
        // Create BSS. This needs to be done before the EXTERNAL block is created in setupImports
        Address bssStartAddr = aSpace.getAddress(this.nxo.getBaseAddress() + adapter.getBssOffset());
        Msg.info(this, String.format("Created bss from 0x%X to 0x%X", bssStartAddr.getOffset(), bssStartAddr.getOffset() + adapter.getBssSize()));
        MemoryBlockUtils.createUninitializedBlock(this.program, false, ".bss", bssStartAddr, adapter.getBssSize(), "", null, true, true, false, new MessageLog());
        
        this.setupImports(monitor);
        this.performRelocations();
        
        // Set all data in the GOT to the pointer data type
        // NOTE: Currently the got range may be null in e.g. old libnx nros
        // We may want to manually figure this out ourselves in future.
        if (adapter.getGotSize() > 0)
        {
            for (Address addr = this.aSpace.getAddress(adapter.getGotOffset()); addr.compareTo(this.aSpace.getAddress(adapter.getGotOffset() + adapter.getGotSize())) < 0; addr = addr.add(adapter.getOffsetSize()))
            {
                this.createPointer(addr);
            }
        }
    }
    catch (IOException | NotFoundException | AddressOverflowException | AddressOutOfBoundsException | CodeUnitInsertionException | DataTypeConflictException | MemoryAccessException | InvalidInputException e)
    {
        e.printStackTrace();
    }
    
    // Ensure memory blocks are ordered from first to last.
    // Normally they are ordered by the order they are added.
    UIUtil.sortProgramTree(this.program);
}
 
Example 5
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 6
Source File: CoffLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processSectionHeaders(ByteProvider provider, CoffFileHeader header,
		Program program, FileBytes fileBytes, TaskMonitor monitor, MessageLog log,
		Map<CoffSectionHeader, Address> map, boolean performFakeLinking)
		throws AddressOverflowException, IOException {

	monitor.setMessage("Process sections...");

	final Language language = program.getLanguage();

	List<CoffSectionHeader> sections = header.getSections();

	if (performFakeLinking) {
		possiblyRelocateSections(program, header, map);
	}

	int sectionNumber = 0;
	for (CoffSectionHeader section : sections) {
		++sectionNumber;
		if (monitor.isCancelled()) {
			break;
		}

		MemoryBlock block = null;

		final int sectionSize = section.getSize(language);

		Address sectionAddr = section.getPhysicalAddress(language);

		if (sectionSize == 0 || section.getFlags() == 0) {
			log.appendMsg("Empty Section, Created Symbol: " + section.getName());
			// don't create a block, but record the section to get at the address!
			block = program.getMemory().getBlock(sectionAddr);
			try {
				program.getSymbolTable().createLabel(sectionAddr, section.getName(),
					SourceType.IMPORTED);
				// TODO: sectionSize somewhere for case where flags==0 ?
			}
			catch (InvalidInputException e) {
				// unexpected
			}
		}
		else if (!section.isAllocated()) {
			block = createInitializedBlock(provider, program, fileBytes, monitor, log, language,
				sectionNumber, section, sectionSize, sectionAddr, true);
			if (block != null) {
				log.appendMsg("Created Overlay Block: " + section + " @ " + sectionAddr);
			}
		}
		else if (section.isUninitializedData()) {
			block = MemoryBlockUtils.createUninitializedBlock(program, false, section.getName(),
				sectionAddr, 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);
			if (block != null) {
				log.appendMsg("Created Uninitialized Block: " + section + " @ " + sectionAddr);
			}
		}
		else {
			block = createInitializedBlock(provider, program, fileBytes, monitor, log, language,
				sectionNumber, section, sectionSize, sectionAddr, false);
			if (block != null) {
				log.appendMsg("Created Initialized Block: " + section + " @ " + sectionAddr);
			}
		}

		if (block != null) {
			sectionAddr = block.getStart();
		}
		map.put(section, sectionAddr);
	}
}
 
Example 7
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);
				}
			}
		}
	}