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

The following examples show how to use ghidra.util.Msg#trace() . 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: BowTieExpandVerticesJob.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 * 
 * @param viewer the graph viewer
 * @param newVertexCollection the collection of new vertices and edges being addeds
 * @param useAnimation true to use animation
 */
public BowTieExpandVerticesJob(GraphViewer<FcgVertex, FcgEdge> viewer,
		FcgExpandingVertexCollection newVertexCollection, boolean useAnimation) {
	super(viewer, useAnimation);

	this.newVertexCollection = newVertexCollection;
	this.incoming = newVertexCollection.isIncoming();
	this.expandingLevel = newVertexCollection.getExpandingLevel();

	if (!(graphLayout instanceof BowTieLayout)) {
		throw new IllegalArgumentException("The current graph layout must be the " +
			BowTieLayout.class.getSimpleName() + " to use this job");
	}

	Msg.trace(this,
		"\nBow Tie Expand Job - new vertices: " + newVertexCollection.getNewVertices());

	// for debug
	// duration = 5000;
}
 
Example 2
Source File: NavigationHistoryPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private LocationMemento restoreLocation(int index, SaveState saveState, Program[] programs) {
	Element mementoElement = saveState.getXmlElement(MEMENTO_DATA + index);
	if (mementoElement == null) {
		return null;
	}

	SaveState mementoState = new SaveState(mementoElement);
	LocationMemento locationMemento = null;
	try {
		locationMemento = LocationMemento.getLocationMemento(mementoState, programs);
	}
	catch (IllegalArgumentException iae) {
		// this can happen if a program is renamed or deleted but the tool config state
		// has not been saved since the delete
		Msg.trace(this, "Unable to restore LocationMemento: " + iae.getMessage(), iae);
	}
	return locationMemento;
}
 
Example 3
Source File: DecompilerDataTypeReferenceFinder.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void searchDecompilation(List<DataTypeReference> results) {

			ClangTokenGroup tokens = decompilation.getCCodeMarkup();

// TODO delete this when the ticket settles down			
//			dumpTokens(tokens, 0);
//			dumpTokenNames(tokens, 0);

			if (tokens == null) {
				// assume a bad function or the user cancelled the decompilation
				Msg.trace(this, "Unable to get decompilation tokens for " + function.getName());
				return;
			}

			List<DecompilerReference> variables = findVariableReferences(tokens);
			variables.forEach(v -> matchUsage(v, results));
		}
 
Example 4
Source File: PropagateExternalParametersAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void addSymbol(SymbolTable symbolTable, Address address, String symbolName) {

		Listing listing = currentProgram.getListing();
		Data data = listing.getDefinedDataAt(address);
		if (data != null && data.hasStringValue()) {
			return; // don't add symbol for string (not sure why)
		}

		try {
			Symbol newSymbol =
				symbolTable.createLabel(address, symbolName, SourceType.USER_DEFINED);
			newSymbol.setPrimary();
		}
		catch (InvalidInputException e) {
			// shouldn't happen
			Msg.trace(this, "Unexpected exception", e);
		}

	}
 
Example 5
Source File: GHelpHTMLEditorKit.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/** Generates a new event with a URL based upon Ghidra's resources if needed. */
private HyperlinkEvent maybeCreateNewHyperlinkEventWithUpdatedURL(HyperlinkEvent event) {
	Element element = event.getSourceElement();
	if (element == null) {
		return event;// this shouldn't happen since we were triggered from an A tag
	}

	AttributeSet a = element.getAttributes();
	AttributeSet anchor = (AttributeSet) a.getAttribute(HTML.Tag.A);
	if (anchor == null) {
		return event;// this shouldn't happen since we were triggered from an A tag
	}

	String HREF = (String) anchor.getAttribute(HTML.Attribute.HREF);
	Msg.trace(this, "HREF of <a> tag: " + HREF);
	URL newUrl = getURLForHREFFromResources(HREF);
	if (newUrl == null) {
		return event;// unable to locate a resource by the name--bad link!
	}

	return new HyperlinkEvent(event.getSource(), event.getEventType(), newUrl,
		event.getDescription(), event.getSourceElement());
}
 
