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

The following examples show how to use ghidra.program.model.scalar.Scalar#getValue() . 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: CreateEquateCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void maybeCreateEquate(DomainObject domain, Data data) {

		if (!data.isDefined()) {
			return;
		}

		Object val = data.getValue();
		if (!(val instanceof Scalar)) {
			return;
		}

		Scalar scalar = (Scalar) val;
		if (scalar.getValue() != targetScalarValue) {
			return;
		}

		int opIndex = getOperandIndex();
		createEquate(domain, data, opIndex, scalar);
	}
 
Example 2
Source File: CreateEquateCmd.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void maybeCreateEquate(DomainObject domain, Instruction instruction) {
	for (int opIndex = 0; opIndex < instruction.getNumOperands(); opIndex++) {
		Object[] opObjects = instruction.getOpObjects(opIndex);
		for (Object opObject : opObjects) {
			if (!(opObject instanceof Scalar)) {
				continue;
			}

			Scalar scalar = (Scalar) opObject;
			if (scalar.getValue() != targetScalarValue) {
				continue;
			}

			createEquate(domain, instruction, opIndex, scalar);
		}
	}
}
 
Example 3
Source File: EquateMerger.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Auto-merges equate changes for a scalar value at a particular address and operand.
 * It also determines the equate conflicts for this scalar at this address and operand.
 * @param addr the address of the code unit.
 * @param opIndex the operand index
 * @param scalar the scalar value.
 * @throws MemoryAccessException
 */
private void getOperandScalarConflicts(Address addr, int opIndex, Scalar scalar) {
	long scalarValue = scalar.getValue();
	Equate latestEquate = latestEquateTab.getEquate(addr, opIndex, scalarValue);
	Equate myEquate = myEquateTab.getEquate(addr, opIndex, scalarValue);
	Equate originalEquate = originalEquateTab.getEquate(addr, opIndex, scalarValue);
	boolean sameOriginalLatest = sameEquates(originalEquate, latestEquate);
	boolean sameOriginalMy = sameEquates(originalEquate, myEquate);
	boolean sameLatestMy = sameEquates(latestEquate, myEquate);
	if (sameLatestMy) {
		return; // Do nothing.
	}
	if (!sameOriginalMy) {
		if (sameOriginalLatest) {
			merge(addr, opIndex, scalar, KEEP_MY);
		}
		else {
			saveConflict(addr, opIndex, scalar);
		}
	}
}
 
Example 4
Source File: SetEquateDialog.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean isValid(String equateStr, Scalar testScalar) {
	// these are valid in the sense that they represent a clear or remove operation.
	if (StringUtils.isBlank(equateStr)) {
		return true;
	}

	// look up the new equate string
	Equate newEquate = equateTable.getEquate(equateStr);

	if (newEquate != null && getEnumDataType() == null) {
		// make sure any existing equate with that name has the same value.
		if (newEquate.getValue() != testScalar.getValue()) {
			setStatus("Equate " + equateStr + " exists with value 0x" +
				Long.toHexString(newEquate.getValue()) + " (" + newEquate.getValue() + ")");
			return false;
		}
	}
	return true;
}
 
Example 5
Source File: AbstractScalarOperandHover.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void formatAsAddressVal(Program program, Address addr, Scalar scalar,
		StringBuilder htmlText) {

	// maybe the scalar is an address..
	long scalarLong = scalar.getValue();
	AddressFactory factory = program.getAddressFactory();
	AddressSpace space = factory.getDefaultAddressSpace();
	Address asAddress;
	try {
		asAddress = factory.getAddress(space.getBaseSpaceID(), scalarLong);
	}
	catch (AddressOutOfBoundsException ex) {
		asAddress = null;	// Constant doesn't make sense as an address
	}

	Memory memory = program.getMemory();
	if (asAddress != null && memory.contains(asAddress)) {
		htmlText.append("<hr>");
		htmlText.append("<table>");

		addReprRow(htmlText, "Address", asAddress.toString());

		// .. and maybe it points to some data...
		Data data = program.getListing().getDataContaining(asAddress);
		if (data != null) {
			Symbol primary = data.getPrimarySymbol();
			if (primary != null) {
				addReprRow(htmlText, "Symbol",
					HTMLUtilities.italic(HTMLUtilities.friendlyEncodeHTML(primary.getName())));
			}
		}

		htmlText.append("</table>");
	}
}
 
