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

The following examples show how to use ghidra.program.model.scalar.Scalar#getSignedValue() . 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: 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);
	SignedLeb128DataType sleb = SignedLeb128DataType.dataType;

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

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

	context.setDecodedValue(offset, readLen);

	return offset;
}
 
Example 2
Source File: LSDAActionRecord.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Address createNextActionRef(Address addr) {
	String comment = "(LSDA Action Table) Next-Action Reference";

	SignedLeb128DataType sleb = SignedLeb128DataType.dataType;

	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	int encodedLen = sleb.getLength(buf, -1);
	Scalar nextDispObj = (Scalar) sleb.getValue(buf, sleb.getDefaultSettings(), encodedLen);
	encodedLen = nextDispObj.bitLength() / 8;

	displacementToNext = (int) nextDispObj.getSignedValue();

	if (displacementToNext == 0) {
		nextActionAddress = Address.NO_ADDRESS;
	}
	else {
		nextActionAddress = addr.add(displacementToNext);
	}

	createAndCommentData(program, addr, sleb, comment, CodeUnit.EOL_COMMENT);

	size += encodedLen;

	return addr.add(encodedLen);
}
 
Example 3
Source File: ScalarSearchProvider.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean acceptsRow(ScalarRowObject rowObject) {

	Scalar scalar = rowObject.getScalar();
	if (scalar == null) {
		return false;
	}

	long value = scalar.getSignedValue();
	if (value < minField.getFilterValue()) {
		return false;
	}

	if (value > maxField.getFilterValue()) {
		return false;
	}

	return true;
}
 
Example 4
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Search list of equates for scalar value match.
 * 
 * @param scalar
 * @param equates list of equates
 * @return equate which matches scalar value or null if not found.
 */
private Equate findEquate(Scalar scalar, List<Equate> equates) {
	Iterator<Equate> equateItr = equates.iterator();
	while (equateItr.hasNext()) {
		Equate equate = equateItr.next();
		if (equate.getValue() == scalar.getSignedValue() ||
			equate.getValue() == scalar.getValue()) {
			return equate;
		}
	}
	return null;
}
 
