Java Code Examples for ghidra.util.Msg#warn()

The following examples show how to use ghidra.util.Msg#warn() . 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: XmlLoader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean doImportWork(final ProgramXmlMgr mgr, final List<Option> options,
		final MessageLog log, Program prog, TaskMonitor monitor,
		final boolean isAddToProgram) throws IOException {
	MessageLog mgrLog = null;
	boolean success = false;
	try {
		XmlProgramOptions xmlOptions = new XmlProgramOptions();
		xmlOptions.setOptions(options);
		xmlOptions.setAddToProgram(isAddToProgram);
		mgrLog = mgr.read(prog, monitor, xmlOptions);
		log.copyFrom(mgrLog);
		success = true;
	}
	catch (Exception e) {
		String message = "(empty)";
		if (mgrLog != null && !"".equals(mgrLog.toString())) {
			message = mgrLog.toString();
		}
		if (log != null && !"".equals(log.toString())) {
			message = log.toString();
		}
		Msg.warn(this, "XML import exception, log: " + message, e);
		throw new IOException(e.getMessage(), e);
	}
	return success;
}
 
Example 2
Source File: SevenZipFileSystem.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getInfoMap(ISimpleInArchiveItem entry) {
	Map<String, String> info = new LinkedHashMap<>();
	try {
		info.put("Name", entry.getPath());
		info.put("Folder?", Boolean.toString(isFolder(entry)));
		info.put("Encrypted?", Boolean.toString(entry.isEncrypted()));
		info.put("Comment", entry.getComment());
		Long compressedSize = getCompressedSize(entry);
		info.put("Compressed Size",
			compressedSize != null ? NumericUtilities.toHexString(compressedSize) : "NA");
		info.put("Uncompressed Size", NumericUtilities.toHexString(getSize(entry)));
		Integer crc = getCRC(entry);
		info.put("CRC",
			crc != null ? NumericUtilities.toHexString(crc.intValue() & 0xffffffffL) : "NA");
		info.put("Compression Method", entry.getMethod());
		Date creationTime = getCreateDate(entry);
		info.put("Time", creationTime != null ? creationTime.toGMTString() : "NA");
	}
	catch (SevenZipException e) {
		Msg.warn(this, "7-Zip exception trying to get info on item", e);
	}
	return info;
}
 
Example 3
Source File: ControlFlowGuard.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Performs markup on the ReturnFlowGuard failure routine, if it exists.
 * 
 * @param lcd The PE LoadConfigDirectory.
 * @param space The program's address space.
 * @param symbolTable The program's symbol table.
 */
private static void markupRfgFailureRoutine(LoadConfigDirectory lcd, AddressSpace space,
		SymbolTable symbolTable) {

	if (lcd.getRfgFailureRoutine() == 0) {
		return;
	}

	try {
		Address routineAddr = space.getAddress(lcd.getRfgFailureRoutine());
		symbolTable.createLabel(routineAddr, "_guard_ss_verify_failure", SourceType.IMPORTED);
	}
	catch (AddressOutOfBoundsException | InvalidInputException e) {
		Msg.warn(ControlFlowGuard.class, "Unable to label ReturnFlowGuard failure routine.", e);
	}
}
 
Example 4
Source File: GFileSystemLoadKernelTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void process(GFile file, TaskMonitor monitor) throws IOException {

		if (isSpecialDirectory(file)) {
			return;
		}

		if (file.isDirectory() &&
			!((GFileSystemProgramProvider) file.getFilesystem()).canProvideProgram(file)) {
			List<GFile> listing = file.getFilesystem().getListing(file);
			for (GFile child : listing) {
				if (monitor.isCancelled()) {
					break;
				}
				process(child, monitor);
			}
		}
		else {
			try {
				loadKext(file, monitor);
			}
			catch (Exception e) {
				Msg.warn(this, "unable to load kext file: " + file.getName(), e);
			}
		}
	}
 
