Java Code Examples for ghidra.program.model.scalar.Scalar#getUnsignedValue()

The following examples show how to use ghidra.program.model.scalar.Scalar#getUnsignedValue() . 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: DexMarkupDataAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processData( Data data, int headerLength, TaskMonitor monitor ) throws Exception {
	for ( int i = 0 ; i < data.getNumComponents( ) ; ++i ) {
		monitor.checkCanceled( );
		Data component = data.getComponent( i );
		if ( component.getNumComponents( ) > 0 ) {
			processData( component, headerLength, monitor );
		}
		if ( component.getReferencesFrom( ).length > 0 ) {
			continue;
		}
		if ( component.getFieldName( ).toLowerCase( ).indexOf( "offset" ) != -1 ) {
			Scalar scalar = component.getScalar( 0 );
			if ( scalar.getUnsignedValue( ) < headerLength ) {// skip low number points into dex header
				continue;
			}
			Address destination = component.getMinAddress( ).getNewAddress( scalar.getUnsignedValue( ) );
			Program program = component.getProgram( );
			ReferenceManager referenceManager = program.getReferenceManager( );
			referenceManager.addMemoryReference( component.getMinAddress( ), destination, RefType.DATA, SourceType.ANALYSIS, 0 );
		}
	}
}
 
Example 2
Source File: DwarfDecoderFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public long doDecode(DwarfDecodeContext context) throws MemoryAccessException {
	Program program = context.getProgram();
	Address addr = context.getAddress();

	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	UnsignedLeb128DataType uleb = UnsignedLeb128DataType.dataType;

	int numAvailBytes = uleb.getLength(buf, -1);

	Scalar scalar = (Scalar) uleb.getValue(buf, uleb.getDefaultSettings(), numAvailBytes);
	long offset = scalar.getUnsignedValue();
	int readLen = uleb.getLength(buf, numAvailBytes);

	context.setDecodedValue(offset, readLen);

	return offset;
}
 
Example 3
Source File: FlatProgramAPI.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new equate on the scalar value
 * at the operand index of the instruction.
 * @param instruction the instruction
 * @param operandIndex the operand index on the instruction
 * @param equateName the name of the equate
 * @return the newly created equate
 * @throws Exception if a scalar does not exist of the specified
 * operand index of the instruction
 */
public final Equate createEquate(Instruction instruction, int operandIndex, String equateName)
		throws Exception {
	Object[] operandObject = instruction.getOpObjects(operandIndex);
	for (Object object : operandObject) {
		if (object instanceof Scalar) {
			Scalar scalar = (Scalar) object;
			long scalarValue = scalar.getUnsignedValue();
			Equate equate =
				currentProgram.getEquateTable().createEquate(equateName, scalarValue);
			equate.addReference(instruction.getMinAddress(), operandIndex);
			return equate;
		}
	}
	throw new InvalidInputException(
		"Unable to create equate on non-scalar instruction operand at " +
			instruction.getMinAddress());
}
 
Example 4
Source File: CliMetadataTokenAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private CliAbstractTableRow getRowForMetadataToken(CliStreamMetadata metaStream, Instruction inst) {
	Object ops[] = inst.getOpObjects(0);
	Scalar tableOp = (Scalar) ops[0];
	Scalar indexOp = (Scalar) ops[1];
	int table = (int) tableOp.getUnsignedValue();
	int index = (int) indexOp.getUnsignedValue();
	CliAbstractTableRow tableRow = metaStream.getTable(table).getRow(index);
	return tableRow;
}
 
Example 5
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 5 votes vote down vote up
Scalar getScalar(int index) {
	Object obj = representationList.get(index);
	if (!(obj instanceof Scalar)) {
		return null;
	}

	Scalar scalar = (Scalar) obj;
	if (scalar.getUnsignedValue() == 0) {
		return processZeroScalar ? scalar : null;
	}
	return scalar;
}
 
