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

The following examples show how to use ghidra.util.Msg#showWarn() . 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: VTControllerImpl.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean hasTransactionsOpen(Program program, VtTask task) {
	Transaction transaction = program.getCurrentTransaction();
	if (transaction != null) {
		Msg.showWarn(this, null, "Unable to " + task.getTaskTitle(),
			"The program \"" + program.getName() + "\"already has a transaction open: " +
				transaction.getDescription());
		return true;
	}

	Transaction matchSetTransaction = session.getCurrentTransaction();
	if (matchSetTransaction != null) {
		Msg.showWarn(this, null, "Unable to " + task.getTaskTitle(),
			"Transaction already open for the Match Set Manager ");
		return true;
	}
	return false;
}
 
Example 2
Source File: ProgramTreeActionManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a range of Modules; called from an action listener on a menu.
 * @return true if program was affected
 */
private boolean deleteRange() {

	TreePath[] paths = tree.getSelectionPaths();

	boolean changesMade = false;
	StringBuffer sb = new StringBuffer();

	for (TreePath element : paths) {
		ProgramNode node = (ProgramNode) element.getLastPathComponent();
		if (tree.removeGroup(node, sb)) {
			changesMade = true;
		}
	}

	if (sb.length() > 0) {
		sb.insert(0, "Failed to delete the following:\n");
		Msg.showWarn(getClass(), tree, "Delete Failed", sb.toString());
	}
	return changesMade;
}
 
Example 3
Source File: TagEditorDialog.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean hasTransactionsOpen(VTSessionDB sessionDB) {
	Program program = sessionDB.getDestinationProgram();
	Transaction transaction = program.getCurrentTransaction();
	if (transaction != null) {
		Msg.showWarn(this, null, "Unable to Set Match Tag",
			"The program \"" + program.getName() + "\"already has a transaction open: " +
				transaction.getDescription());
		return true;
	}

	Transaction matchSetTransaction = sessionDB.getCurrentTransaction();
	if (matchSetTransaction != null) {
		Msg.showWarn(this, null, "Unable to Set Match Tag",
			"Transaction already open for the Match Set Manager ");
		return true;
	}
	return false;
}
 
Example 4
Source File: FSBUtils.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static PluginTool selectPMTool(PluginTool tool) {
	ProgramManager pm = tool.getService(ProgramManager.class);
	if (pm != null) {
		return tool;
	}

	List<PluginTool> pluginTools = FSBUtils.getRunningProgramManagerTools(tool);

	if (pluginTools.size() == 1) {
		return pluginTools.get(0);
	}

	if (pluginTools.isEmpty()) {
		Msg.showWarn(tool, tool.getActiveWindow(), "No open tools",
			"There are no open tools to use to open a program with");
		return null;
	}

	PluginTool pt = SelectFromListDialog.selectFromList(pluginTools, "Select tool",
		"Select a tool to use to open programs", pluginTool -> pluginTool.getName());
	return pt;
}
 
Example 5
Source File: DefaultGraphDisplay.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void setGraph(AttributedGraph graph, String description, boolean append,
		TaskMonitor monitor) {
	iconCache.clear();

	if (append && Objects.equals(description, this.description) && this.graph != null) {
		graph = mergeGraphs(graph, this.graph);
	}

	this.description = description;
	int count = graph.getVertexCount();
	if (count > MAX_NODES) {
		Msg.showWarn(this, null, "Graph Not Rendered - Too many nodes!",
			"Exceeded limit of " + MAX_NODES + " nodes.\n\n  Graph contained " + count +
				" nodes!");
		graph = new AttributedGraph();
		graph.addVertex("1", "Graph Aborted");
	}
	doSetGraphData(graph);
}
 
Example 6
Source File: SetMatchTagTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean hasTransactionsOpen() {
	Program program = sessionDB.getDestinationProgram();
	Transaction transaction = program.getCurrentTransaction();
	if (transaction != null) {
		Msg.showWarn(this, null, "Unable to Set Match Tag",
			"The program \"" + program.getName() + "\"already has a transaction open: " +
				transaction.getDescription());
		return true;
	}

	Transaction matchSetTransaction = sessionDB.getCurrentTransaction();
	if (matchSetTransaction != null) {
		Msg.showWarn(this, null, "Unable to Set Match Tag",
			"Transaction already open for the Match Set Manager ");
		return true;
	}
	return false;
}
 
