generic.continues.RethrowContinuesFactory Java Examples

The following examples show how to use generic.continues.RethrowContinuesFactory. 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: UniversalBinaryFileSystem.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void open(TaskMonitor monitor) throws IOException, CancelledException {
	try {
		header = FatHeader.createFatHeader(RethrowContinuesFactory.INSTANCE, provider);
		List<FatArch> architectures = header.getArchitectures();
		for (FatArch architecture : architectures) {
			Processor processor =
				CpuTypes.getProcessor(architecture.getCpuType(), architecture.getCpuSubType());
			int bitSize = CpuTypes.getProcessorBitSize(architecture.getCpuType());
			String name = processor + "-" + bitSize + "-cpu0x" +
				Integer.toHexString(architecture.getCpuSubType());
			GFileImpl file =
				GFileImpl.fromFilename(this, root, name, false, architecture.getSize(), null);
			list.add(file);
		}
	}
	catch (Exception e) {
		throw new IOException(e);
	}
}
 
Example #2
Source File: PortableExecutableBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canApply(Program program) {
	try {
		Memory memory = program.getMemory();

		ByteProvider provider = new MemoryByteProvider(memory,
			program.getAddressFactory().getDefaultAddressSpace());

		FactoryBundledWithBinaryReader reader = new FactoryBundledWithBinaryReader(
			RethrowContinuesFactory.INSTANCE, provider, !program.getLanguage().isBigEndian());

		DOSHeader dosHeader = DOSHeader.createDOSHeader(reader);

		if (dosHeader.isDosSignature()) {

			reader.setPointerIndex( dosHeader.e_lfanew( ) );

			short peMagic = reader.readNextShort();//we should be pointing at the PE magic value!

			return ( peMagic & 0x0000ffff ) == Constants.IMAGE_NT_SIGNATURE;
		}
	}
	catch (Exception e) {
	}
	return false;
}
 
Example #3
Source File: PEUtil.java    From ghidra with Apache License 2.0 6 votes vote down vote up
static public boolean canAnalyze(Program program) {
	String format = program.getExecutableFormat();
	if (format.equals(PeLoader.PE_NAME)) {
		return true;
	}
	if (format.equals(BinaryLoader.BINARY_NAME)) {
		MemoryByteProvider mbp =
			new MemoryByteProvider(program.getMemory(),
				program.getAddressFactory().getDefaultAddressSpace());
		try {
			FactoryBundledWithBinaryReader reader =
				new FactoryBundledWithBinaryReader(RethrowContinuesFactory.INSTANCE, mbp, true/*LittleEndian*/);
			DOSHeader dosHeader = DOSHeader.createDOSHeader(reader);
			if (dosHeader.e_magic() == DOSHeader.IMAGE_DOS_SIGNATURE) {
				int peHeaderStartIndex = dosHeader.e_lfanew();
				int peMagicNumber = reader.readInt(peHeaderStartIndex);
				if (peMagicNumber == Constants.IMAGE_NT_SIGNATURE) {
					return true;
				}
			}
		}
		catch (IOException e) {
		}
	}
	return false;
}
 
Example #4
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 #5
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 #6
Source File: MachoPrelinkUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the provider looking for PRELINK XML.
 * 
 * @param provider The provider to parse.
 * @param monitor A monitor.
 * @return A list of discovered {@link PrelinkMap}s.  An empty list indicates that the provider
 *   did not represent valid Mach-O PRELINK binary.
 * @throws IOException if there was an IO-related issue.
 * @throws JDOMException if there was a issue parsing the PRELINK XML.
 */
public static List<PrelinkMap> parsePrelinkXml(ByteProvider provider, TaskMonitor monitor)
		throws IOException, JDOMException {

	try {
		MachHeader mainHeader =
			MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE, provider);
		mainHeader.parse(); // make sure first Mach-O header is valid....

		monitor.setMessage("Parsing PRELINK XML...");
		return new PrelinkParser(mainHeader, provider).parse(monitor);
	}
	catch (NoPreLinkSectionException | MachException e) {
		return Collections.emptyList();
	}
}
 