Example 6
Source File: ClassFinder.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static void processClassLoadError(String path, String name, Throwable t) {

		if (t instanceof LinkageError) {
			// We see this sometimes when loading classes that match our naming convention for
			// extension points, but are actually extending 3rd party libraries.  For now, do 
			// not make noise in the log for this case.
			Msg.trace(ClassFinder.class,
				"LinkageError loading class " + name + "; Incompatible class version? ", t);
			return;
		}

		if (!(t instanceof ClassNotFoundException)) {
			Msg.error(ClassFinder.class, "Error loading class " + name + " - " + t.getMessage(), t);
			return;
		}

		processClassNotFoundExcepetion(path, name, (ClassNotFoundException) t);
	}
 
Example 7
Source File: CreateArchive1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateArchiveNameCollision2() throws Exception {

	// create archive
	// attempt to save over a file that exists
	// answer no to overwrite dialog
	// verify that the archive did not get saved to that name.

	// create file to cause a name collision
	File file = writeTempFile("MyArchive.gdt");

	createNewArchive("MyArchive.gdt", false);

	// find the option dialog
	OptionDialog optDialog = waitForDialogComponent(OptionDialog.class);

	JButton button = findButtonByText(optDialog.getComponent(), "No");
	pressButton(button);
	waitForPostedSwingRunnables();
	waitForTree();

	ArchiveNode archiveNode = (ArchiveNode) archiveRootNode.getChild("MyArchive");

	// debug
	if (archiveNode == null) {
		Msg.trace(this, "Did not find a newly created node!!!!");
		// ...try waiting some more, to see if we beat the update
		waitForTree();
		archiveNode = (ArchiveNode) archiveRootNode.getChild("MyArchive");
		Msg.trace(this, "\tand after waiting some more did we?: " + archiveNode);
	}

	assertNull(archiveNode);
}
 
Example 8
Source File: CreateArchive1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateArchiveNameCollision1() throws Exception {
	// create archive
	// attempt to create over a file that exists
	// answer yes to overwrite dialog
	// verify that the archive was saved by opening it again and checking it has the right stuff.

	// create file to cause a name collision
	File file = writeTempFile("MyArchive.gdt");

	int insertedCount = getTreeModelInsertedNodeCount();
	Msg.trace(this, testName.getMethodName() + ":NODE COUNT: " + insertedCount);

	createNewArchive("MyArchive.gdt", false);

	// find the option dialog
	OptionDialog optDialog = waitForDialogComponent(OptionDialog.class);

	JButton button = findButtonByText(optDialog.getComponent(), "Yes");
	Msg.trace(this, "\t" + testName.getMethodName() + ":preparing to answer yes to overwrite");
	pressButton(button);
	waitForTree();

	ArchiveNode archiveNode = (ArchiveNode) archiveRootNode.getChild("MyArchive");
	assertNotNull(archiveNode);

}
 
Example 9
Source File: WatchdogTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void test() {
	long watchdogTimeoutMS = 10;

	// watchdog could take N*2 to trigger
	long watchdogMaxIntrMS = watchdogTimeoutMS * 3;
	AtomicBoolean inerruptedFlag = new AtomicBoolean();

	Thread testThread = Thread.currentThread();
	try (Watchdog watchDog = new Watchdog(watchdogTimeoutMS, () -> {
		Msg.trace(this, "" + System.currentTimeMillis() + ": Interrupting the test thread...");
		inerruptedFlag.set(true);
		testThread.interrupt();
	})) {

		for (int i = 0; i < 10; i++) {
			inerruptedFlag.set(false);
			watchDog.arm();
			long start = System.currentTimeMillis();
			try {
				Thread.sleep(DEFAULT_WAIT_TIMEOUT);
				fail(System.currentTimeMillis() + ": Watchdog did not fire");
			}
			catch (InterruptedException e) {
				assertTrue("" + System.currentTimeMillis() +
					": Sleep was interrupted, but not by watchdog", inerruptedFlag.get());
				long elapsed = System.currentTimeMillis() - start;
				Msg.trace(this, System.currentTimeMillis() + ": Watchdog fired in: " + elapsed +
					"ms, max target is: " + watchdogMaxIntrMS + "ms");
			}
		}
	}

}
 
Example 10
Source File: AbstractWorker.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Schedules the job for execution.  Jobs will be processed in priority order.  The
 * highest priority jobs are those with the lowest value return by the job's getPriority()
 * method. (i.e. the job with priority 0 will be processed before the job with priority 1)
 * @param job the job to be executed.
 */
