Java Code Examples for ghidra.app.util.bin.BinaryReader#setPointerIndex()

The following examples show how to use ghidra.app.util.bin.BinaryReader#setPointerIndex() . 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: NewExt4Analyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canAnalyze( Program program ) {
	ByteProvider provider = new MemoryByteProvider( program.getMemory( ), program.getAddressFactory( ).getDefaultAddressSpace( ) );
	BinaryReader reader = new BinaryReader( provider, true );
	int start = getSuperBlockStart( reader );
	if ( start == -1 ) {
		return false;
	}

	reader.setPointerIndex( start + 0x38 );

	int magic = -1;
	try {
		magic = reader.readNextShort( ) & 0xffff;
	}
	catch ( IOException e ) {
		// ignore
	}
	return magic == Ext4Constants.SUPER_BLOCK_MAGIC;
}
 
Example 2
Source File: ResourceTypeFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public final static Object getResourceObject(BinaryReader reader, ResourceHeader header, ResourceType resourceType) throws IOException {
	long oldIndex = reader.getPointerIndex();
	try {
		switch (resourceType.getType()) {
			case ResourceTypes.TYPE_CFRG:
			{
				ReferenceListEntry referenceListEntry = resourceType.getReferenceList().get(0);
				reader.setPointerIndex(header.getResourceDataOffset() + 
						   header.getEntryDescriptor().getOffset() + 
						   referenceListEntry.getDataOffset() + 
						   4);
				return new CFragResource(reader);
			}
			default:
				return null;
		}
	}
	finally {
		reader.setPointerIndex(oldIndex);
	}
}
 
Example 3
Source File: CliStreamHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new CLI Stream Header datatype.
 * 
 * @param metadataRoot the metadata root.
 * @param reader A binary reader set to start reading at the start of this header.
 * @throws IOException if there is a problem reading the header.
 */
public CliStreamHeader(CliMetadataRoot metadataRoot, BinaryReader reader)
		throws IOException {
	this.metadataRoot = metadataRoot;
	
	long headerStartIndex = reader.getPointerIndex();

	this.offset = reader.readNextInt();
	this.size = reader.readNextInt();
	
	// name is an ASCII string aligned to the next 4-byte boundary
	long startIndex = reader.getPointerIndex();
	this.name = reader.readNextAsciiString();
	long endIndex = reader.getPointerIndex(); // Gives us the index of the byte after the first null terminator
	long stringBytes = endIndex - startIndex;
	long bytesToRoundUp = 0;
	if ((stringBytes % 4) != 0) {
		bytesToRoundUp += 4 - (stringBytes % 4);
	}
	this.nameLen = (int) (stringBytes + bytesToRoundUp);
	
	int totalLen = 2 * DWordDataType.dataType.getLength() + this.nameLen;

	reader.setPointerIndex(headerStartIndex + totalLen);
}
 
Example 4
Source File: CliTableFile.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableFile(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		CliFileRow row = new CliFileRow(reader.readNextInt(), readStringIndex(reader), readBlobIndex(reader));
		rows.add(row);
		strings.add(row.nameIndex);
		blobs.add(row.hashIndex);
	}
	reader.setPointerIndex(this.readerOffset);

}
 
Example 5
Source File: CliTableEvent.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableEvent(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		CliEventRow row = new CliEventRow(reader.readNextShort(), readStringIndex(reader), CliIndexTypeDefOrRef.readCodedIndex(reader, stream));
		rows.add(row);
		strings.add(row.nameIndex);
	}
	reader.setPointerIndex(this.readerOffset);
}
 
Example 6
Source File: AnnotationElement.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public AnnotationElement( BinaryReader reader ) throws IOException {
	nameIndex = Leb128.readUnsignedLeb128( reader.readByteArray( reader.getPointerIndex( ), 5 ) );

	nameIndexLength = Leb128.unsignedLeb128Size( nameIndex );
	reader.setPointerIndex( reader.getPointerIndex( ) + nameIndexLength );

	value = new EncodedValue( reader );
}
 
Example 7
Source File: CliTableDeclSecurity.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableDeclSecurity(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		CliDeclSecurityRow row = new CliDeclSecurityRow(reader.readNextShort(), CliIndexHasDeclSecurity.readCodedIndex(reader, stream), readBlobIndex(reader));
		blobs.add(row.permissionSetIndex);
	}
	reader.setPointerIndex(this.readerOffset);
}
 