Example #7
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 #8
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 #9
Source File: ElfDataType.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected void populateDynamicStructure(MemBuffer buf, Structure struct) {
	try {
        Memory memory = buf.getMemory();
        MemoryBlock block = memory.getBlock(buf.getAddress());
        byte [] bytes = new byte[(int)block.getSize()];
        block.getBytes(block.getStart(), bytes);

        ByteArrayProvider bap = new ByteArrayProvider(bytes);

        ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, bap);
        elf.parse();

        struct.add(elf.toDataType());
	}
	catch (Exception e) {
		
	}
}
 
Example #10
Source File: ElfLoaderOptionsFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
static void addOptions(List<Option> options, ByteProvider provider, LoadSpec loadSpec)
		throws ElfException, LanguageNotFoundException {

	// NOTE: add-to-program is not supported

	options.add(new Option(PERFORM_RELOCATIONS_NAME, PERFORM_RELOCATIONS_DEFAULT, Boolean.class,
		Loader.COMMAND_LINE_ARG_PREFIX + "-applyRelocations"));

	ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);

	long imageBase = elf.findImageBase();
	if (imageBase == 0 && (elf.isRelocatable() || elf.isSharedObject())) {
		imageBase = elf.is64Bit() ? IMAGE64_BASE_DEFAULT : IMAGE_BASE_DEFAULT;
	}
	Language language = loadSpec.getLanguageCompilerSpec().getLanguage();
	AddressSpace defaultSpace = language.getDefaultSpace();

	String hexValueStr = getBaseAddressOffsetString(imageBase, defaultSpace);
	options.add(new Option(IMAGE_BASE_OPTION_NAME, hexValueStr, String.class,
		Loader.COMMAND_LINE_ARG_PREFIX + "-imagebase"));
	
	if (includeDataImageBaseOption(elf, language)) {
		long minDataImageBase = getRecommendedMinimumDataImageBase(elf, language);
		hexValueStr =
			getBaseAddressOffsetString(minDataImageBase, language.getDefaultDataSpace());
		options.add(new Option(IMAGE_DATA_IMAGE_BASE_OPTION_NAME, hexValueStr, String.class,
			Loader.COMMAND_LINE_ARG_PREFIX + "-dataImageBase"));
	}

	options.add(new Option(INCLUDE_OTHER_BLOCKS, INCLUDE_OTHER_BLOCKS_DEFAULT, Boolean.class,
		Loader.COMMAND_LINE_ARG_PREFIX + "-includeOtherBlocks"));

	options.add(
		new Option(RESOLVE_EXTERNAL_SYMBOLS_OPTION_NAME, RESOLVE_EXTERNAL_SYMBOLS_DEFAULT,
			Boolean.class, Loader.COMMAND_LINE_ARG_PREFIX + "-resolveExternalSymbols"));
}
 
Example #11
Source File: SplitUniversalBinariesScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	File ubiFile = askFile("Select Universal Binary File", "C'mon, Do it! Push da bahtahn!");
	File outputDirectory = askDirectory("Select Output Directory", "GO");

	ByteProvider provider = new RandomAccessByteProvider(ubiFile) ;
	FatHeader header = FatHeader.createFatHeader(RethrowContinuesFactory.INSTANCE, provider);

	List<FatArch> architectures = header.getArchitectures();
	for (FatArch arch : architectures) {
		int offset = arch.getOffset();
		int   size = arch.getSize();

		Processor processor = CpuTypes.getProcessor(arch.getCpuType(), arch.getCpuSubType());
		int processorSize = CpuTypes.getProcessorBitSize(arch.getCpuType());

		File outFile = new File(outputDirectory, ubiFile.getName()+"."+processor+"."+processorSize);
		OutputStream out = new FileOutputStream(outFile);
		try {
			for (int i = offset ; i < offset+size ; i+=4096) {
				if (i + 4096 < offset+size) {
					out.write(provider.readBytes(i, 4096));
				}
				else {
					out.write(provider.readBytes(i, offset+size-i));
				}
			}
		}
		finally {
			out.close();
		}
	}
}
 