Example 5
Source File: FunctionPurgeAnalysisCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Given a terminating instruction, discover the purge value encoded in it
 * @param instr is the terminating instruction
 * @return the purge value (or -1 if a value can't be found)
 */
private int getPurgeValue(Instruction instr) {
	if (instr.getFlowType().isCall()) {
		// is an override call-return, terminal/call
		// find a reference to a function, and take it's purge
		Reference[] referencesFrom = instr.getReferencesFrom();
		for (Reference reference : referencesFrom) {
			if (reference.getReferenceType().isFlow()) {
				Function functionAt =
					program.getFunctionManager().getFunctionAt(reference.getToAddress());
				// don't take the purge of a non-returning function
				if (functionAt != null && !functionAt.hasNoReturn()) {
					return functionAt.getStackPurgeSize();
				}
			}
		}
	}
	else {
		int tempPurge = 0;
		Scalar scalar = instr.getScalar(0);
		if (scalar != null) {
			tempPurge = (int) scalar.getSignedValue();
		}
		return tempPurge;
	}
	return -1;
}
 
Example 6
Source File: DisplayableEol.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void handleDirectDataReference(Set<String> set, Address dataAccessAddress, Data data) {

		Object value = data.getValue();
		if (value instanceof Scalar) {
			Scalar scalar = (Scalar) value;
			if (scalar.getSignedValue() == 0) {
				return;
			}
		}

		set.add("= " + getDataValueRepresentation(dataAccessAddress, data));
	}
 
Example 7
Source File: AbstractConvertAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEnabledForContext(ListingActionContext context) {
	ProgramLocation loc = context.getLocation();
	if (!(loc instanceof OperandFieldLocation)) {
		return false;
	}
	Scalar scalar = plugin.getScalar(context);
	if (scalar == null) {
		return false;
	}
	if (isSigned && scalar.getSignedValue() >= 0) {
		return false;
	}
	CodeUnit cu = plugin.getCodeUnit(context);
	if (cu instanceof Data) {
		if (getFormatChoice() == -1) {
			// unsupported data action
			return false;
		}
		Data data = (Data) cu;
		if (!data.isDefined()) {
			return false;
		}
		DataType dataType = data.getBaseDataType();
		if (!(dataType instanceof AbstractIntegerDataType)) {
			return false;
		}
	}
	String menuName = getMenuName(context.getProgram(), scalar, cu instanceof Data);
	if (menuName == null) {
		return false;
	}
	getPopupMenuData().setMenuItemName(menuName);
	return true;
}
 
Example 8
Source File: ConvertToSignedHexAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected String convertToString(Program program, Scalar scalar, boolean isData) {
	if (isData) {
		return null; // unsupported
	}
	long v = scalar.getSignedValue();
	String valueStr = Long.toString(v, 16).toUpperCase();
	if (v < 0) {
		// use of substring removes '-' prefix for negative value
		return "-0x" + valueStr.substring(1);
	}
	return "0x" + valueStr;
}
 
Example 9
Source File: OffsetTablePlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
      public boolean applyTo(DomainObject obj) {
	if (super.applyTo(obj)) {
		Program program = (Program)obj;
		ReferenceManager refManager = program.getReferenceManager();
		Data data = program.getListing().getDefinedDataAt(dataAddr);
		if (data != null) {
			Scalar value = (Scalar)data.getValue();
			long offset = signed ? value.getSignedValue() : value.getUnsignedValue();
			try {
				data.addValueReference(baseAddr.add(offset), RefType.DATA); 
			} catch (AddressOutOfBoundsException e) {
				msg = e.getMessage();
				return false;
			}
			Reference primRef = 
				refManager.getPrimaryReferenceFrom(dataAddr, 0);
			if (primRef == null) {
				Reference[] refs = data.getValueReferences(); 
				refManager.setPrimary(refs[0], true);
			}
			return true;	
		}
		msg = "Data does not exist at " + dataAddr;
	}
	return false;
}
 
Example 10
Source File: ScalarSearchModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addMatch(ScalarRowObject rowObject) {

		if (rowObject == null) {
			return;
		}

		Scalar scalar = rowObject.getScalar();
		long value = scalar.isSigned() ? scalar.getSignedValue() : scalar.getUnsignedValue();
		if ((value < minValue) || (value > maxValue)) {
			return;
		}

		sizedAccumulator.add(rowObject);
	}
 
Example 11
Source File: AbstractDwarfEHDecoder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a signed LEB128-encoded value from <code>program</code> at the address of <code>buf</code>
 * @param buf Buffer to read from
 * @param length Number of bytes to read
 * @param buffer Destination buffer to read into
 * @throws MemoryAccessException if the data can't be read
 */
protected long read_sleb128(MemBuffer buf, int length) throws MemoryAccessException {

	SignedLeb128DataType sleb = SignedLeb128DataType.dataType;

	Scalar scalar =
		(Scalar) sleb.getValue(buf, sleb.getDefaultSettings(), sleb.getLength(buf, -1));
	return scalar.getSignedValue();
}
 
Example 12
Source File: AbstractDwarfEHDecoder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a signed LEB128-encoded value from <code>program</code> at <code>addr</code>
 * @param program Program to read from
 * @param addr Address to read from
 * @throws MemoryAccessException if the data can't be read
 */
protected long read_sleb128(Program program, Address addr) throws MemoryAccessException {

	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.getSignedValue();
}
 
Example 13
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.getSignedValue();
}
 
Example 14
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 15
Source File: NewFunctionStackAnalysisCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private int getStackOpIndex(VarnodeContext context, Instruction cu, int offset) {
		int opIndex = 0;
//		int opLocation = -1;
		for (; opIndex < cu.getNumOperands(); opIndex++) {
			Object obj[] = cu.getOpObjects(opIndex);
//	        if (obj.length <= 1) {
//	        	continue;
//	        }
			int local_offset = 0;
			for (int i = 0; obj != null && i < obj.length; i++) {
				// 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];
					Varnode vnode = context.getRegisterVarnodeValue(reg);
					if (vnode == null) {
						continue;
					}
					String spaceName = vnode.getAddress().getAddressSpace().getName();
					if (spaceName.startsWith("track_") || spaceName.equals(stackReg.getName())) {
//						opLocation = opIndex;
						local_offset += (int) vnode.getOffset();
					}
					else {
						continue;
					}
				}
				else if (obj[i] instanceof Scalar) {
					Scalar sc = (Scalar) obj[i];
					local_offset += sc.getSignedValue();
				}
				else {
					continue;
				}
				if (local_offset == offset) {
					return opIndex;
				}
			}
		}
		return -1;
	}
 
