ghidra.program.model.scalar.Scalar Java Examples

The following examples show how to use ghidra.program.model.scalar.Scalar. 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: Cie.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the CIE Code Alignment Factor Field.
 * 
 * @param addr Address at which the Code Alignment Factor field should be created.
 * @return Address immediately following the Code Alignment Factor field.
 * @throws MemoryAccessException if memory for the CIE couldn't be read.
 */
private Address processCodeAlign(Address addr) throws MemoryAccessException {

	/*
	 * Create a new CIE code alignment field at the specified address and
	 * sets an appropriate comment for the new structure.
	 */
	String comment = "(CIE) Code Alignment";

	UnsignedLeb128DataType uleb = UnsignedLeb128DataType.dataType;
	MemBuffer buf = new DumbMemBufferImpl(program.getMemory(), addr);
	int encodedLen = uleb.getLength(buf, AbstractLeb128DataType.MAX_LEB128_ENCODED_VALUE_LEN);
	Object augLenObj = uleb.getValue(buf, uleb.getDefaultSettings(), encodedLen);

	codeAlignFactor = (int) ((Scalar) augLenObj).getUnsignedValue();

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

	curSize += encodedLen;

	return addr.add(encodedLen);
}
 
Example #2
Source File: Cie.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the CIE Data Alignment Factor field.
 * 
 * @param addr Address at which the Data Alignment Factor field should be created.
 * @return Address immediately following the Data Alignment Factor field.
 * @throws MemoryAccessException if memory for the CIE couldn't be read.
 */
private Address processDataAlign(Address addr) throws MemoryAccessException {

	/*
	 * Create a new CIE data alignment field at the specified address and
	 * sets an appropriate comment for the new structure.
	 */
	String comment = "(CIE) Data Alignment";

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

	dataAlignFactor = (int) ((Scalar) alignObj).getSignedValue();

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

	curSize += encodedLen;

	return addr.add(encodedLen);
}
 
Example #3
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 #4
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Build a suitable variable or stack reference representation with optional
 * scalar replacement.
 * 
 * @param ref variable reference
 * @param var associated variable or null
 * @param replacedScalar replaced scalar object or null
 * @return representation object or null if var is null and ref is not a
 *         stack reference.
 */
private Object getVariableReferenceRepresentation(Reference ref, Variable var,
		Scalar replacedScalar) {
	if (var != null) {
		// Relies on reference-type to specify read/write access
		VariableOffset varOffset = new VariableOffset(ref, var);
		varOffset.setReplacedElement(replacedScalar, options.includeScalarReferenceAdjustment);
		return varOffset;
	}
	if (ref.isStackReference()) {
		OperandRepresentationList compoundList = new OperandRepresentationList();
		compoundList.add("Stack");
		compoundList.add('[');
		compoundList.add(new Scalar(32, ((StackReference) ref).getStackOffset(), true));
		compoundList.add(']');
		return addScalarAdjustment(compoundList, ref.getToAddress(), replacedScalar, false);
	}
	return null;
}
 
Example #5
Source File: CodeUnitFormat.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean markupAddressAsScalar(Instruction instr, Reference primaryRef,
		List<Object> representationList, int addressIndex) {
	Address addr = (Address) representationList.get(addressIndex);
	AddressSpace space = addr.getAddressSpace();
	long offset = addr.getOffset();
	int unitSize = space.getAddressableUnitSize();
	if (unitSize != 1) {
		if (MathUtilities.unsignedModulo(offset, unitSize) == 0) {
			offset = MathUtilities.unsignedDivide(offset, unitSize);
		}
		else {
			return false;
		}
	}
	else {
		offset = MathUtilities.unsignedDivide(offset, unitSize);
	}

	Scalar scalar = new Scalar(space.getSize(), offset, false);
	if (markupScalarWithMemoryReference(instr, scalar, addressIndex, primaryRef,
		representationList)) {
		return true;
	}
	return primaryRef == null;
}
 
Example #6
Source File: ScalarSearchModel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Scalar getScalarFromData(Data data) {

		if (data == null) {
			return null;
		}

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

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

		return (Scalar) value;
	}
 
Example #7
Source File: EquatePlugin1Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertCharUnprintable() {
	putCursorOnOperand(0x0100519f, 0);

	Instruction inst = listing.getInstructionAt(addr(0x0100519f));
	Scalar scalar = inst.getScalar(0);
	assertEquals(2, scalar.getUnsignedValue());

	performAction("Convert To Char");

	ListingTextField tf = (ListingTextField) cb.getCurrentField();
	assertEquals("02h", tf.getFieldElement(0, 11).getText());

	undo(program);
	tf = (ListingTextField) cb.getCurrentField();
	assertEquals("0x" + Long.toString(scalar.getUnsignedValue(), 16),
		tf.getFieldElement(0, 11).getText());

	redo(program);
	tf = (ListingTextField) cb.getCurrentField();
	assertEquals("02h", tf.getFieldElement(0, 11).getText());
}
 
