Java Code Examples for ghidra.app.util.bin.ByteProvider#length()

The following examples show how to use ghidra.app.util.bin.ByteProvider#length() . 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: OmfArchiveFileSystemFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean probe(FSRL containerFSRL, ByteProvider byteProvider, File containerFile,
		FileSystemService fsService, TaskMonitor monitor)
		throws IOException, CancelledException {

	if (byteProvider.length() < OmfLoader.MIN_BYTE_LENGTH) {
		return false;
	}

	try {
		BinaryReader reader = OmfFileHeader.createReader(byteProvider);
		return OmfLibraryRecord.checkMagicNumer(reader);
	}
	catch (IOException e) {
		return false;
	}
}
 
Example 2
Source File: PeLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();

	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}

	PortableExecutable pe = PortableExecutable.createPortableExecutable(
		RethrowContinuesFactory.INSTANCE, provider, SectionLayout.FILE, false, false);
	NTHeader ntHeader = pe.getNTHeader();
	if (ntHeader != null && ntHeader.getOptionalHeader() != null) {
		long imageBase = ntHeader.getOptionalHeader().getImageBase();
		String machineName = ntHeader.getFileHeader().getMachineName();
		String compiler = CompilerOpinion.stripFamily(CompilerOpinion.getOpinion(pe, provider));
		for (QueryResult result : QueryOpinionService.query(getName(), machineName, compiler)) {
			loadSpecs.add(new LoadSpec(this, imageBase, result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, imageBase, true));
		}
	}

	return loadSpecs;
}
 
Example 3
Source File: PefLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();

	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}

	try {
		ContainerHeader header = new ContainerHeader(provider);
		List<QueryResult> results =
			QueryOpinionService.query(getName(), header.getArchitecture(), null);
		for (QueryResult result : results) {
			loadSpecs.add(new LoadSpec(this, header.getImageBase(), result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, header.getImageBase(), true));
		}
	}
	catch (PefException e) {
		// not a problem, it's not a pef
	}

	return loadSpecs;
}
 
Example 4
Source File: NeLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();

	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}
	NewExecutable ne = new NewExecutable(RethrowContinuesFactory.INSTANCE, provider, null);
	WindowsHeader wh = ne.getWindowsHeader();
	if (wh != null) {
		List<QueryResult> results = QueryOpinionService.query(getName(),
			"" + wh.getInformationBlock().getMagicNumber(), null);
		for (QueryResult result : results) {
			loadSpecs.add(new LoadSpec(this, 0, result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, 0, true));
		}
	}

	return loadSpecs;
}
 
Example 5
Source File: MachoPrelinkUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Scans the provider looking for PRELINK Mach-O headers.  
 * <p>
 * NOTE: The "System" Mach-O at offset 0 is not considered a PRELINK Mach-O.
 * <p>
 * NOTE: We used to scan on 0x1000, and then 0x10 byte boundaries.  Now iOS 12 seems to 
 * put them on 0x8-byte boundaries.
 * 
 * @param provider The provider to scan.
 * @param monitor A monitor.
 * @return A list of provider offsets where PRELINK Mach-O headers start (not including the
 *   "System" Mach-O at offset 0).
 * @throws IOException If there was an IO-related issue searching for PRELINK Mach-O headers.
 */
public static List<Long> findPrelinkMachoHeaderOffsets(ByteProvider provider,
		TaskMonitor monitor) throws IOException {
	monitor.setMessage("Finding PRELINK Mach-O headers...");
	monitor.initialize((int) provider.length());

	List<Long> list = new ArrayList<>(); // This list must maintain ordering...don't sort it		
	for (long offset = 0; offset < provider.length() - 4; offset += 8) {
		if (monitor.isCancelled()) {
			break;
		}
		monitor.setProgress((int) offset);

		if (getMachoLoadSpec(provider, offset) != null) {
			if (offset > 0) {
				// Don't put first "System" Mach-O in list
				list.add(offset);
			}
		}
		else if (offset == 0) {
			// if it doesn't start with a Mach-O, just quit
			break;
		}
	}
	return list;
}
 