Example 6
Source File: CreateOperandReferencesInSelectionScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
 public void run() throws Exception {
listing = currentProgram.getListing();
memory = currentProgram.getMemory();
symbolTable = currentProgram.getSymbolTable();
if(currentSelection == null) {
	monitor.setMessage("You must have a selection for this script to run.");
	return;
}
monitor.setMessage("Creating operand references...");
AddressIterator addrIt = currentSelection.getAddresses(true);
while(addrIt.hasNext()){
	Address addr = addrIt.next();
	CodeUnit cu = listing.getCodeUnitContaining(addr);
	int numOps = cu.getNumOperands();
	for(int i=0;i<numOps;i++){
		Scalar scalar = cu.getScalar(i);
		if(scalar != null){
			//check to see if scalar value is a valid address in program memory
			long scalarValue = scalar.getUnsignedValue();
			Address testAddr = addr.getNewAddress(scalarValue);
			if(memory.contains(testAddr)){
			//if so, create the memory reference on the scalar operand
		  //TODO: not sure if the DATA type for the ref is correct
		// RefTypeFactory.getDefaultMemoryRefType(instr, opIndex)
			cu.addOperandReference(i, testAddr, RefType.DATA, SourceType.ANALYSIS);
			}
		}
		
	}
}


 }
 
Example 7
Source File: ScalarSearchModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Scalar getValue(ScalarRowObject rowObject, Settings settings, Program p,
		ServiceProvider provider) throws IllegalArgumentException {
	Scalar scalar = rowObject.getScalar();

	Scalar unsigned = new Scalar(scalar.bitLength(), scalar.getUnsignedValue(), false);
	return unsigned;

}
 
Example 8
Source File: ScalarSearchModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Scalar getValue(ScalarRowObject rowObject, Settings settings, Program p,
		ServiceProvider provider) throws IllegalArgumentException {
	Scalar scalar = rowObject.getScalar();

	Scalar signed = new Scalar(scalar.bitLength(), scalar.getUnsignedValue(), true);
	return signed;

}
 
Example 9
Source File: FlatProgramAPI.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new equate on the scalar value
 * at the value of the data.
 * @param data the data
 * @param equateName the name of the equate
 * @return the newly created equate
 * @throws InvalidInputException if a scalar does not exist on the data
 */
public final Equate createEquate(Data data, String equateName) throws Exception {
	Object value = data.getValue();
	if (value instanceof Scalar) {
		Scalar scalar = (Scalar) value;
		long scalarValue = scalar.getUnsignedValue();
		Equate equate = currentProgram.getEquateTable().createEquate(equateName, scalarValue);
		equate.addReference(data.getMinAddress(), 0);
		return equate;
	}
	throw new InvalidInputException(
		"Unable to create equate on non-scalar value at " + data.getMinAddress());
}
 
Example 10
Source File: GccAnalysisUtils.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads an signed little endian base 128 integer from memory.
 * @param program the program with memory to be read.
 * @param addr the address in memory to begin reading the signed LEB128.
 * @return the signed LEB128 integer.
 */
public static long readSLEB128(Program program, Address addr) {
	SignedLeb128DataType sleb = SignedLeb128DataType.dataType;

	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	Scalar scalar = (Scalar) sleb.getValue(buf, sleb.getDefaultSettings(), sleb.getLength(buf, -1));
	return scalar.getUnsignedValue();
}
 
Example 11
Source File: GccAnalysisUtils.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads an unsigned little endian base 128 integer from memory.
 * @param program the program with memory to be read.
 * @param addr the address in memory to begin reading the unsigned LEB128.
 * @return the unsigned LEB128 integer.
 */
public static long readULEB128(Program program, Address addr) {
	UnsignedLeb128DataType uleb = UnsignedLeb128DataType.dataType;

	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	Scalar scalar = (Scalar) uleb.getValue(buf, uleb.getDefaultSettings(), uleb.getLength(buf, -1));
	return scalar.getUnsignedValue();
}
 