Example 8
Source File: PdbInfoDotNet.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PdbInfoDotNet(BinaryReader reader, int ptr) throws IOException {
	long origIndex = reader.getPointerIndex();
	reader.setPointerIndex(ptr);
	try {
		magic = reader.readNextByteArray(4);
		guid = new GUID(reader);
		age = reader.readNextInt();
		pdbName = reader.readNextAsciiString();
	}
	finally {
		reader.setPointerIndex(origIndex);
	}
}
 
Example 9
Source File: CliTableMethodSemantics.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableMethodSemantics(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		rows.add(new CliMethodSemanticsRow(reader.readNextShort(), readTableIndex(reader, CliTypeTable.MethodDef), CliIndexHasSemantics.readCodedIndex(reader, stream)));
	}
	reader.setPointerIndex(this.readerOffset);
}
 
Example 10
Source File: DIEAggregate.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a range list from the debug_ranges section.
 * See DWARF4 Section 2.17.3 (Non-Contiguous Address Ranges).
 * <p>
 * @param attribute attribute ie. {@link DWARFAttribute#DW_AT_ranges}
 * @return list of ranges
 * @throws IOException if an I/O error occurs
 */
public List<DWARFRange> parseDebugRange(int attribute) throws IOException {
	byte pointerSize = getCompilationUnit().getPointerSize();
	BinaryReader reader = getCompilationUnit().getProgram().getDebugRanges();

	long offset = getUnsignedLong(attribute, -1);
	if (offset == -1) {
		throw new IOException("Bad / missing attribute " + attribute);
	}
	reader.setPointerIndex(offset);
	List<DWARFRange> ranges = new ArrayList<>();

	long baseAddress = getCompilationUnit().getCompileUnit() != null &&
		getCompilationUnit().getCompileUnit().getLowPC() != null
				? getCompilationUnit().getCompileUnit().getLowPC().longValue()
				: 0L;

	while (reader.getPointerIndex() < reader.length()) {
		// Read the beginning and ending addresses
		Number beginning = DWARFUtil.readAddress(reader, pointerSize);
		Number ending = DWARFUtil.readAddress(reader, pointerSize);	// dwarf end addrs are exclusive

		// End of the list
		if (beginning.longValue() == 0 && ending.longValue() == 0) {
			break;
		}

		// Check to see if this is a base address entry
		if (NumberUtil.equalsMaxUnsignedValue(beginning)) {
			baseAddress = ending.longValue();
			continue;
		}

		// Add the range to the list
		ranges.add(new DWARFRange(baseAddress + beginning.longValue(),
			baseAddress + ending.longValue()));
	}
	Collections.sort(ranges);
	return ranges;
}
 
Example 11
Source File: CliBlob.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new blob from the given reader, which should be positioned at the start
 * of the blob.  The reader will be positioned directly after the blob upon completion
 * of the constructor.
 * 
 * @param streamIndex The blob's stream index.
 * @param reader The reader to use to read the blob.
 * @throws IOException if there was a problem reading the blob.
 */
public CliBlob(int streamIndex, BinaryReader reader) throws IOException {
	this.streamIndex = streamIndex;
	this.reader = reader;

	blobOffset = reader.getPointerIndex();
	contentsSize = parseCodedSize(reader);
	contentsOffset = reader.getPointerIndex();
	reader.setPointerIndex(reader.getPointerIndex() + contentsSize);
}
 
Example 12
Source File: KIP1Header.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
public KIP1Header(BinaryReader reader, int readerOffset)
{
    long prevPointerIndex = reader.getPointerIndex();
    
    reader.setPointerIndex(readerOffset);
    this.readHeader(reader);
    
    // Restore the previous pointer index
    reader.setPointerIndex(prevPointerIndex);
}
 
Example 13
Source File: CliTableModule.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableModule(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		CliModuleRow row = new CliModuleRow(reader.readNextShort(), readStringIndex(reader), readBlobIndex(reader), readBlobIndex(reader), readBlobIndex(reader));
		rows.add(row);
		strings.add(row.nameIndex);
	}
	reader.setPointerIndex(this.readerOffset);
}
 
Example 14
Source File: CliTableExportedType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableExportedType(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		CliExportedTypeRow row = new CliExportedTypeRow(reader.readNextInt(), reader.readNextInt(), readStringIndex(reader), readStringIndex(reader),
			CliIndexImplementation.readCodedIndex(reader, stream));
		rows.add(row);
		strings.add(row.typeNameIndex);
		strings.add(row.typeNamespaceIndex);
	}
	reader.setPointerIndex(this.readerOffset);
}
 