Example 7
Source File: GhidraRun.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Open the specified project or the last active project if projectPath is null.
 * Makes the project window visible.
 * @param projectPath optional project to be opened (specifies project file)
 */
private void openProject(String projectPath) {

	updateSplashScreenStatusMessage("Creating project manager...");
	ProjectManager pm = new GhidraProjectManager();
	updateSplashScreenStatusMessage("Creating front end tool...");
	FrontEndTool tool = new FrontEndTool(pm);

	boolean reopen = true;
	ProjectLocator projectLocator = null;
	if (projectPath != null) {
		File projectFile = new File(projectPath);
		String name = projectFile.getName();
		if (!name.endsWith(ProjectLocator.getProjectExtension())) {
			Msg.showInfo(GhidraRun.class, null, "Invalid Project",
				"The specified file is not a project file: " + projectPath);
		}
		else {
			projectLocator = new ProjectLocator(projectFile.getParent(), name);
			reopen = false;
		}
	}
	if (projectLocator == null) {
		updateSplashScreenStatusMessage("Checking for last opened project...");
		projectLocator = pm.getLastOpenedProject();
	}

	if (Application.isTestBuild()) {
		Msg.showWarn(GhidraRun.class, tool.getToolFrame(), "Unsupported Ghidra Distribution",
			"WARNING! Please be aware that this is an unsupported and uncertified\n" +
				"build of Ghidra!  This software may be unstable and data created\n" +
				"may be incompatible with future releases.");
	}

	tool.setVisible(true);

	if (projectLocator != null) {
		openProject(tool, projectLocator, reopen);
	}
}
 
Example 8
Source File: GraphAST.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
	public void run() throws Exception {
		PluginTool tool = state.getTool();
		if (tool == null) {
			println("Script is not running in GUI");
		}
		GraphDisplayBroker graphDisplayBroker = tool.getService(GraphDisplayBroker.class);
		if (graphDisplayBroker == null) {
			Msg.showError(this, tool.getToolFrame(), "GraphAST Error",
				"No graph display providers found: Please add a graph display provider to your tool");
			return;
		}

		func = this.getFunctionContaining(this.currentAddress);
		if (func == null) {
			Msg.showWarn(this, state.getTool().getToolFrame(), "GraphAST Error",
				"No Function at current location");
			return;
		}

		buildAST();

		graph = new AttributedGraph();
		buildGraph();

		GraphDisplay graphDisplay =
			graphDisplayBroker.getDefaultGraphDisplay(false, monitor);
//        graphDisplay.defineVertexAttribute(CODE_ATTRIBUTE); //
//        graphDisplay.defineVertexAttribute(SYMBOLS_ATTRIBUTE);
//        graphDisplay.defineEdgeAttribute(EDGE_TYPE_ATTRIBUTE);
		graphDisplay.setGraph(graph, "Data-flow AST", false, monitor);

		// Install a handler so the selection/location will map
		graphDisplay.setGraphDisplayListener(
			new ASTGraphDisplayListener(tool, graphDisplay, high, func.getProgram()));
	}
 
Example 9
Source File: FunctionBitPatternsMainProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void analyze() {
	if (plugin.getCurrentProgram() == null) {
		Msg.showWarn(this, component, "Null Program", "Please open a program");
		return;
	}
	if (selectedRows.isEmpty()) {
		return;
	}
	PatternEvaluationStats currentStats = clipboard.evaluatePatterns(selectedRows);
	new PatternEvalTableProvider(currentStats, component, plugin,
		plugin.getCurrentProgram());

}
 
