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

The following examples show how to use ghidra.util.Msg#info() . 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: FileSystemBrowserPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void doCreateNewFileSystemBrowser(FileSystemRef fsRef, boolean show) {
	FSRLRoot fsFSRL = fsRef.getFilesystem().getFSRL();
	FileSystemBrowserComponentProvider provider = currentBrowsers.get(fsFSRL);
	if (provider != null) {
		Msg.info(this, "Filesystem browser already open for " + fsFSRL);
		fsRef.close();
	}
	else {
		fsRef.getFilesystem().getRefManager().addListener(this);
		provider = new FileSystemBrowserComponentProvider(this, fsRef);
		currentBrowsers.put(fsFSRL, provider);
		getTool().addComponentProvider(provider, false);
		provider.afterAddedToTool();
	}

	if (show) {
		getTool().showComponentProvider(provider, true);
		getTool().toFront(provider);
	}
}
 
Example 2
Source File: EclipseConnectorTask.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link ProcessBuilder} to launch Eclipse.
 * 
 * @param eclipseExecutableFile The Eclipse executable file.
 * @param eclipseWorkspaceDir The Eclipse workspace directory.  Could be null.
 * @return A {@link ProcessBuilder} to launch Eclipse.
 */
private ProcessBuilder createEclipseProcessBuilder(File eclipseExecutableFile,
		File eclipseWorkspaceDir) {
	List<String> args = new ArrayList<>();
	args.add(eclipseExecutableFile.getAbsolutePath());

	if (eclipseWorkspaceDir != null) {
		args.add("-data");
		args.add(eclipseWorkspaceDir.getAbsolutePath());
	}

	args.add("--launcher.appendVmargs");
	args.add("-vmargs");
	args.add("-Dghidra.install.dir=" + Application.getInstallationDirectory());

	// Eclipse on OS X can have file locking issues if the user home directory is networked.
	// The following property is set in the launch script if we should disable file locking
	// via the appropriate Eclipse JVM arg.
	if (Boolean.getBoolean("eclipse.filelock.disable")) {
		Msg.info(this, "Disabling Eclipse file locking...");
		args.add("-Dosgi.locking=none");
	}

	return new ProcessBuilder(args);
}
 
Example 3
Source File: HelloWorldPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Plugin constructor - all plugins must have a constructor with this signature
 * @param tool the pluginTool that this plugin is added to.
 */
public HelloWorldPlugin(PluginTool tool) {
	super(tool);

	// Create the hello action.
	helloAction = new DockingAction("Hello World", getName()) {
		@Override
		public void actionPerformed(ActionContext context) {
			Msg.info(this, "Hello World!");
		}
	};
	// Enable the action - by default actions are disabled.
	helloAction.setEnabled(true);

	// Put the action in the global "View" menu.
	helloAction.setMenuBarData(new MenuData(new String[] { "View", "Hello World" }));

	// Add the action to the tool.
	tool.addAction(helloAction);
}
 
Example 4
Source File: ConcurrentTestExceptionStatement.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private long getTestTimeout() {
	String timeoutOverrideString =
		System.getProperty(TEST_TIMEOUT_MILLIS_PROPERTY, null);
	if (timeoutOverrideString == null) {
		return TIMEOUT_MILLIS;
	}

	try {
		long timeout = Long.parseLong(timeoutOverrideString);
		Msg.info(this, "Using test timeout override value " + timeout + "ms");
		return timeout;
	}
	catch (NumberFormatException e) {
		Msg.error(this,
			"Unable to parse " + TEST_TIMEOUT_MILLIS_PROPERTY + " Long value '" +
				timeoutOverrideString + "'");
	}
	return TIMEOUT_MILLIS;
}
 
Example 5
Source File: PefBinaryAnalysisCommand.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void processSectionData(SectionHeader section) throws Exception {
	//this section breaks down into fragments later
	if (section.getSectionKind() == SectionKind.Loader) {
		return;
	}

	int size = section.getContainerLength();
	if (size == 0) {
		return;
	}

	int alignment = section.getContainerOffset() % 4;
	if (alignment != 0) {
		Msg.info(this, "section alignment");
	}

	Address sectionAddr = toAddr(section.getContainerOffset() + alignment);
	createFragment("SectionData-" + section.getName(), sectionAddr, size);
}
 