Example 15
Source File: CliTableFieldLayout.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public CliTableFieldLayout(BinaryReader reader, CliStreamMetadata stream, CliTypeTable tableId) throws IOException {
	super(reader, stream, tableId);
	for (int i = 0; i < this.numRows; i++) {
		rows.add(new CliFieldLayoutRow(reader.readNextInt(), readTableIndex(reader, CliTypeTable.Field)));
	}
	reader.setPointerIndex(this.readerOffset);
}
 
Example 16
Source File: ISO9660FileSystem.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {
	BinaryReader reader = new BinaryReader(provider, true);

	//Set start of pointer index of beginning of primary volume descriptor
	if (foundAt0x8001) {
		reader.setPointerIndex(0x8000);
	}
	else if (foundAt0x8801) {
		reader.setPointerIndex(0x8800);
	}
	else if (foundAt0x9001) {
		reader.setPointerIndex(0x9000);
	}
	else {
		throw new IOException("Cannot find index of ISO9660 Header");
	}

	header = new ISO9660Header(reader);
	ISO9660VolumeDescriptor pvd = header.getPrimaryVolumeDescriptor();
	logicalBlockSize = pvd.getLogicalBlockSizeBE();
	ISO9660Directory rootDir = header.getPrimaryDirectory();

	//Get the list containing all directories at the root level of the file system
	List<ISO9660Directory> topLevel =
		createDirectoryList(reader, rootDir, pvd.getLogicalBlockSizeLE(), monitor);

	try {

		//Entry point for the this recursive function to process all nested
		//directories
		createDirectories(reader, topLevel, pvd.getLogicalBlockSizeLE(), monitor);
	}

	catch (Exception e) {
		Msg.showError(this, null, "Directory Creation Error",
			"Failed to create archive directories");

	}

}
 
Example 17
Source File: DexHeader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public DexHeader(BinaryReader reader) throws IOException {
	magic = reader.readNextByteArray( DexConstants.DEX_MAGIC_BASE.length( ) );
	version = reader.readNextByteArray( DexConstants.DEX_VERSION_LENGTH );

	if (!DexConstants.DEX_MAGIC_BASE.equals(new String(magic))) {
		throw new IOException("not a dex file.");
	}

	checksum = reader.readNextInt();
	signature = reader.readNextByteArray(20);
	fileSize = reader.readNextInt();
	headerSize = reader.readNextInt();
	endianTag = reader.readNextInt();
	linkSize = reader.readNextInt();
	linkOffset = reader.readNextInt();
	mapOffset = reader.readNextInt();
	stringIdsSize = reader.readNextInt();
	stringIdsOffset = reader.readNextInt();
	typeIdsSize = reader.readNextInt();
	typeIdsOffset = reader.readNextInt();
	protoIdsSize = reader.readNextInt();
	protoIdsOffset = reader.readNextInt();
	fieldIdsSize = reader.readNextInt();
	fieldIdsOffset = reader.readNextInt();
	methodIdsSize = reader.readNextInt();
	methodIdsOffset = reader.readNextInt();
	classDefsIdsSize = reader.readNextInt();
	classDefsIdsOffset = reader.readNextInt();
	dataSize = reader.readNextInt();
	dataOffset = reader.readNextInt();

	reader.setPointerIndex(mapOffset);
	if (mapOffset > 0) {
		mapList = new MapList(reader);
	}

	reader.setPointerIndex(stringIdsOffset);
	for (int i = 0; i < stringIdsSize; ++i) {
		strings.add(new StringIDItem(reader));
	}

	reader.setPointerIndex(typeIdsOffset);
	for (int i = 0; i < typeIdsSize; ++i) {
		types.add(new TypeIDItem(reader));
	}

	reader.setPointerIndex(protoIdsOffset);
	for (int i = 0; i < protoIdsSize; ++i) {
		prototypes.add(new PrototypesIDItem(reader));
	}

	reader.setPointerIndex(fieldIdsOffset);
	for (int i = 0; i < fieldIdsSize; ++i) {
		fields.add(new FieldIDItem(reader));
	}

	reader.setPointerIndex(methodIdsOffset);
	for (int i = 0; i < methodIdsSize; ++i) {
		methods.add(new MethodIDItem(reader));
	}

	reader.setPointerIndex(classDefsIdsOffset);
	for (int i = 0; i < classDefsIdsSize; ++i) {
		classDefs.add(new ClassDefItem(reader));
	}
}
 
