ghidra.program.model.address.AddressOutOfBoundsException Java Examples

The following examples show how to use ghidra.program.model.address.AddressOutOfBoundsException. 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: DebugFrameSection.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Analyzes and annotates the debug frame section.
 * @return the region descriptors that compose the debug frame section.
 * @throws MemoryAccessException if memory couldn't be read/written while processing the section.
 * @throws AddressOutOfBoundsException if one or more expected addresses weren't in the program.
 * @throws ExceptionHandlerFrameException if the FDE table can't be decoded.
 */
public List<RegionDescriptor> analyze() throws MemoryAccessException,
		AddressOutOfBoundsException, ExceptionHandlerFrameException, CancelledException {

	List<RegionDescriptor> descriptors = new ArrayList<>();

	MemoryBlock[] blocks = program.getMemory().getBlocks();

	int blockCount = blocks.length;
	monitor.setMaximum(blockCount);

	for (MemoryBlock block : blocks) {
		monitor.checkCanceled();
		monitor.incrementProgress(1);
		if (block.getName().startsWith(DEBUG_FRAME_BLOCK_NAME)) {
			descriptors.addAll(analyzeSection(block));
		}
	}

	return Collections.unmodifiableList(descriptors);

}
 
Example #3
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 #4
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
protected void tryCreateDynBlock(String name, ElfDynamicType offsetType, ElfDynamicType sizeType)
{
    NXOAdapter adapter = this.nxo.getAdapter();
    
    try
    {
        if (adapter.getDynamicTable(this.program).containsDynamicValue(offsetType) && adapter.getDynamicTable(this.program).containsDynamicValue(sizeType))
        {
            long offset = adapter.getDynamicTable(this.program).getDynamicValue(offsetType);
            long size = adapter.getDynamicTable(this.program).getDynamicValue(sizeType);
            
            if (size > 0)
            {
                Msg.info(this, String.format("Created dyn block %s at 0x%X of size 0x%X", name, offset, size));
                this.memBlockHelper.addSection(name, offset, offset, size, true, false, false);
            }
        }
    }
    catch (NotFoundException | AddressOutOfBoundsException e)
    {
        Msg.warn(this, String.format("Couldn't create dyn block %s. It may be absent.", name), e);
    }
}
 
Example #5
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
protected void tryCreateDynBlockWithRange(String name, ElfDynamicType start, ElfDynamicType end)
{
    NXOAdapter adapter = this.nxo.getAdapter();
    
    try
    {
        if (adapter.getDynamicTable(this.program).containsDynamicValue(start) && adapter.getDynamicTable(this.program).containsDynamicValue(end))
        {
            long offset = adapter.getDynamicTable(this.program).getDynamicValue(start);
            long size = adapter.getDynamicTable(this.program).getDynamicValue(end) - offset;
            
            if (size > 0)
            {
                Msg.info(this, String.format("Created dyn block %s at 0x%X of size 0x%X", name, offset, size));
                this.memBlockHelper.addSection(name, offset, offset, size, true, false, false);
            }
        }
    }
    catch (NotFoundException | AddressOutOfBoundsException e)
    {
        Msg.warn(this, String.format("Couldn't create dyn block %s. It may be absent.", name), e);
    }
}
 
Example #6
Source File: RTTI2DataType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private long getNumEntries(Program program, Address startAddress,
		DataValidationOptions validationOptions) {

	Memory memory = program.getMemory();
	Address addr = startAddress;
	int ordinal = 0;
	for (; addr != null && validRefData(memory, addr); ordinal++) {

		// Each component is either a direct reference or an image base offset.
		Address rtti1Address = getReferencedAddress(program, addr);
		if (rtti1Address == null || !rtti1.isValid(program, rtti1Address, validationOptions)) {
			return ordinal;
		}

		try {
			addr = addr.add(ENTRY_SIZE); // Add the data type size.
		}
		catch (AddressOutOfBoundsException e) {
			return ordinal + 1; // Ordinal hasn't been incremented yet.
		}
	}

	return ordinal;
}
 