Example 6
Source File: ToolConnectionPanel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void populateProducerList() {

		producerModel.removeAllElements();
		PluginTool[] tools = toolManager.getProducerTools();

		Arrays.sort(tools, (t1, t2) -> {
			return t1.getName().compareTo(t2.getName());
		});

		for (PluginTool tool : tools) {
			producerModel.addElement(tool);
		}
		if (tools.length == 0) {
			Msg.info(this, msgSource + ": No Tool generates events.");
		}
	}
 
Example 7
Source File: IPCTrace.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
public void printTrace()
{
    String out = "\n--------------------\n"+
                 "0x%X, Cmd 0x%X      \n"  +
                 "--------------------\n"  +
                 "Lr:             0x%X\n"  +
                 "Vt:             0x%X\n"  +
                 "Bytes In:       0x%X\n"  +
                 "Bytes Out:      0x%X\n"  +
                 "Buffer Count:   0x%X\n"  +
                 "In Interfaces:  0x%X\n"  +
                 "Out Interfaces: 0x%X\n"  +
                 "In Handles:     0x%X\n"  +
                 "Out Handles:    0x%X\n"  +
                 "--------------------\n";
    
    out = String.format(out, procFuncAddr, cmdId, lr, vtOffset, bytesIn, bytesOut, bufferCount, inInterfaces,
                        outInterfaces, inHandles, outHandles);
    Msg.info(this, out);
}
 
Example 8
Source File: GhidraPythonInterpreter.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a python file using this interpreter.
 *
 * @param file The python file to execute.
 * @param script A PythonScript from which we load state (or null).
 * @throws IllegalStateException if this interpreter has been cleaned up.
 */
public synchronized void execFile(ResourceFile file, PythonScript script)
		throws IllegalStateException {

	if (cleanedUp) {
		throw new IllegalStateException(
			"Ghidra python interpreter has already been cleaned up.");
	}

	injectScriptHierarchy(script);

	Py.getThreadState().tracefunc = interruptTraceFunction;

	// If the remote python debugger is alive, initialize it by calling settrace()
	if (!SystemUtilities.isInDevelopmentMode() && !SystemUtilities.isInHeadlessMode()) {
		if (PyDevUtils.getPyDevSrcDir() != null) {
			try {
				InetAddress localhost = InetAddress.getLocalHost();
				new Socket(localhost, PyDevUtils.PYDEV_REMOTE_DEBUGGER_PORT).close();
				Msg.info(this, "Python debugger found");
				exec("import pydevd; pydevd.settrace(host=\"" + localhost.getHostName() +
					"\", port=" + PyDevUtils.PYDEV_REMOTE_DEBUGGER_PORT + ", suspend=False);");
				Msg.info(this, "Connected to a python debugger.");
			}
			catch (IOException e) {
				Msg.info(this, "Not connected to a python debugger.");
			}
		}
	}

	// Run python file
	execfile(file.getAbsolutePath());
}
 
Example 9
Source File: RecoveryMgr.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * End the recovery snapshot and close the underlying file.
 * @param commit if true the snapshot is finalized and stored, otherwise
 * the snapshot is deleted.
 */
void endSnapshot(boolean commit) {
	if (activeFile == null) {
		throw new AssertException("Snapshot not in progress");
	}
	try {
		if (commit) {
			// Elliminate buffers if they were not put into the snapshot.
			//  This is the result of an undo which may have reverted a buffer to
			// its original unmodified state.
			int[] indexes = oldIndexSet.getValues();
			for (int i = 0; i < indexes.length; i++) {
				activeFile.removeBuffer(indexes[i]);
			}
			buffersRemoved[snapshotIndex] = indexes.length;
			File file = activeFile.getFile();
			activeFile.close();
			lastSnapshotTime = file.lastModified();
			Msg.info(this,
				(new Date()) + " Recovery snapshot created: " + snapshotFiles[snapshotIndex]);
		}
		else {
			activeFile.close();
		}
	}
	catch (IOException e) {
		commit = false;
	}

	activeFile = null;
	if (!commit) {
		snapshotFiles[snapshotIndex].delete();
		--snapshotIndex;
		if (snapshotIndex < 0) {
			snapshotIndex = 1;
		}
	}
}
 