Example 18
Source File: NewExt4Analyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void createInodeTables( Program program, 
								BinaryReader reader, 
								Ext4SuperBlock superBlock, 
								Ext4GroupDescriptor [] groupDescriptors, 
								boolean is64Bit, 
								TaskMonitor monitor ) throws DuplicateNameException, Exception {
	
	int inodeCount = superBlock.getS_inodes_count( );
	Ext4Inode [] inodes = new Ext4Inode [ inodeCount ];
	int inodeIndex = 0;

	for ( int i = 0; i < groupDescriptors.length; i++ ) {
		monitor.checkCanceled( );
		long inodeTableBlockOffset = groupDescriptors[ i ].getBg_inode_table_lo( ) & 0xffffffffL;
		if ( is64Bit ) {
			inodeTableBlockOffset = ( groupDescriptors[ i ].getBg_inode_table_hi( ) << 32 ) | inodeTableBlockOffset;
		}
		long offset = inodeTableBlockOffset * blockSize;
		reader.setPointerIndex( offset );
		Address address = null;
		try {
			address = toAddr( program, offset );
		}
		catch ( Exception e ) {
			throw new IOException( "offset " + offset + " not in program." );
		}

		int inodesPerGroup = superBlock.getS_inodes_per_group( );
		monitor.setMessage( "Creating inode table " + i + " of " + ( groupDescriptors.length - 1 ) + "..." );
		monitor.setMaximum( inodesPerGroup );
		monitor.setProgress( 0 );
		for ( int j = 0; j < inodesPerGroup; j++ ) {
			monitor.checkCanceled( );

			Ext4Inode inode = new Ext4Inode( reader );
			DataType dataType = inode.toDataType( );
			createData( program, address, dataType );

			String comment = "Inode: 0x" + Integer.toHexString( inodeIndex + 1 ) + "\n";
			comment += "Group Descriptor ID: 0x" + Integer.toHexString( i ) + "\n";
			comment += "Inode Offset Into Group: 0x" + Integer.toHexString( j ) + "\n";

			Ext4IBlock iBlock = inode.getI_block( );
			if ( iBlock != null ) {
				for ( Ext4Extent extent : iBlock.getExtentEntries( ) ) {
					monitor.checkCanceled( );
					long lo = extent.getEe_start_lo( ) & 0xffffffffL;
					long hi = extent.getEe_start_hi( ) & 0xffffffffL;
					long value = ( hi << 32 ) | lo;
					long destination = value * blockSize;
					comment += "Extent: 0x" + Long.toHexString( destination ) + "\n";
				}
			}

			setPlateComment( program, address, comment );
			createLabel( program, address, "INODE_" + "0x" + Integer.toHexString( inodeIndex + 1 ) );
			address = address.add( superBlock.getS_inode_size( ) );
			reader.setPointerIndex( address.getOffset( ) );
			monitor.incrementProgress( 1 );
			inodes[ inodeIndex++ ] = inode; //inodes[ inodesPerGroup * i + j ] = inode;
		}
	}

	processInodes( program, reader, superBlock, inodes, monitor );
}
 
Example 19
Source File: SwitchLoader.java    From Ghidra-Switch-Loader with ISC License 4 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException 
{
    List<LoadSpec> loadSpecs = new ArrayList<>();
    BinaryReader reader = new BinaryReader(provider, true);
    String magic_0x0 = reader.readAsciiString(0, 4);
    String magic_0x10 = reader.readAsciiString(0x10, 4);
    
    reader.setPointerIndex(0);

    if (magic_0x0.equals("KIP1")) 
    {
        this.binaryType = BinaryType.KIP1;
    }
    else if (magic_0x0.equals("NSO0"))
    {
        this.binaryType = BinaryType.NSO0;
    }
    else if (magic_0x0.equals("\u00DF\u004F\u0003\u00D5"))
    {
        this.binaryType = BinaryType.KERNEL_800;
    }
    else if (magic_0x10.equals("NRO0"))
    {
        this.binaryType = BinaryType.NRO0;
    }
    else if (magic_0x10.equals("KIP1"))
    {
        // Note: This is kinda a bad way of determining this, but for now it gets the job done
        // and I don't believe there are any clashes.
        this.binaryType = BinaryType.SX_KIP1; 
    }
    else
        return loadSpecs;

    var adapter = this.binaryType.createAdapter(null, provider);
    
    if (adapter.isAarch32())
    {
        loadSpecs.add(new LoadSpec(this, 0, new LanguageCompilerSpecPair(AARCH32_LANGUAGE_ID, new CompilerSpecID("default")), true));
    }
    else
    {
        loadSpecs.add(new LoadSpec(this, 0, new LanguageCompilerSpecPair(AARCH64_LANGUAGE_ID, new CompilerSpecID("default")), true));
    }

    return loadSpecs;
}
 
