ghidra.program.model.address.AddressOverflowException Java Examples

The following examples show how to use ghidra.program.model.address.AddressOverflowException. 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: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
protected void setupStringTable() throws AddressOverflowException, CodeUnitInsertionException, DataTypeConflictException
{
   NXOAdapter adapter = this.nxo.getAdapter();
   ElfStringTable stringTable = adapter.getStringTable(this.program);
   
   if (stringTable == null)
       return;
   
   long stringTableAddrOffset = stringTable.getAddressOffset();
    
    Address address = this.aSpace.getAddress(stringTableAddrOffset);
    Address end = address.addNoWrap(stringTable.getLength() - 1);
    
    while (address.compareTo(end) < 0) 
    {
        int length = this.createString(address);
        address = address.addNoWrap(length);
    }
}
 
Example #2
Source File: RELProgramBuilder.java    From Ghidra-GameCube-Loader with Apache License 2.0 6 votes vote down vote up
public RELProgramBuilder(RELHeader rel, ByteProvider provider, Program program,
		TaskMonitor monitor, File originalFile, boolean autoloadMaps, boolean saveRelocations,
		boolean createDefaultMemSections, boolean specifyModuleMemAddrs)
				throws IOException, AddressOverflowException, AddressOutOfBoundsException, MemoryAccessException {
	this.rel = rel;
	this.program = program;
	this.monitor = monitor;
	this.autoloadMaps = autoloadMaps;
	this.saveRelocations = saveRelocations;
	this.specifyModuleMemAddrs = specifyModuleMemAddrs;
	this.binaryName = provider.getName();
	this.symbolInfoList = new ArrayList<Map<Long, SymbolInfo>>();
	
	this.load(provider, originalFile);
	if (createDefaultMemSections) {
		SystemMemorySections.Create(program);
	}
}
 