Example 10
Source File: BatchImportTableModel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
	if (rowIndex >= list.size()) {
		return;
	}

	BatchGroup row = list.get(rowIndex);
	switch (COLS.getCol(columnIndex)) {
		case SELECTED:
			boolean newValue = (Boolean) aValue;
			// dont allow enable unless there is a lang chosen
			if (newValue == true && row.getSelectedBatchGroupLoadSpec() == null) {
				Msg.showWarn(this, null, "Missing language",
					"Select a language for this group before enabling");
				return;
			}

			row.setEnabled(newValue);
			break;
		case LANG:
			row.setSelectedBatchGroupLoadSpec((BatchGroupLoadSpec) aValue);
			break;
		case FILES:
			// ignore
			break;
		default:
			throw new RuntimeException("bad column");
	}
}
 
Example 11
Source File: GhidraScriptComponentProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void deleteScript() {
	ResourceFile script = getSelectedScript();
	if (script == null) {
		return;
	}
	ResourceFile directory = script.getParentFile();

	Path path = GhidraScriptUtil.getScriptPath(directory);
	if (path == null || path.isReadOnly()) {
		Msg.showWarn(getClass(), getComponent(), getName(),
			"Unable to delete scripts in '" + directory + "'.");
		return;
	}

	int result = OptionDialog.showYesNoDialog(getComponent(), getName(),
		"Are you sure you want to delete script '" + script.getName() + "'?");
	if (result == OptionDialog.OPTION_ONE) {
		if (removeScript(script)) {
			GhidraScriptProvider provider = GhidraScriptUtil.getProvider(script);
			if (provider.deleteScript(script)) {
				restoreSelection(script);
			}
			else {
				Msg.showInfo(getClass(), getComponent(), getName(),
					"Unable to delete script '" + script.getName() + "'" + "\n" +
						"Please verify the file permissions.");
			}
		}
	}
}
 
Example 12
Source File: CreateLibraryAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(SymbolTreeActionContext context) {
	GTree tree = (GTree) context.getContextObject();
	if (tree.isFiltered()) {
		Msg.showWarn(getClass(), tree, "Create Library Not Allowed",
			"Cannot create library name while the tree is filtered!");
		return;
	}
	createExternalLibrary(context);
}
 
Example 13
Source File: GhidraScriptComponentProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void renameScript() {
	ResourceFile script = getSelectedScript();
	ResourceFile directory = script.getParentFile();
	Path path = GhidraScriptUtil.getScriptPath(directory);
	if (path == null || path.isReadOnly()) {
		Msg.showWarn(getClass(), getComponent(), getName(),
			"Unable to rename scripts in '" + directory + "'.");
		return;
	}
	if (isEditorOpen(script)) {
		Msg.showWarn(getClass(), getComponent(), "Unable to rename script",
			"The script is open for editing.\nPlease close the script and try again.");
		return;
	}

	GhidraScriptProvider provider = GhidraScriptUtil.getProvider(script);
	SaveDialog dialog = new SaveDialog(getComponent(), "Rename Script", this, script,
		actionManager.getRenameHelpLocation());
	if (dialog.isCancelled()) {
		plugin.getTool().setStatusInfo("User cancelled rename.");
		return;
	}

	ResourceFile renameFile = dialog.getFile();
	if (renameFile == null) {
		return;
	}

	if (renameFile.exists()) {
		Msg.showWarn(getClass(), getComponent(), "Unable to rename script",
			"Destination file already exists.");
		return;
	}

	checkNewScriptDirectoryEnablement(renameFile);

	renameScriptByCopying(script, provider, renameFile);
}
 
