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

The following examples show how to use ghidra.program.model.mem.MemoryBlock#isInitialized() . 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: ArmAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Disassemble at the specified target address and optionally create a mnemonic flow reference.
 * @param monitor
 * @param instruction flow from instruction
 * @param target disassembly address
 * @param flowType if not null a reference from the instruction mnemonic will be created to the specified
 * target address using this flowType.
 * @param addRef true if a reference should be added.
 *
 */
void doArmThumbDisassembly(Program program, Instruction instruction, VarnodeContext context,
		Address target, FlowType flowType, boolean addRef, TaskMonitor monitor) {
	if (target == null) {
		return;
	}
	
	target = flowArmThumb(program, instruction, context, target, flowType, addRef);
	if (target == null) {
		return;
	}

	// this is here so the reference gets created, but not - disassembled if it is in a bad part of memory.
	// something computed it into the memory
	MemoryBlock block = program.getMemory().getBlock(target);
	if (block == null || !block.isExecute() || !block.isInitialized() ||
		block.getName().equals("EXTERNAL")) {
		return;
	}
	
	Disassembler dis = Disassembler.getDisassembler(program, monitor, null);
	AddressSet disassembleAddrs = dis.disassemble(target, null);
	AutoAnalysisManager.getAnalysisManager(program).codeDefined(disassembleAddrs);
}
 
Example 5
Source File: DataPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private int getDataTypeSize(Program program, DataType dataType, Address start) {

		int newSize = dataType.getLength();
		if (newSize >= 0) {
			return newSize;
		}

		if (dataType instanceof Dynamic || dataType instanceof FactoryDataType) {
			MemoryBlock block = program.getMemory().getBlock(start);
			if (block == null || !block.isInitialized()) {
				tool.setStatusInfo(
					dataType.getName() + " may only be applied on initialized memory");
				return -1;
			}
		}

		DataTypeInstance dataTypeInstance = DataTypeInstance.getDataTypeInstance(dataType,
			new DumbMemBufferImpl(program.getMemory(), start));
		if (dataTypeInstance == null) {
			tool.setStatusInfo("Unallowed data type at " + start + ": " + dataType.getName());
			return -1;
		}

		return dataTypeInstance.getLength();
	}
 
Example 6
Source File: PCSX2SaveStateImporter.java    From ghidra-emotionengine with Apache License 2.0 5 votes vote down vote up
private void replaceBlock(MemoryBlock block, ByteBuffer buf) throws Exception {
    byte[] bytes = new byte[(int) block.getSize()];
    buf.get(bytes);
    if (!block.isInitialized()) {
        if (block instanceof MemoryBlockDB) {
            ((MemoryBlockDB) block).initializeBlock((byte) 0);
            block.setRead(true);
            block.setWrite(true);
        }
    }
    block.putBytes(block.getStart(), bytes);
}
 
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: ElfDefaultGotPltMarkup.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private Data createPointer(Address addr, boolean keepRefWhenValid)
		throws CodeUnitInsertionException {

	MemoryBlock block = memory.getBlock(addr);
	if (block == null || !block.isInitialized()) {
		return null;
	}
	int pointerSize = program.getDataTypeManager().getDataOrganization().getPointerSize();
	Pointer pointer = PointerDataType.dataType;
	if (elf.is32Bit() && pointerSize != 4) {
		pointer = Pointer32DataType.dataType;
	}
	else if (elf.is64Bit() && pointerSize != 8) {
		pointer = Pointer64DataType.dataType;
	}
	Data data = listing.getDataAt(addr);
	if (data == null || !pointer.isEquivalent(data.getDataType())) {
		if (data != null) {
			listing.clearCodeUnits(addr, addr.add(pointerSize - 1), false);
		}
		data = listing.createData(addr, pointer);
	}
	Address refAddr = (Address) data.getValue();
	if (keepRefWhenValid) {
		if (memory.contains(refAddr)) {
			return data;
		}
		Symbol syms[] = program.getSymbolTable().getSymbols(refAddr);
		if (syms != null && syms.length > 0 && syms[0].getSource() != SourceType.DEFAULT) {
			return data;
		}
	}
	removeMemRefs(data);
	return data;
}
 