Example 12
Source File: AbstractImageBaseOffsetDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	DataType dt = getScalarDataType();
	Address imageBase = buf.getMemory().getProgram().getImageBase();
	Scalar value = (Scalar) dt.getValue(buf, settings, length);
	if (value != null && value.getUnsignedValue() != 0) {
		try {
			return imageBase.add(value.getUnsignedValue());
		}
		catch (AddressOutOfBoundsException e) {
			// ignore
		}
	}
	return null;
}
 
Example 13
Source File: Pic12Analyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void handleCallOrBranch(Instruction instr) {

		String mnemonic = instr.getMnemonicString();
		if (CALL_BRANCH_INSTRUCTIONS.contains(mnemonic)) {
			if (paContext.hasValue()) {
				Object[] objs = instr.getOpObjects(0);
				if (objs.length == 1 && objs[0] instanceof Scalar) {
					Scalar s = (Scalar) objs[0];
					long offset =
						((paContext.longValue() << 9) + s.getUnsignedValue()) * INSTRUCTION_LENGTH;
					Address destAddr = instr.getMinAddress().getNewAddress(offset);
					RefType flowType = instr.getFlowType().isCall() ? RefType.UNCONDITIONAL_CALL
							: RefType.UNCONDITIONAL_JUMP;
					refMgr.addMemoryReference(instr.getMinAddress(), destAddr, flowType,
						SourceType.DEFAULT, 0);
					disassembleAt(destAddr);
				}
			}
		}

		// Handle DECFSZ, INCFSZ, BTFSC and BTFSS
		else if (SKIP_INSTRUCTIONS.contains(mnemonic)) {
			Address skipAddr = instr.getMinAddress().add(2 * INSTRUCTION_LENGTH);
			refMgr.addMemoryReference(instr.getMinAddress(), skipAddr, RefType.CONDITIONAL_JUMP,
				SourceType.DEFAULT, Reference.MNEMONIC);
			disassembleAt(skipAddr);
		}
	}
 
Example 14
Source File: CallDepthChangeInfo.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public int getStackOffset(Instruction cu, int opIndex) {
	int offset = 0;
	int offsetReg = 0;
	Register offReg = null;
	Scalar s = null;
	Object obj[] = cu.getOpObjects(opIndex);
	for (int i = 0; obj != null && i < obj.length; i++) {
		if (obj[i] instanceof Scalar) {
			Scalar newsc = (Scalar) obj[i];
			if (s != null) {
				return Function.INVALID_STACK_DEPTH_CHANGE;
			}
			// choose the biggest value....
			if (Math.abs(offset) < newsc.getUnsignedValue()) {
				offset = (int) newsc.getSignedValue();
				s = newsc;
			}
		}

		// check if any register is the stack pointer
		// if it is, need to compute stack depth offset for function
		//
		if (obj[i] instanceof Register) {
			Register reg = (Register) obj[i];
			int depth = getRegDepth(cu.getMinAddress(), reg);
			if (depth != Function.INVALID_STACK_DEPTH_CHANGE &&
				depth != Function.UNKNOWN_STACK_DEPTH_CHANGE) {
				offReg = reg;
				offsetReg = depth;
			}
		}
	}

	// must have a register that has the stack depth in it and a scalar
	if (offReg == null || s == null) {
		return Function.INVALID_STACK_DEPTH_CHANGE;
	}
	offset += offsetReg;

	return offset;
}
 