Example #7
Source File: CodeUnitDB.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public int getBytes(byte[] b, int offset) {
	lock.acquire();
	try {
		checkIsValid();
		populateByteArray();
		if (offset < 0 || (offset + b.length) > bytes.length) {
			return program.getMemory().getBytes(address.add(offset), b);
		}
		System.arraycopy(bytes, offset, b, 0, b.length);
		return b.length;
	}
	catch (AddressOutOfBoundsException | MemoryAccessException e) {
		return 0;
	}
	finally {
		lock.release();
	}
}
 
Example #8
Source File: CodeUnitDB.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public byte getByte(int offset) throws MemoryAccessException {
	lock.acquire();
	try {
		checkIsValid();
		populateByteArray();
		if (offset < 0 || offset >= bytes.length) {
			try {
				return program.getMemory().getByte(address.add(offset));
			}
			catch (AddressOutOfBoundsException e) {
				throw new MemoryAccessException(e.getMessage());
			}
		}
		return bytes[offset];
	}
	finally {
		lock.release();
	}
}
 
Example #9
Source File: StringDataInstance.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private int getNullTerminatedLength() {
	int localLen = length;
	boolean localNT = stringLayout.isNullTerminated();
	if (isProbe() || stringLayout == StringLayoutEnum.NULL_TERMINATED_UNBOUNDED) {
		localLen = MAX_STRING_LENGTH;
		localNT = true;
	}

	int internalCharOffset = buf.isBigEndian() ? paddedCharSize - charSize : 0;
	byte[] charBuf = new byte[charSize];
	for (int offset = 0; offset < localLen; offset += paddedCharSize) {
		try {
			if (!readChar(charBuf, offset + internalCharOffset)) {
				break;
			}
			if (localNT && isNullChar(charBuf)) {
				return offset + paddedCharSize;
			}
		}
		catch (AddressOutOfBoundsException exc) {
			return (stringLayout == StringLayoutEnum.NULL_TERMINATED_UNBOUNDED) ? -1 : offset;
		}
	}

	return (stringLayout == StringLayoutEnum.NULL_TERMINATED_UNBOUNDED) ? -1 : length;
}
 
Example #10
Source File: SegmentedCodePointerDataType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)
 */
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	Address addr = buf.getAddress();
	try {
		long segment = buf.getShort(0) & 0xffff;
		long offset = buf.getShort(2) & 0xffff;
		long addrValue = segment << 16 | offset;
		return addr.getNewAddress(addrValue, true);
	}
	catch (AddressOutOfBoundsException | MemoryAccessException ex) {
		// Do nothing... Tried to form an address that was not readable or
		// writeable.
	}
	return null;
}
 
Example #11
Source File: Rtti2Model.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void validateAllRtti1RefEntries(Program program, Address startAddress, long numEntries,
		boolean validateReferredToData) throws InvalidDataTypeException {

	Memory memory = program.getMemory();
	Address addr = startAddress;
	for (int ordinal = 0; ordinal < numEntries && addr != null &&
		validRefData(memory, addr); ordinal++) {

		validateRtti1ReferenceEntry(program, validateReferredToData, addr);

		try {
			addr = addr.add(entrySize); // Add the data type size.
		}
		catch (AddressOutOfBoundsException e) {
			if (ordinal < (numEntries - 1)) {
				invalid();
			}
			break;
		}
	}
}
 
Example #12
Source File: ExceptionHandlerFrameHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Method that creates an Exception Handler Frame Header Structure
 * at the address specified by 'addr'. If addr is 'null', this method returns without creating
 * the structure.
 * 
 * @param addr - Address at which the Exception Handler Frame Header Structure should be created.
 * @throws AddressOutOfBoundsException if the memory needed for this frame header isn't in the program.
 * @throws MemoryAccessException if the memory needed for this frame header isn't in the program.
 */
