Java Code Examples for ghidra.program.model.mem.MemoryBlock#isExecute()

The following examples show how to use ghidra.program.model.mem.MemoryBlock#isExecute() . 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: MipsR5900AddressAnalyzer.java    From ghidra-emotionengine with Apache License 2.0 6 votes vote down vote up
Address MipsExtDisassembly(Program program, Instruction instruction, VarnodeContext context,
		Address target, TaskMonitor monitor) {
	if (target == null) {
		return null;
	}

	Address addr = instruction.getMinAddress().getNewAddress(target.getOffset() & 0xfffffffe);
	if (addr != null) {
		MemoryBlock block = program.getMemory().getBlock(addr);
		if (block == null || !block.isExecute() || !block.isInitialized() ||
			block.getName().equals("EXTERNAL")) {
			return addr;
		}

		Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
		AddressSet disassembleAddrs = dis.disassemble(addr, null);
		AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembleAddrs);
	}

	return addr;
}
 
Example 2
Source File: MipsAddressAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
Address MipsExtDisassembly(Program program, Instruction instruction, VarnodeContext context,
		Address target, TaskMonitor monitor) {
	if (target == null) {
		return null;
	}

	Address addr = flowISA(program, instruction, context, target);
	if (addr != null) {
		MemoryBlock block = program.getMemory().getBlock(addr);
		if (block == null || !block.isExecute() || !block.isInitialized() ||
			block.getName().equals("EXTERNAL")) {
			return addr;
		}

		Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
		AddressSet disassembleAddrs = dis.disassemble(addr, null);
		AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembleAddrs);
	}

	return addr;
}
 
Example 3
Source File: MemoryBytePatternSearcher.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private long getNumToSearch(Program program, AddressSetView searchSet) {
	long numAddresses = 0;
	MemoryBlock[] blocks = program.getMemory().getBlocks();
	for (MemoryBlock block : blocks) {
		// check if entire block has anything that is searchable
		if (!block.isInitialized()) {
			continue;
		}
		if (doExecutableBlocksOnly && !block.isExecute()) {
			continue;
		}
		if (searchSet != null && !searchSet.isEmpty() &&
			!searchSet.intersects(block.getStart(), block.getEnd())) {
			continue;
		}
		numAddresses += block.getSize();
	}
	return numAddresses;
}
 
Example 4
Source File: PowerPC64_ElfExtension.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void paintTocAsR2value(long tocBaseOffset, ElfLoadHelper elfLoadHelper,
		TaskMonitor monitor) {

	Program program = elfLoadHelper.getProgram();
	ProgramContext programContext = program.getProgramContext();
	Register r2reg = program.getRegister("r2");
	RegisterValue tocValue = new RegisterValue(r2reg, BigInteger.valueOf(tocBaseOffset));

	for (MemoryBlock block : program.getMemory().getBlocks()) {
		if (block.isExecute()) {
			try {
				programContext.setRegisterValue(block.getStart(), block.getEnd(), tocValue);
			}
			catch (ContextChangeException e) {
				String msg = "Failed to set r2 as TOC_BASE on memory block " + block.getName();
				Msg.error(this, msg + ": " + e.getMessage());
				elfLoadHelper.log(msg);
			}
		}
	}

}
 
Example 5
Source File: AggressiveInstructionFinderAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Check if there are blocks marked executable.
 *   If there are exec blocks, remove all un-exec blocks from the set.
 * @param program
 * @param set
 */
private AddressSetView checkExecBlocks(Program program, AddressSetView set) {
	// check if there is a block marked unexec

	AddressSet execSet = new AddressSet();
	MemoryBlock blocks[] = program.getMemory().getBlocks();
	for (MemoryBlock block : blocks) {
		if (block.isExecute()) {
			execSet.addRange(block.getStart(), block.getEnd());
		}
	}

	if (execSet.isEmpty()) {
		return set;
	}
	return set.intersect(execSet);
}
 
Example 6
Source File: DragonHelper.java    From dragondance with GNU General Public License v3.0 5 votes vote down vote up
public static List<MemoryBlock> getExecutableMemoryBlocks() {
	MemoryBlock[] blocks = fapi.getCurrentProgram().getMemory().getBlocks();
	List<MemoryBlock> memList = new ArrayList<MemoryBlock>();
	
	for (MemoryBlock block : blocks) {
		if (block.isExecute()) {
			memList.add(block);
		}
	}
	
	return memList;
}
 