Example 20
Source File: NewExt4Analyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean analyze( Program program, AddressSetView set, TaskMonitor monitor, MessageLog log ) throws Exception {

	program2 = findOtherProgram( program, "0x70000000" );
	int transactionId2 = -1;
	if ( program2 != null ) {
		transactionId2 = program2.startTransaction( getName( ) );
	}

	program3 = findOtherProgram( program, "0xE0000000" );
	int transactionId3 = -1;
	if ( program3 != null ) {
		transactionId3 = program3.startTransaction( getName( ) );
	}

	try { 
		ByteProvider provider = new MultiProgramMemoryByteProvider( program, program2, program3 );
		BinaryReader reader = new BinaryReader( provider, true );
		int start = getSuperBlockStart( reader );
		int groupStart = 0;
		reader.setPointerIndex( start );
		Ext4SuperBlock superBlock = new Ext4SuperBlock( reader );
		Address superBlockAddress = toAddr( program, start );
		createData( program, superBlockAddress, superBlock.toDataType( ) );
		

		boolean is64Bit = ( superBlock.getS_desc_size( ) > 32 ) && ( ( superBlock.getS_feature_incompat( ) & 0x80 ) > 0 );

		long numBytes = program.getMaxAddress( ).getOffset( ) - program.getMinAddress( ).getOffset( ) + 1;
		if ( program2 != null ) {
			numBytes = program2.getMaxAddress( ).getOffset( ) - program.getMinAddress( ).getOffset( ) + 1;
		}
		if ( program3 != null ) {
			numBytes = program3.getMaxAddress( ).getOffset( ) - program.getMinAddress( ).getOffset( ) + 1;
		}

		int groupSize = calculateGroupSize( superBlock );
		int numGroups = ( int ) ( numBytes / groupSize );
		if ( numBytes % groupSize != 0 ) {
			numGroups++;
		}

		setPlateComment( program, superBlockAddress, "SuperBlock (main) \n" + 
						"Group Size In Bytes: 0x" + Integer.toHexString( groupSize ) + "\n" +
						"Number of Groups: 0x" + Integer.toHexString( numGroups ) );

		long groupDescOffset = groupStart + blockSize;
		Address groupDescAddress = toAddr( program, groupDescOffset );
		reader.setPointerIndex( groupDescOffset );
		Ext4GroupDescriptor groupDescriptors[] = new Ext4GroupDescriptor [ numGroups ];
		monitor.setMessage( "Creating group descriptors..." );
		monitor.setMaximum( numGroups );
		for ( int i = 0; i < numGroups; i++ ) {
			monitor.checkCanceled( );
			groupDescriptors[ i ] = new Ext4GroupDescriptor( reader, is64Bit );
			DataType groupDescDataType = groupDescriptors[ i ].toDataType( );
			createData( program, groupDescAddress, groupDescDataType );
			setPlateComment( program, groupDescAddress, "group descriptor: " + i );

			groupDescAddress = groupDescAddress.add( groupDescDataType.getLength( ) );
			monitor.incrementProgress( 1 );
		}

		boolean isSparseSuper = ( superBlock.getS_feature_ro_compat( ) & 1 ) != 0;
		createSuperBlockCopies( program, reader, groupSize, numGroups, is64Bit, isSparseSuper, monitor );

		createInodeTables( program, reader, superBlock, groupDescriptors, is64Bit, monitor );
		
//		test(program, reader);
	}
	catch ( Exception e ) {
		throw e;
	}
	finally {
		if ( program2 != null ) {
			program2.endTransaction( transactionId2, true );
			program2 = null;
		}
		if ( program3 != null ) {
			program3.endTransaction( transactionId3, true );
			program3 = null;
		}
	}

	return true;
}