public void create(Address addr) throws MemoryAccessException, AddressOutOfBoundsException {
	CreateStructureCmd dataCmd = null;
	
	if (addr == null || monitor.isCancelled()) {
		return;
	}
	
	/* Create a new structure at the start of the .eh_frame_hdr section */
	dataCmd = new CreateStructureCmd( ehFrameHdrStruct, addr );
	dataCmd.applyTo(prog);
	
	/* Set a comment on the newly created structure */
	SetCommentCmd commentCmd = new SetCommentCmd(addr, CodeUnit.PLATE_COMMENT, "Exception Handler Frame Header");
	commentCmd.applyTo(prog);
	
	// Set the class members accordingly
	eh_version = prog.getMemory().getByte(addr) & 0xFF;
	eh_FramePtrEncoding = prog.getMemory().getByte(addr.add(1)) & 0xFF;
	eh_FrameDescEntryCntEncoding = prog.getMemory().getByte(addr.add(2)) & 0xFF;
	eh_FrameTableEncoding = prog.getMemory().getByte(addr.add(3)) & 0xFF;
}
 
Example #13
Source File: PcRelative31AddressDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		int ptr = buf.getInt(0) & 0xFFFFFFFF;
		ptr |= 0x80000000;
		int offset = (ptr << 1) >> 1;
		return buf.getAddress().add(offset);
	}
	catch (MemoryAccessException | AddressOutOfBoundsException mae) {
		return null;
	}
}
 
Example #14
Source File: Rtti2Model.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private int getNumEntries(Program program, Address rtti2Address) {

		Memory memory = program.getMemory();
		Address addr = rtti2Address;
		boolean shouldValidateReferredToData = validationOptions.shouldValidateReferredToData();
		int ordinal = 0;
		for (; addr != null && validRefData(memory, addr); ordinal++) {

			// Each component is either a direct reference or an image base offset.
			Address rtti1Address = getReferencedAddress(program, addr);
			if (rtti1Address == null) {
				return ordinal; // It has reached the end.
			}
			Rtti1Model rtti1Model = new Rtti1Model(program, rtti1Address, validationOptions);
			if (shouldValidateReferredToData) {
				try {
					rtti1Model.validate();
				}
				catch (InvalidDataTypeException e1) {
					return ordinal; // It has reached the end.
				}
			}
			else if (!rtti1Model.isLoadedAndInitializedAddress()) {
				return ordinal;
			}

			try {
				addr = addr.add(entrySize); // Add the data type size.
			}
			catch (AddressOutOfBoundsException e) {
				return ordinal + 1; // Ordinal hasn't been incremented yet.
			}
		}

		return ordinal;
	}
 
Example #15
Source File: EhFrameSection.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Analyzes and annotates the eh frame section.
 * 
 * @param fdeTableCount the number of exception handler FDEs.
 * @return the region descriptors for the eh frame section.
 * @throws MemoryAccessException if memory couldn't be read/written while processing the eh frame.
 * @throws AddressOutOfBoundsException if one or more expected addresses weren't in the program.
 * @throws ExceptionHandlerFrameException if a problem was encountered determining eh frame data.
 */
public List<RegionDescriptor> analyze(int fdeTableCount)
		throws MemoryAccessException, AddressOutOfBoundsException, ExceptionHandlerFrameException {

	MemoryBlock memBlock = program.getMemory().getBlock(EH_FRAME_BLOCK_NAME);

	if (memBlock != null && !monitor.isCancelled()) {
		return Collections.unmodifiableList(analyzeSection(memBlock));
	}

	return new ArrayList<RegionDescriptor>();
}
 