Example 6
Source File: MzLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();

	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}
	OldStyleExecutable ose = new OldStyleExecutable(RethrowContinuesFactory.INSTANCE, provider);
	DOSHeader dos = ose.getDOSHeader();
	if (dos.isDosSignature() && !dos.hasNewExeHeader() && !dos.hasPeHeader()) {
		List<QueryResult> results =
			QueryOpinionService.query(getName(), "" + dos.e_magic(), null);
		for (QueryResult result : results) {
			loadSpecs.add(new LoadSpec(this, 0, result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, 0, true));
		}
	}

	return loadSpecs;
}
 
Example 7
Source File: DbgLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();
	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}
	SeparateDebugHeader debug =
		new SeparateDebugHeader(RethrowContinuesFactory.INSTANCE, provider);
	if (debug.getSignature() == SeparateDebugHeader.IMAGE_SEPARATE_DEBUG_SIGNATURE) {
		long imageBase = Conv.intToLong(debug.getImageBase());
		String machineName = debug.getMachineName();
		for (QueryResult result : QueryOpinionService.query(getName(), machineName, null)) {
			loadSpecs.add(new LoadSpec(this, imageBase, result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, imageBase, true));
		}
	}

	return loadSpecs;
}
 
Example 8
Source File: DexLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void load(ByteProvider provider, LoadSpec loadSpec, List<Option> options,
		Program program, TaskMonitor monitor, MessageLog log) throws IOException {

	monitor.setMessage( "DEX Loader: creating dex memory" );
	try {
		Address start = program.getAddressFactory().getDefaultAddressSpace().getAddress( 0x0 );
		long length = provider.length();

		try (InputStream inputStream = provider.getInputStream(0)) {
			program.getMemory().createInitializedBlock(".dex", start, inputStream, length,
				monitor, false);
		}

		BinaryReader reader = new BinaryReader( provider, true );
		DexHeader header = new DexHeader( reader );

		monitor.setMessage( "DEX Loader: creating method byte code" );

		createMethodLookupMemoryBlock( program, monitor );
		createMethodByteCodeBlock( program, length, monitor);

		for ( ClassDefItem item : header.getClassDefs( ) ) {
			monitor.checkCanceled( );

			ClassDataItem classDataItem = item.getClassDataItem( );
			if ( classDataItem == null ) {
				continue;
			}

			createMethods( program, header, item, classDataItem.getDirectMethods( ), monitor, log );
			createMethods( program, header, item, classDataItem.getVirtualMethods( ), monitor, log );
		}
	}
	catch ( Exception e) {
		log.appendException( e );
	}
}
 
Example 9
Source File: OmfLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();

	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}

	BinaryReader reader = OmfFileHeader.createReader(provider);
	if (OmfFileHeader.checkMagicNumber(reader)) {
		reader.setPointerIndex(0);
		OmfFileHeader scan;
		try {
			scan = OmfFileHeader.scan(reader, TaskMonitorAdapter.DUMMY_MONITOR, true);
		}
		catch (OmfException e) {
			throw new IOException("Bad header format: " + e.getMessage());
		}
		List<QueryResult> results = QueryOpinionService.query(getName(), scan.getMachineName(),
			mapTranslator(scan.getTranslator()));
		for (QueryResult result : results) {
			loadSpecs.add(new LoadSpec(this, IMAGE_BASE, result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, IMAGE_BASE, true));
		}
	}
	return loadSpecs;
}
 