Example 10
Source File: GhidraScriptProperties.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Load a .properties file.
 * 
 * @param file  the .properties file
 * @throws IOException if there is an exception loading the properties file
 */
protected void loadGhidraScriptProperties(ResourceFile file) throws IOException {

	Msg.info(this, "Reading script properties file: " + file.getAbsolutePath());
	if (!file.isFile()) {
		Msg.warn(this, ".properties file '" + file.toString() + "' is not a valid file.");
		return;
	}

	try (Scanner scanner = new Scanner(file.getInputStream(), "ASCII")) {

		while (scanner.hasNextLine()) {
			String line = scanner.nextLine().trim();

			// Ignore any comments or empty lines
			if (line.startsWith("#") || line.startsWith("!") || line.isEmpty()) {
				continue;
			}

			// break on '=' character
			int equalsIndex = line.indexOf('=');
			if (equalsIndex > 0) {
				String key = line.substring(0, equalsIndex).trim();
				String value = line.substring(equalsIndex + 1).trim();
				propertiesMap.put(key, value);
			}
		}
	}
	catch (FileNotFoundException fnfe) {
		throw new IOException("Could not find .properties file '" + file.toString() + "'");
	}
}
 
Example 11
Source File: VarnodeContext.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Propogate any results that are in the value cache.
 * 
 * @param clearContext  true if the cache should be cleared.
 *                      The propogation could be for flow purposes, and the
 *                      processing of the instruction is finished, so it's effects should be kept.
 */
public void propogateResults(boolean clearContext) {
	Iterator<Entry<Varnode, Varnode>> iter = tempVals.entrySet().iterator();

	while (iter.hasNext()) {
		Entry<Varnode, Varnode> element = iter.next();

		Varnode node = element.getKey();
		if (!isRegister(node)) {
			continue;
		}

		Register reg = trans.getRegister(node);
		if (reg == null) {
			continue;
		}
		Varnode val = element.getValue();

		// if we must clear the values that should be unknown because of a decision stmt
		if (clearVals.contains(node)) {
			val = null;
		}
		if (val != null) {
			propogateValue(reg, node, val, offsetContext.getAddress());
		}
		else {
			if (debug) {
				Msg.info(this, "      " + reg.getName() + "<-" + " Clear");
			}
			clearRegister(reg);
		}
	}
	if (clearContext) {
		if (!keepTempUniqueValues) {
			tempUniqueVals = new HashMap<Varnode, Varnode>();
		}
		tempVals = new HashMap<Varnode, Varnode>();
		clearVals = new HashSet<Varnode>();
	}
}
 
Example 12
Source File: SSLContextInitializer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize default SSLContext
 * @return true if successful, else false (see logged error)
 */
public static synchronized boolean initialize() {

	if (sslContext != null) {
		SSLContext.setDefault(sslContext);
		return true;
	}

	Msg.info(SSLContextInitializer.class, "Initializing SSL Context");

	KeyManager[] keyManagers = ApplicationKeyManagerFactory.getInstance().getKeyManagers();

	try {

		sslContext = SSLContext.getInstance(getSSLProtocol());
		SecureRandom random = SecureRandomFactory.getSecureRandom();
		sslContext.init(keyManagers, ApplicationTrustManagerFactory.getTrustManagers(), random);
		SSLContext.setDefault(sslContext);

		// Must install default HostnameVerifier - otherwise all traffic will fail
		HostnameVerifier originalVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
		if (!(originalVerifier instanceof HttpsHostnameVerifier)) {
			HttpsURLConnection.setDefaultHostnameVerifier(new HttpsHostnameVerifier());
		}

		return true;

	}
	catch (Exception e) {
		Msg.error(SSLContextInitializer.class,
			"SSL Context initialization failed: " + e.getMessage(), e);
	}
	return false;
}
 