Example 7
Source File: MemoryBytePatternSearcher.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Search initialized memory blocks for all patterns(bytes/mask/action).
 * Call associated action for each pattern matched.
 * 
 * @param program to be searched
 * @param searchSet set of bytes to restrict search, if null or empty then search all memory blocks
 * @param monitor allow canceling and reporting of progress
 * 
 * @throws CancelledException if canceled
 */
public void search(Program program, AddressSetView searchSet, TaskMonitor monitor)
		throws CancelledException {
	if (root == null) {
		root = SequenceSearchState.buildStateMachine(patternList);
	}

	numToSearch = getNumToSearch(program, searchSet);
	monitor.setMessage(searchName + " Search");
	monitor.initialize(numToSearch);

	MemoryBlock[] blocks = program.getMemory().getBlocks();
	for (MemoryBlock block : blocks) {
		monitor.setProgress(numSearched);
		// check if entire block has anything that is searchable
		if (!block.isInitialized()) {
			continue;
		}
		if (doExecutableBlocksOnly && !block.isExecute()) {
			continue;
		}
		if (searchSet != null && !searchSet.isEmpty() &&
			!searchSet.intersects(block.getStart(), block.getEnd())) {
			continue;
		}

		try {
			searchBlock(root, program, block, searchSet, monitor);
		}
		catch (IOException e) {
			Msg.error(this, "Unable to scan block " + block.getName() + " for " + searchName);
		}
		numSearched += block.getSize();
	}
}
 
Example 8
Source File: DisassembleCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private AddressSetView getExecutableSet(Program program) {
	Memory memory = program.getMemory();
	AddressSet set = new AddressSet();
	for (MemoryBlock block : memory.getBlocks()) {
		if (block.isExecute()) {
			set.add(block.getStart(), block.getEnd());
		}
	}
	return set;
}
 
Example 9
Source File: ObjectiveC1_Utilities.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the address is THUMB code.
 */
public static boolean isThumb(Program program, Address address) {
	Processor ARM = Processor.findOrPossiblyCreateProcessor("ARM");
	if (program.getLanguage().getProcessor().equals(ARM)) {
		Memory memory = program.getMemory();
		MemoryBlock block = memory.getBlock(address);
		if (block != null && block.isExecute()) {
			return (address.getOffset() % 2) != 0;
		}
	}
	return false;
}
 
Example 10
Source File: ElfDefaultGotPltMarkup.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void processPLT(TaskMonitor monitor) throws CancelledException {

		// TODO: Handle case where PLT is non-executable pointer table

		if (elf.isRelocatable()) {
			return; //relocatable files do not have .PLT sections
		}

		MemoryBlock pltBlock = memory.getBlock(ElfSectionHeaderConstants.dot_plt);
		// TODO: This is a band-aid since there are many PLT implementations and this assumes only one.
		if (pltBlock == null || !pltBlock.isExecute() ||
			pltBlock.getSize() <= ElfConstants.PLT_ENTRY_SIZE) {
			return;
		}

		int skipPointers = ElfConstants.PLT_ENTRY_SIZE;

		// ARM, AARCH64 and others may not store pointers at start of .plt
		if (elf.e_machine() == ElfConstants.EM_ARM || elf.e_machine() == ElfConstants.EM_AARCH64) {
			// TODO: Should be handled by extension
			skipPointers = 0;
		}

		// Process PLT section
		Address minAddress = pltBlock.getStart().add(skipPointers);
		Address maxAddress = pltBlock.getEnd();
		processLinkageTable(ElfSectionHeaderConstants.dot_plt, minAddress, maxAddress, monitor);
	}
 