Example 5
Source File: FileSystemRefManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Called from the {@link GFileSystem#close()} before any destructive changes have
 * been made to gracefully shutdown the ref manager.
 * <p>
 * Broadcasts {@link FileSystemEventListener#onFilesystemClose(GFileSystem)}.
 */
public void onClose() {
	GFileSystem fsCopy;
	synchronized (this) {
		if (fs == null) {
			throw new IllegalArgumentException("FileSystemRefManager already closed!");
		}
		if (!refs.isEmpty()) {
			Msg.warn(this, "Closing filesystem even though it has active handles open: " + fs);
		}
		fsCopy = fs;
		fs = null;
		refs.clear();
		refs = null;
	}
	for (FileSystemEventListener listener : listeners) {
		listener.onFilesystemClose(fsCopy);
	}
}
 
Example 6
Source File: DomainFileIndex.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void reconcileFileIDConflict(GhidraFile df1, GhidraFile df2) {
	try {
		String path1 = df1.getPathname();
		String path2 = df2.getPathname();
		if (!df1.isCheckedOut() && !df1.isVersioned()) {
			Msg.warn(this, "WARNING! changing file-ID for " + path1);
			df1.resetFileID();
		}
		else if (!df2.isCheckedOut() && !df2.isVersioned()) {
			Msg.warn(this, "WARNING! changing file-ID for " + path2);
			df2.resetFileID();
		}
		else {
			// Unable to resolve conflict
			Msg.error(this, "The following project files have conflicting file-IDs!\n" + path1 +
				"\n" + path2);
		}
		fileIdToPathIndex.put(df1.getFileID(), path1);
		fileIdToPathIndex.put(df2.getFileID(), path2);
	}
	catch (IOException e) {
		Msg.error(this, "Error while resolving file IDs", e);
		e.printStackTrace();
	}
}
 
Example 7
Source File: MDMangParseInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public String getParseInfo_orig() {
	StringBuilder builder = new StringBuilder();
	int mangledIndex = 0;
	int infoIndex = 0;
	while (infoIndex < infoList.size()) {
		// Output one line that looks like: "C +--+--+--Item"
		if (mangledIndex == infoList.get(infoIndex).startIndex) {
			outputMangledCharAndInfo(builder, mangledIndex, infoList.get(infoIndex).itemDepth,
				infoList.get(infoIndex).itemName);
			// Output multiple lines that looks like: "  +--+--+--Item"
			while ((++infoIndex < infoList.size()) &&
				(mangledIndex == infoList.get(infoIndex).startIndex)) {
				outputMangledCharAndInfo(builder, -1, infoList.get(infoIndex).itemDepth,
					infoList.get(infoIndex).itemName);
			}
		}
		// Doing ">= mangled.length(), allowing for one additional character for optional
		//  parsable items after the last mangled character
		else if ((mangledIndex >= mangled.length()) ||
			(mangledIndex == infoList.get(infoIndex).startIndex)) {
			// Problem
			Msg.warn(this, "Problem with Parse Info Stack");
			break;
		}
		else {
			// Output multiple lines that looks like: "C |  |  |  |"
			while ((mangledIndex < infoList.get(infoIndex).startIndex)) {
				if ((infoIndex == 0) || ((infoIndex != 0) &&
					(mangledIndex > infoList.get(infoIndex - 1).startIndex))) {
					outputMangledCharAndInfo(builder, mangledIndex,
						infoList.get(infoIndex).itemDepth, null);
				}
				mangledIndex++;
			}
		}
	}
	return builder.toString();
}
 
Example 8
Source File: DecompilerParameterIdCmd.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void resetFunctionSourceTypes(Set<Address> set) {
	FunctionManager functionManager = program.getFunctionManager();
	//For those functions that we will process, appropriately clear SourceType, meaning
	// move ANALYSIS (or other, depending on ClearLevel) SourceType back to DEFAULT SourceType,
	// but keep higher SoureTypes fixed.  Should we do this for individual parameters and returns too? --> yes/no TODO
	for (Address entryPoint : set) {
		Function func = functionManager.getFunctionAt(entryPoint);
		try {
			//Do not clear prototypes of "pseudo-analyzed" external functions.
			if (func.isExternal()) {
				continue;
			}
			if (funcIsExternalGlue(func)) {
				continue;
			}

			// TODO: should refactor to avoid changing source type to default
			// since decompile could fail and leave the source types changed.
			Parameter retParam = func.getReturn();
			if (retParam != null) {
				if (!retParam.getSource().isHigherPriorityThan(sourceTypeClearLevel)) {
					func.setReturn(retParam.getDataType(), retParam.getVariableStorage(),
						SourceType.DEFAULT);
				}
			}
			if (!func.getSignatureSource().isHigherPriorityThan(sourceTypeClearLevel)) {
				func.setSignatureSource(SourceType.DEFAULT);
			}
		}
		catch (InvalidInputException e) {
			Msg.warn(this,
				"Error changing signature SourceType on--" + func.getName(), e);
		}
	}
}
 
Example 9
Source File: CppExporter.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private CPPResult doWork(Function function, DecompInterface decompiler,
		TaskMonitor monitor) {
	Address entryPoint = function.getEntryPoint();
	CodeUnit codeUnitAt = function.getProgram().getListing().getCodeUnitAt(entryPoint);
	if (codeUnitAt == null || !(codeUnitAt instanceof Instruction)) {
		return new CPPResult(entryPoint, function.getPrototypeString(false, false), null);
	}

	monitor.setMessage("Decompiling " + function.getName());

	DecompileResults dr =
		decompiler.decompileFunction(function, options.getDefaultTimeout(), monitor);
	String errorMessage = dr.getErrorMessage();
	if (!"".equals(errorMessage)) {
		Msg.warn(CppExporter.this, "Error decompiling: " + errorMessage);
		if (options.isWARNCommentIncluded()) {
			monitor.incrementProgress(1);
			return new CPPResult(entryPoint, null,
				"/*" + EOL + "Unable to decompile '" + function.getName() + "'" + EOL +
					"Cause: " + errorMessage + EOL + "*/" + EOL);
		}
		return null;
	}

	DecompiledFunction decompiledFunction = dr.getDecompiledFunction();
	return new CPPResult(entryPoint, decompiledFunction.getSignature(),
		decompiledFunction.getC());
}
 
Example 10
Source File: RepositoryServerAdapter.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void disconnect(boolean unexpected) {
	if (server == null) {
		return; // disconnect/reconnect not supported (Project level URL mechanism)
	}
	unexpectedDisconnect = unexpected;
	Msg.warn(this, "Disconnected from Ghidra Server at " + serverInfoStr);
	serverHandle = null;
	fireStateChanged();
}
 
Example 11
Source File: x86AVX2AssemblyTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testAssemble_VMOVSS_mRBP_n0x4m_XMM0() {
	try {
		assertOneCompatRestExact("VMOVSS dword ptr [RBP + -0x4],XMM0", "c5:fa:11:45:fc");
	}
	catch (DisassemblyMismatchException e) {
		Msg.warn(this, "Swapping to test case with [I+R] form");
		assertOneCompatRestExact("VMOVSS dword ptr [-0x4 + RBP],XMM0", "c5:fa:11:45:fc");
	}
}
 
Example 12
Source File: AbstractActionBuilder.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the key binding for this action
 * 
 * @param keyStrokeString the string to parse as a KeyStroke. See
 *  {@link KeyStroke#getKeyStroke(String)} for the format of the string.
 * @return this builder (for chaining)
 */
public B keyBinding(String keyStrokeString) {
	this.keyBinding = KeyBindingUtils.parseKeyStroke(keyStrokeString);
	if (keyBinding == null && keyStrokeString != null) {
		Msg.warn(this, "Can't parse KeyStroke: " + keyStrokeString);
	}
	return self();
}
 
Example 13
Source File: GIconLabel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * This is a half-way method of turning this label into an immutable instance.
 * <p>
 * If the user has a type of "GIconLabel", they will see the deprecated warning on calls to setText().
 * <p>
 * If there are calls to setText() with any non-null or non-empty value, a
 * warning will be printed in the log.
 * <p>
 * @param text string this label will NOT display
 */
@Deprecated
@Override
public void setText(String text) {
	if (!StringUtils.isEmpty(text)) {
		Msg.warn(this, "Trying to set text on an icon label! New text: [" + text + "]",
			ReflectionUtilities.createJavaFilteredThrowable());
		return;
	}
	super.setText(text);
}
 
Example 14
Source File: HeadlessClientAuthenticator.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private char[] getPassword(String usage, String prompt) {

		if (!passwordPromptAlowed) {
			Msg.warn(this, "Headless client not configured to supply required password");
			return BADPASSWORD;
		}

		char[] password = null;
		int c;
		try {

			String passwordPrompt = "";
			if (usage != null) {
				passwordPrompt += usage;
				passwordPrompt += "\n";
			}

			if (prompt == null) {
				prompt = "Password:";
			}

			// With the new GhidraClassLoader/GhidraLauncher it should be possible to get a Console 
			// object, which allow masking of passwords.
			Console cons = System.console();

			if (cons != null) {
				passwordPrompt += prompt + " ";
				password = cons.readPassword(passwordPrompt);
			}
			else {
				// Couldn't get console instance, passwords will be in the clear
				passwordPrompt += "*** WARNING! Password entry will NOT be masked ***\n" + prompt;

				System.out.print(passwordPrompt);

				while (true) {
					c = System.in.read();
					if (c <= 0 || (Character.isWhitespace((char) c) && c != ' ')) {
						break;
					}
					if (password == null) {
						password = new char[1];
					}
					else {
						char[] newPass = new char[password.length + 1];
						for (int i = 0; i < password.length; i++) {
							newPass[i] = password[i];
							password[i] = 0;
						}
						password = newPass;
					}
					password[password.length - 1] = (char) c;
				}
			}
		}
		catch (IOException e) {
			Msg.error(this, "Error reading standard-input for password", e);
		}
		return password;
	}
 
Example 15
Source File: ElfRelocationTable.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private List<ElfRelocation> parseAndroidRelocations(FactoryBundledWithBinaryReader reader)
		throws IOException {

	String identifier = reader.readNextAsciiString(4);
	if (!"APS2".equals(identifier)) {
		throw new IOException("Unsupported Android relocation table format");
	}

	List<ElfRelocation> relocations = new ArrayList<>();

	try {
		int relocationIndex = 0;
		long remainingRelocations = LEB128.decode(reader, true);
		long offset = LEB128.decode(reader, true);
		long addend = 0;

		while (remainingRelocations > 0) {

			long groupSize = LEB128.decode(reader, true);
			if (groupSize > remainingRelocations) {
				Msg.warn(this, "Group relocation count " + groupSize +
					" exceeded total count " + remainingRelocations);
				break;
			}

			long groupFlags = LEB128.decode(reader, true);
			boolean groupedByInfo =
				(groupFlags & AndroidElfRelocationGroup.RELOCATION_GROUPED_BY_INFO_FLAG) != 0;
			boolean groupedByDelta = (groupFlags &
				AndroidElfRelocationGroup.RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG) != 0;
			boolean groupedByAddend =
				(groupFlags & AndroidElfRelocationGroup.RELOCATION_GROUPED_BY_ADDEND_FLAG) != 0;
			boolean groupHasAddend =
				(groupFlags & AndroidElfRelocationGroup.RELOCATION_GROUP_HAS_ADDEND_FLAG) != 0;

			long groupOffsetDelta = groupedByDelta ? LEB128.decode(reader, true) : 0;
			long groupRInfo = groupedByInfo ? LEB128.decode(reader, true) : 0;

			if (groupedByAddend && groupHasAddend) {
				addend += LEB128.decode(reader, true);
			}

			for (int i = 0; i < groupSize; i++) {
				offset += groupedByDelta ? groupOffsetDelta : LEB128.decode(reader, true);

				long info = groupedByInfo ? groupRInfo : LEB128.decode(reader, true);

				long rAddend = 0;
				if (groupHasAddend) {
					if (!groupedByAddend) {
						addend += LEB128.decode(reader, true);
					}
					rAddend = addend;
				}

				relocations.add(ElfRelocation.createElfRelocation(reader.getFactory(),
					elfHeader, relocationIndex++, addendTypeReloc, offset, info, rAddend));
			}

			if (!groupHasAddend) {
				addend = 0;
			}

			remainingRelocations -= groupSize;
		}
	}
	catch (IOException e) {
		Msg.error(this, "Error reading relocations.", e);
	}

	return relocations;
}
 
Example 16
Source File: FunctionPurgeAnalysisCmd.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * For x86 16-bit find the models stdcallnear, stdcallfar, cdeclnear, and cdeclfar so they can
 * be applied at the same time function purge is set.
 */
private void setupNearFarModels() {
	int countModels = 0;
	nearFarModels = new PrototypeModel[4];
	nearFarModels[0] = null;
	nearFarModels[1] = null;
	nearFarModels[2] = null;
	nearFarModels[3] = null;
	PrototypeModel[] models = program.getCompilerSpec().getCallingConventions();
	for (PrototypeModel model : models) {
		if (model.isMerged()) {
			continue;
		}
		int pos = -1;
		if (model.getStackshift() == 4) {
			if (model.getExtrapop() == PrototypeModel.UNKNOWN_EXTRAPOP) {
				pos = STDCALL_FAR;
			}
			else if (model.getExtrapop() == 4) {
				pos = CDECL_FAR;
			}
		}
		else if (model.getStackshift() == 2) {
			if (model.getExtrapop() == PrototypeModel.UNKNOWN_EXTRAPOP) {
				pos = STDCALL_NEAR;
			}
			else if (model.getExtrapop() == 2) {
				pos = CDECL_NEAR;
			}
		}
		if (pos >= 0) {
			if (nearFarModels[pos] == null) {
				nearFarModels[pos] = model;
				countModels += 1;
			}
		}
	}
	if (countModels < 4) {
		Msg.warn(this,
			"FunctionPurgeAnalysis is missing full range of near/far prototype models");
	}
}
 
Example 17
Source File: PartitionCodeSubModel.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Extract Model-P subroutines from Model-M subroutine graph following
 * call to partitionGraph().
 * @param monitor task monitor which allows user to cancel operation.
 * @return array of Model-P subroutine blocks.
 * @throws CancelledException if the monitor cancels the operation.
 */
private CodeBlock[] fromGraphToSubs(TaskMonitor monitor) throws CancelledException {

	DirectedGraph[] components = g.getComponents();
	CodeBlock[] subs = new CodeBlock[components.length];

	// Build the CodeBlock for each Model-P subroutine
	for (int i = 0; i < subs.length; i++) {

		if (monitor.isCancelled()) {
			throw new CancelledException();
		}

		GraphIterator<Vertex> vertIter = components[i].vertexIterator();
		AddressSet addrSet = new AddressSet();
		Address entry = null;

		// Follow all vertex references to build subroutine address set.
		// One of the vertices will be tagged as an entry point for each subroutine
		while (vertIter.hasNext()) {
			Vertex v = vertIter.next();
			CodeBlock block = (CodeBlock) g.getReferent(v);
			try {
				// check for entry point attribute
				int ix = entAttribute.getValue(v);
				Address[] entryPts = block.getStartAddresses();
				entry = entryPts[ix];
			}
			catch (NoValueException e) {
				// entry point not in this block/vertex
			}
			addrSet.add(block);
		}
		// Fabricate entry point if necessary
		if (entry == null) {
			entry = addrSet.getMinAddress();
			Msg.warn(this,
				"WARNING: fabricating entry point for Partitioned subroutine at " + entry);
		}
		subs[i] = createSub(addrSet, entry);
	}

	// delete all edges and verteces and attributes from graph
	entAttribute.clear();
	vertexAttributes.removeAttribute(ENTRY_POINT_TAG);
	vertexAttributes.removeAttribute(SOURCE_NUMBER);
	g.clear();

	return subs;
}
 
Example 18
Source File: SimpleBlockModel.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Get the First Code Block that contains the address.
 *
 * @param addr   Address to find a containing block.
 * @param monitor task monitor which allows user to cancel operation.
 * @return A SimpleBlock if any block contains the address.
 *        null otherwise.
 * @throws CancelledException if the monitor cancels the operation.
 */
@Override
public CodeBlock getFirstCodeBlockContaining(Address addr, TaskMonitor monitor)
		throws CancelledException {

	if (addr == null) {
		return null;
	}
	// First check out the Block cache
	Object blocks[] = foundBlockMap.getObjects(addr);
	if (blocks.length > 0) {
		return (CodeBlock) blocks[0];
	}

	if (addr.isExternalAddress()) {
		return getCodeBlockAt(addr, monitor);
	}

	Instruction instr = listing.getInstructionContaining(addr);
	if (instr != null) {

		// search backwards until instruction that starts a block is found
		Address fallFrom = instr.getFallFrom();
		while (!isBlockStart(instr, fallFrom)) {
			if (monitor != null && monitor.isCancelled()) {
				throw new CancelledException();
			}
			if (fallFrom == null) {
				Msg.warn(this, "WARNING: Invalid delay slot or offcut instruction found at " +
					instr.getMinAddress());
				try {
					fallFrom = instr.getMinAddress().subtractNoWrap(1);
				}
				catch (AddressOverflowException e) {
					break;
				}
			}
			instr = listing.getInstructionContaining(fallFrom);
			fallFrom = instr.getFallFrom();
		}
		return getCodeBlockAt(instr, monitor);
	}

	Data data = listing.getDefinedDataContaining(addr);
	if (data != null) {
		return getCodeBlockAt(data.getMinAddress(), monitor);
	}
	return null;
}
 
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: ApplyEnumsAsLabelsAction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private CreateLabelResult createLabels(Enum enumDt) {
	long[] values = enumDt.getValues();
	SymbolTable symbolTable = program.getSymbolTable();
	CreateLabelResult result = new CreateLabelResult();
	for (long value : values) {
		// Check to see if value is an address that exists in the program.
		// If so then create a label there with the enum value's name.
		String labelName = enumDt.getName(value);
		labelName = SymbolUtilities.replaceInvalidChars(labelName, true);
		AddressFactory addressFactory = program.getAddressFactory();
		String addressString = Long.toHexString(value);
		Address address = addressFactory.getAddress(addressString);
		if (address == null) {
			continue;
		}

		Memory memory = program.getMemory();
		if (!memory.contains(address)) {
			Msg.warn(this, "Couldn't create label for \"" + labelName + "\" at " +
				addressString + ".");
			result.failedToCreateSomeLabels = true;
			continue;
		}

		try {
			Symbol symbol = symbolTable.getGlobalSymbol(labelName, address);
			if (symbol == null) {
				symbolTable.createLabel(address, labelName, SourceType.USER_DEFINED);
				result.numberCreated++;
			}
			else {
				result.someAlreadyExisted = true;
			}
		}
		catch (InvalidInputException e) {
			Msg.warn(this, "Couldn't create label for \"" + labelName + "\" at " +
				addressString + "." + "\n" + e.getMessage());
			result.failedToCreateSomeLabels = true;
		}
	}

	return result;
}