public void schedule(T job) {
	if (isDisposed) {
		Msg.trace(this, "A job was scheduled after this worker was disposed - " + job);
		return;
	}

	setBusy(true);
	concurrentQ.add(job);
}
 
Example 11
Source File: GhidraScriptUtil.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the given {@link ResourceFile} to find its class file.  This method is needed
 * due to the fact that we sometimes can find a class file in more than one location, 
 * such as when using an installation version of Ghidra in the same environment as 
 * a development version of Ghidra.  We get better debugging when we use the class file
 * that is associated with the given source file.
 * 
 * @param sourceFile the source file for which to find the generated class file.
 * @param rawName the name of the class, without file extension or path info.
 * @return the class file generated from the given source file.
 */
static ResourceFile getClassFileByResourceFile(ResourceFile sourceFile, String rawName) {
	String javaAbsolutePath = sourceFile.getAbsolutePath();
	String classAbsolutePath = javaAbsolutePath.replace(".java", ".class");

	String path = rawName.replace('.', '/');
	String className = path + ".class";

	ResourceFile classFile =
		findClassFile(getDevelopmentScriptBinDirectories(), classAbsolutePath, className);
	if (classFile != null) {
		Msg.trace(GhidraScriptUtil.class,
			"Resource file " + sourceFile + " class found at " + classFile);
		return classFile;
	}

	ResourceFile defaultCompilerDirectory = getScriptCompileOutputDirectory(sourceFile);
	classFile =
		new ResourceFile(new File(defaultCompilerDirectory.getAbsolutePath(), className));
	if (classFile.exists()) {
		// This should always exist when we compile the script ourselves
		Msg.trace(GhidraScriptUtil.class,
			"Resource file " + sourceFile + " class found at " + classFile);
		return classFile;
	}

	classFile = findClassFile(getScriptBinDirectories(), classAbsolutePath, className);
	if (classFile != null) {
		Msg.trace(GhidraScriptUtil.class,
			"Resource file " + sourceFile + " class found at " + classFile);
		return classFile;
	}

	// default to a non-existent file
	return new ResourceFile(GhidraScriptUtil.USER_SCRIPTS_BIN_DIR + "/" + className);
}
 
Example 12
Source File: CreateArchiveAction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionContext context) {
	DataTypeArchiveGTree gTree = plugin.getProvider().getGTree();
	ArchiveFileChooser fileChooser = new ArchiveFileChooser(gTree);
	fileChooser.setApproveButtonText("Create Archive");
	fileChooser.setApproveButtonToolTipText("Create Archive");
	fileChooser.setTitle("Create Archive");

	Msg.trace(this, "Showing filechooser to get new archive name...");
	File file = fileChooser.promptUserForFile("New_Archive");
	if (file == null) {
		Msg.trace(this, "No new archive filename chosen by user - not performing action");
		return;
	}

	Msg.trace(this, "User picked file: " + file.getAbsolutePath());

	if (file.exists()) {
		Msg.trace(this, "Need to overwrite--showing dialog");
		if (OptionDialog.showYesNoDialogWithNoAsDefaultButton(gTree,
			"Overwrite Existing File?",
			"Do you want to overwrite existing file\n" +
				file.getAbsolutePath()) != OptionDialog.OPTION_ONE) {
			Msg.trace(this, "\tdo not overwrite was chosen");
			return;
		}
		Msg.trace(this, "\toverwriting file!");
		file.delete();
	}
	Archive newArchive = plugin.getDataTypeManagerHandler().createArchive(file);
	if (newArchive != null) {
		Msg.trace(this, "Created new archive: " + newArchive.getName());
		selectNewArchive(newArchive, gTree);
	}
}
 