Example #12
Source File: PortableExecutableBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean analysisWorkerCallback(Program program, Object workerContext,
		TaskMonitor monitor) throws Exception, CancelledException {

	ByteProvider provider = new MemoryByteProvider(currentProgram.getMemory(),
		program.getAddressFactory().getDefaultAddressSpace());

	PortableExecutable pe =
		PortableExecutable.createPortableExecutable(RethrowContinuesFactory.INSTANCE, provider,
			SectionLayout.FILE);

	DOSHeader dos = pe.getDOSHeader();
	if (dos == null || dos.e_magic() != DOSHeader.IMAGE_DOS_SIGNATURE) {
		messages.appendMsg("Not a binary PE program: DOS header not found.");
		return false;
	}

	NTHeader nt = pe.getNTHeader();
	if (nt == null) {
		messages.appendMsg("Not a binary PE program: NT header not found.");
		return false;
	}

	createDataTypes(pe);

	return true;
}
 
Example #13
Source File: ElfBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean analysisWorkerCallback(Program program, Object workerContext,
		TaskMonitor analysisMonitor) throws Exception, CancelledException {

	set(program, analysisMonitor);

	Listing listing = currentProgram.getListing();
	SymbolTable symbolTable = currentProgram.getSymbolTable();

	ByteProvider provider = new MemoryByteProvider(currentProgram.getMemory(),
		currentProgram.getAddressFactory().getDefaultAddressSpace());
	try {
		ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);
		elf.parse();

		processElfHeader(elf, listing);
		processProgramHeaders(elf, listing);
		processSectionHeaders(elf, listing);
		processInterpretor(elf, provider, program);
		processDynamic(elf, provider, program);
		processSymbolTables(elf, listing, symbolTable);
		processStrings(elf);
		processRelocationTables(elf, listing);

		return true;
	}
	catch (ElfException e) {
		messages.appendMsg("Not a binary ELF program: ELF header not found.");
		return false;
	}
}
 
Example #14
Source File: ElfLoader.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<>();

	try {
		ElfHeader elf = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);
		// TODO: Why do we convey image base to loader ?  This will be managed by each loader !
		List<QueryResult> results =
			QueryOpinionService.query(getName(), elf.getMachineName(), elf.getFlags());
		for (QueryResult result : results) {
			boolean add = true;
			// Some languages are defined with sizes smaller than 32
			if (elf.is32Bit() && result.pair.getLanguageDescription().getSize() > 32) {
				add = false;
			}
			if (elf.is64Bit() && result.pair.getLanguageDescription().getSize() <= 32) {
				add = false;
			}
			if (elf.isLittleEndian() &&
				result.pair.getLanguageDescription().getEndian() != Endian.LITTLE) {
				add = false;
			}
			if (elf.isBigEndian() &&
				result.pair.getLanguageDescription().getEndian() != Endian.BIG) {
				add = false;
			}
			if (add) {
				loadSpecs.add(new LoadSpec(this, 0, result));
			}
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, 0, true));
		}
	}
	catch (ElfException e) {
		// not a problem, it's not an elf
	}

	return loadSpecs;
}
 
Example #15
Source File: MachoLoader.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<>();

	// Efficient check to fail fast
	if (provider.length() < MIN_BYTE_LENGTH) {
		return loadSpecs;
	}

	// Efficient check to fail fast
	byte[] magicBytes = provider.readBytes(0, 4);
	if (!MachConstants.isMagic(LittleEndianDataConverter.INSTANCE.getInt(magicBytes))) {
		return loadSpecs;
	}

	try {
		MachHeader machHeader =
			MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE, provider);
		String magic =
			CpuTypes.getMagicString(machHeader.getCpuType(), machHeader.getCpuSubType());
		List<QueryResult> results = QueryOpinionService.query(getName(), magic, null);
		for (QueryResult result : results) {
			loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), result));
		}
		if (loadSpecs.isEmpty()) {
			loadSpecs.add(new LoadSpec(this, machHeader.getImageBase(), true));
		}
	}
	catch (MachException e) {
		// not a problem, just don't add it
	}
	return loadSpecs;
}
 