Example 14
Source File: ExportPatternFileActionListener.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {

	List<PatternInfoRowObject> selected = clipboardPanel.getLastSelectedObjects();
	if (selected.isEmpty()) {
		return;
	}
	//scan through all of them: must be at least one pre-pattern and 
	//at least one post-pattern
	boolean containsPostPattern = false;
	boolean containsPrePattern = false;
	for (PatternInfoRowObject row : selected) {
		if (row.getPatternType().equals(PatternType.FIRST)) {
			containsPostPattern = true;
		}
		if (row.getPatternType().equals(PatternType.PRE)) {
			containsPrePattern = true;
		}
	}
	if (!containsPostPattern) {
		Msg.showWarn(this, component, "No Post Pattern",
			"Selected patterns must contain at least one post pattern");
		return;
	}
	if (!containsPrePattern) {
		Msg.showWarn(this, component, "No Pre Pattern",
			"Selected patterns must contain at least one pre pattern");
		return;
	}

	boolean proceed = checkConsistencyForExport(selected);
	if (!proceed) {
		return;
	}
	GhidraFileChooser gFileChooser = new GhidraFileChooser(component);
	gFileChooser.setFileSelectionMode(GhidraFileChooser.FILES_ONLY);
	ExtensionFileFilter xmlFilter = new ExtensionFileFilter("xml", "XML Files");
	gFileChooser.setFileFilter(xmlFilter);
	String baseDir = Preferences.getProperty(XML_EXPORT_DIR_PROPERTY);
	if (baseDir != null) {
		gFileChooser.setCurrentDirectory(new File(baseDir));
	}
	gFileChooser.setTitle("Select Export File");
	File outFile = gFileChooser.getSelectedFile();
	if (gFileChooser.wasCancelled() || outFile == null) {
		return;
	}
	Preferences.setProperty(XML_EXPORT_DIR_PROPERTY,
		gFileChooser.getCurrentDirectory().getAbsolutePath());
	Preferences.store();
	BitsInputDialogComponentProvider bitsProvider =
		new BitsInputDialogComponentProvider(BITS_PROVIDER_MESSAGE);
	if (bitsProvider.isCanceled()) {
		return;
	}
	int totalBits = bitsProvider.getTotalBits();
	int postBits = bitsProvider.getPostBits();
	try {
		PatternInfoRowObject.exportXMLFile(selected, outFile, postBits, totalBits);
	}
	catch (IOException e1) {
		Msg.showError(this, component, "IO Error", "IO error exporting pattern xml file", e1);
		e1.printStackTrace();
	}
}
 
Example 15
Source File: ApplyEnumsAsLabelsAction.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void run(TaskMonitor monitor) {
	DataTypeManager dataTypeManager = program.getDataTypeManager();
	int totalLabelsCreated = 0;
	boolean someAlreadyExisted = false;
	boolean failedToCreateSome = false;

	int transactionID = -1;
	boolean commit = false;
	try {
		// start a transaction
		transactionID =
			dataTypeManager.startTransaction("Create Labels From Selected Enum Data Types");

		TreePath[] selectionPaths = gTree.getSelectionPaths();
		for (TreePath path : selectionPaths) {
			GTreeNode node = (GTreeNode) path.getLastPathComponent();
			if (!(node instanceof DataTypeNode)) {
				continue;
			}

			DataTypeNode dtNode = (DataTypeNode) node;
			DataType dataType = dtNode.getDataType();
			if (!(dataType instanceof Enum)) {
				continue;
			}

			Enum enumDt = (Enum) dataType;
			CreateLabelResult result = createLabels(enumDt);
			totalLabelsCreated += result.numberCreated;
			someAlreadyExisted |= result.someAlreadyExisted;
			failedToCreateSome |= result.failedToCreateSomeLabels;
		}

		commit = true;
	}
	finally {
		// commit the changes
		dataTypeManager.endTransaction(transactionID, commit);
	}

	if (failedToCreateSome) {
		Msg.showWarn(this, gTree, "Couldn't Create Some Labels",
			"One or more labels couldn't be created from the Enum values." +
				"\nSee user log in system console for more info.");
	}

	//@formatter:off
	String message = (totalLabelsCreated > 0) ?
					 	"Labels created: " + totalLabelsCreated + ".":
					 	"Couldn't create any labels for the selected data types.";
	//@formatter:on
	if (someAlreadyExisted) {
		message += " Some labels already exist.";
	}

	plugin.getTool().setStatusInfo(message);
}
 