Example 13
Source File: JavaScriptProvider.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private boolean doCompile(ResourceFile sourceFile, final PrintWriter writer) {

		JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
		if (javaCompiler == null) {
			String message =
				"Compile failed: java compiler provider not found (you must be using a JDK " +
					"to compile scripts)!";
			writer.println(message);
			Msg.error(this, message); // the writer may not be the same as Msg, so log it too
			return false;
		}

		JavaFileManager fileManager =
			new ResourceFileJavaFileManager(GhidraScriptUtil.getScriptSourceDirectories());

		List<ResourceFileJavaFileObject> list = new ArrayList<>();
		list.add(
			new ResourceFileJavaFileObject(sourceFile.getParentFile(), sourceFile, Kind.SOURCE));

		String outputDirectory =
			GhidraScriptUtil.getScriptCompileOutputDirectory(sourceFile).getAbsolutePath();
		Msg.trace(this, "Compiling script " + sourceFile + " to dir " + outputDirectory);

		List<String> options = new ArrayList<>();
		options.add("-g");
		options.add("-d");
		options.add(outputDirectory);
		options.add("-sourcepath");
		options.add(getSourcePath());
		options.add("-classpath");
		options.add(getClassPath());
		options.add("-proc:none"); // Prevents warning when script imports something that will get compiled

		CompilationTask task = javaCompiler.getTask(writer, fileManager, null, options, null, list);
		return task.call();
	}
 
Example 14
Source File: PropagateExternalParametersAnalyzer.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean added(Program program, AddressSetView set, TaskMonitor monitor, MessageLog log)
		throws CancelledException {
	this.currentProgram = program;

	Listing listing = program.getListing();
	FunctionManager functionManager = program.getFunctionManager();
	ReferenceManager referenceManager = program.getReferenceManager();

	// iterate over all external symbols
	SymbolTable symbolTable = program.getSymbolTable();
	SymbolIterator externalSymbols = symbolTable.getExternalSymbols();
	for (Symbol externalSymbol : externalSymbols) {
		if (externalSymbol.getSymbolType() != SymbolType.FUNCTION) {
			continue;
		}

		Function externalFunction = functionManager.getFunctionAt(externalSymbol.getAddress());
		Parameter[] params = externalFunction.getParameters();
		if (params.length == 0) {
			continue;
		}

		Reference[] references = externalSymbol.getReferences();
		processExternalFunction(listing, referenceManager, references, externalFunction,
			params);
	}

	// use the 'results' to propagate param info to the local variables, data, and params of
	// the calling function
	Msg.trace(this, "Processing propagation results - count: " + results.size());
	for (int i = 0; i < results.size(); i++) {
		PushedParamInfo paramInfo = results.get(i);
		Address paramAddress = paramInfo.getAddress();
		Instruction instruction = listing.getInstructionAt(paramAddress);

		// wait on applying data types - the microsoft analyzer does some of this
		// see how much/well it does first
		if (!instruction.getOperandRefType(0).isData()) {
			continue;
		}

		int opType = instruction.getOperandType(0);
		if (!isAddressReferenceOperand(opType)) {
			continue;
		}

		Address referencedAddress = getReferencedAddress(paramAddress);
		if (referencedAddress == null) {
			continue;
		}

		String paramName = paramInfo.getName();
		String symbolName = paramName + "_" + referencedAddress.toString();

		addSymbol(symbolTable, referencedAddress, symbolName);

		String paramText = paramName + " parameter of " + paramInfo.getCalledFunctionName();
		String newComment = paramText + "\n";
		Msg.trace(this, "External Function Call at " + paramAddress + " : " + paramText +
			" at " + referencedAddress.toString());

		createComment(referencedAddress, newComment, paramInfo);

		clearUndefinedDataType(referencedAddress, monitor);

		createData(paramInfo, referencedAddress);
	}

	return true;
}
 
Example 15
Source File: GMouseListenerAdapter.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void trace(String message) {
	Msg.trace(GMouseListenerAdapter.class, message);
}
 