Example 15
Source File: DecompilerSwitchAnalysisCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address[] getPointerTable(JumpTable.LoadTable loadtable, Address[] switchCases) {

		int size = loadtable.getSize();
		int num = loadtable.getNum();

		if (size > 8) {
			return null;
		}

		AddressSpace addrspace = switchCases[0].getAddressSpace();
		Address[] addresses = new Address[num];

		DataType entrydt =
			AbstractIntegerDataType.getUnsignedDataType(size, program.getDataTypeManager());

		Address addr = loadtable.getAddress();
		DumbMemBufferImpl buf = new DumbMemBufferImpl(program.getMemory(), addr);
		for (int i = 0; i < num; i++) {
			int tableOffset = size * i;
			Address nextAddr = addr.add(tableOffset);
			buf.setPosition(nextAddr);

			Scalar scalar = (Scalar) entrydt.getValue(buf, SettingsImpl.NO_SETTINGS, 0);
			long unsignedOffset = scalar.getUnsignedValue() * addrspace.getAddressableUnitSize();
			long signedOffset = scalar.getSignedValue() * addrspace.getAddressableUnitSize();

			boolean found = false;
			for (Address caddr : switchCases) {
				long offset = caddr.getOffset();
				if (offset == unsignedOffset || offset == signedOffset) {
					found = true;
					addresses[i] = caddr;
					break;
				}
			}
			if (!found) {
				return null;
			}
		}
		return addresses;
	}
 
Example 16
Source File: ScalarColumnConstraintProvider.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Long convert(Scalar value) {
	return value.getUnsignedValue();
}
 
Example 17
Source File: ConvertCommand.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private boolean valuesAreDifferent(Equate equate, Scalar scalar) {
	long value = equate.getValue();
	return value != scalar.getSignedValue() && value != scalar.getUnsignedValue();
}
 
Example 18
Source File: ScalarOperandAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
void checkOperands(Program program, Instruction instr) {
	// Check for scalar operands that are a valid address
	//
	for (int i = 0; i < instr.getNumOperands(); i++) {
		Object objs[] = instr.getOpObjects(i);
		for (int j = 0; j < objs.length; j++) {
			if (!(objs[j] instanceof Scalar)) {
				continue;
			}
			Scalar scalar = (Scalar) objs[j];

			//if a relocation exists, then this is a valid address
			boolean found = false;
			for (int r = 0; r < instr.getLength(); ++r) {
				Address addr = instr.getMinAddress().add(r);
				RelocationTable relocTable = program.getRelocationTable();
				Relocation reloc = relocTable.getRelocation(addr);
				if (reloc != null) {
					try {
						switch (scalar.bitLength()) {
							case 8:
								if (program.getMemory().getByte(addr) == scalar.getSignedValue()) {
									found = true;
								}
								break;
							case 16:
								if (program.getMemory().getShort(addr) == scalar.getSignedValue()) {
									found = true;
								}
								break;
							case 32:
								if (program.getMemory().getInt(addr) == scalar.getSignedValue()) {
									found = true;
								}
								break;
							case 64:
								if (program.getMemory().getLong(addr) == scalar.getSignedValue()) {
									found = true;
								}
								break;
						}
					}
					catch (MemoryAccessException e) {
						// don't care, squelch it.
					}
				}
			}

			if (!found) {
				// don't do any addresses that could be numbers, even if they are in the
				//   address space.
				long value = scalar.getUnsignedValue();
				if (value < 4096 || value == 0xffff || value == 0xff00 || value == 0xffffff ||
					value == 0xff0000 || value == 0xff00ff || value == 0xffffffff ||
					value == 0xffffff00 || value == 0xffff0000 || value == 0xff000000) {
					continue;
				}
			}

			// check the address in this space first
			if (addReference(program, instr, i, instr.getMinAddress().getAddressSpace(), scalar)) {
				continue;
			}

			// then check all spaces
			AddressSpace[] spaces = program.getAddressFactory().getAddressSpaces();
			for (int as = 0; as < spaces.length; as++) {
				if (addReference(program, instr, i, spaces[as], scalar)) {
					break;
				}
			}
		}
	}
}
 