Example 16
Source File: ConvertToSignedDecimalAction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
protected String convertToString(Program program, Scalar scalar, boolean isData) {
	return "" + scalar.getSignedValue();
}
 
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: LSDAActionRecord.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private Address createTypeFilter(Address addr) {

		String comment = "(LSDA Action Table) Type Filter";

		SignedLeb128DataType sleb = SignedLeb128DataType.dataType;
		MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
		int encodedLen = sleb.getLength(buf, -1);
		Scalar typeFilterObj = (Scalar) sleb.getValue(buf, sleb.getDefaultSettings(), encodedLen);

		encodedLen = typeFilterObj.bitLength() / 8;

		typeFilter = (int) typeFilterObj.getSignedValue();

		createAndCommentData(program, addr, sleb, comment, CodeUnit.EOL_COMMENT);

		size += encodedLen;

		return addr.add(encodedLen);
	}
 
Example 19
Source File: VariableOffset.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private List<Object> getObjects(boolean showScalarAdjustment) {

		DataType dt = variable.getDataType();
		StringBuffer name = new StringBuffer(variable.getName());

		long scalarAdjustment = 0;
		if (showScalarAdjustment && (replacedElement instanceof Scalar)) {
			Scalar s = (Scalar) replacedElement;
			scalarAdjustment = variable.isStackVariable() ? s.getSignedValue() : s.getValue();
			scalarAdjustment -= offset;
			if (variable.isStackVariable() || variable.isMemoryVariable()) {
				Address storageAddr = variable.getMinAddress();
				scalarAdjustment -= storageAddr.getOffset();
			}
		}

		long absOffset = offset < 0 ? -offset : offset;
		if (absOffset <= Integer.MAX_VALUE) {

			if (dt instanceof TypeDef) {
				dt = ((TypeDef) dt).getBaseDataType();
			}

			boolean displayAsPtr = false;
			if (indirect && (dt instanceof Pointer)) {
				dt = ((Pointer) dt).getDataType();
				displayAsPtr = true;
			}

			int intOff = (int) absOffset;
			while (intOff > 0 || (dataAccess && intOff == 0)) {

				if (dt instanceof TypeDef) {
					dt = ((TypeDef) dt).getBaseDataType();
				}
				if (dt instanceof Structure) {
					DataTypeComponent cdt = ((Structure) dt).getComponentAt(intOff);
					if (cdt == null || cdt.isBitFieldComponent()) {
						// NOTE: byte offset is insufficient to identify a specific bitfield
						break;
					}
					String fieldName = cdt.getFieldName();
					if (fieldName == null) {
						fieldName = cdt.getDefaultFieldName();
					}
					name.append(displayAsPtr ? "->" : ".");
					name.append(fieldName);
					intOff -= cdt.getOffset();
					dt = cdt.getDataType();
				}
				else if (dt instanceof Array) {
					Array a = (Array) dt;
					int elementLen = a.getElementLength();
					if (intOff >= a.getLength()) {
						break; // unexpected
					}
					int index = intOff / elementLen;
					if (displayAsPtr) {
						name.insert(0, '*');
					}
					name.append('[');
					name.append(Integer.toString(index));
					name.append(']');
					intOff -= index * elementLen;
					dt = a.getDataType();
				}
				else {
					break;
				}
				displayAsPtr = false;
			}
			absOffset = intOff;
		}

		List<Object> list = new ArrayList<>();
		list.add(new LabelString(name.toString(), LabelString.VARIABLE));

		if (absOffset != 0 || scalarAdjustment != 0) {
			long adjustedOffset = (offset < 0 ? -absOffset : absOffset) + scalarAdjustment;
			if (adjustedOffset < 0) {
				adjustedOffset = -adjustedOffset;
				list.add('-');
			}
			else {
				list.add('+');
			}
			list.add(new Scalar(32, adjustedOffset));
		}
		return list;
	}
 
Example 20
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;
}