Example #3
Source File: CreateStringScript.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address findStartOfString(Address endAddr) {
	Address addr = endAddr;
	Address startAddr = endAddr;
	try {
		addr = addr.subtract(1);
		while (isAsciiAndNotTerminator(addr)) {
			startAddr = addr;
			addr = addr.subtractNoWrap(1);
		}
	}
	catch (AddressOverflowException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return startAddr;
}
 
Example #4
Source File: ByteMappingScheme.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate the address within a mapped block for a specified mapped source offset.
 * If the specified mappedSourceOffset corresponds to a non-mapped (i.e., skipped) byte
 * the address returned will correspond to the last mapped byte.  Care must be used
 * when using this method.
 * @param mappedBlock mapped block
 * @param mappedSourceOffset byte offset within mapped source relative to mapped base source address.
 * @param skipBack controls return address when mappedSourceOffset corresponds to a non-mapped/skipped byte.
 * If true the returned address will correspond to the previous mapped address, if false the next mapped
 * address will be returned.
 * @return mapped address within block or null if skipBack is false and unable to map within block limits
 * @throws AddressOverflowException thrown for 1:1 mapping when mappedSourceOffset exceeds length of mappedBlock
 */
Address getMappedAddress(MemoryBlock mappedBlock, long mappedSourceOffset, boolean skipBack)
		throws AddressOverflowException {
	if (mappedSourceOffset < 0) {
		throw new IllegalArgumentException("negative source offset");
	}
	long mappedOffset = mappedSourceOffset;
	if (!isOneToOneMapping()) {
		mappedOffset = (mappedByteCount * (mappedSourceOffset / mappedSourceByteCount));
		long offsetLimit = mappedBlock.getSize() - 1;
		long mod = mappedSourceOffset % mappedSourceByteCount;
		if (mod < mappedByteCount) {
			mappedOffset += mod;
		}
		else if (!skipBack) {
			mappedOffset += mappedByteCount;
			if (mappedOffset > offsetLimit) {
				return null;
			}
		}
	}
	return mappedBlock.getStart().addNoWrap(mappedOffset);
}
 
Example #5
Source File: GameCubeLoader.java    From Ghidra-GameCube-Loader with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean loadProgramInto(ByteProvider provider, LoadSpec loadSpec, List<Option> options,
        MessageLog messageLog, Program program, TaskMonitor monitor) 
        throws IOException {
	
	if (this.binaryType != BinaryType.UNKNOWN) {
 	boolean autoLoadMaps = OptionUtils.getBooleanOptionValue(AUTOLOAD_MAPS_OPTION_NAME, options, true);
 	boolean saveRelocations = OptionUtils.getBooleanOptionValue(ADD_RELOCATIONS_OPTION_NAME, options, false);
 	boolean createDefaultSections = OptionUtils.getBooleanOptionValue(ADD_RESERVED_AND_HARDWAREREGISTERS, options, true);
 	boolean specifyFileMemAddresses = OptionUtils.getBooleanOptionValue(SPECIFY_BINARY_MEM_ADDRESSES, options, false);
 	
     if (this.binaryType == BinaryType.DOL) {
     	new DOLProgramBuilder(dolHeader, provider, program, monitor, autoLoadMaps, createDefaultSections);
     }
     else if (this.binaryType == BinaryType.REL) {
     	try {
     		// We have to check if the source file is compressed & decompress it again if it is.
     		var file = provider.getFile();
     		Yaz0 yaz0 = new Yaz0();
     		if (yaz0.IsValid(provider)) {
     			provider = yaz0.Decompress(provider);
     		}
     		
	new RELProgramBuilder(relHeader, provider, program, monitor, file,
			autoLoadMaps, saveRelocations, createDefaultSections, specifyFileMemAddresses);
} catch (AddressOverflowException | AddressOutOfBoundsException | MemoryAccessException e ) {
	e.printStackTrace();
}
     }
     else {
     	new ApploaderProgramBuilder(apploaderHeader, provider, program, monitor, createDefaultSections);
     }
    	return true;
	}
	return false;
}
 
Example #6
Source File: AssemblyTestCase.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Disassemble an instruction, presumably the result of assembly
 *
 * @param addr the address of the instruction
 * @param ins the instruction bytes
 * @param ctx the input context
 * @return the resulting decoded instruction
 * @throws InsufficientBytesException
 * @throws UnknownInstructionException
 * @throws AddressOverflowException
 * @throws MemoryAccessException
 */
protected PseudoInstruction disassemble(long addr, byte[] ins, byte[] ctx)
		throws InsufficientBytesException, UnknownInstructionException,
		AddressOverflowException, MemoryAccessException {
	Address at = lang.getDefaultSpace().getAddress(addr);
	context.setContextRegister(ctx);
	MemBuffer buf = new ByteMemBufferImpl(at, ins, lang.isBigEndian());
	SleighDebugLogger logger =
		new SleighDebugLogger(buf, context, lang, SleighDebugMode.VERBOSE);
	InstructionPrototype ip = lang.parse(buf, context, false);
	if (VERBOSE_DIS) {
		dbg.println("SleighLog:\n" + logger.toString());
	}
	return new PseudoInstruction(at, ip, buf, context);
}
 
Example #7
Source File: DisassembledViewPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the {@link DisassembledAddressInfo}s for the given address.  
 * This method will disassamble {@link #LOOK_AHEAD_COUNT a few} addresses 
 * after the one that is passed in.
 * 
 * @param  address The address for which an info object will be obtained.
 * @return An array of info objects describing the initial address and any
 *         others that could be obtained.
 */
private DisassembledAddressInfo[] getAddressInformation(Address address) {
	List<DisassembledAddressInfo> infoList = new ArrayList<>();

	if (address != null) {
		try {
			DisassembledAddressInfo addressInfo = new DisassembledAddressInfo(address);

			// Now get some follow-on addresses to provide a small level of 
			// context.  This loop will stop if we cannot find an Address
			// or a CodeUnit for a given address.
			for (int i = 0; (i < LOOK_AHEAD_COUNT) && (address != null) &&
				addressInfo.isValidAddress(); i++) {
				infoList.add(addressInfo);

				// Increment the address for the next code unit preview.
				// This call throws an AddressOverflowException
				address = address.addNoWrap(addressInfo.getCodeUnitLength());

				if (address != null) {
					addressInfo = new DisassembledAddressInfo(address);
				}
			}
		}
		catch (AddressOverflowException aoe) {
			// we don't really care because there is nothing left to show
			// here, as we've reached the end of the address space
		}
	}

	return infoList.toArray(new DisassembledAddressInfo[infoList.size()]);
}
 
Example #8
Source File: RepeatCountDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.program.model.data.DynamicDataType#getAllComponents(ghidra.program.model.mem.MemBuffer)
 */
@Override
protected DataTypeComponent[] getAllComponents(MemBuffer buf) {
	try {
		int n = (buf.getByte(0) & 0xff) * 16 + (buf.getByte(1) & 0xff) + 1;
		DataTypeComponent[] comps = new DataTypeComponent[n];
		comps[0] = new ReadOnlyDataTypeComponent(new WordDataType(), this, 2, 0, 0, "Size", "");
		int countSize = comps[0].getLength();
		int offset = countSize;
		MemoryBufferImpl newBuf = new MemoryBufferImpl(buf.getMemory(), buf.getAddress());
		newBuf.advance(countSize);
		for (int i = 1; i < n; i++) {
			DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(repeatDataType, newBuf);
			if (dti == null) {
				Msg.error(this, "ERROR: problem with data at " + newBuf.getAddress());
				return null;
			}
			int len = dti.getLength();
			comps[i] = new ReadOnlyDataTypeComponent(dti.getDataType(), this, len, i, offset);
			offset += len;
			newBuf.advance(len);
		}
		return comps;

	}
	catch (AddressOverflowException | AddressOutOfBoundsException | MemoryAccessException e) {
		Msg.error(this, "ERROR: problem with data at " + buf.getAddress());
	}
	return null;
}
 
Example #9
Source File: ExpandBlockDownModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @see ghidra.app.plugin.core.memory.ExpandBlockModel#setLength(int)
 */
@Override
   void setLength(long length) {
	message = "";
	this.length = length;
	if (isValidLength()) {
		try {
			endAddr = block.getStart().addNoWrap(length-1);
		} catch(AddressOverflowException e) {
			message = "Expanded block is too large";
		}
	}
	listener.stateChanged(null);	

}
 
Example #10
Source File: StructuredDynamicDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected DataTypeComponent[] getAllComponents(MemBuffer buf) {
	Memory memory = buf.getMemory();

	DataTypeComponent[] comps = new DataTypeComponent[components.size()];
	int offset = 0;
	MemoryBufferImpl newBuf = new MemoryBufferImpl(memory, buf.getAddress());
	try {
		for (int i = 0; i < components.size(); i++) {
			DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(components.get(i), newBuf);
			if (dti == null) {
				Msg.error(this, "Invalid data at " + newBuf.getAddress());
				return null;
			}
			int len = dti.getLength();
			comps[i] =
				new ReadOnlyDataTypeComponent(dti.getDataType(), this, len, i, offset,
					componentNames.get(i) + "_" + newBuf.getAddress(), componentDescs.get(i));
			offset += len;
			newBuf.advance(len);
		}
	}
	catch (AddressOverflowException e) {
		Msg.error(this, "Invalid data at " + newBuf.getAddress());
		return null;
	}
	return comps;
}
 
Example #11
Source File: PostCommentFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Get the code unit immediately following the
 * specified code unit.
 * @param cu code unit
 * @return the next code unit or null if not found.
 */
private CodeUnit getNextCodeUnit(CodeUnit cu) {
	CodeUnit next = null;
	try {
		Address nextAddr = cu.getMaxAddress().addNoWrap(1);
		if (nextAddr != null) {
			next = cu.getProgram().getListing().getCodeUnitAt(nextAddr);
		}
		return next;
	}
	catch (AddressOverflowException e) {
		// don't care
	}
	return null;
}
 
Example #12
Source File: MemoryMapDBAdapterV2.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
MemoryBlockDB createBlock(MemoryBlockType blockType, String name, Address startAddr,
		long length, Address mappedAddress, boolean initializeBytes, int permissions,
		int mappingScheme)
		throws AddressOverflowException, IOException {
	throw new UnsupportedOperationException();
}
 
Example #13
Source File: MemoryBlockUtils.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private static MemoryBlock createBlockNoDuplicateName(Program program, String blockName,
		Address start, FileBytes fileBytes, long offset, long length)
		throws LockException, MemoryConflictException, AddressOverflowException {
	int count = 1;
	String name = blockName;
	while (true) {
		try {
			return program.getMemory().createInitializedBlock(name, start, fileBytes, offset,
				length, true);
		}
		catch (DuplicateNameException e) {
			name = blockName + "_" + count++;
		}
	}
}
 
Example #14
Source File: AddByteMappedMemoryBlockCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected MemoryBlock createMemoryBlock(Memory memory)
		throws LockException, MemoryConflictException, AddressOverflowException,
		IllegalArgumentException, DuplicateNameException {
	return memory.createByteMappedBlock(name, start, mappedAddress, length,
		byteMappingScheme,
		isOverlay);
}
 
Example #15
Source File: ByteMappingScheme.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Write an array of bytes to memory utilizing this mapping scheme.  
 * @param memory program memory
 * @param mappedSourceBaseAddress base source memory address for byte-mapped subblock
 * @param offsetInSubBlock byte offset from start of subblock where writing should begin
 * @param b an array to get bytes from
 * @param off start source index within byte array b where bytes should be read
 * @param len number of bytes to be written
 * @throws MemoryAccessException if write of uninitialized or non-existing memory occurs
 * @throws AddressOverflowException if address computation error occurs
 */
void setBytes(Memory memory, Address mappedSourceBaseAddress, long offsetInSubBlock,
		byte[] b,
		int off, int len) throws MemoryAccessException, AddressOverflowException {

	if (isOneToOneMapping()) {
		memory.setBytes(mappedSourceBaseAddress.addNoWrap(offsetInSubBlock), b, off, len);
		return;
	}

	long patternCount = offsetInSubBlock / mappedByteCount;
	int partialByteCount = (int) (offsetInSubBlock % mappedByteCount);
	long mappedOffset = (mappedSourceByteCount * patternCount) + partialByteCount;

	Address destAddr = mappedSourceBaseAddress.addNoWrap(mappedOffset);

	int index = off;
	int cnt = 0;
	int i = mappedByteCount - partialByteCount;
	while (cnt < len) {
		memory.setBytes(destAddr, b, index, i);
		index += i;
		cnt += i;
		destAddr = destAddr.addNoWrap(i + nonMappedByteCount);
		i = mappedByteCount;
	}
}
 
Example #16
Source File: ByteMappingScheme.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the mapped source address for a specified offset with the mapped sub-block.
 * @param mappedSourceBaseAddress mapped source base address for sub-block
 * @param offsetInSubBlock byte offset within sub-block to be mapped into source
 * @return mapped source address
 * @throws AddressOverflowException if offset in sub-block produces a wrap condition in
 * the mapped source address space.
 */
public Address getMappedSourceAddress(Address mappedSourceBaseAddress,
		long offsetInSubBlock)
		throws AddressOverflowException {
	if (offsetInSubBlock < 0) {
		throw new IllegalArgumentException("negative offset");
	}
	long sourceOffset = offsetInSubBlock;
	if (!isOneToOneMapping()) {
		sourceOffset = (mappedSourceByteCount * (offsetInSubBlock / mappedByteCount)) +
			(offsetInSubBlock % mappedByteCount);
	}
	return mappedSourceBaseAddress.addNoWrap(sourceOffset);
}
 
Example #17
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
protected void createGlobalOffsetTable() throws AddressOverflowException, AddressOutOfBoundsException, IOException
{
    NXOAdapter adapter = this.nxo.getAdapter();
    ByteProvider memoryProvider = adapter.getMemoryProvider();
    
    // .got.plt needs to have been created first
    long gotStartOff = adapter.getGotOffset() - this.nxo.getBaseAddress();
    long gotSize = adapter.getGotSize();
    
    if (gotSize > 0)
    {
        Msg.info(this, String.format("Created got from 0x%X to 0x%X", gotStartOff, gotStartOff + gotSize));
        this.memBlockHelper.addSection(".got", gotStartOff, gotStartOff, gotSize, true, false, false);
    }
}
 
Example #18
Source File: MemoryEvent.java    From gdbghidra with MIT License 5 votes vote down vote up
public static void handleEvent(MemoryEvent memEvent, Program currentProgram)  {
	MemoryConflictHandler memoryConflictHandler = MemoryConflictHandler.ALWAYS_OVERWRITE;
	MemoryBlockUtil mbu = new MemoryBlockUtil( currentProgram, memoryConflictHandler );
	try {
		var tx = currentProgram.startTransaction("adding memory");
		
		
		var r = mbu.createInitializedBlock(
				memEvent.getName(), 
				memEvent.getAddress(currentProgram), 
				memEvent.getData(), 
				memEvent.getDataSize(), 
				"", // comment?
				"gdb", 
				memEvent.getReadPermission(), 
				memEvent.getWritePermission(), 
				memEvent.getExecutePermission(), 
				TaskMonitor.DUMMY);
		if(r == null) {
			var msg = mbu.getMessages();
			if(msg.contains("Overwrote memory")) {
				System.out.println("[GDBGhidra] "+ mbu.getMessages());
			} else {
				System.err.println("[GDBGhidra] could not write new memory block: "+ mbu.getMessages());
			}
		} else {
			System.out.println("[GDBGhidra]" + r.toString());
		}
		
		currentProgram.endTransaction(tx, true);
	} catch (AddressOverflowException e) {
		e.printStackTrace();
	}
}
 
Example #19
Source File: MemoryBlockDefinition.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public void createBlock(Program program) throws LockException, MemoryConflictException,
		AddressOverflowException, DuplicateNameException {
	if (blockName == null || addressString == null || length <= 0) {
		return;
	}

	Memory mem = program.getMemory();
	Address addr = XmlProgramUtilities.parseAddress(program.getAddressFactory(), addressString);

	MemoryBlock block;
	if (bitMappedAddress != null) {
		Address mappedAddr =
			XmlProgramUtilities.parseAddress(program.getAddressFactory(), bitMappedAddress);
		block = mem.createBitMappedBlock(blockName, addr, mappedAddr, length, false);
	}
	else if (initialized) {
		try {
			block =
				mem.createInitializedBlock(blockName, addr, length, (byte) 0,
					TaskMonitor.DUMMY, false);
		}
		catch (CancelledException e) {
			throw new AssertException(e); // unexpected
		}
	}
	else {
		block = mem.createUninitializedBlock(blockName, addr, length, false);
	}
	block.setRead(readPermission);
	block.setWrite(writePermission);
	block.setExecute(executePermission);
	block.setVolatile(volatilePermission);
}
 
Example #20
Source File: CodeUnitTableCellData.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private CodeUnit getCodeUnitBefore(CodeUnit cu) {
	if (cu != null) {
		try {
			return getCodeUnitContaining(cu.getMinAddress().subtractNoWrap(1));
		}
		catch (AddressOverflowException e) {
			// don't care; we really want null in this case
		}
	}
	return null;
}
 
Example #21
Source File: CodeUnitTableCellData.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private CodeUnit getCodeUnitAfter(CodeUnit cu) {
	if (cu != null) {
		try {
			return getCodeUnitContaining(cu.getMaxAddress().addNoWrap(1));
		}
		catch (AddressOverflowException e) {
			// don't care; we really want null in this case
		}
	}
	return null;
}
 
Example #22
Source File: PseudoDataComponent.java    From ghidra with Apache License 2.0 5 votes vote down vote up
PseudoDataComponent(Program program, Address address, PseudoData parent, DataType dt,
		int ordinal, int offset, int length, MemBuffer memBuffer)
		throws AddressOverflowException {
	super(program, address, dt, new WrappedMemBuffer(memBuffer, offset));
	this.indexInParent = ordinal;
	this.parent = parent;
	this.offset = offset;
	this.level = parent.level + 1;
	this.length = length;
}
 
Example #23
Source File: PseudoDataComponent.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @throws AddressOverflowException 
 * @throws MemoryAccessException 
 * 
 */
PseudoDataComponent(Program program, Address address, PseudoData parent,
		DataTypeComponent component, MemBuffer memBuffer)
				throws AddressOverflowException, MemoryAccessException {
	super(program, address, component.getDataType(), new WrappedMemBuffer(memBuffer,
		component.getOffset()));
	this.indexInParent = component.getOrdinal();
	this.parent = parent;
	this.component = component;
	this.level = parent.level + 1;
	this.offset = component.getOffset();
	this.length = component.getLength();
}
 
Example #24
Source File: CreateStringScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {

	Address addr = find(null, TERMINATOR);
	while (addr != null) {
		createString(addr);
		try {
			addr = addr.addNoWrap(1);
			addr = find(addr, TERMINATOR);
		}
		catch (AddressOverflowException e) {
			// must be at largest possible address - so we are done
		}
	}
}
 
Example #25
Source File: PseudoData.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PseudoData(Program program, Address address, DataType dataType, MemBuffer memBuffer)
		throws AddressOverflowException {
	super(program, address, computeLength(dataType, address), memBuffer);
	if (dataType == null) {
		dataType = DataType.DEFAULT;
	}
	this.dataType = dataType;
	baseDataType = getBaseDataType(dataType);
	if (program instanceof ProgramDB) {
		dataMgr = ((ProgramDB) program).getDataTypeManager();
	}
}
 
Example #26
Source File: RepeatedDynamicDataType.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * @see ghidra.program.model.data.DynamicDataType#getAllComponents(ghidra.program.model.mem.MemBuffer)
 */
@Override
protected DataTypeComponent[] getAllComponents(MemBuffer buf) {
	Memory memory = buf.getMemory();
	ArrayList<DataTypeComponent> compList = new ArrayList<DataTypeComponent>();

	ReadOnlyDataTypeComponent comp;
	int countSize = 0;
	int ordinal = 0;
	if (header != null) {
		comp =
			new ReadOnlyDataTypeComponent(header, this, header.getLength(), ordinal, 0,
				header.getName() + "_" + buf.getAddress(), "");
		compList.add(ordinal++, comp);
		countSize = comp.getLength();
	}
	int offset = countSize;
	MemoryBufferImpl newBuf = new MemoryBufferImpl(memory, buf.getAddress());
	try {
		newBuf.advance(countSize);
		while (moreComponents(memory, newBuf.getAddress())) {
			DataTypeInstance dti = DataTypeInstance.getDataTypeInstance(baseStruct, newBuf);
			if (dti == null) {
				Msg.error(this, "ERROR: problem with data at " + newBuf.getAddress());
				return null;
			}
			int len = dti.getLength();
			comp =
				new ReadOnlyDataTypeComponent(dti.getDataType(), this, len, ordinal, offset,
					baseStruct.getName() + "_" + newBuf.getAddress(), "");
			compList.add(ordinal, comp);
			offset += len;
			newBuf.advance(len);
			ordinal++;
		}
	}
	catch (AddressOverflowException e) {
		Msg.error(this, "ERROR: problem with data at " + newBuf.getAddress());
		return null;
	}

	DataTypeComponent[] comps = new DataTypeComponent[compList.size()];
	for (int i = 0; i < compList.size(); i++) {
		comps[i] = compList.get(i);
	}
	return comps;
}
 
Example #27
Source File: AddUninitializedMemoryBlockCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected MemoryBlock createMemoryBlock(Memory memory) throws LockException,
		MemoryConflictException, AddressOverflowException, DuplicateNameException {
	return memory.createUninitializedBlock(name, start, length, isOverlay);
}
 
Example #28
Source File: OmfLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options,
		Program program, TaskMonitor monitor, MessageLog log)
		throws IOException, CancelledException {

	OmfFileHeader header = null;
	BinaryReader reader = OmfFileHeader.createReader(provider);
	try {
		header = OmfFileHeader.parse(reader, monitor);
		header.resolveNames();
		header.sortSegmentDataBlocks();
		OmfFileHeader.doLinking(IMAGE_BASE, header.getSegments(), header.getGroups());
	}
	catch (OmfException ex) {
		if (header == null) {
			throw new IOException("OMF File header was corrupted");
		}
		log.appendMsg("File was corrupted - leaving partial program " + provider.getName());
	}

	// We don't use the file bytes to create block because the bytes are manipulated before
	// forming the block.  Creating the FileBytes anyway in case later we want access to all
	// the original bytes.
	MemoryBlockUtils.createFileBytes(program, provider, monitor);

	int id = program.startTransaction("loading program from OMF");
	boolean success = false;
	try {
		processSegmentHeaders(reader, header, program, monitor, log);
		processExternalSymbols(header, program, monitor, log);
		processPublicSymbols(header, program, monitor, log);
		processRelocations(header, program, monitor, log);
		success = true;
	}
	catch (AddressOverflowException e) {
		throw new IOException(e);
	}
	finally {
		program.endTransaction(id, success);
	}
}
 
Example #29
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);
				}
			}
		}
	}
 
Example #30
Source File: AbstractAddMemoryBlockCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected abstract MemoryBlock createMemoryBlock(Memory memory)
throws LockException, MemoryConflictException, AddressOverflowException,
DuplicateNameException, CancelledException;