Example #16
Source File: ElfCompatibilityProvider.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
public ElfCompatibilityProvider(Program program, ByteProvider provider, boolean isAarch32)
{
    this.program = program;
    this.provider = provider;
    this.factoryReader = new LegacyFactoryBundledWithBinaryReader(RethrowContinuesFactory.INSTANCE, this.provider, true);
    this.isAarch32 = isAarch32;
    this.dummyElfHeader = new DummyElfHeader(isAarch32);
}
 
Example #17
Source File: ElfSectionProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public ElfSectionProvider(File exeFile) throws IOException {
	provider = new RandomAccessByteProvider(exeFile);
	try {
		// Parse the ELF header to get the sections
		header = ElfHeader.createElfHeader(RethrowContinuesFactory.INSTANCE, provider);
		header.parse();
	}
	catch (ElfException e) {
		provider.close();
		throw new IOException("Error parsing ELF", e);
	}
}
 
Example #18
Source File: DSymSectionProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public DSymSectionProvider(File dsymFile) throws IOException, MachException {
	this.provider = new RandomAccessByteProvider(dsymFile);
	
	machHeader = MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE, provider);
	machHeader.parse();
	for (Section s : machHeader.getAllSections()) {
		// strip leading "_"'s from section name to normalize
		String fixedSectionName = s.getSectionName().replaceFirst("^_*", "");
		machSectionsByName.put(fixedSectionName, s);
	}
}
 
Example #19
Source File: DyldCacheLocalSymbolsInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void parseNList(MessageLog log, TaskMonitor monitor) throws CancelledException {
	FactoryBundledWithBinaryReader nListReader = new FactoryBundledWithBinaryReader(
		RethrowContinuesFactory.INSTANCE, reader.getByteProvider(), reader.isLittleEndian());
	monitor.setMessage("Parsing DYLD nlist symbol table...");
	monitor.initialize(nlistCount * 2);
	nListReader.setPointerIndex(startIndex + nlistOffset);
	try {

		for (int i = 0; i < nlistCount; ++i) {
			nlistList.add(NList.createNList(nListReader, is32bit));
			monitor.checkCanceled();
			monitor.incrementProgress(1);
		}
		// sort the entries by the index in the string table, so don't jump around reading
		List<NList> sortedList = nlistList
				.stream()
				.sorted((o1, o2) -> Integer.compare(o1.getStringTableIndex(),
					o2.getStringTableIndex()))
				.collect(Collectors.toList());

		// initialize the NList strings from string table
		long stringTableOffset = startIndex + stringsOffset;
		for (NList nList : sortedList) {
			monitor.checkCanceled();
			monitor.incrementProgress(1);
			nList.initString(nListReader, stringTableOffset);
		}
	}
	catch (IOException e) {
		log.appendMsg(DyldCacheAccelerateInfo.class.getSimpleName(), "Failed to parse nlist.");
	}
}
 
Example #20
Source File: MachoProcessBindScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {
	File file = new File( currentProgram.getExecutablePath() );
	if ( !file.exists() ) {
		file = askFile( "Please select original file used to import this program:", "Original File" );
	}
	if (file == null) {
		popup("File cannot be null");
		return;
	}
	if ( !file.exists() ) {
		popup( "Cannot find original binary at \n" + file.getAbsolutePath() );
		return;
	}
	ByteProvider provider = new RandomAccessByteProvider( file ) ;
	try {
		MachHeader header = MachHeader.createMachHeader( RethrowContinuesFactory.INSTANCE, provider );
		if ( header == null ) {
			popup( "unable to create mach header from original file" );
			return;
		}
		header.parse();
		List<DyldInfoCommand> commands = header.getLoadCommands( DyldInfoCommand.class );
		for ( DyldInfoCommand command : commands ) {
			if ( monitor.isCancelled() ) {
				break;
			}
			processCommand( header, provider, command );
		}
	}
	finally {
		provider.close();
	}
}
 
Example #21
Source File: MachoLoader.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Overrides the default implementation to account for Universal Binary (UBI) files. 
 * These must be specially parsed to find the internal file matching the current architecture.
 * <p>
 * {@link FatHeader} is used to parse the file to determine if it is a
 * UBI. If so, each file within the archive is run through the import process until one is
 * found that is successful (meaning it matches the correct architecture). Only one file
 * in the UBI will ever be imported. If the provided file is NOT a UBI, default 
 * import method will be invoked. 
 */