Example 10
Source File: BinaryLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean loadProgramInto(ByteProvider provider, LoadSpec loadSpec,
		List<Option> options, MessageLog log, Program prog, TaskMonitor monitor)
		throws IOException, CancelledException {
	long length = getLength(options);
	//File file = provider.getFile();
	long fileOffset = getFileOffset(options);
	Address baseAddr = getBaseAddr(options);
	String blockName = getBlockName(options);
	boolean isOverlay = isOverlay(options);

	if (length == 0) {
		length = provider.length();
	}

	length = clipToMemorySpace(length, log, prog);

	FileBytes fileBytes =
		MemoryBlockUtils.createFileBytes(prog, provider, fileOffset, length, monitor);
	try {
		AddressSpace space = prog.getAddressFactory().getDefaultAddressSpace();
		if (baseAddr == null) {
			baseAddr = space.getAddress(0);
		}
		if (blockName == null || blockName.length() == 0) {
			blockName = generateBlockName(prog, isOverlay, baseAddr.getAddressSpace());
		}
		createBlock(prog, isOverlay, blockName, baseAddr, fileBytes, length, log);

		return true;
	}
	catch (AddressOverflowException e) {
		throw new IllegalArgumentException("Invalid address range specified: start:" +
			baseAddr + ", length:" + length + " - end address exceeds address space boundary!");
	}
}
 
Example 11
Source File: SwitchLoader.java    From Ghidra-Switch-Loader with ISC License 4 votes vote down vote up
@Override
protected boolean loadProgramInto(ByteProvider provider, LoadSpec loadSpec, List<Option> options,
        MessageLog messageLog, Program program, TaskMonitor monitor) 
                throws IOException
{
    var space = program.getAddressFactory().getDefaultAddressSpace();
    
    if (this.binaryType == BinaryType.SX_KIP1)
    {
        provider = new ByteProviderWrapper(provider, 0x10, provider.length() - 0x10);
    }

    var adapter = this.binaryType.createAdapter(program, provider);
    
    // Set the base address
    try 
    {
        long baseAddress = adapter.isAarch32() ? 0x60000000L : 0x7100000000L;
        
        if (this.binaryType == BinaryType.KERNEL_800)
        {
            baseAddress = 0x80060000L;
        }

        program.setImageBase(space.getAddress(baseAddress), true);
    } 
    catch (AddressOverflowException | LockException | IllegalStateException | AddressOutOfBoundsException e) 
    {
        Msg.error(this, "Failed to set image base", e);
    }

    var loader = new NXProgramBuilder(program, provider, adapter);
    loader.load(monitor);
    
    if (this.binaryType == BinaryType.KIP1)
    {
        // KIP1s always start with a branch instruction at the start of their text
        loader.createEntryFunction("entry", program.getImageBase().getOffset(), monitor);
    }
    
    return true;
}
 
Example 12
Source File: CoffLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<LoadSpec> findSupportedLoadSpecs(ByteProvider provider) throws IOException {
	List<LoadSpec> loadSpecs = new ArrayList<>();

	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}

	CoffFileHeader header = new CoffFileHeader(provider);

	// Check to prevent false positives when the file is full of '\0' bytes.
	// If the machine type is unknown (0), check the first 64 bytes of the file and bail if
	// they are also all 0.
	if (header.getMagic() == CoffMachineType.IMAGE_FILE_MACHINE_UNKNOWN /* ie. == 0 */ &&
		provider.length() > COFF_NULL_SANITY_CHECK_LEN) {
		byte[] headerBytes = provider.readBytes(0, COFF_NULL_SANITY_CHECK_LEN);
		boolean allZeros = true;
		for (byte b : headerBytes) {
			allZeros = (b == 0);
			if (!allZeros) {
				break;
			}
		}
		if (allZeros) {
			return loadSpecs;
		}
	}

	if (CoffMachineType.isMachineTypeDefined(header.getMagic())) {
		header.parseSectionHeaders(provider);

		if (isVisualStudio(header) != isMicrosoftFormat()) {
			// Only one of the CoffLoader/MSCoffLoader will survive this check
			return loadSpecs;
		}
		String secondary = isCLI(header) ? "cli" : null;
		List<QueryResult> results =
			QueryOpinionService.query(getName(), header.getMachineName(), secondary);
		for (QueryResult result : results) {
			loadSpecs.add(new LoadSpec(this, header.getImageBase(true), result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, header.getImageBase(false), true));
		}
	}
	return loadSpecs;
}