Example 11
Source File: ArmSymbolAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log) {
	monitor.setMessage("ARM/Thumb symbol analyzer");

	Memory memory = program.getMemory();

	// Get and iterate over symbols
	SymbolIterator it = program.getSymbolTable().getPrimarySymbolIterator(set, true);
	while (it.hasNext() && !monitor.isCancelled()) {
		Symbol primarySymbol = it.next();
		Address address = primarySymbol.getAddress();
		if (!address.isMemoryAddress()) {
			continue;
		}

		MemoryBlock block = memory.getBlock(address);
		if (block == null || !block.isExecute()) {
			continue;
		}

		// Check if last bit is set to indicate Thumb
		if ((address.getOffset() & 0x01) != 0x01) {
			continue;
		}

		Address newAddress = address.subtract(1L);

		moveFunction(program, address, newAddress);

		moveSymbols(program, address, newAddress);

		updateEntryPoint(program, address, newAddress);

		setTModeRegister(program, newAddress);

	}
	return true;
}
 
Example 12
Source File: MemoryTypeProgramLocationBasedTableColumn.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void updateForExecute(MemoryBlock block, StringBuffer buffy,
		StringBuffer tooltipBuffy) {

	if (block.isExecute()) {
		buffy.append("<b>E</b>");
		tooltipBuffy.append("<image src=\"" + onIcon.getDescription() + "\">");
	}
	else {
		buffy.append(HTMLUtilities.colorString(disabledColor, "E"));
		tooltipBuffy.append("<image src=\"" + offIcon.getDescription() + "\">");
	}
	tooltipBuffy.append(HTMLUtilities.spaces(2)).append("Execute<br>");
}
 
Example 13
Source File: VxWorksSymTab_Finder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean isExecute(Address addr) {

		// Search all program memory blocks
		for (MemoryBlock block : getMemoryBlocks()) {
			if (block.contains(addr)) {
				return block.isExecute();
			}
		}

		return false;
	}
 
Example 14
Source File: ClipboardPanel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate a set of patterns
 * @param rows patterns to evaluate
 * @return statistics about the pattern matches
 */
public PatternEvaluationStats evaluatePatterns(List<PatternInfoRowObject> rows) {
	ArrayList<Pattern> patternList = getPatternList(rows);
	if (onlyPrePatterns) {
		Msg.showWarn(this, this, "Only Pre-Patterns",
			"Only Pre-Patterns in selection: no true/false positive information will be calculated.");
	}
	SequenceSearchState root = SequenceSearchState.buildStateMachine(patternList);
	indexToSize.clear();
	for (Pattern pattern : patternList) {
		indexToSize.put(pattern.getIndex(), pattern.getSize());
	}
	Program currentProgram = plugin.getCurrentProgram();
	MemoryBlock[] blocks = currentProgram.getMemory().getBlocks();
	PatternEvaluationStats matchStats = new PatternEvaluationStats();
	for (MemoryBlock block : blocks) {
		if (!block.isInitialized()) {
			continue;
		}
		//TODO: add toggle for searching non-executable blocks?
		if (!block.isExecute()) {
			continue;
		}
		searchBlock(root, block, matchStats, currentProgram, TaskMonitor.DUMMY);
	}
	return matchStats;
}
 
Example 15
Source File: FunctionStartAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @return true - if there are any blocks marked executable
 */
private boolean checkForExecuteBlock(Program program) {
	MemoryBlock[] blocks = program.getMemory().getBlocks();

	for (MemoryBlock block : blocks) {
		if (block.isExecute()) {
			return true;
		}
	}
	return false;
}
 
Example 16
Source File: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
public Address createEntryFunction(String name, long entryAddr, TaskMonitor monitor) 
{
    Address entryAddress = this.aSpace.getAddress(entryAddr);

    // TODO: Entry may refer to a pointer - make sure we have execute permission
    MemoryBlock block = this.program.getMemory().getBlock(entryAddress);
    
    if (block == null || !block.isExecute()) 
    {
        return entryAddress;
    }

    Function function = program.getFunctionManager().getFunctionAt(entryAddress);
    
    if (function != null) 
    {
        program.getSymbolTable().addExternalEntryPoint(entryAddress);
        return entryAddress; // symbol-based function already created
    }

    try 
    {
        this.createOneByteFunction(name, entryAddress, true);
    }
    catch (Exception e) 
    {
        Msg.error(this, "Could not create symbol at entry point: " + e);
    }

    return entryAddress;
}
 