Example 16
Source File: GenerateOldLanguagePlugin.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void buildDefaultTranslator(Language newLang, File transFile) throws IOException {

			DummyLanguageTranslator defaultTrans = new DummyLanguageTranslator(oldLang, newLang);
			if (!defaultTrans.isValid()) {
				throw new AssertException();
			}

			Element root = new Element("language_translation");

			Element fromLang = new Element("from_language");
			fromLang.setAttribute("version", Integer.toString(oldLang.getVersion()));
			fromLang.setText(oldLang.getLanguageID().getIdAsString());
			root.addContent(fromLang);

			Element toLang = new Element("to_language");
			toLang.setAttribute("version", Integer.toString(newLang.getVersion()));
			toLang.setText(newLang.getLanguageID().getIdAsString());
			root.addContent(toLang);

			for (CompilerSpecDescription oldCompilerSpecDescription : oldLang.getCompatibleCompilerSpecDescriptions()) {
				CompilerSpecID oldCompilerSpecID = oldCompilerSpecDescription.getCompilerSpecID();
				String newId;
				try {
					newId =
						newLang.getCompilerSpecByID(oldCompilerSpecID).getCompilerSpecID().getIdAsString();
				}
				catch (CompilerSpecNotFoundException e) {
					newId = newLang.getDefaultCompilerSpec().getCompilerSpecID().getIdAsString();
				}
				Element compilerSpecMapElement = new Element("map_compiler_spec");
				compilerSpecMapElement.setAttribute("from", oldCompilerSpecID.getIdAsString());
				compilerSpecMapElement.setAttribute("to", newId);
				root.addContent(compilerSpecMapElement);
			}

			if (!defaultTrans.canMapSpaces) {
				for (AddressSpace space : oldLang.getAddressFactory().getPhysicalSpaces()) {
					Element mapSpaceElement = new Element("map_space");
					mapSpaceElement.setAttribute("from", space.getName());
					mapSpaceElement.setAttribute("to", "?" + space.getSize());
					root.addContent(mapSpaceElement);
				}
			}

			for (Register reg : oldLang.getRegisters()) {
				Register newReg = defaultTrans.getNewRegister(reg);
				if (newReg == null) {
					Element mapRegElement = new Element("map_register");
					mapRegElement.setAttribute("from", reg.getName());
					mapRegElement.setAttribute("to", ("?" + reg.getMinimumByteSize()));
					mapRegElement.setAttribute("size", Integer.toString(reg.getMinimumByteSize()));
					root.addContent(mapRegElement);
				}
			}

			Document doc = new Document(root);
			FileOutputStream out = new FileOutputStream(transFile);
			XMLOutputter xml = new GenericXMLOutputter();
			xml.output(doc, out);
			out.close();

			Register oldCtx = oldLang.getContextBaseRegister();
			Register newCtx = newLang.getContextBaseRegister();
			boolean contextWarning = false;
			if (oldCtx != null && defaultTrans.isValueTranslationRequired(oldCtx)) {
				contextWarning = true;
			}
			else if (oldCtx == null && newCtx != null) {
				contextWarning = true;
			}
			if (contextWarning) {
				Msg.showWarn(getClass(), tool.getToolFrame(), "Translator Warning",
					"The new context register differs from the old context!\n"
						+ "A set_context element or custom translator may be required.");
			}
		}
 
Example 17
Source File: ProgramAnnotatedStringHandler.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void navigate(DomainFile programFile, SymbolPath symbolPath, Navigatable navigatable,
		ServiceProvider serviceProvider) {

	GoToService goToService = serviceProvider.getService(GoToService.class);
	if (goToService == null) {
		// shouldn't happen
		Msg.showWarn(this, null, "Service Missing",
			"This annotation requires the GoToService to be enabled");
		return;
	}

	ProgramManager programManager = serviceProvider.getService(ProgramManager.class);
	Program program = programManager.openProgram(programFile, DomainFile.DEFAULT_VERSION,
		ProgramManager.OPEN_HIDDEN);
	if (program == null) {
		return; // cancelled
	}

	if (symbolPath == null) { // no symbol; just open and go to the program
		Address start = program.getMemory().getMinAddress();
		goToService.goTo(navigatable, new ProgramLocation(program, start), program);
		return;
	}

	// try any symbols(s) first
	List<Symbol> symbols = NamespaceUtils.getSymbols(symbolPath.getPath(), program);
	if (goToSymbol(symbols, navigatable, program, goToService)) {
		return;
	}

	String symbolName = symbolPath.getName();
	Address address = getAddress(symbolName, program);
	if (goToAddress(address, program, navigatable, goToService)) {
		return;
	}

	Msg.showInfo(getClass(), null, "No Symbol: " + symbolName,
		"Unable to navigate to '" + symbolName + "' in the program '" + programFile.getName() +
			"'.\nMake sure that the given symbol/address exists.");
	if (!programManager.isVisible(program)) {
		// we opened a hidden program, but could not navigate--close the program
		programManager.closeProgram(program, true);
	}
}
 