Example 9
Source File: ElfSectionHeader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
ElfSectionHeader(ElfHeader header, MemoryBlock block, int sh_name, long imageBase)
		throws MemoryAccessException {

	this.header = header;
	this.sh_name = sh_name;

	if (block.isInitialized()) {
		sh_type = ElfSectionHeaderConstants.SHT_PROGBITS;
	}
	else {
		sh_type = ElfSectionHeaderConstants.SHT_NOBITS;
	}
	sh_flags = ElfSectionHeaderConstants.SHF_ALLOC | ElfSectionHeaderConstants.SHF_WRITE |
		ElfSectionHeaderConstants.SHF_EXECINSTR;
	sh_addr = block.getStart().getOffset();
	sh_offset = block.getStart().getAddressableWordOffset() - imageBase;
	sh_size = block.getSize();
	sh_link = 0;
	sh_info = 0;
	sh_addralign = 0;
	sh_entsize = 0;
	name = block.getName();

	data = new byte[(int) sh_size];
	if (block.isInitialized()) {
		block.getBytes(block.getStart(), data);
	}

	modified = true;
}
 
Example 10
Source File: MemoryByteProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public long length() throws IOException {
	MemoryBlock block = memory.getBlock(baseAddress);
	if (block == null || !block.isInitialized()) {
		return 0;
	}
	return block.getEnd().subtract(baseAddress) + 1;
}
 
Example 11
Source File: ConstantPropagationAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected AddressSetView removeUninitializedBlock(Program program, AddressSetView set) {
	MemoryBlock[] blocks = program.getMemory().getBlocks();
	for (MemoryBlock block : blocks) {
		if (block.isInitialized()) {
			continue;
		}
		AddressSet blocksSet = new AddressSet();
		blocksSet.addRange(block.getStart(), block.getEnd());
		set = set.subtract(blocksSet);
	}
	return set;
}
 
Example 12
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 13
Source File: FidServiceLibraryIngest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether a function is external.
 * @param function the function
 * @return whether the function is external
 */
private static boolean functionIsExternal(Function function) {
	if (function.isExternal()) {
		return true;
	}
	Address entryPoint = function.getEntryPoint();
	MemoryBlock block = function.getProgram().getMemory().getBlock(entryPoint);
	if (!block.isInitialized()) {
		return true;
	}
	return false;
}
 
Example 14
Source File: MipsPreAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private AddressSetView removeUninitializedBlock(Program program, AddressSetView set) {
	MemoryBlock[] blocks = program.getMemory().getBlocks();
	for (MemoryBlock block : blocks) {
		if (block.isInitialized() && block.isLoaded()) {
			continue;
		}
		AddressSet blocksSet = new AddressSet();
		blocksSet.addRange(block.getStart(), block.getEnd());
		set = set.subtract(blocksSet);
	}
	return set;
}
 
Example 15
Source File: AddressTypeOverviewColorService.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private boolean isInInitializedBlock(Address address) {
	MemoryBlock block = program.getMemory().getBlock(address);
	return block != null && block.isInitialized();
}
 
Example 16
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 17
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 18
Source File: ApplyFunctionDataTypesCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void checkDoApplyFunctionDefinition(TaskMonitor monitor, String functionName,
		FunctionDefinition fdef, Symbol sym) {

	monitor.setMessage("Apply Function Signature '" + functionName + "'");

	// function
	//    maybe change its signature
	Address address = sym.getAddress();

	Function func = program.getFunctionManager().getFunctionAt(address);
	if (func != null) {
		if (func.isThunk() || func.getSignature(true).equals(fdef)) {
			return;
		}

		SourceType mostTrusted = getMostTrustedParameterSource(func);
		if (alwaysReplace || !source.isLowerPriorityThan(mostTrusted)) {
			applyFunction(sym, fdef);
		}
		return;
	}

	// check if already part of a function
	func = program.getFunctionManager().getFunctionContaining(address);
	if (func != null) {
		// overlap, don't apply
		return;
	}

	if (!isValidFunctionStart(monitor, address)) {
		return;
	}

	// no function
	//    maybe apply
	CreateFunctionCmd functionCmd = new CreateFunctionCmd(address);
	Listing listing = program.getListing();
	if (sym.isExternal() || listing.getInstructionAt(address) != null) {
		// instruction or external - create function, change its signature
		functionCmd.applyTo(program);
		applyFunction(sym, fdef);
		return;
	}

	// symbols in uninitialized blocks are pushed into externals by importer
	MemoryBlock block = program.getMemory().getBlock(address);
	if (block != null && !block.isInitialized()) {
		return;
	}

	if (listing.getUndefinedDataAt(address) != null) {
		// undefined data - check for likely code
		PseudoDisassembler pdis = new PseudoDisassembler(program);
		if (pdis.isValidSubroutine(address)) {
			DisassembleCommand disassembleCmd = new DisassembleCommand(address, null, true);
			disassembleCmd.applyTo(program);
			functionCmd.applyTo(program);
			applyFunction(sym, fdef);
		}
	}
}
 