Example #8
Source File: EHDataTypeUtilities.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * If the indicated component in the data type exists and is a Scalar value, this returns
 * the scalar value contained in that component of the data type.
 * @param dataType the data type whose base type is a structure and whose component's
 * scalar 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 scalar value is being
 * determined by this method.
 * @param memBuffer memory buffer that starts where the indicated data type is laid down.
 * @return the scalar value held by indicated component in the data type when laid down on
 * the specified memory.
 */
public static Scalar getScalarValue(DataType dataType, int componentOrdinal,
		MemBuffer memBuffer) {
	DataTypeComponent comp = getComponent(dataType, componentOrdinal, memBuffer);
	if (comp == null) {
		throw new IllegalArgumentException("Couldn't get component " + componentOrdinal +
			" of " + dataType.getName() + " @ " + memBuffer.getAddress() + ".");
	}
	Address compAddress = getComponentAddress(comp, memBuffer);
	DataType compDt = comp.getDataType();
	int length = comp.getLength();
	DumbMemBufferImpl compMemBuffer = new DumbMemBufferImpl(memBuffer.getMemory(), compAddress);
	Object value = compDt.getValue(compMemBuffer, comp.getDefaultSettings(), length);
	if (value instanceof Scalar) {
		return (Scalar) value;
	}
	throw new IllegalArgumentException(
		"Component " + componentOrdinal + " of " + dataType.getName() + " is a " +
			compDt.getName() + " data type, which doesn't produce a Scalar value.");
}
 
Example #9
Source File: PowerPCAddressAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected boolean isPEFCallingConvention(Program program, Instruction instr) {

		if (instr.getMnemonicString().equals("lwz")) {
			Register reg = instr.getRegister(0);
			if (reg != null && reg.getName().equals("r2")) {
				Object[] objs = instr.getOpObjects(1);
				Register stackRegister = program.getCompilerSpec().getStackPointer();
				for (Object obj : objs) {
					if (obj instanceof Register && ((Register) obj) != stackRegister) {
						return false;
					}
					// TODO: verify stack offset for 64-bit PEF
					if (obj instanceof Scalar && ((Scalar) obj).getValue() != 0x14) {
						return false;
					}
				}
				Address fallAddr = instr.getFallFrom();
				Instruction fallInstr = program.getListing().getInstructionContaining(fallAddr);
				if (fallInstr != null && fallInstr.getFlowType().isCall()) {
					return true;
				}
			}
		}
		return false;
	}
 
Example #10
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 #11
Source File: EHModelTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidIPToState32() throws Exception {
	ProgramBuilder builder = build32BitX86();
	ProgramDB program = builder.getProgram();
	setupIPToState32(builder, 0x01001340, 0x01001364, -1);
	Address address = builder.addr(0x01001340);
	EHIPToStateModel model =
		new EHIPToStateModel(program, 1, address, defaultValidationOptions);
	model.validate();
	assertEquals(address, model.getAddress());
	assertEquals(0x01001364, ((Scalar) model.getIP(0)).getValue());
	assertEquals(0xFFFFFFFF, model.getState(0));
}
 
Example #12
Source File: AbstractScalarOperandHover.java    From ghidra with Apache License 2.0 5 votes vote down vote up
protected String formatScalar(Program program, Address addr, Scalar scalar) {

		StringBuilder sb = new StringBuilder(HTMLUtilities.HTML);
		formatIntegerTypes(program, addr, scalar, sb);
		formatCharTypes(program, addr, scalar, sb);
		formatAsAddressVal(program, addr, scalar, sb);

		return sb.toString();
	}
 
Example #13
Source File: AbstractScalarOperandHover.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void formatCharTypes(Program program, Address addr, Scalar scalar,
			StringBuilder htmlText) {

		// The CharDataType can change depending on the DataOrg of the current program, so this
		// can't be a static array like INTEGER_DISPLAY_TYPES
		List<DataType> charDataTypes = Arrays.asList(new CharDataType(program.getDataTypeManager()),
			new WideChar16DataType(program.getDataTypeManager()),
			new WideChar32DataType(program.getDataTypeManager()));

		String prevCharVal = "";
		StringBuilder localHTMLText = new StringBuilder();

//		Endian progEndian = program.getMemory().isBigEndian() ? Endian.BIG : Endian.LITTLE;
		for (DataType charDt : charDataTypes) {
			// for each char data type, append its representation to the buffer, if it is
			// a new way to display the scalar
			ByteMemBufferImpl charMemBuffer =
				getScalarOperandAsMemBuffer(addr, scalar, charDt.getLength());
			prevCharVal =
				appendCharDataTypeFormattedHTML(prevCharVal, charDt, charMemBuffer, localHTMLText);
		}

		if (localHTMLText.length() > 0) {
			htmlText.append("<hr>");
			htmlText.append("<table width=\"100%\">") //
				.append(localHTMLText) //
				.append("</table>");
		}
	}
 
Example #14
Source File: TypeDescriptorModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the hash value if this data type has one.
 * @return the hash value.
 * @throws InvalidDataTypeException if valid TypeDescriptor data can't be created at the
 * model's address.
 * @throws UndefinedValueException if the type descriptor doesn't have a hash value.
 */