Example 6
Source File: CreateEquateCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param scalar user defined scalar to search for in program
 * @param iter the range of code units for which to maybe create equates 
 * @param equateName user defined name for the new equate to be set
 * @param overwriteExisting
 */
public CreateEquateCmd(Scalar scalar, CodeUnitIterator iter, String equateName,
		boolean overwriteExisting, ListingActionContext context) {
	super("Create New Equate", true /* has progress */, true /* can cancel */,
		false /* is modal */);
	this.targetScalarValue = scalar.getValue();
	this.iterator = iter;
	this.equateName = equateName;
	this.overwriteExisting = overwriteExisting;
	this.context = context;
}
 
Example 7
Source File: CreateEquateCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param scalar user defined scalar to search for in program
 * @param iter the range of code units for which to maybe create equates 
 * @param enoom the enum to use for formatting the equate name
 * @param overwriteExisting
 */
public CreateEquateCmd(Scalar scalar, CodeUnitIterator iter, Enum enoom,
		boolean overwriteExisting, ListingActionContext context) {
	super("Create New Equate", true /* has progress */, true /* can cancel */,
		false /* is modal */);
	this.targetScalarValue = scalar.getValue();
	this.iterator = iter;
	this.overwriteExisting = overwriteExisting;
	this.context = context;
	this.enoom = enoom;
}
 
Example 8
Source File: CreateEnumEquateCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void maybeCreateEquateOnScalar(Instruction instruction, int opIndex,
		Object operandRepresentation) {

	if (!(operandRepresentation instanceof Scalar)) {
		return;
	}

	Scalar scalar = (Scalar) operandRepresentation;

	int enoomLength = enoom.getLength();
	boolean anyValuesMatch = Arrays.stream(enoom.getValues()).anyMatch(enumValue -> {
		return scalar.equals(new Scalar(enoomLength * 8, enumValue, scalar.isSigned()));
	});

	if (!anyValuesMatch) {
		return;
	}

	if (program.getDataTypeManager().findDataTypeForID(enoom.getUniversalID()) == null) {
		enoom = (Enum) program.getDataTypeManager().addDataType(enoom, null);
	}

	Address addr = instruction.getAddress();
	removeUnusedEquates(opIndex, scalar, addr);

	long value = scalar.getValue();
	String equateName = EquateManager.formatNameForEquate(enoom.getUniversalID(), value);
	Equate equate = getOrCreateEquate(equateName, value);
	equate.addReference(addr, opIndex);
}
 
Example 9
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 10
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 11
Source File: BitFieldDataTypeTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private int getValue(BitFieldDataType bitField, int... bytes) throws Exception {
	MemBuffer membuf = membuf(bytes);
	Scalar scalar = (Scalar) bitField.getValue(membuf, null, bitField.getStorageSize());
	return (int) scalar.getValue();
}
 
Example 12
Source File: ScalarToLongColumnTypeMapper.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public Long convert(Scalar value) {
	return value.getValue();
}
 