Example 17
Source File: VxWorksSymTab_Finder.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address findSymTbl(VxSymbol vxSymbol) throws Exception {

		int testLen = 100;		// number of symbol tbl entries to look for

		boolean hasNonExecute = checkNonExecute();

		// Iterate through all memory blocks
		for (MemoryBlock block : currentProgram.getMemory().getBlocks()) {

			// Skip code/execute blocks if there are non-execute blocks,
			//  otherwise search everything.
			if (hasNonExecute && block.isExecute()) {
				continue;
			}

			// skip uninit
			if (!block.isInitialized()) {
				continue;
			}

			// Search current block for run of testLen symbol table entries
			int testBlkSize = vxSymbol.length * testLen;
			printf("   block: " + block.getName() + " (" + block.getStart() + ", " +
				block.getEnd() + ") ");
			printf("testBlkSize = " + Integer.toHexString(testBlkSize) + "  ");
			System.out.flush();
			long prevOffset = 0;
			Address cursor = block.getStart();
			while ((cursor != null) && isAddress(cursor.getOffset() + testBlkSize, block)) {

				// Script cancel check and visual feedback
				if (monitor.isCancelled()) {
					return null;
				}
				if ((cursor.getOffset() - prevOffset) >= 0x100000) {
					printf(".");
					System.out.flush();
					prevOffset = cursor.getOffset();
				}

				// Determine whether cursor now points to a symbol table
				int i = 0;
				for (Address entry = cursor; isSymTblEntry(entry, vxSymbol) &&
					(i < testLen); entry = entry.add(vxSymbol.length()), i++) {
				}
				if (i == testLen) {
					// May have symbol table -- verify length
					if (getSymTblLen(cursor, vxSymbol) != 0) {
						printf("\n");
						System.out.flush();
						return cursor;	// found  table -- stop searching
					}
					if (debug) {
						printf("Possible symbol table at " + cursor + " has length error\n");
					}
				}

				cursor = cursor.add(4);
			}
			printf("\n");
			printf("   search terminated at:  " + cursor + "\n");
			System.out.flush();
		}
		return null;
	}
 
Example 18
Source File: DemangledVariable.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean applyTo(Program program, Address address, DemanglerOptions options,
		TaskMonitor monitor) throws Exception {

	if (isAlreadyDemangled(program, address)) {
		return true;
	}

	if (!super.applyTo(program, address, options, monitor)) {
		return false;
	}

	Symbol demangledSymbol = applyDemangledName(address, true, true, program);
	DataType demangledDT = getProgramDataType(program);

	if (address.isExternalAddress()) {
		if (demangledSymbol == null) {
			throw new AssertException("Undefined external address: " + address);
		}
		if (demangledDT != null) {
			ExternalLocation extLoc = (ExternalLocation) demangledSymbol.getObject();
			extLoc.setDataType(demangledDT);
		}
		return true;
	}

	Listing listing = program.getListing();

	Data d = listing.getDefinedDataAt(address);
	if (d != null) {
		if (demangledDT == null || !Undefined.isUndefined(d.getDataType())) {
			return true; // preserve existing data quietly
		}
	}

	if (demangledDT != null) {
		CreateDataCmd cmd = new CreateDataCmd(address, demangledDT, false,
			ClearDataMode.CLEAR_ALL_UNDEFINED_CONFLICT_DATA);
		if (!cmd.applyTo(program)) {
			Msg.error(this, "Failed to create data at " + address + ": " + cmd.getStatusMsg());
			return false;
		}
		return true;
	}

	// if the block is marked Executable, don't worry about creating data here
	// unless we really know what type of data it is
	MemoryBlock block = program.getMemory().getBlock(address);
	if (block == null || block.isExecute()) {
		return true;
	}

	// get the symbol after this one.  If smaller than pointer, can't be a pointer
	Address nextSymbolLoc = getNextSymbolLocation(program, address);

	// could be a pointer
	long maximumDataTypeSize = nextSymbolLoc.subtract(address);
	if (createPointer(program, address, maximumDataTypeSize)) {
		return true;
	}

	// Create an undefined data type here to stop any code from being created.
	// Might have to change the data reference creation to ignore undefined data types
	//   when trying to figure out what the data is.
	if (d != null) {
		// something is already there
		return true;
	}

	int size = (maximumDataTypeSize <= 8) ? (int) maximumDataTypeSize : 1;
	demangledDT = Undefined.getUndefinedDataType(size);

	try {
		listing.createData(address, demangledDT);
	}
	catch (CodeUnitInsertionException e) {
		Msg.trace(this, "Unable to create demangled data '" + demangledDT + "' @ " + address);
	}

	return true; // return true, as we did not fail to demangle
}
 