public Scalar getHashValue() throws InvalidDataTypeException, UndefinedValueException {
	checkValidity();
	if (hasVFPointer) {
		throw new UndefinedValueException(
			"No hash value is defined for this TypeDescriptor model.");
	}
	// component 0 is either vf table pointer or hash value.
	return EHDataTypeUtilities.getScalarValue(getDataType(), VF_TABLE_OR_HASH_ORDINAL,
		getMemBuffer());
}
 
Example #15
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 #16
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 #17
Source File: EHCatchHandlerModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the scalar for the displacement of the address of the function frame in the 
 * indicated HandlerType map entry.
 * @param catchHandlerOrdinal 0-based ordinal indicating which HandlerType entry in the map.
 * @return scalar for the displacement of the address of the function frame.
 * @throws InvalidDataTypeException if valid HandlerType data can't be created for 
 * the indicated ordinal.
 */
public Scalar getFunctionFrameAddressDisplacement(int catchHandlerOrdinal)
		throws InvalidDataTypeException {
	checkValidity(catchHandlerOrdinal);
	DataType catchHandlerDt = getDataType();
	MemBuffer specificMemBuffer = getSpecificMemBuffer(catchHandlerOrdinal, catchHandlerDt);
	// component 4 is the displacement of the address of function frame.
	// Component is a dword.
	return EHDataTypeUtilities.getScalarValue(catchHandlerDt, FUNCTION_FRAME_ORDINAL,
		specificMemBuffer);
}
 
Example #18
Source File: RTTI3DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the number of RTTI1 structures that are referred to by an RTTI3 structure being placed
 * at the rtti3Address of the indicated memory.
 * @param memory the memory with the data for the RTTI structures.
 * @param rtti3Address address of an RTTI3 structure
 * @return the RTTI1 count or 0.
 */
public long getRtti1Count(Memory memory, Address rtti3Address) {
	Address rtti1CountAddress = rtti3Address.add(RTTI_1_COUNT_OFFSET);
	try {
		long rtti1Count =
			new Scalar(32, memory.getInt(rtti1CountAddress, memory.isBigEndian())).getValue();
		return rtti1Count;
	}
	catch (MemoryAccessException e) {
		Msg.error(this, "Unexpected Exception: " + e.getMessage(), e);
		return 0;
	}
}
 
Example #19
Source File: ObjectiveC2_DecompilerMessageAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String getValueAtAddress(Program program, Address address) {
	String value = null;
	Data data = program.getListing().getDataAt(address);
	Object dataValue = data.getValue();
	if (dataValue instanceof Scalar) {
		value = dataValue.toString();
	}
	return value;
}
 
Example #20
Source File: DefaultDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Get the Undefined byte as a Scalar.
 *
 * @param buf the data buffer.
 * @param settings the display settings to use.
 * @param length the number of bytes to get the value from.
 * @return the data Object.
 */
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		return new Scalar(8, buf.getByte(0));
	}
	catch (MemoryAccessException e) {
		return null;
	}
}
 
Example #21
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 #22
Source File: Undefined4DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)
 */
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		return new Scalar(32, getValue(buf));
	}
	catch (MemoryAccessException e) {
		return null;
	}
}
 
Example #23
Source File: BitFieldDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(MemBuffer buf, Settings settings, int length) {
	if (effectiveBitSize == 0) {
		return new Scalar(0, 0);
	}
	BigInteger big = getBigIntegerValue(buf, settings);
	if (big == null) {
		return null;
	}
	if (effectiveBitSize <= 64) {
		return new Scalar(effectiveBitSize, big.longValue(),
			getPrimitiveBaseDataType().isSigned());
	}
	return big;
}
 
Example #24
Source File: Undefined5DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)
 */
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		return new Scalar(40, getValue(buf));
	}
	catch (MemoryAccessException e) {
		return null;
	}
}
 
Example #25
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 #26
Source File: Undefined1DataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @see ghidra.program.model.data.DataType#getValue(ghidra.program.model.mem.MemBuffer, ghidra.docking.settings.Settings, int)
 */
public Object getValue(MemBuffer buf, Settings settings, int length) {
	try {
		return new Scalar(8, getValue(buf));
	}
	catch (MemoryAccessException e) {
		return null;
	}
}
 
Example #27
Source File: AbstractDwarfEHDecoder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Reads an unsigned 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_leb128(Program program, Address addr) throws MemoryAccessException {
	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 #28
Source File: SetEquateDialog.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param tool the EquatePlugin that launched this dialog(used to validate input)
 * @param program the program the equate is located in.
 * @param value the equate value to set.
 */

public SetEquateDialog(PluginTool tool, Program program, Scalar value) {
	super("Set Equate", true, true, true, false);
	this.tool = tool;
	this.program = program;
	this.scalar = value;
	this.dataTypeManager = program.getDataTypeManager();
	this.equateTable = program.getEquateTable();
	addWorkPanel(buildMainPanel());
	addOKButton();
	addCancelButton();
	setRememberSize(false);
}
 
Example #29
Source File: ConvertToDoubleAction.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
	}
	BigDecimal value = value(program, scalar);
	return value != null ? value.toString() : null;
}
 
Example #30
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;
}