Example 13
Source File: ElfProgramBuilder.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void createDynamicEntryPoints(ElfDynamicType dynamicEntryType,
		ElfDynamicType entryArraySizeType, String baseName, TaskMonitor monitor) {

	ElfDynamicTable dynamicTable = elf.getDynamicTable();
	if (dynamicTable == null) {
		return;
	}

	try {
		long entryAddrOffset =
			elf.adjustAddressForPrelink(dynamicTable.getDynamicValue(dynamicEntryType));

		if (entryArraySizeType == null) {
			// single entry addr case
			createEntryFunction("_" + dynamicEntryType.name, entryAddrOffset, monitor);
			return;
		}

		// entryAddrOffset points to array of entry addresses
		DataType dt = elf.is32Bit() ? DWordDataType.dataType : QWordDataType.dataType;
		Address entryArrayAddr = getDefaultAddress(entryAddrOffset);
		long arraySize = dynamicTable.getDynamicValue(entryArraySizeType);
		long elementCount = arraySize / dt.getLength();

		for (int i = 0; i < elementCount; i++) {
			Address addr = entryArrayAddr.add(i * dt.getLength());
			Data data = createData(addr, dt);
			if (data == null) {
				break;
			}
			Scalar value = (Scalar) data.getValue();
			if (value != null) {
				if (i != 0 && value.getValue() == 0) {
					continue;
				}
				long funcAddrOffset = elf.adjustAddressForPrelink(value.getValue());
				Address funcAddr = createEntryFunction(baseName + i, funcAddrOffset, monitor);
				if (funcAddr != null) {
					data.addOperandReference(0, funcAddr, RefType.DATA, SourceType.ANALYSIS);
				}
			}
		}

	}
	catch (NotFoundException e) {
		// ignore
	}

}
 
Example 14
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Markup scalar with implied register variable reference if one can be
 * determined.
 * 
 * @param instr instruction
 * @param func function containing instruction
 * @param scalarToReplace
 * @param scalarIndex index of scalarToReplace within representationList
 * @param associatedRegister register associated with scalarToReplace via an
 *            INT_ADD operation
 * @param representationList
 */
private boolean markupScalarWithImpliedRegisterVariable(Instruction instr, Function func,
		Scalar scalarToReplace, int scalarIndex, Register associatedRegister,
		List<Object> representationList) {

	if (func == null || !options.doRegVariableMarkup ||
		!options.includeInferredVariableMarkup) {
		return false;
	}

	long scalarValue = scalarToReplace.getValue();
	if (scalarToReplace.isSigned() && scalarValue <= 0) {
		return false;
	}

	Variable regVar =
		instr.getProgram().getFunctionManager().getReferencedVariable(instr.getMinAddress(),
			associatedRegister.getAddress(), associatedRegister.getMinimumByteSize(), true);
	if (regVar == null) {
		return false;
	}

	// TODO: SCR 8400 - prevent this type of markup unless variable is a composite pointer
	// with positive offset within the bounds of the a single composite instance
	DataType dt = removeTypeDefs(regVar.getDataType());
	if (!(dt instanceof Pointer)) {
		return false;
	}

	dt = ((Pointer) dt).getDataType();
	dt = removeTypeDefs(dt);
	if (dt == null || !(dt instanceof Composite) || scalarValue > dt.getLength()) {
		return false;
	}

	VariableOffset variableOffset = new VariableOffset(regVar, scalarValue, true, true);
	variableOffset.setReplacedElement(scalarToReplace,
		options.includeScalarReferenceAdjustment);
	representationList.set(scalarIndex, variableOffset);
	return true;
}
 
Example 15
Source File: EHDataTypeUtilities.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * If the indicated component in the data type exists and is an integer value, this returns
 * the integer value contained in that component of the data type.
 * @param dataType the data type whose base type is a structure and whose component's
 * integer value is wanted. (i.e., The component data type referenced by the ordinal value must
 * be one that returns a Scalar value; such as an IntegerDataType, EnumDataType,
 * UndefinedDataType, etc.)
 * @param componentOrdinal 0-based ordinal indicating the component whose integer value is being
 * determined by this method.
 * @param memBuffer memory buffer that starts where the indicated data type is laid down.
 * @return the integer value held by indicated component in the data type when laid down on
 * the specified memory.
 */
public static int getIntegerValue(DataType dataType, int componentOrdinal,
		MemBuffer memBuffer) {
	Scalar scalar = getScalarValue(dataType, componentOrdinal, memBuffer);
	return (int) scalar.getValue();
}
 
Example 16
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Check for value equality between a constant varnode and a scalar value.
 * 
 * @param v constant varnode
 * @param value scalar value
 * @return true if values are equals
 */
private boolean equals(Varnode v, Scalar value) {
	Scalar s = new Scalar(v.getSize() * 8, v.getOffset(), value.isSigned());
	return s.getValue() == value.getValue();
}