Example 19
Source File: PatternStats.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected void run() throws Exception {
	searchNonExecutableBlocks = true;
	maxFalsePositives = 20;
	File askDirectory = askDirectory("Result Directory", "Save");
	if (!askDirectory.isDirectory()) {
		println("Result directory does not exist: " + askDirectory.getAbsolutePath());
		return;
	}
	ResourceFile[] fileList = null;
	boolean localPattern = askYesNo("Local Pattern", "Use a local pattern file?");
	if (localPattern) {
		File patFile = askFile("Pattern File", "OK");
		fileList = new ResourceFile[1];
		fileList[0] = new ResourceFile(patFile);
	}
	if (!this.isRunningHeadless()) {
		if (askYesNo("DoSummary", "Would you like to summarize results?")) {
			runSummary(askDirectory);
			return;
		}
	}
	functionManager = currentProgram.getFunctionManager();
	listing = currentProgram.getListing();
	String fileName = "pat_" + currentProgram.getExecutableMD5();
	File resFile = new File(askDirectory, fileName);
	if (resFile.exists()) {
		println("Accumulation file already exists, skipping: " + resFile.getAbsolutePath());
		return;
	}
	ProgramDecisionTree patternDecisionTree = Patterns.getPatternDecisionTree();
	if (fileList == null) {
		fileList = Patterns.findPatternFiles(currentProgram, patternDecisionTree);
	}
	ArrayList<Pattern> patternlist = new ArrayList<>();
	for (ResourceFile element : fileList) {
		Pattern.readPatterns(element, patternlist, this);
	}
	if (patternlist.size() == 0) {
		return;
	}
	root = SequenceSearchState.buildStateMachine(patternlist);
	accumList = new ArrayList<>();
	for (int i = 0; i < patternlist.size(); ++i) {
		accumList.add(new PatternAccumulate(patternlist.get(i)));
	}
	MemoryBlock[] blocks = currentProgram.getMemory().getBlocks();
	for (MemoryBlock block2 : blocks) {
		MemoryBlock block = block2;
		if (!block.isInitialized()) {
			continue;
		}
		if (!searchNonExecutableBlocks && !block.isExecute()) {
			continue;
		}
		searchBlock(currentProgram, block, monitor);
	}
	FileWriter out = new FileWriter(resFile);
	out.write("<accumlist>\n");
	for (int i = 0; i < accumList.size(); ++i) {
		StringBuffer buf = new StringBuffer();
		accumList.get(i).saveXml(buf);
		out.write(buf.toString());
	}
	out.write("</accumlist>\n");
	out.close();
}
 
Example 20
Source File: FindUndefinedFunctionsScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void run() throws Exception {
	PatternMatcher[] expectedPatterns = getPatterns();

	boolean doIT =
		askYesNo("Find and Create Functions?", "Would you like find and create functions?");
	if (!doIT) {
		return;
	}

	for (PatternMatcher expectedPattern : expectedPatterns) {
		Address address = currentProgram.getMinAddress();
		while (true) {
			if (monitor.isCancelled()) {
				break;
			}

			Data nextUndefined =
				currentProgram.getListing().getUndefinedDataAfter(address, monitor);
			if (nextUndefined == null) {
				break;
			}
			Address undefinedAddress = nextUndefined.getMinAddress();

			MemoryBlock block = currentProgram.getMemory().getBlock(undefinedAddress);
			if (!block.isExecute()) {
				address = undefinedAddress;
				continue;
			}

			if (expectedPattern.isMatch(undefinedAddress)) {
				disassemble(undefinedAddress);
				createFunction(undefinedAddress, null);
				address = undefinedAddress.add(1);
			}
			else {
				address = undefinedAddress;
			}
		}
	}
}