Example 19
Source File: Pic17c7xxAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void handleBSRModification(Instruction instr) {
	bsrContext.writeValue(instr.getMaxAddress());
	String mnemonic = instr.getMnemonicString();
	if ("CLRF".equals(mnemonic)) {
		bsrContext.setValueAt(instr, 0, false);
	}
	else if ("BSF".equals(mnemonic)) {
		if (!bsrContext.setBitAt(instr, instr.getScalar(1), 0)) {
			// Unhandled bsr modification
			Msg.warn(this, "Unhandled BSR bit-set at: " + instr.getMinAddress());
		}
	}
	else if ("BCF".equals(mnemonic)) {
		if (!bsrContext.clearBitAt(instr, instr.getScalar(1), 0)) {
			// Unhandled bsr modification
			Msg.warn(this, "Unhandled BSR bit-set at: " + instr.getMinAddress());
		}
	}
	else if ("BTG".equals(mnemonic)) {
		Scalar s = instr.getScalar(1);
		if (s != null && bsrContext.hasValue()) {
			byte bitmask = (byte) (1 << s.getUnsignedValue());
			long bsrVal = bsrContext.longValue();
			if ((bsrVal & bitmask) == 0) {
				bsrVal = (byte) (bsrVal | bitmask); // set bit
			}
			else {
				bsrVal = (byte) (bsrVal & ~bitmask); // clear bit
			}
			bsrContext.setValueAt(instr, bsrVal, false);
		}
		else {
			// Unhandled bsr modification
			Msg.warn(this, "Unhandled BSR bit-toggle at: " + instr.getMinAddress());
			bsrContext.setValueUnknown();
		}
	}
	else if ("MOVWF".equals(mnemonic)) {
		if (wContext.hasValue()) {
			bsrContext.setValueAt(instr, wContext.longValue(), false);
		}
		else {
			bsrContext.setValueUnknown();
			Msg.warn(this, "Unhandled BSR change at: " + instr.getMinAddress());
		}
	}
	else if ("MOVFP".equals(mnemonic) || "MOVPF".equals(mnemonic)) {
		Object[] objs = instr.getOpObjects(0);
		if (objs.length == 0 && (wReg.equals(objs[0]) || wReg.getAddress().equals(objs[0])) &&
			wContext.hasValue()) {
			bsrContext.setValueAt(instr, wContext.longValue(), false);
		}
		else {
			bsrContext.setValueUnknown();
			Msg.warn(this, "Unhandled BSR change at: " + instr.getMinAddress());
		}
	}
	else if (REG_S_MODIFICATION_MNEMONICS.contains(mnemonic)) {
		bsrContext.setValueUnknown();
		Msg.warn(this, "Unhandled BSR change at: " + instr.getMinAddress());
	}
	else if (REG_MODIFICATION_MNEMONICS.contains(mnemonic)) {
		if (instr.getNumOperands() == 2) { // REG_D type instructions
			List<?> repObjs = instr.getDefaultOperandRepresentationList(1);
			if (repObjs.size() == 1 && DEST_FREG.equals(repObjs.get(0))) {
				// Unhandled alusta modification
				bsrContext.setValueUnknown();
				Msg.warn(this, "Unhandled BSR change at: " + instr.getMinAddress());
			}
		}
		else if (instr.getNumOperands() == 1) {
			// Unhandled alusta modification
			bsrContext.setValueUnknown();
			Msg.warn(this, "Unhandled BSR change at: " + instr.getMinAddress());
		}
	}

}
 
Example 20
Source File: RegisterContextBuilder.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * The specified instr has set the specified bit for this context reg.
 * If setting fails the value will be left in an unknown state.
 * @param instr instruction which has made the bit modification
 * @param bit the bit to be set.
 * @param rightShiftFactor value will be subtracted from specified bit to determine actual bit
 * to be set. 
 * @return false if setting not possible (caused by instr not having a fall-through or
 * this is a multi-bit register without a previous value setting, or bit is null). 
 */
public boolean setBitAt(Instruction instr, Scalar bit, int rightShiftFactor) {
	if (bit != null) {
		int bitNum = (int) bit.getUnsignedValue() - rightShiftFactor;
		return setBitAt(instr, bitNum);
	}
	value = null;
	return false;
}