Example #16
Source File: EhFrameHeaderSection.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Analyzes and annotates the eh frame header.
 * @param monitor a status monitor for indicating progress or allowing a task to be cancelled.
 * @return the number of records in the FDE table or 0 if there was no EH frame header to analyze.
 * @throws MemoryAccessException if memory couldn't be read/written while processing the header.
 * @throws AddressOutOfBoundsException if one or more expected addresses weren't in the program.
 * @throws ExceptionHandlerFrameException if the FDE table can't be decoded.
 */
public int analyze(TaskMonitor monitor) throws MemoryAccessException,
		AddressOutOfBoundsException, ExceptionHandlerFrameException {

	MemoryBlock memBlock = program.getMemory().getBlock(EH_FRAME_HEADER_BLOCK_NAME);

	if (memBlock != null && !monitor.isCancelled()) {
		return analyzeSection(memBlock, monitor);
	}
	return 0;
}
 
Example #17
Source File: EhFrameHeaderSection.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private int analyzeSection(MemoryBlock curMemBlock, TaskMonitor monitor)
		throws MemoryAccessException, AddressOutOfBoundsException,
		ExceptionHandlerFrameException {

	monitor.setMessage("Analyzing .eh_frame_hdr section");

	ProgramLocation loc = new ProgramLocation(program, curMemBlock.getStart());
	Address curAddress = loc.getAddress();

	ExceptionHandlerFrameHeader eh_frame_hdr =
		new ExceptionHandlerFrameHeader(monitor, program);
	eh_frame_hdr.addToDataTypeManager();
	eh_frame_hdr.create(curAddress);

	curAddress = curAddress.add(eh_frame_hdr.getLength());

	// NOTE: The process... method calls that follow are order dependent.
	//       Each one is passed the address of the field it will process and 
	//       returns the next address after that field, which will then be 
	//       used by the next field's process method.

	curAddress = processEncodedFramePointer(curAddress, eh_frame_hdr, curMemBlock);

	DwarfEHDecoder fdeCountDecoder = getFdeCountDecoder(eh_frame_hdr);
	Address fdeCountAddress = curAddress;

	curAddress = processEncodedFdeCount(fdeCountAddress, fdeCountDecoder);

	int fdeTableCnt = getFdeTableCount(fdeCountAddress, curMemBlock, fdeCountDecoder);
	if (fdeTableCnt > 0) {
		createFdeTable(curAddress, eh_frame_hdr, fdeTableCnt, monitor);
	}
	return fdeTableCnt;
}
 
Example #18
Source File: Cie.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
	 * Creates the initial set of Call Frame instructions. The
	 * number of instructions is determined by the remaining space in the CIE
	 * record.
	 * 
	 * @param addr Address at which the initial instructions array should be created.
	 * @return Address immediately following the initial instructions array
	 * @throws MemoryAccessException if memory for the CIE couldn't be read.
	 */
	private Address processInitialInstructions(Address addr) throws MemoryAccessException {
		CreateArrayCmd arrayCmd = null;

		// Create initial instructions array with remaining bytes
		initialInstructionCount = intLength - curSize;
		arrayCmd = new CreateArrayCmd(addr, initialInstructionCount, new ByteDataType(), BYTE_LEN);
		arrayCmd.applyTo(program);
		SetCommentCmd.createComment(program, addr, "(CIE) Initial Instructions",
			CodeUnit.EOL_COMMENT);

		initialInstructions = new byte[initialInstructionCount];
		int numBytesRead = program.getMemory().getBytes(addr, initialInstructions);

		// *** The following commented out code is for debugging purposes. ***
//		DwarfCallFrameOpcodeParser parser =
//			new DwarfCallFrameOpcodeParser(program, addr, numBytesRead);
//		parser.parse();

		curSize += numBytesRead;

		try {
			return addr.add(numBytesRead);
		}
		catch (AddressOutOfBoundsException e) {
			return null; // reached end of block
		}
	}
 