Example 18
Source File: LoadPdbTask.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void run(final TaskMonitor monitor) {
	final MessageLog log = new MessageLog();

	AnalysisWorker worker = new AnalysisWorker() {

		@Override
		public String getWorkerName() {
			return "Load PDB";
		}

		@Override
		public boolean analysisWorkerCallback(Program currentProgram, Object workerContext,
				TaskMonitor currentMonitor) throws Exception, CancelledException, PdbException {

			PdbParser parser =
				new PdbParser(pdbFile, program, service, true, currentMonitor);

			parser.parse();
			parser.openDataTypeArchives();
			parser.applyTo(log);

			analyzeSymbols(currentMonitor, log);
			return !monitor.isCancelled();
		}
	};

	boolean analyzed =
		program.getOptions(Program.PROGRAM_INFO).getBoolean(Program.ANALYZED, false);
	if (analyzed) {
		Msg.showWarn(this, null, "PDB Warning",
			"Loading PDB after analysis has been performed will produce" +
				"\npoor results.  PDBs should be loaded prior to analysis or" +
				"\nautomatically during auto-analysis.");
	}

	try {
		AutoAnalysisManager.getAnalysisManager(program)
				.scheduleWorker(worker, null, true,
					monitor);
	}
	catch (InterruptedException | CancelledException e1) {
		// ignore
	}
	catch (InvocationTargetException e) {
		String message;

		Throwable t = e.getCause();

		if (t == null) {
			message = "Unknown cause";
		}
		else {
			message = t.getMessage();

			if (message == null) {
				message = t.toString();
			}
		}

		Msg.showError(getClass(), null, "Load PDB Failed", message, t);
	}

	if (log.getMsgCount() > 0) {
		MultiLineMessageDialog dialog = new MultiLineMessageDialog("Load PDB File",
			"There were warnings/errors loading the PDB file.", log.toString(),
			MultiLineMessageDialog.WARNING_MESSAGE, false);
		DockingWindowManager.showDialog(null, dialog);
	}
}
 
Example 19
Source File: CryptoKeyFactory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Loads the crypto key XML file if it is not currently loaded OR if it has
 * changed since it was last loaded.
 */
private static void loadIfNeeded() {
	ResourceFile cryptoDirectory = getCryptoDirectory();

	ResourceFile[] files = cryptoDirectory.listFiles();
	for (ResourceFile file : files) {
		if (!file.getName().endsWith(".xml")) {
			continue;
		}
		if (fileDatesMap.containsKey(file.getName())) {
			if (fileDatesMap.get(file.getName()) == file.lastModified()) {
				continue;
			}
		}
		fileDatesMap.put(file.getName(), file.lastModified());
		try {
			InputStream is = file.getInputStream();
			try {
				SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
				Document doc = sax.build(is);
				Element root = doc.getRootElement();
				String firmwareName = root.getAttributeValue("NAME");
				if (!cryptoMap.containsKey(firmwareName)) {
					cryptoMap.put(firmwareName, new HashMap<String, CryptoKey>());
				}
				List<Element> firmwareFileList =
					CollectionUtils.asList(root.getChildren(), Element.class);
				Iterator<Element> firmwareFileIter = firmwareFileList.iterator();
				while (firmwareFileIter.hasNext()) {
					Element firmwareFileElement = firmwareFileIter.next();
					String path = firmwareFileElement.getAttributeValue("PATH");
					if (firmwareFileElement.getAttribute("not_encrypted") != null) {
						cryptoMap.get(firmwareName).put(path, CryptoKey.NOT_ENCRYPTED_KEY);
					}
					else {
						Element keyElement = firmwareFileElement.getChild("KEY");
						String keyString = keyElement.getText().trim();
						if ((keyString.length() % 2) != 0) {
							throw new CryptoException("Invalid key length in [" + firmwareName +
								".xml] for [" + path + "]");
						}
						byte[] key = NumericUtilities.convertStringToBytes(keyString);
						Element ivElement = firmwareFileElement.getChild("IV");
						String ivString = ivElement.getText().trim();
						if ((ivString.length() % 2) != 0) {
							throw new CryptoException("Invalid iv length in [" + firmwareName +
								".xml] for [" + path + "]");
						}
						byte[] iv = NumericUtilities.convertStringToBytes(ivString);
						CryptoKey cryptoKey = new CryptoKey(key, iv);
						cryptoMap.get(firmwareName).put(path, cryptoKey);
					}
				}
			}
			finally {
				is.close();
			}
		}
		catch (Exception e) {
			Msg.showWarn(CryptoKeyFactory.class, null, "Error Parsing Crypto Keys File",
				"Unable to process crypto keys files.", e);
		}
	}
}
 