@Override
protected boolean importLibrary(String libName, DomainFolder libFolder, File libFile,
		LoadSpec loadSpec, List<Option> options, MessageLog log, Object consumer,
		Set<String> unprocessedLibs, List<Program> programList, TaskMonitor monitor)
		throws CancelledException, IOException {

	if (!libFile.isFile()) {
		return false;
	}

	try (ByteProvider provider = new RandomAccessByteProvider(libFile)) {

		FatHeader header =
			FatHeader.createFatHeader(RethrowContinuesFactory.INSTANCE, provider);
		List<FatArch> architectures = header.getArchitectures();

		if (architectures.isEmpty()) {
			log.appendMsg("WARNING! No archives found in the UBI: " + libFile);
			return false;
		}

		for (FatArch architecture : architectures) {

			// Note: The creation of the byte provider that we pass to the importer deserves a
			// bit of explanation:
			//
			// At this point in the process we have a FatArch, which provides access to the 
			// underlying bytes for the Macho in the form of an input stream. From that we could
			// create a byte provider. That doesn't work however. Here's why:
			//
			// The underlying input stream in the FatArch has already been parsed and the first
			// 4 (magic) bytes read. If we create a provider from that stream and pass it to 
			// the parent import method, we'll have a problem because that parent method will 
			// try to read those first 4 magic bytes again, which violates the contract of the 
			// input stream provider (you can't read the same bytes over again) and will throw 
			// an exception. To avoid that, just create the provider from the original file 
			// provider, and not from the FatArch input stream. 
			try (ByteProvider bp = new ByteProviderWrapper(provider, architecture.getOffset(),
				architecture.getSize())) {
				if (super.importLibrary(libName, libFolder, libFile, bp, loadSpec, options, log,
					consumer, unprocessedLibs, programList, monitor)) {
					return true;
				}
			}
		}
	}
	catch (UbiException | MachException ex) {
		// Not a Universal Binary file; just continue and process as a normal file. This is 
		// not an error condition so no need to log.
	}

	return super.importLibrary(libName, libFolder, libFile, loadSpec, options, log, consumer,
		unprocessedLibs, programList, monitor);
}
 
Example #22
Source File: DwarfLineNumberAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private ByteProvider getByteProvider(Program program, DwarfSectionNames sectionNames)
		throws IOException {
	File exePath = new File(program.getExecutablePath());
	if (MachoLoader.MACH_O_NAME.equals(program.getExecutableFormat())) {
		File parent = exePath.getParentFile();
		File dSymFile =
			new File(parent, exePath.getName() + ".dSYM/Contents/Resources/DWARF/" +
				exePath.getName());
		if (!dSymFile.exists()) {
			return null;
		}
		RandomAccessByteProvider provider = new RandomAccessByteProvider(dSymFile);
		try {
			MachHeader header =
				MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE, provider);
			header.parse();
			List<Section> allSections = header.getAllSections();
			for (Section section : allSections) {
				if (section.getSectionName().equals(sectionNames.SECTION_NAME_LINE())) {
					return new InputStreamByteProvider(section.getDataStream(header),
						section.getSize());
				}
			}
			return null;
		}
		catch (MachException e) {
		}
		finally {
			provider.close();
		}
		return null;//no line number section existed!
	}
	else if (ElfLoader.ELF_NAME.equals(program.getExecutableFormat())) {
		// We now load the .debug section as an overlay block, no need for the
		// original file
		MemoryBlock block = null;
		block = program.getMemory().getBlock(sectionNames.SECTION_NAME_LINE());
		if (block != null) {
			return new MemoryByteProvider(program.getMemory(), block.getStart());
		}
		// TODO: this will not handle the case where the .debug section is
		// in a separate file.  Can the file in a separate location?
		return null;  // no line number section existed!
	}
	throw new IllegalArgumentException("Unrecognized program format: " +
		program.getExecutableFormat());
}
 