Example #19
Source File: VarnodeLocationCellEditor.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean stopCellEditing() {
	switch (type) {
		case Register:
			Object selectedObj = combo.getSelectedItem();
			if (selectedObj instanceof String) {
				if (program.getRegister((String) selectedObj) == null) {
					Msg.showError(this, editorComponent, "Invalid Register",
						"Register does not exist: " + selectedObj);
					return false;
				}
			}
			break;

		case Stack:
			BigInteger value = offsetInput.getValue();
			if (value != null) {
				try {
					program.getAddressFactory().getStackSpace().getAddress(value.longValue());
				}
				catch (AddressOutOfBoundsException e) {
					Msg.showError(this, editorComponent, "Invalid Stack Offset",
						"Invalid stack offset: " + offsetInput.getText());
					return false;
				}
			}
			break;

		default:
	}
	fireEditingStopped();
	return true;
}
 
Example #20
Source File: ApploaderProgramBuilder.java    From Ghidra-GameCube-Loader with Apache License 2.0 5 votes vote down vote up
public ApploaderProgramBuilder(ApploaderHeader header, ByteProvider provider, Program program,
		TaskMonitor monitor, boolean createSystemMemSections)
				throws AddressOutOfBoundsException {
	this.header = header;
	
	this.program = program;
	this.monitor = monitor;
	
	this.load(provider);
	if (createSystemMemSections) {
		SystemMemorySections.Create(program);
	}
}
 
Example #21
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 #22
Source File: EHDataTypeUtilities.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private static Address getComponentAddress(DataTypeComponent comp, MemBuffer memBuffer) {
	int offset = comp.getOffset();
	Address minAddress = memBuffer.getAddress();
	try {
		return minAddress.add(offset);
	}
	catch (AddressOutOfBoundsException e) {
		throw new IllegalArgumentException("Can't get component " + comp.getOrdinal() +
			" from memory buffer for data type " + comp.getParent().getName() + ".", e);
	}
}
 
Example #23
Source File: MultiProgramMemoryByteProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidIndex( long index ) {
	for ( int i = 0 ; i < programs.length ; ++i ) {
		try {
			Address indexAddress = baseAddresses[ i ].add( index );
			return programs[ i ].getMemory( ).contains( indexAddress );
		}
		catch (AddressOutOfBoundsException e) {
		}
	}
	return false;
}
 
Example #24
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 #25
Source File: HighFunction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected Address getPCAddress(Varnode rep) {
	Address pcaddr = null;
	if (!rep.isAddrTied()) {
		pcaddr = rep.getPCAddress();
		if (pcaddr == Address.NO_ADDRESS) {
			try {
				pcaddr = func.getEntryPoint().add(-1);
			}
			catch (AddressOutOfBoundsException e) {
				pcaddr = func.getEntryPoint();
			}
		}
	}
	return pcaddr;
}
 
Example #26
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 #27
Source File: AbstractImageBaseOffsetDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	DataType dt = getScalarDataType();
	Address imageBase = buf.getMemory().getProgram().getImageBase();
	Scalar value = (Scalar) dt.getValue(buf, settings, length);
	if (value != null && value.getUnsignedValue() != 0) {
		try {
			return imageBase.add(value.getUnsignedValue());
		}
		catch (AddressOutOfBoundsException e) {
			// ignore
		}
	}
	return null;
}
 
