Java Code Examples for ghidra.program.model.address.Address#getAddressableWordOffset()

The following examples show how to use ghidra.program.model.address.Address#getAddressableWordOffset() . 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: PseudoData.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Scalar getScalar(int opIndex) {
	if (opIndex == 0) {
		Object obj = getValue();
		if (obj instanceof Scalar) {
			return (Scalar) obj;
		}
		else if (obj instanceof Address) {
			Address addrObj = (Address) obj;
			long offset = addrObj.getAddressableWordOffset();
			return new Scalar(addrObj.getAddressSpace().getPointerSize() * 8, offset, false);
		}
	}
	return null;
}
 
Example 2
Source File: GNUExternalDisassembler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Get detailed instruction list for a block of instructions.
 * 
 * @param lang
 *            processor language (corresponding LanguageID must be defined
 *            within LanguageMap.txt)
 * @param blockAddr
 *            start of block ( must be true: (offset & -(2^blockSizeFactor)
 *            == offset)
 * @param blockSizeFactor
 *            the block size factor where blockSize = 2^blockSizeFactor
 *            (must be > 0)
 * @param byteProvider
 *            provider for block of bytes to be disassembled starting at
 *            offset 0
 * @return list of instructions or null if language not supported by GNU
 *         Disassembler
 * @throws Exception
 */
public List<GnuDisassembledInstruction> getBlockDisassembly(Language lang, Address blockAddr,
		int blockSizeFactor, ByteProvider byteProvider) throws Exception {

	GdisConfig gdisConfig = checkLanguage(lang);
	if (gdisConfig == null || gdisConfig.architecture == UNSUPPORTED) {
		return null;
	}

	if (blockSizeFactor < 0 || blockSizeFactor > 8) {
		throw new IllegalArgumentException("blockSizeFactor must be > 0 and <= 8");
	}
	int blockSize = pow2(blockSizeFactor);

	if ((blockAddr.getOffset() & -blockSize) != blockAddr.getOffset()) {
		throw new IllegalArgumentException("Address must be block aligned");
	}

	long addressOffset = blockAddr.getAddressableWordOffset();
	String address = "0x" + Long.toHexString(addressOffset);

	// for aligned languages, don't try on non-aligned block addr/size.
	int alignment = lang.getInstructionAlignment();
	if (blockAddr.getOffset() % alignment != 0) {
		throw new IllegalArgumentException(
			"Address does not satisfy instruction alignment constraint: " + alignment);
	}

	String bytes = getBytes(byteProvider, blockSize);

	return runDisassembler(gdisConfig, address, bytes);
}
 
Example 3
Source File: eBPF_ElfRelocationHandler.java    From eBPF-for-Ghidra with MIT License 4 votes vote down vote up
@Override
public void relocate(ElfRelocationContext elfRelocationContext, ElfRelocation relocation,
		Address relocationAddress) throws MemoryAccessException, NotFoundException {
	
	ElfHeader elf = elfRelocationContext.getElfHeader();
	if (elf.e_machine() != ElfConstants.EM_BPF) {
		return;
	}

	Program program = elfRelocationContext.getProgram();
	Memory memory = program.getMemory();

	int type = relocation.getType();	
	int symbolIndex = relocation.getSymbolIndex();				
	long value;
	boolean appliedSymbol = true;

	if (type == 1) {			
		try {					
			int SymbolIndex= relocation.getSymbolIndex();
			ElfSymbol Symbol = elfRelocationContext.getSymbol(SymbolIndex);
			String map = Symbol.getNameAsString();				
				
			SymbolTable table = program.getSymbolTable();
			Address mapAddr = table.getSymbol(map).getAddress();
			String sec_name = elfRelocationContext.relocationTable.getSectionToBeRelocated().getNameAsString();
			if (sec_name.toString().contains("debug")) {
				return;
			}
				
			value = mapAddr.getAddressableWordOffset();		
			Byte dst = memory.getByte(relocationAddress.add(0x1));
			memory.setLong(relocationAddress.add(0x4), value);			
			memory.setByte(relocationAddress.add(0x1), (byte) (dst + 0x10));				
			}
			catch(NullPointerException e) {}
	}		

	if (appliedSymbol && symbolIndex == 0) {
		markAsWarning(program, relocationAddress, Long.toString(type),
			"applied relocation with symbol-index of 0", elfRelocationContext.getLog());
	}

}
 
Example 4
Source File: PIC30_ElfRelocationHandler.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void relocate(ElfRelocationContext elfRelocationContext, ElfRelocation relocation, Address relocationAddress)
		throws MemoryAccessException, NotFoundException {

	int type = relocation.getType();
	if (type == R_PIC30_NONE) {
		return;
	}

	Program program = elfRelocationContext.getProgram();
	Memory memory = program.getMemory();

	int symbolIndex = relocation.getSymbolIndex();

	int addend = (int) relocation.getAddend();

	if (symbolIndex == 0) {// TODO
		return;
	}

	long relocWordOffset = (int) relocationAddress.getAddressableWordOffset();

	ElfSymbol sym = elfRelocationContext.getSymbol(symbolIndex);
	int symbolValue = (int) elfRelocationContext.getSymbolValue(sym); // word offset

	int oldValue = memory.getInt(relocationAddress);
	short oldShortValue = memory.getShort(relocationAddress);

	int newValue;

	ElfHeader elf = elfRelocationContext.getElfHeader();
	if (elf.e_machine() == ElfConstants.EM_DSPIC30F) {
		switch (type) {
		case R_PIC30_16: // 2
			newValue = (symbolValue + addend + oldShortValue) & 0xffff;
			memory.setShort(relocationAddress, (short) newValue);
			break;
		case R_PIC30_32: // 3
			newValue = symbolValue + addend + oldValue;
			memory.setInt(relocationAddress, newValue);
			break;
		case R_PIC30_FILE_REG_WORD_WITH_DST: // 7
			int reloc = symbolValue >> 1;
			reloc += addend;
			reloc += oldValue >> 4;
			reloc &= 0x7fff;
			newValue = (reloc << 4) | (oldValue & ~0x7fff0);
			memory.setInt(relocationAddress, newValue);
			break;
		case R_PIC30_WORD: // 8
		case R_PIC30_WORD_TBLOFFSET: // 0x15
			reloc = symbolValue;
			reloc += addend;
			reloc += oldValue >> 4;
			reloc &= 0xffff;
			newValue = (reloc << 4) | (oldValue & ~0x0ffff0);
			memory.setInt(relocationAddress, newValue);
			break;
		case R_PIC30_WORD_TBLPAGE: // 0x18
			reloc = symbolValue >> 16;
			reloc += addend;
			reloc += oldValue >> 4;
			reloc &= 0xffff;
			if (isEDSVariant(elfRelocationContext)) {
				reloc |= 0x100;
			}
			newValue = (reloc << 4) | (oldValue & ~0x0ffff0);
			memory.setInt(relocationAddress, newValue);
			break;
		case R_PIC30_PCREL_BRANCH: // 0x1c
			newValue = (int) (symbolValue - relocWordOffset + oldShortValue - 2);
			newValue >>>= 1;
			memory.setShort(relocationAddress, (short) (newValue & 0xffff));
			break;
		default:
			String symbolName = sym.getNameAsString();
			markAsUnhandled(program, relocationAddress, type, symbolIndex, symbolName,
					elfRelocationContext.getLog());
			break;
		}
	}
}
 
Example 5
Source File: EndInstructionValue.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public long getValue(ParserWalker walker) throws MemoryAccessException {
	Address addr = walker.getNaddr();
	return addr.getAddressableWordOffset();
}
 
Example 6
Source File: StartInstructionValue.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public long getValue(ParserWalker walker) throws MemoryAccessException {
	Address addr = walker.getAddr();
	return addr.getAddressableWordOffset();
}
 
Example 7
Source File: RefTypeFactory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private static RefType getMemRefType(Instruction instr, Address memAddr) {

		long memOffset = memAddr.getAddressableWordOffset();

		RefType refType = null;
		Varnode offsetVarnode = null;
		Varnode valueVarnode = null;
		for (PcodeOp op : instr.getPcode()) {
			Varnode[] inputs = op.getInputs();
			if (op.getOpcode() == PcodeOp.INT_ZEXT || op.getOpcode() == PcodeOp.COPY) {
				if (inputs[0].isConstant() && inputs[0].getOffset() == memOffset) {
					offsetVarnode = op.getOutput();
					refType = RefType.DATA;
					continue;
				}
			} // TODO: Could track copy of offsetVarnode thus producing multiple offsetVarnodes
			if (op.getOpcode() == PcodeOp.STORE) {
				if (memAddr.getAddressSpace().getUnique() == inputs[0].getSpace() &&
					(memOffset == inputs[1].getOffset() || inputs[1].equals(offsetVarnode))) {
					if (refType != null && refType.isRead()) {
						return RefType.READ_WRITE;
					}
					refType = RefType.WRITE;
				}
			}
			else if (op.getOpcode() == PcodeOp.LOAD) {
				if (memAddr.getAddressSpace().getUniqueSpaceID() == inputs[0].getOffset() &&
					(memOffset == inputs[1].getOffset() || inputs[1].equals(offsetVarnode))) {
					if (refType != null && refType.isWrite()) {
						return RefType.READ_WRITE;
					}
					refType = RefType.READ;
					valueVarnode = op.getOutput();
				}
			}
			else {
				for (Varnode in : inputs) {
					if (refType == null && in.isConstant() && in.getOffset() == memOffset) {
						refType = RefType.DATA;
					}
					// changed to only compare the address offsets because of problem with overlay spaces
					// probably should look into why one is in an overlay and the other isn't when
					// they should match
					else if (in.isAddress() && in.getAddress().getOffset() == memAddr.getOffset()) {
						if (refType != null && refType.isWrite()) {
							return RefType.READ_WRITE;
						}
						refType = RefType.READ;
					}
				}
			}
			if (valueVarnode != null && isFlowOp(op) && valueVarnode.equals(inputs[0])) {
				return RefType.INDIRECTION;
			}
		}
		return refType;
	}
 
Example 8
Source File: EmbeddedFinderScript.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
  public void run() throws Exception {
byte[] MAGIC_DOS_HEADER = new byte[] { 0x4d, 0x5a };				// M Z
byte[] MAGIC_NT_HEADER  = new byte[] { 0x50, 0x45, 0x00, 0x00 };	// P E 0x00 0x00

List<Address> allFound = new ArrayList<Address>();

Memory memory = currentProgram.getMemory();
Address baseAddr = memory.getMinAddress();
Address currAddr = baseAddr;

while (currAddr != null) {
	// The purpose of breaking each check into small segments (where they could be combined)
	// is to make way for future file type support, keep code clean, and to encourage readability.
	boolean DOSExists = false;
	boolean NTExists = false;
	boolean DOSAgreesWithNT = false;

	Address DOS = memory.findBytes(currAddr, MAGIC_DOS_HEADER, null, true, getMonitor());
	if (DOS != null) {
		// IMAGE_DOS_HEADER is 128 bytes in length, so let's check if that much memory is available
		if (memory.contains(DOS.add(128)))
			DOSExists = true;
	}

	Address NT = memory.findBytes(DOS, MAGIC_NT_HEADER, null, true, getMonitor());
	if (NT != null) {
		// IMAGE_NT_HEADERS32 is 80 bytes in length, so let's check if that much memory is available
		if (memory.contains(NT.add(80)))
			NTExists = true;
	}

	if (DOSExists && NTExists) {
		// It would be better to import the proper structs rather than hard coding offsets.
		// However I'm unsure of what the best way of doing this would be. It's possible to include WINNT.h
		// but this requires the non-development environment to have access to it which makes things
		// less flexible and renders it brittle for future embedded target-type searches.
		// IMAGE_DOS_HEADER + 0x3c is the IMAGE_NT_HEADERS32 offset
		long impliedOffset = memory.getShort(DOS.add(0x3c));
		long actualOffset = NT.getAddressableWordOffset() - DOS.getAddressableWordOffset();
		if (impliedOffset == actualOffset)
			DOSAgreesWithNT = true;
	}

	if (DOSAgreesWithNT) {
		byte[] MAGIC_NT_HEADER_TEST = new byte[4];	// [TODO] Get this to dynamically pull correct size, not hardcoded
		memory.getBytes(NT, MAGIC_NT_HEADER_TEST);

		if (Arrays.equals(MAGIC_NT_HEADER, MAGIC_NT_HEADER_TEST)) {
			if (DOS != baseAddr)
				allFound.add(DOS);		// We only care about targets that are not also the parent file
		}
	}

	if (DOS != null)
		currAddr = DOS.add(1);	// Ensure next search doesn't overlap with current target
	else
		currAddr = null;
}

// Present user with target discovery(s)

if (allFound.isEmpty())
	println("No embedded targets identified");
else {
	println("Embedded targets identified");
	for (Address found : allFound)
		println("\t" + found.toString());
}
  }
 
Example 9
Source File: ElfRelocationContext.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Get the adjusted symbol value based upon its placement within the program.
 * This value may differ from symbol.getValue() and will reflect the addressable
 * unit/word offset of it program address.
 * @param symbol Elf symbol
 * @return adjusted Elf symbol value or 0 if symbol mapping not found
 */
public long getSymbolValue(ElfSymbol symbol) {
	Address symAddr = symbolMap.get(symbol);
	return symAddr != null ? symAddr.getAddressableWordOffset() : 0;
}