Example 19
Source File: CondenseRepeatingBytes.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
   public void run() throws Exception {
	
	if (currentAddress == null) {
            println("No Location.");
            return;
        }
	MemoryBlock currentMemoryBlock = currentProgram.getMemory().getBlock(currentAddress);
	if(!currentMemoryBlock.isInitialized()){
		println("Script cannot run in uninitialized memory.");
		return;
	}
		
	Listing listing = currentProgram.getListing();
	Address currentAddr = currentAddress;
	byte repeatingByte = currentProgram.getMemory().getByte(currentAddr);
	int repeatLen = 1;
	currentAddr = currentAddr.addNoWrap(1);
	byte nextByte;		
	boolean sameMemoryBlock;
	if(currentProgram.getMemory().getBlock(currentAddr).equals(currentMemoryBlock)) {
		nextByte = currentProgram.getMemory().getByte(currentAddr);
		sameMemoryBlock = true;
	}
	else{
		sameMemoryBlock = false;
		return;
	}
	
	boolean noCollisions = true;
	
	while((sameMemoryBlock) && (nextByte == repeatingByte) && (noCollisions)){
		repeatLen++;
		currentAddr = currentAddr.addNoWrap(1);
		if(currentProgram.getMemory().getBlock(currentAddr) != currentMemoryBlock){
			sameMemoryBlock = false;				
		}
		else{
			nextByte = currentProgram.getMemory().getByte(currentAddr);
			noCollisions = listing.isUndefined(currentAddr,currentAddr);
		}			
	}
	

	listing.createData(currentAddress, new AlignmentDataType(), repeatLen);				
	
	println("Applied Alignment datatype at " + currentAddress.toString());				
		
}
 
Example 20
Source File: CondenseRepeatingBytesAtEndOfMemory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
   public void run() throws Exception {		
		
	if (currentAddress == null) {
		println("No Location.");
	    return;
	}
	MemoryBlock memoryBlock = currentProgram.getMemory().getBlock(currentAddress);
	if(!memoryBlock.isInitialized()){
		println("Script cannot run in uninitialized memory.");
		return;
	}
	Listing listing = currentProgram.getListing();
	

	Address currentAddr = currentAddress;        
	
	boolean isInitializedBlock = memoryBlock.isInitialized();
	if(isInitializedBlock){
		currentAddr = memoryBlock.getEnd();
		println("end of byte addr is " + currentAddr);
		byte repeatingByte = currentProgram.getMemory().getByte(currentAddr);
		
	
		MemoryBlock currentMemoryBlock = null;		
	
		
		// search for next repeatedByte from the end of memory
		// until it hits defined area or different byte		
					
		byte prevByte = repeatingByte;
		int repeatLen = 0;
		boolean noCollisions = listing.isUndefined(currentAddr,currentAddr);
		boolean hasLabels = currentProgram.getSymbolTable().hasSymbol(currentAddr);
		println("no collisions at end = " + noCollisions);
		currentMemoryBlock = currentProgram.getMemory().getBlock(currentAddr);
		while((prevByte == repeatingByte) && (noCollisions) && (currentMemoryBlock.equals(memoryBlock)) && (!hasLabels)){
			repeatLen++;
			currentAddr = currentAddr.addNoWrap(-1);
			prevByte = currentProgram.getMemory().getByte(currentAddr);
			noCollisions = listing.isUndefined(currentAddr,currentAddr);
			hasLabels = currentProgram.getSymbolTable().hasSymbol(currentAddr);
			currentMemoryBlock = currentProgram.getMemory().getBlock(currentAddr);					
		}
		if(repeatLen > 0){
		// this takes care of the last one tested that failed
		currentAddr = currentAddr.addNoWrap(1);												
		listing.createData(currentAddr, new AlignmentDataType(), repeatLen);				
		
		println("Applied Alignment datatype at " + currentAddr.toString());												
		 
		}
		else{
			println("No repeating bytes OR data already defined at end of " + memoryBlock);
		}
	}
	else{
		println("Cannot condense uninitialized memory.");
	}		
}