Example #28
Source File: VfTableModel.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void validateModelSpecificInfo() throws InvalidDataTypeException {

	Program program = getProgram();
	Address startAddress = getAddress();

	// Get the model from the meta pointer.
	Address metaAddress = getMetaAddress();
	Address rtti4Address = getAbsoluteAddress(program, metaAddress);
	rtti4Model = new Rtti4Model(program, rtti4Address, validationOptions);

	// Get the table
	DataType individualEntryDataType = new PointerDataType(program.getDataTypeManager());
	long entrySize = individualEntryDataType.getLength();

	// Each entry is a pointer to where a function can possibly be created.
	long numEntries = getCount();
	if (numEntries == 0) {
		throw new InvalidDataTypeException(
			getName() + " data type at " + getAddress() + " doesn't have a valid vf table.");
	}

	Address vfTableFieldAddress = startAddress;
	for (int ordinal = 0; ordinal < numEntries && vfTableFieldAddress != null; ordinal++) {

		// Each component is a pointer (to a function).
		Address functionAddress = getAbsoluteAddress(program, vfTableFieldAddress);
		if (functionAddress == null) {
			throw new InvalidDataTypeException(
				getName() + " at " + getAddress() + " doesn't refer to a valid function.");
		}

		try {
			vfTableFieldAddress = vfTableFieldAddress.add(entrySize); // Add the data type size.
		}
		catch (AddressOutOfBoundsException e) {
			if (ordinal < (numEntries - 1)) {
				throw new InvalidDataTypeException(
					getName() + " at " + getAddress() + " isn't valid.");
			}
			break;
		}
	}
}
 
Example #29
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 #30
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 4 votes vote down vote up
protected void setupRelocations() throws AddressOverflowException, AddressOutOfBoundsException, IOException, NotFoundException, CodeUnitInsertionException, DataTypeConflictException
{
    NXOAdapter adapter = this.nxo.getAdapter();
    ByteProvider memoryProvider = adapter.getMemoryProvider();
    BinaryReader memoryReader = adapter.getMemoryReader();
    ImmutableList<NXRelocation> pltRelocs = adapter.getPltRelocations(this.program);
    
    if (pltRelocs.isEmpty())
    {
        Msg.info(this, "No plt relocations found.");
        return;
    }
        
    long pltGotStart = pltRelocs.get(0).offset;
    long pltGotEnd = pltRelocs.get(pltRelocs.size() - 1).offset + adapter.getOffsetSize();
    
    if (adapter.getDynamicTable(this.program).containsDynamicValue(ElfDynamicType.DT_PLTGOT))
    {
        long pltGotOff = adapter.getDynamicTable(this.program).getDynamicValue(ElfDynamicType.DT_PLTGOT);
        this.memBlockHelper.addSection(".got.plt", pltGotOff, pltGotOff, pltGotEnd - pltGotOff, true, false, false);
    }
    
    // Only add .plt on aarch64
    if (adapter.isAarch32())
    {
        return;
    }
    
    int last = 12;
    
    while (true)
    {
        int pos = -1;
        
        for (int i = last; i < adapter.getSection(NXOSectionType.TEXT).getSize(); i++)
        {
            if (memoryReader.readInt(i) == 0xD61F0220)
            {
                pos = i;
                break;
            }
        }
        
        if (pos == -1) break;
        last = pos + 1;
        if ((pos % 4) != 0) continue;
        
        int off = pos - 12;
        long a = Integer.toUnsignedLong(memoryReader.readInt(off));
        long b = Integer.toUnsignedLong(memoryReader.readInt(off + 4));
        long c = Integer.toUnsignedLong(memoryReader.readInt(off + 8));
        long d = Integer.toUnsignedLong(memoryReader.readInt(off + 12));

        if (d == 0xD61F0220L && (a & 0x9f00001fL) == 0x90000010L && (b & 0xffe003ffL) == 0xf9400211L)
        {
            long base = off & ~0xFFFL;
            long immhi = (a >> 5) & 0x7ffffL;
            long immlo = (a >> 29) & 3;
            long paddr = base + ((immlo << 12) | (immhi << 14));
            long poff = ((b >> 10) & 0xfffL) << 3;
            long target = paddr + poff;
            if (pltGotStart <= target && target < pltGotEnd)
                this.pltEntries.add(new PltEntry(off, target));
        }
    }
    
    long pltStart = this.pltEntries.get(0).off;
    long pltEnd = this.pltEntries.get(this.pltEntries.size() - 1).off + 0x10;
    this.memBlockHelper.addSection(".plt", pltStart, pltStart, pltEnd - pltStart, true, false, false);
}