Example #23
Source File: PrelinkFileSystem.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processKModInfoStructures(List<Long> machoHeaderOffsets, TaskMonitor monitor)
		throws IOException {

	Map<PrelinkMap, Long> infoToMachoMap = new HashMap<>();

	kernelCacheDirectory = GFileImpl.fromFilename(this, root, "kernelcache", true, -1, null);

	//
	// if we failed to parse the PRELINK XML file,
	// then look for the kmod_info structure in each KEXT file
	// and use use the
	//
	for (long machoHeaderOffset : machoHeaderOffsets) {
		if (monitor.isCancelled()) {
			break;
		}
		String kextName = "Kext_0x" + Conv.toHexString(machoHeaderOffset) + ".kext";
		try {
			MachHeader header = MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE,
				provider, machoHeaderOffset);
			header.parse();
			String name = findNameOfKext(header, monitor);
			if (name != null) {
				kextName = name + ".kext";
			}
		}
		catch (Exception e) {
			// Failed to parse...shouldn't happen
			Msg.debug(this, "Exception while parsing: " + kextName, e);
		}
		if (machoHeaderOffset == 0x0) {
			kextName = SYSTEM_KEXT; // TODO: this won't happen anymore since the System kext isn't in list of offsets. Problem?
		}
		if (!infoToMachoMap.containsValue(machoHeaderOffset)) {//if there is not already a KEXT at this address, then store it
			long length = provider.length() - machoHeaderOffset;
			GFileImpl file = GFileImpl.fromFilename(this, kernelCacheDirectory, kextName, false,
				length, null);
			unnamedMachoFileMap.put(machoHeaderOffset, file);
			fileToMachoOffsetMap.put(file, machoHeaderOffset);
		}
	}
}
 
Example #24
Source File: PrelinkFileSystem.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void processSystemKext(LanguageService languageService, Program systemProgram,
		TaskMonitor monitor) throws Exception {
	for (GFile file : fileToPrelinkInfoMap.keySet()) {
		if (monitor.isCancelled()) {
			break;
		}

		if (!isChildOf(systemKextFile, file)) {
			continue;
		}

		PrelinkMap prelinkMap = fileToPrelinkInfoMap.get(file);
		if (prelinkMap == null || prelinkMap.getPrelinkExecutableLoadAddr() == -1) {
			continue;
		}

		Address address = systemProgram.getAddressFactory().getDefaultAddressSpace().getAddress(
			prelinkMap.getPrelinkExecutableLoadAddr());

		ByteProvider systemKextProvider =
			new MemoryByteProvider(systemProgram.getMemory(), address);

		MachHeader machHeader = MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE,
			systemKextProvider, 0, false);
		machHeader.parse();

		//MachoLoader loader = new MachoLoader();
		//loader.load( machHeader, systemProgram, new MessageLog(), monitor );

		Namespace namespace = systemProgram.getSymbolTable().createNameSpace(null,
			file.getName(), SourceType.IMPORTED);

		List<SymbolTableCommand> commands =
			machHeader.getLoadCommands(SymbolTableCommand.class);
		for (SymbolTableCommand symbolTableCommand : commands) {
			List<NList> symbols = symbolTableCommand.getSymbols();
			for (NList symbol : symbols) {
				if (monitor.isCancelled()) {
					return;
				}
				Symbol sym = SymbolUtilities.getLabelOrFunctionSymbol(systemProgram,
					symbol.getString(), err -> Msg.error(this, err));
				if (sym != null) {
					sym.setNamespace(namespace);
				}
			}
		}
	}
}
 
Example #25
Source File: MachoBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean analysisWorkerCallback(Program program, Object workerContext,
		TaskMonitor monitor) throws Exception, CancelledException {

	BookmarkManager bookmarkManager = program.getBookmarkManager();

	ByteProvider provider = new MemoryByteProvider(program.getMemory(),
		program.getAddressFactory().getDefaultAddressSpace());

	try {
		MachHeader header = MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE,
			provider, getAddress(program).getOffset(), isRelativeToAddress);
		header.parse();

		Address machAddress = getAddress(program);
		DataType headerDT = header.toDataType();
		createData(machAddress, headerDT);
		setHeaderComment(header, machAddress);

		int commandStartIndex = headerDT.getLength();
		Address commandAddress = machAddress.add(commandStartIndex);

		createFragment(module, headerDT.getDisplayName(), machAddress, commandStartIndex);

		List<LoadCommand> commands = header.getLoadCommands();
		for (LoadCommand command : commands) {
			command.markup(header, this, getAddress(program), true, module, monitor, messages);
			commandAddress = commandAddress.add(command.getCommandSize());
			if (command instanceof UnsupportedLoadCommand) {
				bookmarkManager.setBookmark(machAddress.add(command.getStartIndex()),
					BookmarkType.WARNING, "Load commands", command.getCommandName());
			}
		}

		return true;
	}
	catch (MachException e) {
		messages.appendMsg("Not a binary Mach-O program: Mach header not found.");
		return false;
	}
}
 