Example 13
Source File: KitchenSinkPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void setupActions() {
    DockingAction action = new DockingAction("Hello World", getName() ) {
        @Override
        public void actionPerformed( ActionContext context ) {
            Msg.info(this, "Hello World:: action");
            announce("Hello World");
        }
    };
    action.setEnabled( true );
    String helloGroup = "Hello";
    ImageIcon prevImage = ResourceManager.loadImage(PREV_IMAGE);
    action.setMenuBarData( new MenuData( new String[] {"Misc", "Hello World"}, prevImage, helloGroup ) );
    action.setPopupMenuData( new MenuData( new String[] {"Hello World"}, prevImage, helloGroup ) );
    action.setKeyBindingData( new KeyBindingData( KeyStroke.getKeyStroke('H', Event.CTRL_MASK ) ) );
    action.setToolBarData( new ToolBarData( prevImage, helloGroup ) );
    action.setDescription("Hello World");
    action.setHelpLocation(new HelpLocation("SampleHelpTopic", "KS_Hello_World"));

    tool.addAction(action);

    action = new DockingAction("Hello Program", getName() ) {
        @Override
        public void actionPerformed( ActionContext context ) {
            Msg.info(this, "Hello Program:: action");
            sayHelloProgram();        
        }
    };
    action.setEnabled(false);
    ImageIcon nextImage = ResourceManager.loadImage(NEXT_IMAGE);
    action.setMenuBarData( new MenuData( new String[]{"Misc", "Hello Program"}, nextImage, helloGroup ) );
    action.setKeyBindingData( new KeyBindingData( KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK ) ) );
    action.setToolBarData( new ToolBarData( nextImage, helloGroup ) );
    action.setDescription("Hello Program");
    action.setHelpLocation(new HelpLocation("SampleHelpTopic", "KS_Hello_Program"));
    tool.addAction(action);

    // remember this action so I can enable/disable it later
    helloProgramAction = action;
}
 
Example 14
Source File: PasteFileTask.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Move a file into a folder.
 * <p>
 * Displays a error dialog if there was an exception
 * 
 * @param file {@link DomainFile file} being moved
 * @param folder destination {@link DomainFolder folder} 
 */
private void moveFile(DomainFile file, DomainFolder folder) {
	try {
		String name = file.getName();
		file.moveTo(folder);
		Msg.info(this, "Moved file " + name + " to " + folder.toString());
	}
	catch (Exception e) {
		ClientUtil.handleException(repository, e, "Move File", tool.getToolFrame());
	}
}
 
Example 15
Source File: CodeUnitIteratorTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * ** Diagnostic Aid ** Open program in tool
 * @throws Exception
 */
private void openProgramInTool() throws Exception {

	TestEnv env = new TestEnv();
	try {
		PluginTool tool = env.getTool();
		tool.addPlugin(CodeBrowserPlugin.class.getName());
		tool.addPlugin(NextPrevAddressPlugin.class.getName());
		tool.addPlugin(DisassemblerPlugin.class.getName());
		tool.addPlugin(ClearPlugin.class.getName());
		tool.addPlugin(GhidraScriptMgrPlugin.class.getName());
		tool.addPlugin(BookmarkPlugin.class.getName());
		tool.addPlugin(GoToAddressLabelPlugin.class.getName());

		ProgramManager pm = tool.getService(ProgramManager.class);
		pm.openProgram(program);

		showTool(tool);

		// Place breakpoint on next line when this method is used for diagnostic
		Msg.info(this, "Opened test program in tool");

		pm.closeAllPrograms(true);
	}
	finally {
		env.dispose();
	}
}
 
Example 16
Source File: SymbolLoader.java    From Ghidra-GameCube-Loader with Apache License 2.0 5 votes vote down vote up
private String TryRenameMemoryBlocks(MemoryMapSectionInfo sectionInfo, long sectionAddress) {
	if (sectionInfo.startingAddress >= this.objectAddress &&
		sectionInfo.startingAddress < this.addressSpace.getMaxAddress().getOffset()) {
			sectionAddress = sectionInfo.startingAddress;
	}

	var name = sectionInfo.name;
	var address = this.addressSpace.getAddress(sectionAddress);
	var memoryBlock = this.program.getMemory().getBlock(address);
	if (memoryBlock != null) {
		try {
			var blockName = memoryBlock.getName();
			var originalName = memoryBlock.getName();
			if (blockName.contains("_")) {
				blockName = blockName.substring(0, blockName.lastIndexOf("_"));
			}
			blockName += "_" + name;
			memoryBlock.setName(blockName);
			this.renameFragment(address, blockName);
			
			Msg.info(this, String.format("Symbol Loader: set memory block name of %s to %s!", originalName, memoryBlock.getName()));
			if (name.toLowerCase().contains("rodata")) {
				memoryBlock.setWrite(false);
				memoryBlock.setRead(true);
			}
			
			return memoryBlock.getName();
		} catch (DuplicateNameException | LockException e) {
			e.printStackTrace();
			return memoryBlock.getName();
		}
	}
	
	return name;
}
 