Example 16
Source File: AbstractCreateArchiveTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected void createNewArchive(String archiveName, boolean deleteExisting) throws Exception {
	File archiveFile = new File(getTestDirectoryPath(), archiveName);
	if (deleteExisting && archiveFile.exists()) {
		Msg.trace(this, "\t" + testName.getMethodName() + ": found existing file - deleting: " +
			archiveFile.getAbsolutePath());
		boolean didDelete = archiveFile.delete();
		Msg.trace(this,
			"\t\t" + testName.getMethodName() + ": did it get deleted?: " + didDelete);

		if (!didDelete) {
			// try one more time
			waitForPostedSwingRunnables();
			sleep(1000);
			waitForPostedSwingRunnables();
			didDelete = archiveFile.delete();
			Msg.trace(this, "\t\t" + testName.getMethodName() +
				"after sleeping: did it get deleted?: " + didDelete);
			if (!didDelete) {
				Assert.fail(
					"Unable to create an archive, as the file already exists: " + archiveName);
			}
		}
	}

	DockingActionIf action = getAction(plugin, "New File Data Type Archive");
	DataTypeTestUtils.performAction(action, tree, false);

	GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);
	assertNotNull("File chooser was never shown", chooser);
	archiveFile.deleteOnExit();
	selectFileInChooser(chooser, archiveFile);
	waitForUpdateOnChooser(chooser);

	// hit "Create Archive" button
	Msg.trace(this, testName.getMethodName() + ": calling create archive...");
	JButton createArchiveButton = findButtonByText(chooser, "Create Archive");
	pressButton(createArchiveButton);
	Msg.trace(this, testName.getMethodName() + ":\tpressed the button on the swing thread");
	waitForPostedSwingRunnables();
	Msg.trace(this,
		"\t" + testName.getMethodName() + ":\tdone waiting for thread - created archive");

	chooser = getDialogComponent(GhidraFileChooser.class);
	assertNull("Chooser did not get closed", chooser);
	waitForTree();
}
 
Example 17
Source File: GraphJobRunner.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void trace(String message) {
	Msg.trace(this, message);
}
 
Example 18
Source File: VisualGraphPluggableGraphMouse.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void trace(String s) {
	Msg.trace(this, s);
}
 
Example 19
Source File: VisualGraphPluggableGraphMouse.java    From ghidra with Apache License 2.0 4 votes vote down vote up
private void trace(String s, MouseEvent e) {
	Msg.trace(this, "click count = " + e.getClickCount() + " - " + s);
}
 
Example 20
Source File: DemangledVariable.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public boolean applyTo(Program program, Address address, DemanglerOptions options,
		TaskMonitor monitor) throws Exception {

	if (isAlreadyDemangled(program, address)) {
		return true;
	}

	if (!super.applyTo(program, address, options, monitor)) {
		return false;
	}

	Symbol demangledSymbol = applyDemangledName(address, true, true, program);
	DataType demangledDT = getProgramDataType(program);

	if (address.isExternalAddress()) {
		if (demangledSymbol == null) {
			throw new AssertException("Undefined external address: " + address);
		}
		if (demangledDT != null) {
			ExternalLocation extLoc = (ExternalLocation) demangledSymbol.getObject();
			extLoc.setDataType(demangledDT);
		}
		return true;
	}

	Listing listing = program.getListing();

	Data d = listing.getDefinedDataAt(address);
	if (d != null) {
		if (demangledDT == null || !Undefined.isUndefined(d.getDataType())) {
			return true; // preserve existing data quietly
		}
	}

	if (demangledDT != null) {
		CreateDataCmd cmd = new CreateDataCmd(address, demangledDT, false,
			ClearDataMode.CLEAR_ALL_UNDEFINED_CONFLICT_DATA);
		if (!cmd.applyTo(program)) {
			Msg.error(this, "Failed to create data at " + address + ": " + cmd.getStatusMsg());
			return false;
		}
		return true;
	}

	// if the block is marked Executable, don't worry about creating data here
	// unless we really know what type of data it is
	MemoryBlock block = program.getMemory().getBlock(address);
	if (block == null || block.isExecute()) {
		return true;
	}

	// get the symbol after this one.  If smaller than pointer, can't be a pointer
	Address nextSymbolLoc = getNextSymbolLocation(program, address);

	// could be a pointer
	long maximumDataTypeSize = nextSymbolLoc.subtract(address);
	if (createPointer(program, address, maximumDataTypeSize)) {
		return true;
	}

	// Create an undefined data type here to stop any code from being created.
	// Might have to change the data reference creation to ignore undefined data types
	//   when trying to figure out what the data is.
	if (d != null) {
		// something is already there
		return true;
	}

	int size = (maximumDataTypeSize <= 8) ? (int) maximumDataTypeSize : 1;
	demangledDT = Undefined.getUndefinedDataType(size);

	try {
		listing.createData(address, demangledDT);
	}
	catch (CodeUnitInsertionException e) {
		Msg.trace(this, "Unable to create demangled data '" + demangledDT + "' @ " + address);
	}

	return true; // return true, as we did not fail to demangle
}