Example #26
Source File: PrelinkFileSystem.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Program getProgram(GFile file, LanguageService languageService, TaskMonitor monitor,
		Object consumer) throws Exception {
	Long offset = fileToMachoOffsetMap.get(file);
	if (offset == null) {
		return null;
	}
	MachHeader machHeader =
		MachHeader.createMachHeader(RethrowContinuesFactory.INSTANCE, provider, offset, true);
	LanguageCompilerSpecPair lcs = MacosxLanguageHelper.getLanguageCompilerSpecPair(
		languageService, machHeader.getCpuType(), machHeader.getCpuSubType());
	Program program =
		new ProgramDB(file.getName(), lcs.getLanguage(), lcs.getCompilerSpec(), consumer);
	int id = program.startTransaction(getName());
	boolean success = false;
	try {
		FileBytes fileBytes = MemoryBlockUtils.createFileBytes(program, provider, offset,
			provider.length() - offset, monitor);
		ByteProvider providerWrapper =
			new ByteProviderWrapper(provider, offset, provider.length() - offset);
		MachoProgramBuilder.buildProgram(program, providerWrapper, fileBytes, new MessageLog(),
			monitor);
		program.setExecutableFormat(MachoLoader.MACH_O_NAME);
		program.setExecutablePath(file.getPath());

		if (file.equals(systemKextFile)) {
			processSystemKext(languageService, program, monitor);
		}

		success = true;
	}
	catch (Exception e) {
		throw e;
	}
	finally {
		program.endTransaction(id, success);
		if (!success) {
			program.release(consumer);
		}
	}
	return program;
}
 
Example #27
Source File: PortableExecutableRichPrintScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void run() throws Exception {

	ByteProvider provider =
		new MemoryByteProvider(currentProgram.getMemory(), currentProgram.getImageBase());

	PortableExecutable pe = null;

	try {
		pe = PortableExecutable.createPortableExecutable(RethrowContinuesFactory.INSTANCE,
			provider, SectionLayout.MEMORY, false, false);
	}
	catch (Exception e) {
		printerr("Unable to create PE from current program");
		provider.close();
		return;
	}

	RichHeader rich = pe.getRichHeader();
	if (rich == null || rich.getSize() == 0) {
		print("Rich Header not found");
		provider.close();
		return;
	}

	provider.close();

	String format = "%6s %10s %14s %16s %-16s %s\n";
	printf(format, "Index", "@comp.id", "Ref. Count", "Product Code", "Type", "Description");

	for (RichHeaderRecord record : rich.getRecords()) {

		CompId compid = record.getCompId();

		RichProduct prod = RichHeaderUtils.getProduct(compid.getProductId());

		StringBuilder sb = new StringBuilder();

		String prodVersion = prod == null
				? "Unknown Product (" + Integer.toHexString(compid.getProductId()) + ")"
				: prod.getProductVersion();
		MSProductType prodType = prod == null ? MSProductType.Unknown : prod.getProductType();

		if (prodType != MSProductType.Unknown) {
			sb.append(prodType).append(" from ").append(prodVersion).append(", build ").append(
				compid.getBuildNumber());
		}
		else {
			sb.append(prodVersion);
		}

		printf(format, record.getIndex(), Integer.toHexString(compid.getValue()),
			record.getObjectCount(), Integer.toHexString(compid.getProductId()), prodType,
			sb.toString());
	}

	try {
		verifyChecksum(provider, pe);

	}
	finally {
		provider.close();
	}

}