Example 17
Source File: ProgramMappingService.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively searches the current active {@link Project} for {@link DomainFile}s that
 * have metadata that matches a {@link FSRL} in the specified list.
 * <p>
 * Warning, this operation is expensive and should only be done in a Task thread.
 * <p>
 * @param fsrls List of {@link FSRL} to match against the metadata of each DomainFile in Project.
 * @param monitor {@link TaskMonitor} to watch for cancel and update with progress.
 * @return Map of FSRLs to {@link DomainFile}s of the found files, never null.
 */
public static Map<FSRL, DomainFile> searchProjectForMatchingFiles(List<FSRL> fsrls,
		TaskMonitor monitor) {
	int fc = AppInfo.getActiveProject().getProjectData().getFileCount();
	if (fc > 0) {
		monitor.setShowProgressValue(true);
		monitor.setMaximum(fc);
		monitor.setProgress(0);
	}
	else {
		monitor.setIndeterminate(true);
	}
	monitor.setMessage("Searching project for matching files");

	Map<String, FSRL> fsrlsToFindByMD5;
	try {
		fsrlsToFindByMD5 = buildFullyQualifiedFSRLMap(fsrls, monitor);
	}
	catch (CancelledException ce) {
		Msg.info(ProgramMappingService.class, "Canceling project search");
		return Collections.emptyMap();
	}

	Map<FSRL, DomainFile> results = new HashMap<>();

	for (DomainFile domainFile : ProjectDataUtils.descendantFiles(
		AppInfo.getActiveProject().getProjectData().getRootFolder())) {
		if (monitor.isCancelled() || fsrlsToFindByMD5.isEmpty()) {
			break;
		}

		monitor.incrementProgress(1);
		Map<String, String> metadata = domainFile.getMetadata();

		FSRL dfFSRL = getFSRLFromMetadata(metadata, domainFile);
		if (dfFSRL != null) {
			// side effect: create association between the FSRL in the DomainFile's props
			// to the DomainFile's path if there is room in the cache.
			// (ie. don't blow out the cache for files that haven't been requested yet)
			createAssociation(dfFSRL, domainFile, true);
		}
		String dfMD5 = (dfFSRL != null) ? dfFSRL.getMD5() : getMD5FromMetadata(metadata);
		if (dfMD5 != null) {
			FSRL matchedFSRL = fsrlsToFindByMD5.get(dfMD5);
			if (matchedFSRL != null) {
				results.put(matchedFSRL, domainFile);
				fsrlsToFindByMD5.remove(dfMD5);
			}
		}
	}

	return results;
}
 