Example 20
Source File: JavaAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void appendLoadableInfo(StringBuffer sb, AbstractConstantPoolInfoJava[] constantPool,
		int argIndex) {
	AbstractConstantPoolInfoJava cpoolInfo = constantPool[argIndex];
	if (cpoolInfo instanceof ConstantPoolIntegerInfo) {
		ConstantPoolIntegerInfo intInfo = (ConstantPoolIntegerInfo) cpoolInfo;
		sb.append(intInfo.getValue());
		return;
	}
	if (cpoolInfo instanceof ConstantPoolFloatInfo) {
		ConstantPoolFloatInfo floatInfo = (ConstantPoolFloatInfo) cpoolInfo;
		sb.append(floatInfo.getValue());
		return;
	}
	if (cpoolInfo instanceof ConstantPoolLongInfo) {
		ConstantPoolLongInfo longInfo = (ConstantPoolLongInfo) cpoolInfo;
		sb.append(longInfo.getValue());
		return;
	}
	if (cpoolInfo instanceof ConstantPoolDoubleInfo) {
		ConstantPoolDoubleInfo doubleInfo = (ConstantPoolDoubleInfo) cpoolInfo;
		sb.append(doubleInfo.getValue());
		return;
	}
	if (cpoolInfo instanceof ConstantPoolClassInfo) {
		ConstantPoolClassInfo classInfo = (ConstantPoolClassInfo) cpoolInfo;
		ConstantPoolUtf8Info className =
			(ConstantPoolUtf8Info) constantPool[classInfo.getNameIndex()];
		sb.append(className.getString());
		return;
	}
	if (cpoolInfo instanceof ConstantPoolStringInfo) {
		ConstantPoolStringInfo stringInfo = (ConstantPoolStringInfo) cpoolInfo;
		ConstantPoolUtf8Info utf8 =
			(ConstantPoolUtf8Info) constantPool[stringInfo.getStringIndex()];
		sb.append("\"");
		sb.append(utf8.getString());
		sb.append("\"");
		return;
	}
	if (cpoolInfo instanceof ConstantPoolMethodHandleInfo) {
		appendMethodHandleInfo(sb, constantPool, argIndex);
		return;
	}
	if (cpoolInfo instanceof ConstantPoolMethodTypeInfo) {
		ConstantPoolMethodTypeInfo mtInfo = (ConstantPoolMethodTypeInfo) cpoolInfo;
		ConstantPoolUtf8Info descriptor =
			(ConstantPoolUtf8Info) constantPool[mtInfo.getDescriptorIndex()];
		sb.append(descriptor.getString());
		return;
	}
	if (cpoolInfo instanceof ConstantPoolDynamicInfo) {
		ConstantPoolDynamicInfo dynamicInfo = (ConstantPoolDynamicInfo) cpoolInfo;
		ConstantPoolNameAndTypeInfo ntInfo =
			(ConstantPoolNameAndTypeInfo) constantPool[dynamicInfo.getNameAndTypeIndex()];
		ConstantPoolUtf8Info name = (ConstantPoolUtf8Info) constantPool[ntInfo.getNameIndex()];
		sb.append(name.getString());
		return;
	}
	Msg.showWarn(this, null, "Unsupported Constant Pool Type", cpoolInfo.getClass().getName());
	return;
}