Example 18
Source File: DelayImportDataDirectory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
		NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException,
		DataTypeConflictException, IOException {

   	monitor.setMessage(program.getName()+": delay import(s)...");
	Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
	if (!program.getMemory().contains(addr)) {
		return;
	}
	createDirectoryBookmark(program, addr);
	AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();
	for (DelayImportDescriptor descriptor : descriptors) {
		if (monitor.isCancelled()) {
			return;
		}
		//apply descriptor structure
		PeUtils.createData(program, addr, descriptor.toDataType(), log);
		createSymbol(program, addr,
			SymbolUtilities.getAddressAppendedName(DelayImportDescriptor.NAME, addr));

		Data data = program.getListing().getDataAt(addr);
		if (data == null || !data.isDefined()) continue;
		if (data.getNumComponents() < 7) {
			Msg.info(this, "Unexpected data at "+addr);
			continue;
		}

		//create string for descriptor dll name
		Address tmpAddr = addr(space, isBinary, descriptor, descriptor.getPointerToDLLName());
		createTerminatedString(program, tmpAddr, true, log);

		tmpAddr = addr(space, isBinary, descriptor, descriptor.getAddressOfModuleHandle());
		createSymbol(program, tmpAddr, SymbolUtilities.getAddressAppendedName(
			DelayImportDescriptor.NAME + "_Module_Handle", tmpAddr));

		tmpAddr = addr(space, isBinary, descriptor, descriptor.getAddressOfIAT());
		createSymbol(program, tmpAddr, SymbolUtilities.getAddressAppendedName(
			DelayImportDescriptor.NAME + "_IAT", tmpAddr));
		markupThunk(program, isBinary, space, descriptor, descriptor.getAddressOfIAT(),
			descriptor.getThunksIAT(), monitor, log);

		tmpAddr = addr(space, isBinary, descriptor, descriptor.getAddressOfINT());
		createSymbol(program, tmpAddr, SymbolUtilities.getAddressAppendedName(
			DelayImportDescriptor.NAME + "_INT", tmpAddr));
		markupThunk(program, isBinary, space, descriptor, descriptor.getAddressOfINT(),
			descriptor.getThunksINT(), monitor, log);

		// This table is optional
		if (descriptor.getAddressOfBoundIAT() != 0) {
			tmpAddr = addr(space, isBinary, descriptor, descriptor.getAddressOfBoundIAT());
			createSymbol(program, tmpAddr, SymbolUtilities.getAddressAppendedName(
				DelayImportDescriptor.NAME + "_Bound_IAT", tmpAddr));
			markupThunk(program, isBinary, space, descriptor, descriptor.getAddressOfBoundIAT(),
				descriptor.getThunksBoundIAT(), monitor, log);
		}

		// This table is optional
		if (descriptor.getAddressOfOriginalIAT() != 0) {
			tmpAddr = addr(space, isBinary, descriptor, descriptor.getAddressOfOriginalIAT());
			createSymbol(program, tmpAddr, SymbolUtilities.getAddressAppendedName(
				DelayImportDescriptor.NAME + "_Unload_IAT", tmpAddr));
			markupThunk(program, isBinary, space, descriptor,
				descriptor.getAddressOfOriginalIAT(), descriptor.getThunksUnloadIAT(), monitor,
				log);
		}


		markupImportByName(program, isBinary, space, descriptor, monitor, log);

		addr = addr.add(descriptor.sizeof());
	}
   }
 
Example 19
Source File: PCodeTestCombinedTestResults.java    From ghidra with Apache License 2.0 4 votes vote down vote up
void saveToXml() throws IOException {

		File dir = xmlFile.getParentFile();
		if (!dir.exists() && !dir.mkdir()) {
			throw new IOException("Failed to created directory: " + dir);
		}

		Element root = new Element("PCODE_TESTS");
		root.setAttribute("VERSION", XML_VERSION);

		for (String name : combinedResults.keySet()) {
			PCodeTestResults testResults = combinedResults.get(name);
			root.addContent(testResults.saveToXml());
		}

		// Store checkout data in temporary file
		File tmpFile = new File(xmlFile.getParentFile(), xmlFile.getName() + ".new");
		tmpFile.delete();
		FileOutputStream ostream = new FileOutputStream(tmpFile);
		BufferedOutputStream bos = new BufferedOutputStream(ostream);

		try {
			Document doc = new Document(root);
			XMLOutputter xmlout = new GenericXMLOutputter();
			xmlout.output(doc, bos);
		}
		finally {
			bos.close();
		}

		// Rename files
		File oldFile = null;
		if (xmlFile.exists()) {
			oldFile = new File(xmlFile.getParentFile(), xmlFile.getName() + ".bak");
			oldFile.delete();
			if (!xmlFile.renameTo(oldFile)) {
				throw new IOException("Failed to update: " + xmlFile.getAbsolutePath());
			}
		}
		if (!tmpFile.renameTo(xmlFile)) {
			if (oldFile != null) {
				oldFile.renameTo(xmlFile);
			}
			throw new IOException("Failed to update: " + xmlFile.getAbsolutePath());
		}

		Msg.info(this, "XML results file updated: " + xmlFile.getAbsolutePath());

		if (oldFile != null) {
			oldFile.delete();
		}
	}
 
Example 20
Source File: AbstractDockingTest.java    From ghidra with Apache License 2.0 2 votes vote down vote up
/**
 * Writes the given image to the given file
 *
 * @param image the image
 * @param imageFile the file
 * @throws IOException if there is any issue writing the image
 */
public static void writeImage(Image image, File imageFile) throws IOException {
	ImageUtils.writeFile(image, imageFile);
	Msg.info(AbstractDockingTest.class, "Wrote image to " + imageFile.getCanonicalPath());
}