Ghidra is a software reverse engineering (SRE) framework
GT-3035 - Restore Integration Tests - test fixes
dragonmacherdfcba5f39e1e
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/test/TestEnv.java b/Ghidra/Features/Base/src/main/java/ghidra/test/TestEnv.javaindex a78010c223..512e7229a7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/test/TestEnv.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/test/TestEnv.java@@ -381,16 +381,7 @@ public class TestEnv {String projectDirectoryName = AbstractGTest.getTestDirectoryPath();GhidraProject gp = GhidraProject.createProject(projectDirectoryName, projectName, true);- //- // Unusual Code Alert: The default tool is not always found in the testing environment,- // depending upon where the test lives. This code maps the test tool to that tool name- // so that tests will have the default tool as needed.- //- Project project = gp.getProject();- ToolChest toolChest = project.getLocalToolChest();- ToolTemplate template = getToolTemplate(AbstractGenericTest.DEFAULT_TEST_TOOL_NAME);- template.setName(AbstractGenericTest.DEFAULT_TOOL_NAME);- AbstractGenericTest.runSwing(() -> toolChest.replaceToolTemplate(template));+ installDefaultTool(gp);return gp;}@@ -410,6 +401,19 @@ public class TestEnv {}}+ private static void installDefaultTool(GhidraProject gp) {+ //+ // Unusual Code Alert: The default tool is not always found in the testing environment,+ // depending upon where the test lives. This code maps the test tool to that tool name+ // so that tests will have the default tool as needed.+ //+ Project project = gp.getProject();+ ToolChest toolChest = project.getLocalToolChest();+ ToolTemplate template = getToolTemplate(AbstractGenericTest.DEFAULT_TEST_TOOL_NAME);+ template.setName(AbstractGenericTest.DEFAULT_TOOL_NAME);+ AbstractGenericTest.runSwing(() -> toolChest.replaceToolTemplate(template));+ }+private void initializeSimpleTool() {if (tool != null) {@@ -1241,5 +1245,7 @@ public class TestEnv {DefaultProjectManager pm = gp.getProjectManager();pm.addDefaultTools(tc);++ installDefaultTool(gp);}}diff --git a/Ghidra/Test/IntegrationTest/certification.manifest b/Ghidra/Test/IntegrationTest/certification.manifestindex 50bf3491fd..c615302c68 100644--- a/Ghidra/Test/IntegrationTest/certification.manifest+++ b/Ghidra/Test/IntegrationTest/certification.manifest@@ -1,2 +1,3 @@##VERSION: 2.0build.gradle||GHIDRA||||END|+src/test.slow/java/ghidra/pcodeCPort/slgh_compile/pcode1.xml||GHIDRA||||END|diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/script/WindowsResourceReferenceScriptTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/script/WindowsResourceReferenceScriptTest.javanew file mode 100644index 0000000000..68109a5291--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/plugin/core/script/WindowsResourceReferenceScriptTest.java@@ -0,0 +1,172 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.plugin.core.script;++import static org.junit.Assert.assertNotNull;+import static org.junit.Assert.assertTrue;++import java.io.File;++import org.junit.*;+import org.junit.experimental.categories.Category;++import generic.jar.ResourceFile;+import generic.test.category.NightlyCategory;+import ghidra.app.services.ProgramManager;+import ghidra.framework.Application;+import ghidra.program.model.address.Address;+import ghidra.program.model.listing.*;+import ghidra.program.model.symbol.RefType;+import ghidra.program.model.symbol.Reference;+import ghidra.test.*;++@Category(NightlyCategory.class)+public class WindowsResourceReferenceScriptTest extends AbstractGhidraHeadedIntegrationTest {++ private TestEnv env;+ private File script;++ @Before+ public void setUp() throws Exception {+ env = new TestEnv();++ ResourceFile resourceFile =+ Application.getModuleFile("Decompiler", "ghidra_scripts/WindowsResourceReference.java");++ script = resourceFile.getFile(true);+ }++ private void openProgram(Program program) {+ ProgramManager pm = env.getTool().getService(ProgramManager.class);+ pm.openProgram(program.getDomainFile());+ }++ private void closeProgram() {+ ProgramManager pm = env.getTool().getService(ProgramManager.class);+ pm.closeProgram();+ waitForPostedSwingRunnables();+ }++ @After+ public void tearDown() throws Exception {+ env.dispose();+ }++ /*+ * Checks against known result set of addresses for use in regression testing.+ * Checks each address location of created reference and checks+ * that the correct format of address has been created to the resource+ */+ @Test+ public void testWinmineNormalCases() throws Exception {+ Reference[] refs; //Array of mnemonic references+ RefType type; //Type of reference+ Instruction inst;+ Boolean isAddr;++ Program program = env.getProgram("Winmine__XP.exe.gzf");+ openProgram(program);++ ScriptTaskListener scriptId = env.runScript(script);+ waitForScriptCompletion(scriptId, 65000);+ program.flushEvents();+ waitForPostedSwingRunnables();++ Listing listing = program.getListing();++ //Fill array with addresses of reference results+ Address[] winmineTestAddrs = propagateWinMineTestAddrs(program);++ for (Address winmineTestAddr : winmineTestAddrs) {+ inst = listing.getInstructionAt(winmineTestAddr);+ refs = inst.getMnemonicReferences();+ //Check a reference exists on the Mnemonic+ assertNotNull(refs);+ type = refs[0].getReferenceType();+ isAddr = refs[0].getToAddress().isMemoryAddress();+ //Check the reference is a real memory address+ assertTrue(isAddr);+ //Check the reference type created is of type DATA+ assertTrue(type.equals(RefType.DATA));+ }+ closeProgram();+ }++ @Test+ public void testMIPNormalCases() throws Exception {+ Reference[] refs; //Array of mnemonic references+ RefType type; //Type of reference+ Boolean isAddr;+ Instruction inst;++ Program program = env.getProgram("mip.exe.gzf");+ openProgram(program);++ ScriptTaskListener scriptID = env.runScript(script);+ waitForScriptCompletion(scriptID, 60000);+ program.flushEvents();+ waitForPostedSwingRunnables();++ Listing listing = program.getListing();++ Address[] mipTestAddrs = propagateMIPTestAddrs(program);+ for (Address mipTestAddr : mipTestAddrs) {+ inst = listing.getInstructionAt(mipTestAddr);+ refs = inst.getMnemonicReferences();+ //Check a reference exists on the mnemonic+ assertNotNull(refs);+ type = refs[0].getReferenceType();+ isAddr = refs[0].getToAddress().isMemoryAddress();+ //check the reference is a real memory address+ assertTrue(isAddr);+ //check the reference type created is of type DATA+ assertTrue(type.equals(RefType.DATA));+ }++ closeProgram();+ }++ private Address addr(long offset, Program program) {+ return program.getAddressFactory().getDefaultAddressSpace().getAddress(offset);+ }++ /*+ * Creates and returns the known result set to check against for use+ * in regression testing+ */+ protected Address[] propagateWinMineTestAddrs(Program pgm) {+ Address[] winmineTestAddrs = { addr(0x01001b99, pgm), addr(0x01001bc2, pgm),+ addr(0x01001b5e, pgm), addr(0x010022c2, pgm), addr(0x01002243, pgm),+ addr(0x01003d52, pgm), addr(0x010022ac, pgm), addr(0x01002334, pgm),+ addr(0x01001f3b, pgm), addr(0x0100398f, pgm), addr(0x01003ade, pgm),+ addr(0x01003aec, pgm), addr(0x01003ad0, pgm), addr(0x010039c5, pgm),+ addr(0x01003d45, pgm), addr(0x0100385b, pgm), addr(0x01003d36, pgm),+ addr(0x01003920, pgm), addr(0x0100390e, pgm) };++ return winmineTestAddrs;+ }++ protected Address[] propagateMIPTestAddrs(Program pgm) {+ Address[] mipTestAddrs =++ { addr(0x1400172c7L, pgm), addr(0x14005282dL, pgm), addr(0x14005276cL, pgm),+ addr(0x1400523baL, pgm), addr(0x14004ca38L, pgm), addr(0x14003d855L, pgm),+ addr(0x14001a964L, pgm), addr(0x14001846fL, pgm), addr(0x140025c87L, pgm) };++ return mipTestAddrs;+ }++}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/bin/format/dwarf4/next/DWARFRegisterMappingsTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/bin/format/dwarf4/next/DWARFRegisterMappingsTest.javanew file mode 100644index 0000000000..5cd7cbad6a--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/bin/format/dwarf4/next/DWARFRegisterMappingsTest.java@@ -0,0 +1,195 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.util.bin.format.dwarf4.next;++import static org.junit.Assert.assertNotNull;++import java.io.IOException;++import org.jdom.JDOMException;+import org.junit.Before;+import org.junit.Test;+import org.junit.experimental.categories.Category;++import generic.jar.ResourceFile;+import generic.test.category.NightlyCategory;+import ghidra.program.model.lang.*;+import ghidra.program.util.DefaultLanguageService;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;+import ghidra.util.xml.XmlUtilities;+import utilities.util.FileResolutionResult;+import utilities.util.FileUtilities;++@Category(NightlyCategory.class)+public class DWARFRegisterMappingsTest extends AbstractGhidraHeadlessIntegrationTest {++ private Language x86Lang;++ @Before+ public void setup() throws Exception {+ x86Lang = DefaultLanguageService.getLanguageService().getLanguage(+ new LanguageID("x86:LE:32:default"));+ }++ /**+ * Test reading the DWARF register mappings for every language that has a DWARF register+ * mapping file specified in its LDEF file.+ * @throws IOException+ */+ @Test+ public void testReadMappings() throws IOException {+ for (LanguageDescription langDesc : DefaultLanguageService.getLanguageService().getLanguageDescriptions(+ false)) {++ if (!DWARFRegisterMappingsManager.hasDWARFRegisterMapping(langDesc)) {+ continue;+ }++ Language lang =+ DefaultLanguageService.getLanguageService().getLanguage(langDesc.getLanguageID());++ ResourceFile mappingFile =+ DWARFRegisterMappingsManager.getDWARFRegisterMappingFileFor(lang);+ FileResolutionResult dwarfFileFRR;+ if ((dwarfFileFRR = FileUtilities.existsAndIsCaseDependent(mappingFile)) != null &&+ !dwarfFileFRR.isOk()) {+ throw new IOException(+ "DWARF register mapping filename case problem: " + dwarfFileFRR.getMessage());+ }++ DWARFRegisterMappings drm = DWARFRegisterMappingsManager.readMappingForLang(lang);+ assertNotNull("DWARF mapping read failed for " + langDesc.getLanguageID(), drm);+ }+ }++ @Test+ public void testOkMappings() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/></register_mappings><call_frame_cfa value=\"4\"/></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testMissingStackPointerMappings() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\"/></register_mappings><call_frame_cfa value=\"4\"/></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadStackPointerAttrMappings() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"NOT_A_BOOLEAN_STRING\"/></register_mappings><call_frame_cfa value=\"4\"/></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testMissingMappingsElemMappings() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(XmlUtilities.fromString("<dwarf></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadDuplicateMapping() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/><register_mapping dwarf=\"0\" ghidra=\"EBX\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test+ public void testGoodDuplicateMapping() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/><register_mapping dwarf=\"1\" ghidra=\"EAX\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadDWARFRegVal() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping missing_dwarf_attrib=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadDWARFRegVal2() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"not_a_number\" ghidra=\"EAX\" stackpointer=\"true\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testMissingGhidraReg() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" missing_ghidra_attr=\"EAX\" stackpointer=\"true\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadGhidraReg() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"BLAH\" stackpointer=\"true\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test+ public void testAutoInc() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/><register_mapping dwarf=\"1\" ghidra=\"ST0\" auto_count=\"8\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testTooLargeAutoIncCount() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/><register_mapping dwarf=\"1\" ghidra=\"ST0\" auto_count=\"16\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadFormatAutoIncCount() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/><register_mapping dwarf=\"1\" ghidra=\"ST0\" auto_count=\"foo\"/></register_mappings></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testBadCFAValue() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/></register_mappings><call_frame_cfa value=\"foo\"/></dwarf>"),+ x86Lang);+ }++ @Test(expected = IOException.class)+ public void testNegCFAValue() throws JDOMException, IOException {+ DWARFRegisterMappingsManager.readMappingFrom(+ XmlUtilities.fromString(+ "<dwarf><register_mappings><register_mapping dwarf=\"0\" ghidra=\"EAX\" stackpointer=\"true\"/></register_mappings><call_frame_cfa value=\"-1\"/></dwarf>"),+ x86Lang);+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/DemangledAddressTableTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/DemangledAddressTableTest.javanew file mode 100644index 0000000000..6889b77e14--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/DemangledAddressTableTest.java@@ -0,0 +1,248 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.util.demangler;++import static org.junit.Assert.*;++import org.junit.*;++import ghidra.program.database.ProgramDB;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Listing;+import ghidra.program.model.symbol.*;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;+import ghidra.test.ToyProgramBuilder;+import ghidra.util.task.TaskMonitor;++public class DemangledAddressTableTest extends AbstractGhidraHeadlessIntegrationTest {++ private ProgramDB program;+ private int txID;++ @Before+ public void setUp() throws Exception {+ ToyProgramBuilder builder = new ToyProgramBuilder("test", true);+ builder.createMemory(".text", "0x0100", 0x100);++ // Extent of Address Table determined by one of the following in order of precedence:+ // 1. Size of undefined array at start of table+ // 2. Next label beyond start which resides within current block+ // 3. End of block containing table++ // Address Pointers will only be created if extent of table contains only+ // Undefined types or pointers++ //@formatter:off+ builder.setBytes("0x0110", new byte[] {+ 0, 0, 1, 0x40,+ 0, 0, 1, 0x41,+ 0, 0, 1, 0x42,+ 0, 0, 1, 0x43,+ 0, 0, 1, 0x44,+ 0, 0, 1, 0x45,+ 0, 0, 1, 0x46,+ 0, 0, 0, 0, // should be skipped+ 0, 0, 1, 0x48,+ 0, 0, 2, 0x49, // should stop table (no memory)+ 0, 0, 1, 0x4a,+ 0, 0, 1, 0x4b+ });+ //@formatter:on++ program = builder.getProgram();+ txID = program.startTransaction("Test");+ }++ @After+ public void tearDown() throws Exception {+ program.endTransaction(txID, false);+ }++ /**+ * Test that the DemangledAddressTable will properly create a sequence of data+ * pointers. This test deals with the simple case where no existing data+ * is present. End of block considered end of address table.+ */+ @Test+ public void testApply_NoNextSymbol_NoData() throws Exception {++ // this is: vtable for UnqiueSpace+ String mangled = "_ZTV11UniqueSpace";+ Address addr = addr("0x0110");++ SymbolTable symbolTable = program.getSymbolTable();+ symbolTable.createLabel(addr, mangled, SourceType.IMPORTED);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledAddressTable);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ // expected: UniqueSpace::vtable+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("vtable", symbols[0].getName());+ assertEquals(mangled, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("UniqueSpace", ns.getName(false));++ assertPointersAt(0, 0, "0x110", "0x114", "0x118", "0x11c", "0x120", "0x124", "0x128",+ /* skip 0 */ "0x130");+ }++ /**+ * Test that the DemangledAddressTable will not create a sequence of data+ * pointers due to a data collision. This test deals with the case where primitive types have been+ * previously created. End of block considered end of address table.+ */+ @Test+ public void testApply_NoNextSymbol_DataCollision() throws Exception {++ // this is: vtable for UnqiueSpace+ String mangled = "_ZTV11UniqueSpace";+ Address addr = addr("0x0110");++ SymbolTable symbolTable = program.getSymbolTable();+ symbolTable.createLabel(addr, mangled, SourceType.IMPORTED);++ Listing listing = program.getListing();+ listing.createData(addr("0x114"), Undefined4DataType.dataType);+ listing.createData(addr("0x118"), Undefined4DataType.dataType);+ listing.createData(addr("0x120"), DWordDataType.dataType);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledAddressTable);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ // expected: UniqueSpace::vtable+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("vtable", symbols[0].getName());+ assertEquals(mangled, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("UniqueSpace", ns.getName(false));++ // should fail to create pointers since table region (to end of block) contains+ // data other than pointer or undefined+ assertPointersAt(3, 0);+ }++ /**+ * Test that the DemangledAddressTable will properly create a sequence of data+ * pointers. This test deals with the case where primitive types have been+ * previously created. Next label considered end of address table.+ */+ @Test+ public void testApply_WithNextSymbol_UndefinedData() throws Exception {++ // this is: vtable for UnqiueSpace+ String mangled = "_ZTV11UniqueSpace";+ Address addr = addr("0x0110");++ SymbolTable symbolTable = program.getSymbolTable();+ symbolTable.createLabel(addr, mangled, SourceType.IMPORTED);++ Listing listing = program.getListing();+ listing.createData(addr("0x114"), Undefined4DataType.dataType);+ listing.createData(addr("0x118"), Undefined4DataType.dataType);+ listing.createData(addr("0x120"), DWordDataType.dataType);++ symbolTable.createLabel(addr("0x120"), "NextLabel", SourceType.IMPORTED);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledAddressTable);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ // expected: UniqueSpace::vtable+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("vtable", symbols[0].getName());+ assertEquals(mangled, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("UniqueSpace", ns.getName(false));++ assertPointersAt(1, 0, "0x110", "0x114", "0x118", "0x11c");+ }++ /**+ * Test that the DemangledAddressTable will properly create a sequence of data+ * pointers. This test deals with the case where primitive types have been+ * previously created where the first is an undefined array which dictates the+ * extent of the address table. Next label beyond end of address table.+ */+ @Test+ public void testApply_WithUndefinedArray() throws Exception {++ // this is: vtable for UnqiueSpace+ String mangled = "_ZTV11UniqueSpace";+ Address addr = addr("0x0110");++ SymbolTable symbolTable = program.getSymbolTable();+ symbolTable.createLabel(addr, mangled, SourceType.IMPORTED);++ Listing listing = program.getListing();+ listing.createData(addr("0x110"), Undefined.getUndefinedDataType(12));+ listing.createData(addr("0x11c"), Undefined4DataType.dataType);+ listing.createData(addr("0x120"), DWordDataType.dataType);++ symbolTable.createLabel(addr("0x120"), "NextLabel", SourceType.IMPORTED);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledAddressTable);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ // expected: UniqueSpace::vtable+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("vtable", symbols[0].getName());+ assertEquals(mangled, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("UniqueSpace", ns.getName(false));++ assertPointersAt(2, 0, "0x110", "0x114", "0x118");+ }++ private void assertPointersAt(int totalNonPointerData, int totalInstructions, String... addrs) {+ Listing listing = program.getListing();+ int index = 0;+ for (Data d : listing.getDefinedData(true)) {+ if (d.isPointer()) {+ assertTrue("too many pointers found, expected only " + addrs.length,+ index < addrs.length);+ assertEquals("unexpected pointer at " + d.getAddress(), addr(addrs[index++]),+ d.getAddress());+ }+ }+ assertEquals("insufficient pointers created", addrs.length, index);+ assertEquals("missing expected non-pointer data", totalNonPointerData,+ listing.getNumDefinedData() - index);+ assertEquals("missing expected instructions", totalInstructions,+ listing.getNumInstructions());+ }++ private Address addr(String addr) {+ return program.getAddressFactory().getAddress(addr);+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/DemangledFunctionTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/DemangledFunctionTest.javanew file mode 100644index 0000000000..7ba4755622--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/DemangledFunctionTest.java@@ -0,0 +1,356 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.util.demangler;++import static org.junit.Assert.*;++import java.util.Arrays;++import org.junit.*;++import ghidra.program.database.ProgramBuilder;+import ghidra.program.database.ProgramDB;+import ghidra.program.model.address.Address;+import ghidra.program.model.address.AddressSet;+import ghidra.program.model.data.VoidDataType;+import ghidra.program.model.listing.*;+import ghidra.program.model.symbol.*;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;+import ghidra.test.ToyProgramBuilder;+import ghidra.util.task.TaskMonitor;++public class DemangledFunctionTest extends AbstractGhidraHeadlessIntegrationTest {++ private ProgramBuilder programBuilder;+ private ProgramDB program;+ private int txID;++ @Before+ public void setUp() throws Exception {+ programBuilder = new ToyProgramBuilder("test", true);+ programBuilder.createMemory(".text", "0x0100", 0x100);+ program = programBuilder.getProgram();+ txID = program.startTransaction("Test");+ }++ @After+ public void tearDown() throws Exception {+ program.endTransaction(txID, false);+ }++ /**+ * Test that the DemangledFunction will properly create a cascade of namespaces for+ * functions that live inside of a class that lives inside of a namespace.+ * This test applies a demangled name where the mangled name does NOT exist.+ */+ @Test+ public void testApply_FunctionInClassInNamespace() throws Exception {++ // this is: public long __thiscall ATL::CRegKey::Close(void)+ String mangled = "?CloseM@CRegKeyM@ATL@@QAEJXZ";+ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledFunction);++ Address addr = addr("0x0101");+ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ assertFunction("CloseM", addr);++ SymbolTable symbolTable = program.getSymbolTable();++ // expected: ATL::CRegKey::Close+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(1, symbols.length);+ assertEquals("CloseM", symbols[0].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("CRegKeyM", ns.getName(false));++ ns = ns.getParentNamespace();+ assertEquals("ATL", ns.getName(false));+ }++ /**+ * Test that the DemangledFunction will properly update a thunk function+ * with its namespace, and ripple through to the underlying default thunked+ * function. The thunk 'this' parameter should utilize the Class+ * within which the thunk resides.+ */+ @Test+ public void testApplyToThunk_FunctionInClassInNamespace() throws Exception {++ // this is: public long __thiscall ATL::CRegKey::Close(void)+ String mangled = "?Close@CRegKey@ATL@@QAEJXZ";+ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledFunction);++ FunctionManager functionMgr = program.getFunctionManager();+ Function f1 = functionMgr.createFunction(null, addr("0x0110"),+ new AddressSet(addr("0x0110")), SourceType.DEFAULT);+ Function f2 = functionMgr.createFunction(mangled, addr("0x0100"),+ new AddressSet(addr("0x0100")), SourceType.IMPORTED);+ f2.setThunkedFunction(f1);++ Address addr = addr("0x0100");+ demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY);++ assertFunction("Close", addr);+ assertNoBookmarkAt(addr);++ SymbolTable symbolTable = program.getSymbolTable();++ // expected: ATL::CRegKey::Close+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length); // both mangled and demangled+ assertTrue(symbols[0].isPrimary());+ assertEquals("Close", symbols[0].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("CRegKey", ns.getName(false));++ ns = ns.getParentNamespace();+ assertEquals("ATL", ns.getName(false));++ Parameter[] parameters = f2.getParameters();+ assertEquals("Missing parameter", 1, parameters.length);+ assertTrue(parameters[0].isAutoParameter());+ assertEquals("The 'this' param has incorrect type", "CRegKey *",+ parameters[0].getDataType().getDisplayName());++ }++ /**+ * Test that the DemangledFunction will properly create a cascade of namespaces for+ * functions that live inside of a class that lives inside of a namespace.+ * This test applies a demangled name where the mangled name exists.+ */+ @Test+ public void testApply_FunctionInClassInNamespace2() throws Exception {++ // this is: public long __thiscall ATL::CRegKey::Close(void)+ String mangled = "?Close@CRegKey@ATL@@QAEJXZ";+ Address addr = addr("0x0101");++ SymbolTable symbolTable = program.getSymbolTable();+ symbolTable.createLabel(addr, mangled, SourceType.IMPORTED);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledFunction);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ assertFunction("Close", addr);+ assertNoBookmarkAt(addr);++ // expected: ATL::CRegKey::Close+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("Close", symbols[0].getName());+ assertEquals(mangled, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("CRegKey", ns.getName(false));++ ns = ns.getParentNamespace();+ assertEquals("ATL", ns.getName(false));+ }++ /**+ * Test that the DemangledFunction will properly create a cascade of namespaces for+ * functions that live inside of a class that lives inside of a namespace.+ * This test applies a demangled name where the mangled name exists with address suffix.+ */+ @Test+ public void testApply_FunctionInClassInNamespace3() throws Exception {++ // this is: public long __thiscall ATL::CRegKey::Close(void)+ String mangled = "?Close@CRegKey@ATL@@QAEJXZ";+ Address addr = addr("0x0101");++ SymbolTable symbolTable = program.getSymbolTable();+ String mangledWithAddr = SymbolUtilities.getAddressAppendedName(mangled, addr);+ symbolTable.createLabel(addr, mangledWithAddr, SourceType.IMPORTED);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledFunction);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ assertFunction("Close", addr);+ assertNoBookmarkAt(addr);++ // expected: ATL::CRegKey::Close+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("Close", symbols[0].getName());+ assertEquals(mangledWithAddr, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("CRegKey", ns.getName(false));++ ns = ns.getParentNamespace();+ assertEquals("ATL", ns.getName(false));+ }++ /**+ * Test that the DemangledFunction will properly create a cascade of namespaces for+ * functions that live inside of a class that lives inside of a namespace.+ * This test applies a demangled name where both the mangled name exists and+ * the simple demangled name exists in the global space.+ */+ @Test+ public void testApply_FunctionInClassInNamespace4() throws Exception {++ // this is: public long __thiscall ATL::CRegKey::Close(void)+ String mangled = "?Close@CRegKey@ATL@@QAEJXZ";+ Address addr = addr("0x0101");++ SymbolTable symbolTable = program.getSymbolTable();+ symbolTable.createLabel(addr, "Close", SourceType.IMPORTED);+ symbolTable.createLabel(addr, mangled, SourceType.IMPORTED);++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledFunction);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ assertFunction("Close", addr);+ assertNoBookmarkAt(addr);++ // expected: ATL::CRegKey::Close+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("Close", symbols[0].getName());+ assertEquals(mangled, symbols[1].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("CRegKey", ns.getName(false));++ ns = ns.getParentNamespace();+ assertEquals("ATL", ns.getName(false));+ }++ /**+ * Test that the DemangledFunction will properly create a cascade of namespaces for+ * functions that live inside of a class that lives inside of a namespace.+ * This test applies a demangled name where the mangled name exists on an external+ * location symbol.+ */+ @Test+ public void testApply_ExtrnalFunctionInClassInNamespace() throws Exception {++ // this is: public long __thiscall ATL::CRegKey::Close(void)+ String mangled = "?Close@CRegKey@ATL@@QAEJXZ";++ ExternalManager externalManager = program.getExternalManager();+ Library lib = externalManager.addExternalLibraryName("MY.DLL", SourceType.IMPORTED);+ ExternalLocation extLoc =+ externalManager.addExtLocation(lib, mangled, null, SourceType.IMPORTED);++ Address addr = extLoc.getExternalSpaceAddress();++ DemangledObject demangled = DemanglerUtil.demangle(mangled);+ assertTrue(demangled instanceof DemangledFunction);++ assertTrue(demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY));++ assertFunction("Close", addr);+ assertNoBookmarkAt(addr);++ SymbolTable symbolTable = program.getSymbolTable();++ // expected: ATL::CRegKey::Close+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(1, symbols.length);+ assertEquals("Close", symbols[0].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("CRegKey", ns.getName(false));++ ns = ns.getParentNamespace();+ assertEquals("ATL", ns.getName(false));++ extLoc = externalManager.getExternalLocation(symbols[0]);+ assertNotNull(extLoc);++ assertEquals("Close", extLoc.getLabel());+ assertEquals(mangled, extLoc.getOriginalImportedName());++ }++ @Test+ public void testFunctionVariable() throws Exception {++ //+ // This makes sure that a variable inside of a function namespace prevents a class+ // namespace object from being created when a function does not exist. Instead it should+ // create a simple namespace.+ //++ String mangled = "_ZZ18__gthread_active_pvE20__gthread_active_ptr";+ String functionName = "__gthread_active_p";+ programBuilder.createEmptyFunction(functionName, "0x0101", 10, new VoidDataType());++ programBuilder.createLabel("0x0103", mangled);++ DemangledObject demangled = DemanglerUtil.demangle(program, mangled);+ assertNotNull(demangled);+ assertTrue(demangled instanceof DemangledVariable);++ assertEquals("__gthread_active_p()::__gthread_active_ptr", demangled.getSignature(false));++ Address addr = addr("0x0103");+ demangled.applyTo(program, addr, new DemanglerOptions(), TaskMonitor.DUMMY);++ assertSimpleNamespaceExists("__gthread_active_p()");+ assertNoBookmarkAt(addr);++ SymbolTable symbolTable = program.getSymbolTable();+ Symbol[] symbols = symbolTable.getSymbols(addr);+ assertEquals(2, symbols.length);+ assertEquals("_ZZ18__gthread_active_pvE20__gthread_active_ptr", symbols[1].getName());+ assertEquals("__gthread_active_ptr", symbols[0].getName());++ Namespace ns = symbols[0].getParentNamespace();+ assertEquals("__gthread_active_p()", ns.getName(false));+ }++ private void assertNoBookmarkAt(Address addr) {+ BookmarkManager bm = program.getBookmarkManager();+ Bookmark[] bookmarks = bm.getBookmarks(addr);+ if (bookmarks.length > 0) {+ fail("Expected no bookmark; found " + Arrays.toString(bookmarks));+ }+ }++ private void assertSimpleNamespaceExists(String name) {+ SymbolTable symbolTable = program.getSymbolTable();+ Namespace ns = symbolTable.getNamespace(name, program.getGlobalNamespace());+ assertNotNull(ns);+ assertEquals(SymbolType.NAMESPACE, ns.getSymbol().getSymbolType());+ }++ private void assertFunction(String name, Address addr) {+ FunctionManager fm = program.getFunctionManager();+ Function function = fm.getFunctionAt(addr);+ assertNotNull("Expected function to get created at " + addr, function);+ assertEquals(name, function.getName());+ }++ private Address addr(String addr) {+ return program.getAddressFactory().getAddress(addr);+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/gnu/GnuDemanglerIntegrationTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/gnu/GnuDemanglerIntegrationTest.javanew file mode 100644index 0000000000..c439821a3b--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/app/util/demangler/gnu/GnuDemanglerIntegrationTest.java@@ -0,0 +1,81 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.app.util.demangler.gnu;++import static org.junit.Assert.*;++import org.junit.Before;+import org.junit.Test;++import ghidra.app.cmd.label.DemanglerCmd;+import ghidra.app.util.demangler.*;+import ghidra.program.database.ProgramDB;+import ghidra.program.model.address.Address;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;+import ghidra.test.ToyProgramBuilder;++public class GnuDemanglerIntegrationTest extends AbstractGhidraHeadlessIntegrationTest {++ private ProgramDB program;++ @Before+ public void setUp() throws Exception {+ ToyProgramBuilder builder = new ToyProgramBuilder("test", true);+ builder.createMemory(".text", "0x01001000", 0x100);+ program = builder.getProgram();+ }++ @Test+ public void testExceptionOnFailToDemangle() throws Exception {++ String mangled = "?InvokeHelper@CWnd@@QAAXJGGPAXPBEZZ_00912eaf";++ DemanglerCmd cmd = new DemanglerCmd(addr("01001000"), mangled);++ // this used to trigger an exception+ cmd.applyTo(program);+ }++ @Test+ public void testDemangler_Format_EDG_DemangleOnlyKnownPatterns_False_DollarInNamespace()+ throws DemangledException {++ String mangled = "MyFunction__11MyNamespacePQ215$ParamNamespace9paramName";++ GnuDemangler demangler = new GnuDemangler();+ demangler.canDemangle(program);// this perform initialization++ DemangledObject result = demangler.demangle(mangled, false);+ assertNotNull(result);+ assertEquals("undefined MyNamespace::MyFunction($ParamNamespace::paramName *)",+ result.getSignature(false));++ DemanglerOptions options = new DemanglerOptions();+ options.setDemangleOnlyKnownPatterns(false);+ DemanglerCmd cmd = new DemanglerCmd(addr("01001000"), mangled, options);++ // this used to trigger an exception+ boolean success = applyCmd(program, cmd);+ assertTrue("Demangler command failed: " + cmd.getStatusMsg(), success);++ assertNotNull(cmd.getDemangledObject());+ }++ private Address addr(String address) {+ return program.getAddressFactory().getAddress(address);+ }++}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/AnalysisManagerTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/AnalysisManagerTest.javanew file mode 100644index 0000000000..e484698a05--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/AnalysisManagerTest.java@@ -0,0 +1,261 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.analysis;++import static org.junit.Assert.assertNotNull;++import java.io.*;+import java.util.ArrayList;++import org.junit.*;++import generic.jar.ResourceFile;+import ghidra.app.script.GhidraScriptUtil;+import ghidra.app.services.*;+import ghidra.framework.task.GScheduledTask;+import ghidra.framework.task.GTaskListener;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.database.ProgramDB;+import ghidra.program.model.symbol.Symbol;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;+import mockit.*;++public class AnalysisManagerTest extends AbstractGhidraHeadlessIntegrationTest {+ @Mocked+ GTaskListener listener;++ private ProgramBuilder programBuilder;+ private ProgramDB program;+ private AnalysisManager analysisManager;+ private ArrayList<Analyzer> analyzers;++ class TaskTypeDelegate implements Delegate<GScheduledTask> {+ private String name;++ TaskTypeDelegate(String name) {+ this.name = name;+ }++ void validate(GScheduledTask scheduledTask) {+ Assert.assertEquals(name, scheduledTask.getTask().getClass().getSimpleName());+ }+ }++ class TaskNameDelegate implements Delegate<GScheduledTask> {+ private String name;++ TaskNameDelegate(String name) {+ this.name = name;+ }++ void validate(GScheduledTask scheduledTask) {+ Assert.assertEquals(name, scheduledTask.getTask().getName());+ }+ }++ @Before+ public void setUp() throws Exception {+ programBuilder = new ProgramBuilder();+ programBuilder.createMemory("AAA", "0x100", 0x1000);+ program = programBuilder.getProgram();+ analyzers = new ArrayList<>();+ }++ @Test+ public void testTwoAnalyzersWithOnePhases() {++ analyzers.add(new Analyzer1());+ analyzers.add(new Analyzer2());+ AnalysisRecipe recipe = new AnalysisRecipe("Test Recipe", analyzers, program);+ analysisManager = new AnalysisManager(program, recipe);+ analysisManager.addTaskListener(listener);++ analysisManager.runAnalysis(null);+ analysisManager.waitForAnalysis(1000);++ new VerificationsInOrder() {+ {+ listener.initialize();+ listener.taskStarted(with(new TaskTypeDelegate("StartPhaseTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("StartPhaseTask")), null);+ listener.taskStarted(with(new TaskTypeDelegate("KickStartAnalyzersTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("KickStartAnalyzersTask")), null);+ listener.taskStarted(with(new TaskNameDelegate("Analyzer1")));+ listener.taskCompleted(with(new TaskNameDelegate("Analyzer1")), null);+ listener.taskStarted(with(new TaskNameDelegate("Analyzer2")));+ listener.taskCompleted(with(new TaskNameDelegate("Analyzer2")), null);+ }+ };++ }++ @Test+ public void testTwoAnalyzersWithTwoPhases() {+ analyzers.add(new Analyzer1());+ analyzers.add(new Analyzer2());+ AnalysisRecipe recipe = new AnalysisRecipe("Test Recipe", analyzers, program);+ AnalysisPhase firstPhase = recipe.createPhase();+ recipe.setAnalyzerStartPhase(analyzers.get(0), firstPhase);++ analysisManager = new AnalysisManager(program, recipe);+ analysisManager.addTaskListener(listener);++ analysisManager.runAnalysis(null);+ analysisManager.waitForAnalysis(1000);++ new VerificationsInOrder() {+ {+ listener.initialize();+ listener.taskStarted(with(new TaskTypeDelegate("StartPhaseTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("StartPhaseTask")), null);+ listener.taskStarted(with(new TaskTypeDelegate("KickStartAnalyzersTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("KickStartAnalyzersTask")), null);+ listener.taskStarted(with(new TaskNameDelegate("Analyzer1")));+ listener.taskCompleted(with(new TaskNameDelegate("Analyzer1")), null);+ listener.taskStarted(with(new TaskTypeDelegate("StartPhaseTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("StartPhaseTask")), null);+ listener.taskStarted(with(new TaskNameDelegate("Analyzer2")));+ listener.taskCompleted(with(new TaskNameDelegate("Analyzer2")), null);+ }+ };+ }++ @Test+ public void testTwoAnalyzersWithTwoPhasesAnalyzerInSecondPhaseOff() {+ analyzers.add(new Analyzer1());+ analyzers.add(new Analyzer2());+ AnalysisRecipe recipe = new AnalysisRecipe("Test Recipe", analyzers, program);+ AnalysisPhase firstPhase = recipe.createPhase();+ recipe.setAnalyzerStartPhase(analyzers.get(0), firstPhase);+ recipe.setAnalyzerEnablement(analyzers.get(1), false);++ analysisManager = new AnalysisManager(program, recipe);+ analysisManager.addTaskListener(listener);++ analysisManager.runAnalysis(null);+ analysisManager.waitForAnalysis(1000);++ new VerificationsInOrder() {+ {+ listener.initialize();+ listener.taskStarted(with(new TaskTypeDelegate("StartPhaseTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("StartPhaseTask")), null);+ listener.taskStarted(with(new TaskTypeDelegate("KickStartAnalyzersTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("KickStartAnalyzersTask")), null);+ listener.taskStarted(with(new TaskNameDelegate("Analyzer1")));+ listener.taskCompleted(with(new TaskNameDelegate("Analyzer1")), null);+ listener.taskStarted(with(new TaskTypeDelegate("StartPhaseTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("StartPhaseTask")), null);+ listener.taskStarted((GScheduledTask) any);+ times = 0; // make sure no more taskStarted calls are mode+ }+ };++ }++ @Test+ public void testSciptAnalyzer() throws Exception {+ final ResourceFile scriptFile = createScriptFile();+ analyzers.add(new Analyzer1());+ GhidraScriptAnalyzerAdapter analyzer =+ new GhidraScriptAnalyzerAdapter(scriptFile, AnalyzerType.BYTE_ANALYZER, 10000);+ analyzers.add(analyzer);+ AnalysisRecipe recipe = new AnalysisRecipe("Test Recipe", analyzers, program);+ analysisManager = new AnalysisManager(program, recipe);+ analysisManager.addTaskListener(listener);++ analysisManager.runAnalysis(null);+ analysisManager.waitForAnalysis(10000);++ // verify that the script ran+ Symbol symbol = getUniqueSymbol(program, "TEST_SYMBOL");+ assertNotNull(symbol);++ new VerificationsInOrder() {+ {+ listener.initialize();+ listener.taskStarted(with(new TaskTypeDelegate("StartPhaseTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("StartPhaseTask")), null);+ listener.taskStarted(with(new TaskTypeDelegate("KickStartAnalyzersTask")));+ listener.taskCompleted(with(new TaskTypeDelegate("KickStartAnalyzersTask")), null);+ listener.taskStarted(with(new TaskNameDelegate("Analyzer1")));+ listener.taskCompleted(with(new TaskNameDelegate("Analyzer1")), null);+ listener.taskStarted(with(new TaskNameDelegate("Script: " + scriptFile.getName())));+ listener.taskCompleted(+ with(new TaskNameDelegate("Script: " + scriptFile.getName())), null);+ listener.taskStarted((GScheduledTask) any);+ times = 0; // make sure no more taskStarted calls are mode+ }+ };++ }++ private ResourceFile createScriptFile() throws Exception {+ ResourceFile newScriptFile = createTempScriptFile("TestAnalyzerScript");+ String filename = newScriptFile.getName();+ String className = filename.replaceAll("\\.java", "");++ //@formatter:off+ String newScript =+ "import ghidra.app.script.GhidraScript;\n\n"++ "import ghidra.program.model.address.Address;\n"++ "import ghidra.program.model.symbol.SourceType;\n"++ "public class "+className+" extends GhidraScript {\n\n"++ " @Override\n"++ " protected void run() throws Exception {\n"++ " Address minAddress = currentProgram.getMinAddress();\n"++ " currentProgram.getSymbolTable().createLabel(minAddress, \"TEST_SYMBOL\",\n"++ " SourceType.USER_DEFINED);\n"++ " }\n\n"++ "}\n";+ //@formatter:on++ writeStringToFile(newScriptFile, newScript);++ return newScriptFile;+ }++ private void writeStringToFile(ResourceFile file, String string) throws IOException {+ BufferedWriter writer = new BufferedWriter(new FileWriter(file.getFile(false)));+ writer.write(string);+ writer.close();+ }++ private ResourceFile createTempScriptFile(String name) throws IOException {+ File userScriptsDir = new File(GhidraScriptUtil.USER_SCRIPTS_DIR);+ if (name.length() > 50) {+ // too long and the script manager complains+ name = name.substring(name.length() - 50);+ }+ File tempFile = File.createTempFile(name, ".java", userScriptsDir);+ tempFile.deleteOnExit();+ return new ResourceFile(tempFile);+ }++ public static class Analyzer1 extends AnalyzerTestStub {++ Analyzer1() {+ super("Analyzer1", AnalyzerType.BYTE_ANALYZER, true, new AnalysisPriority("1", 1));+ }+ }++ public static class Analyzer2 extends AnalyzerTestStub {++ Analyzer2() {+ super("Analyzer2", AnalyzerType.BYTE_ANALYZER, true, new AnalysisPriority("2", 2));+ }+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/AnalysisRecipeTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/AnalysisRecipeTest.javanew file mode 100644index 0000000000..905704b6f0--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/AnalysisRecipeTest.java@@ -0,0 +1,152 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.analysis;++import static org.junit.Assert.*;++import java.util.ArrayList;+import java.util.List;++import org.jdom.Element;+import org.junit.Before;+import org.junit.Test;++import ghidra.app.script.GhidraScriptUtil;+import ghidra.app.script.ScriptInfo;+import ghidra.app.services.*;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.database.ProgramDB;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.Namespace;+import ghidra.program.model.symbol.Symbol;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;++public class AnalysisRecipeTest extends AbstractGhidraHeadlessIntegrationTest {++ private AnalysisRecipe recipe;+ private ProgramBuilder programBuilder;+ private ProgramDB program;+ private ArrayList<Analyzer> analyzers;++ @Before+ public void setUp() throws Exception {+ programBuilder = new ProgramBuilder();+ programBuilder.createMemory("AAA", "0x100", 0x1000);+ program = programBuilder.getProgram();+ analyzers = new ArrayList<>();+ }++ @Test+ public void testXML() {+ Analyzer1 analyzer1 = new Analyzer1();+ Analyzer2 analyzer2 = new Analyzer2();+ analyzers.add(analyzer1);+ analyzers.add(analyzer2);+ recipe = new AnalysisRecipe("Test Recipe", analyzers, program);+ AnalysisPhase lastPhase = recipe.getLastPhase();+ AnalysisPhase firstPhase = recipe.createPhase();++ recipe.setAnalyzerStartPhase(analyzer1, firstPhase);++ assertEquals(firstPhase, recipe.getAnalyzerStartPhase(analyzer1));+ assertEquals(lastPhase, recipe.getAnalyzerStartPhase(analyzer2));++ Element xml = recipe.toXML();+ AnalysisRecipe savedRecipe = new AnalysisRecipe("FOO", analyzers, program);+ savedRecipe.loadFromXML(xml);+ List<AnalysisPhase> analysisPhases = savedRecipe.getAnalysisPhases();+ assertEquals(2, analysisPhases.size());+ AnalysisPhase phase1 = analysisPhases.get(0);+ AnalysisPhase phase2 = analysisPhases.get(1);++ assertEquals("Test Recipe", savedRecipe.getName());+ assertEquals("1", phase1.getName());+ assertEquals("2", phase2.getName());++ assertEquals(firstPhase, recipe.getAnalyzerStartPhase(analyzer1));+ assertEquals(lastPhase, recipe.getAnalyzerStartPhase(analyzer2));++ }++ @Test+ public void testXMLWithScriptAnalzyers() {+ Analyzer1 analyzer1 = new Analyzer1();+ Analyzer2 analyzer2 = new Analyzer2();+ analyzers.add(analyzer1);+ analyzers.add(analyzer2);+ recipe = new AnalysisRecipe("Test Recipe", analyzers, program);+ ScriptInfo info = GhidraScriptUtil.findScriptByName("HelloWorldScript.java");+ assertNotNull(info);+ recipe.addScriptAnalyzer(info.getSourceFile(), AnalyzerType.INSTRUCTION_ANALYZER, 15);+ AnalysisPhase lastPhase = recipe.getLastPhase();+ AnalysisPhase firstPhase = recipe.createPhase();++ recipe.setAnalyzerStartPhase(analyzer1, firstPhase);++ assertEquals(firstPhase, recipe.getAnalyzerStartPhase(analyzer1));+ assertEquals(lastPhase, recipe.getAnalyzerStartPhase(analyzer2));++ Element xml = recipe.toXML();+ AnalysisRecipe savedRecipe = new AnalysisRecipe("FOO", analyzers, program);+ savedRecipe.loadFromXML(xml);+ List<AnalysisPhase> analysisPhases = savedRecipe.getAnalysisPhases();+ assertEquals(2, analysisPhases.size());+ AnalysisPhase phase1 = analysisPhases.get(0);+ AnalysisPhase phase2 = analysisPhases.get(1);++ assertEquals("Test Recipe", savedRecipe.getName());+ List<Analyzer> analyzerList = savedRecipe.getAnalyzers();+ assertEquals(3, analyzerList.size());+ Analyzer scriptAnalyzer = analyzerList.get(0);+ assertEquals(GhidraScriptAnalyzerAdapter.class, scriptAnalyzer.getClass());+ assertEquals("Script: HelloWorldScript.java", scriptAnalyzer.getName());+ assertEquals(AnalyzerType.INSTRUCTION_ANALYZER, scriptAnalyzer.getAnalysisType());+ assertEquals(15, scriptAnalyzer.getPriority().priority());+ }++ public static class Analyzer1 extends AnalyzerTestStub {++ Analyzer1() {+ super("Analyzer1", AnalyzerType.BYTE_ANALYZER, true, new AnalysisPriority("1", 100));+ }+ }++ public static class Analyzer2 extends AnalyzerTestStub {++ Analyzer2() {+ super("Analyzer2", AnalyzerType.BYTE_ANALYZER, true, new AnalysisPriority("2", 200));+ }+ }++ public Namespace get(Program program, Namespace otherNamespace) {+ Program source = otherNamespace.getSymbol().getProgram();+ if (source == program) {+ return otherNamespace;+ }+ getCorrespondingNamespace(source, otherNamespace, program);+ return null;+ }++ private Namespace getCorrespondingNamespace(Program source, Namespace ns, Program p) {+ Namespace parent = ns.getParentNamespace();+ if (parent == source.getGlobalNamespace()) {+ return p.getGlobalNamespace();+ }+ Namespace other = getCorrespondingNamespace(source, parent, p);+ Symbol symbol = getUniqueSymbol(p, ns.getName(), other);+ return (Namespace) symbol.getObject();+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/RecipeDialogTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/RecipeDialogTest.javanew file mode 100644index 0000000000..4b792a0a8a--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/analysis/RecipeDialogTest.java@@ -0,0 +1,65 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.analysis;++import static org.junit.Assert.*;++import org.junit.Before;+import org.junit.Test;++import docking.DockingWindowManager;+import ghidra.SwingExceptionHandler;+import ghidra.program.database.ProgramBuilder;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;++public class RecipeDialogTest extends AbstractGhidraHeadedIntegrationTest {++ private ProgramBuilder builder;+ private AnalysisRecipe recipe;++ public RecipeDialogTest() {+ super();+ }++ @Before+ public void setUp() throws Exception {+ builder = new ProgramBuilder();+ recipe = AnalysisRecipeBuilder.getRecipe(builder.getProgram());+ recipe.createPhase();+ recipe.createPhase();+ recipe.createPhase();+ }++ @Test+ public void testNothing() {+ //+ }++ public void dontTestDialog() {+ RecipeEditorDialog dialog = new RecipeEditorDialog(recipe);+ DockingWindowManager.showDialog(null, dialog);+ assertNotNull(dialog);+ }++ public static void main(String[] args) throws Exception {+ SwingExceptionHandler.registerHandler();++ RecipeDialogTest test = new RecipeDialogTest();+ test.setUp();+ test.dontTestDialog();+ System.exit(0);+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ByteViewerToolConnectionTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ByteViewerToolConnectionTest.javanew file mode 100644index 0000000000..ab707f0049--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ByteViewerToolConnectionTest.java@@ -0,0 +1,286 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main;++import static org.junit.Assert.*;++import java.awt.Rectangle;+import java.util.Set;+import java.util.concurrent.atomic.AtomicReference;++import javax.swing.*;++import org.junit.*;++import docking.ActionContext;+import docking.action.DockingActionIf;+import docking.test.AbstractDockingTest;+import ghidra.app.plugin.core.byteviewer.ByteViewerPlugin;+import ghidra.app.services.ProgramManager;+import ghidra.framework.model.Tool;+import ghidra.framework.plugintool.Plugin;+import ghidra.framework.plugintool.PluginTool;+import ghidra.framework.plugintool.util.PluginException;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.model.listing.Program;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.TestEnv;++// The ByteViewer is in its own plugin; the CodeBrowser is in Base, this we need+// the ModuleClassLoaderDependent interface+public class ByteViewerToolConnectionTest extends AbstractGhidraHeadedIntegrationTest {++ private FrontEndTool frontEndTool;+ private TestEnv env;+ private ToolConnectionDialog dialog;++ @Before+ public void setUp() throws Exception {+ env = new TestEnv();+ env.resetDefaultTools();+ frontEndTool = env.getFrontEndTool();+ env.showFrontEndTool();+ setErrorGUIEnabled(false);+ }++ @After+ public void tearDown() throws Exception {+ if (dialog != null) {+ pressButtonByText(dialog, "OK");+ }++ closeAllWindowsAndFrames();+ env.dispose();+ }++ @Test+ public void testConnectToolsDialog() throws Exception {+ PluginTool cbTool = runTool("CodeBrowser");+ PluginTool cbTool2 = runTool("CodeBrowser");++ DockingActionIf connectAction = getAction("Connect Tools");+ performAction(connectAction, true);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);+ JList<?> producerList = (JList<?>) findComponentByName(dialog, "Producers");+ JList<?> consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ JList<?> eventList = (JList<?>) findComponentByName(dialog, "Events");++ assertNotNull(producerList);+ assertNotNull(consumerList);+ assertNotNull(eventList);++ producerList.setSelectedIndex(0);+ consumerList.setSelectedIndex(1);+ clickRow(eventList, 1);++ Program p = buildProgram();++ ProgramManager pm = cbTool.getService(ProgramManager.class);+ SwingUtilities.invokeAndWait(() -> pm.openProgram(p.getDomainFile()));++ ProgramManager pm2 = cbTool2.getService(ProgramManager.class);+ assertEquals(p, pm2.getCurrentProgram());++ env.release(p);+ }++ private void clickRow(JList<?> list, int row) {++ AtomicReference<Rectangle> ref = new AtomicReference<>();+ runSwing(() -> {+ Rectangle rect = list.getCellBounds(row, row);+ ref.set(rect);+ });+ clickMouse(list, 1, ref.get().x + 5, ref.get().y + 5, 1, 0);+ }++ private Program buildProgram() throws Exception {+ ProgramBuilder builder = new ProgramBuilder("sample", ProgramBuilder._TOY);+ builder.createMemory("test2", "0x1001000", 0x2000);+ Program p = builder.getProgram();+ p.clearUndo();+ return p;+ }++ @Test+ public void testPluginsRemoved() throws Exception {+ PluginTool cbTool = runTool("CodeBrowser");+ PluginTool cbTool2 = runTool("CodeBrowser");+ DockingActionIf connectAction = getAction("Connect Tools");+ performAction(connectAction);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);+ JList<?> producerList = (JList<?>) findComponentByName(dialog, "Producers");+ JList<?> consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ JList<?> eventList = (JList<?>) findComponentByName(dialog, "Events");++ selectListItem(producerList, 0);+ selectListItem(consumerList, 1);++ JCheckBox cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(cb.getText().equals("ByteBlockChange"));+ close(dialog);++ Plugin p1 = getPlugin(cbTool, ByteViewerPlugin.class);+ removePlugin(cbTool, p1);++ Plugin p2 = getPlugin(cbTool2, ByteViewerPlugin.class);+ removePlugin(cbTool2, p2);++ performAction(connectAction);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);++ producerList = (JList<?>) findComponentByName(dialog, "Producers");+ consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ eventList = (JList<?>) findComponentByName(dialog, "Events");++ selectListItem(producerList, 0);+ selectListItem(consumerList, 1);++ cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(!cb.getText().equals("ByteBlockChange"));+ }++ @Test+ public void testPluginsAdded() throws Exception {+ PluginTool cbTool = runTool("CodeBrowser");+ PluginTool cbTool2 = runTool("CodeBrowser");+ DockingActionIf connectAction = getAction("Connect Tools");+ performAction(connectAction, true);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);+ JList<?> producerList = (JList<?>) findComponentByName(dialog, "Producers");+ JList<?> consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ JList<?> eventList = (JList<?>) findComponentByName(dialog, "Events");++ selectListItem(producerList, 0);+ selectListItem(consumerList, 1);++ JCheckBox cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(cb.getText().equals("ByteBlockChange"));+ close(dialog);++ Plugin p1 = getPlugin(cbTool, ByteViewerPlugin.class);+ removePlugin(cbTool, p1);++ Plugin p2 = getPlugin(cbTool2, ByteViewerPlugin.class);+ removePlugin(cbTool2, p2);++ performAction(connectAction, true);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);++ producerList = (JList<?>) findComponentByName(dialog, "Producers");+ consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ eventList = (JList<?>) findComponentByName(dialog, "Events");++ selectListItem(producerList, 0);+ selectListItem(consumerList, 1);++ cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(!cb.getText().equals("ByteBlockChange"));+ close(dialog);++ // add ByteViewer back in+ addPlugin(cbTool, ByteViewerPlugin.class.getName());+ addPlugin(cbTool2, ByteViewerPlugin.class.getName());+ performAction(connectAction, true);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);++ producerList = (JList<?>) findComponentByName(dialog, "Producers");+ consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ eventList = (JList<?>) findComponentByName(dialog, "Events");++ selectListItem(producerList, 0);+ selectListItem(consumerList, 1);++ cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(cb.getText().equals("ByteBlockChange"));+ close(dialog);+ if (!dialog.isVisible()) {+ dialog = null;+ }+ }++//==================================================================================================+// Private Methods+//==================================================================================================++ private void selectListItem(final JList<?> list, final int index) throws Exception {+ SwingUtilities.invokeAndWait(() -> list.setSelectedIndex(index));++ }++ private void addPlugin(final PluginTool tool, final String className) throws Exception {+ SwingUtilities.invokeAndWait(() -> {+ try {+ tool.addPlugin(className);+ }+ catch (PluginException e) {+ e.printStackTrace();+ }+ tool.getProject().getToolManager().toolChanged(tool);+ });+ }++ private void removePlugin(final PluginTool tool, final Plugin plugin) throws Exception {+ SwingUtilities.invokeAndWait(() -> {+ tool.removePlugins(new Plugin[] { plugin });+ tool.getProject().getToolManager().toolChanged(tool);+ });+ }++ private DockingActionIf getAction(String actionName) {+ DockingActionIf action =+ AbstractDockingTest.getAction(frontEndTool, "FrontEndPlugin", actionName);+ return action;+ }++ private DockingActionIf getAction(String toolName, String action) {++ Set<DockingActionIf> actions =+ getActionsByOwnerAndName(frontEndTool, "FrontEndPlugin", toolName);+ for (DockingActionIf a : actions) {+ String[] menuPath = a.getMenuBarData().getMenuPath();+ if (menuPath.length > 2) {+ if (menuPath[1].indexOf(action) >= 0) {+ return a;+ }+ }+ }+ return null;+ }++ private PluginTool runTool(String toolName) throws Exception {+ DockingActionIf runAction = getAction(toolName, "Run Tool");+ assertNotNull(runAction);// if action is null, the name of the tool changed+ performAction(runAction, toolName, true);+ Tool[] tools = frontEndTool.getToolServices().getRunningTools();+ return (PluginTool) tools[tools.length - 1];+ }++ private void performAction(final DockingActionIf action, String name, boolean doWait)+ throws Exception {++ final JMenuItem item = new JMenuItem(name);+ Runnable r = () -> action.actionPerformed(new ActionContext(null, null, item));+ if (doWait) {+ SwingUtilities.invokeAndWait(r);+ }+ else {+ SwingUtilities.invokeLater(r);+ }+ waitForPostedSwingRunnables();+ }++}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/NewProjectWizardTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/NewProjectWizardTest.javanew file mode 100644index 0000000000..5d66e312dd--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/NewProjectWizardTest.java@@ -0,0 +1,555 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main;++import static org.junit.Assert.*;++import java.io.File;+import java.net.InetAddress;+import java.net.UnknownHostException;++import javax.swing.*;++import org.junit.*;+import org.junit.experimental.categories.Category;++import docking.action.DockingActionIf;+import docking.wizard.WizardManager;+import generic.test.AbstractGenericTest;+import generic.test.category.PortSensitiveCategory;+import ghidra.framework.GenericRunInfo;+import ghidra.framework.client.*;+import ghidra.framework.model.Project;+import ghidra.framework.model.ProjectLocator;+import ghidra.framework.preferences.Preferences;+import ghidra.server.remote.ServerTestUtil;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.TestEnv;+import utilities.util.FileUtilities;++/**+ * Test for the New Project Wizard.+ *+ */+@Category(PortSensitiveCategory.class)+public class NewProjectWizardTest extends AbstractGhidraHeadedIntegrationTest {++ private TestEnv env;+ private FrontEndTool frontEndTool;+ private File serverRoot;+ private RepositoryServerAdapter repositoryServer;++ private static final String USER = ClientUtil.getUserName();+ private static final int SERVER_PORT = 14100;+ private static String LOCALHOST = createLocalHostString();++ private static String createLocalHostString() {+ String localHostString = null;+ try {+ localHostString = InetAddress.getLocalHost().getHostName();+ }+ catch (UnknownHostException e) {+ localHostString = "127.0.0.1";+ }+ return localHostString;+ }++ public NewProjectWizardTest() {+ super();+ }++ @Before+ public void setUp() throws Exception {+ env = new TestEnv();++ File projectDirectory = new File(GenericRunInfo.getProjectsDirPath());+ deleteProject(projectDirectory.getAbsolutePath(), "ProjectTest");++ // Note: we must call clear() on the preferences, and not delete the file, since+ // the preferences have already been loaded at this point. Also, even if you deleted the+ // file before the data was loaded, then the preferences would simply load from+ // another directory.+ Preferences.clear();++ frontEndTool = env.getFrontEndTool();+ env.showFrontEndTool();++ }++ @After+ public void tearDown() throws Exception {++ try {++ DockingActionIf saveAction = getAction("Save Project");+ performAction(saveAction, true);+ DockingActionIf action = getAction("Close Project");+ performAction(action, true);++ File projectDirectory = new File(GenericRunInfo.getProjectsDirPath());++ deleteProject(projectDirectory.getAbsolutePath(), "ProjectTest");+ }+ finally {+ cleanupResources();+ }+ }++ private void cleanupResources() throws Exception {+ env.dispose();++ try {+ Preferences.setProperty("ServerInfo", null);+ Preferences.store();+ }+ finally {+ if (serverRoot != null) {+ ServerTestUtil.disposeServer();+ FileUtilities.deleteDir(serverRoot);+ }+ }+ }++ @Test+ public void testCreateNonSharedProject() {+ try {+ DockingActionIf action = getAction("New Project");+ performAction(action, false);+ waitForPostedSwingRunnables();++ WizardManager wm =+ waitForDialogComponent(frontEndTool.getToolFrame(), WizardManager.class, 2000);+ assertNotNull(wm);++ ProjectTypePanel typePanel = findComponent(wm, ProjectTypePanel.class);+ assertNotNull(typePanel);+ JRadioButton rb =+ (JRadioButton) findAbstractButtonByText(typePanel, "Non-Shared Project");+ assertNotNull(rb);+ assertTrue(rb.isSelected());++ JButton nextButton = findButtonByText(wm, "Next >>");+ assertNotNull(nextButton);+ assertTrue(nextButton.isEnabled());+ JButton finishButton = findButtonByText(wm, "Finish");+ assertNotNull(finishButton);+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton, true);+ assertTrue(!nextButton.isEnabled());++ SelectProjectPanel projPanel = findComponent(wm, SelectProjectPanel.class);+ assertNotNull(projPanel);++ JTextField dirField = (JTextField) findComponentByName(projPanel, "Project Directory");+ assertNotNull(dirField);+ assertTrue(dirField.getText().length() > 0);++ final JTextField projField =+ (JTextField) findComponentByName(projPanel, "Project Name");+ assertNotNull(projField);+ assertEquals("", projField.getText());++ SwingUtilities.invokeAndWait(() -> projField.setText("ProjectTest"));+ waitForPostedSwingRunnables();++ assertTrue(createSelectProjectPanelOutputMessage(wm.getStatusMessage(), projPanel),+ finishButton.isEnabled());++ pressButton(finishButton, true);+ Thread.sleep(500);+ waitForPostedSwingRunnables();++ Project project = frontEndTool.getProject();+ assertNotNull(project);+ ProjectLocator url = project.getProjectLocator();+ assertEquals("ProjectTest", url.getName());+ }+ catch (Exception e) {+ e.printStackTrace();+ org.junit.Assert.fail(e.toString());+ }+ }++ @Test+ public void testCreateNonSharedProject2() {+ try {+ // test entering a directory that does not exist++ DockingActionIf action = getAction("New Project");+ performAction(action, false);+ waitForPostedSwingRunnables();++ WizardManager wm =+ waitForDialogComponent(frontEndTool.getToolFrame(), WizardManager.class, 2000);+ assertNotNull(wm);++ ProjectTypePanel typePanel = findComponent(wm, ProjectTypePanel.class);+ assertNotNull(typePanel);+ JRadioButton rb =+ (JRadioButton) findAbstractButtonByText(typePanel, "Non-Shared Project");+ assertNotNull(rb);+ assertTrue(rb.isSelected());++ JButton nextButton = findButtonByText(wm, "Next >>");+ assertNotNull(nextButton);+ assertTrue(nextButton.isEnabled());+ JButton finishButton = findButtonByText(wm, "Finish");+ assertNotNull(finishButton);+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton, true);+ assertTrue(!nextButton.isEnabled());++ SelectProjectPanel projPanel = findComponent(wm, SelectProjectPanel.class);+ assertNotNull(projPanel);++ final JTextField dirField =+ (JTextField) findComponentByName(projPanel, "Project Directory");+ assertNotNull(dirField);++ final JTextField projField =+ (JTextField) findComponentByName(projPanel, "Project Name");+ assertNotNull(projField);++ SwingUtilities.invokeAndWait(() -> {+ String dirText = dirField.getText();+ dirText = dirText + File.separator + "new";+ dirField.setText(dirText);+ projField.setText("MyProject");+ });+ waitForPostedSwingRunnables();++ assertTrue(!finishButton.isEnabled());+ assertEquals("Project directory does not exist.", wm.getStatusMessage());+ pressButtonByText(wm, "Cancel");+ }+ catch (Exception e) {+ e.printStackTrace();+ org.junit.Assert.fail(e.toString());+ }+ }++ @Test+ public void testCreateSharedProject() {+ try {+ // start a local server+ startServer();++ DockingActionIf action = getAction("New Project");+ performAction(action, false);+ waitForPostedSwingRunnables();++ WizardManager wm =+ waitForDialogComponent(frontEndTool.getToolFrame(), WizardManager.class, 2000);+ assertNotNull(wm);++ ProjectTypePanel typePanel = findComponent(wm, ProjectTypePanel.class);+ assertNotNull(typePanel);+ final JRadioButton rb =+ (JRadioButton) findAbstractButtonByText(typePanel, "Shared Project");+ assertNotNull(rb);+ assertTrue(!rb.isSelected());++ SwingUtilities.invokeAndWait(() -> rb.setSelected(true));+ waitForPostedSwingRunnables();++ JButton nextButton = findButtonByText(wm, "Next >>");+ assertNotNull(nextButton);+ assertTrue(nextButton.isEnabled());+ JButton finishButton = findButtonByText(wm, "Finish");+ assertNotNull(finishButton);+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton, true);++ ServerInfoPanel serverPanel = findComponent(wm, ServerInfoPanel.class);+ assertNotNull(serverPanel);++ final JTextField serverField =+ (JTextField) findComponentByName(serverPanel, "Server Name");+ final JTextField portNumberField =+ (JTextField) findComponentByName(serverPanel, "Port Number");+ assertNotNull(serverField);+ assertNotNull(portNumberField);++ SwingUtilities.invokeAndWait(() -> {+ serverField.setText(LOCALHOST);+ portNumberField.setText(Integer.toString(SERVER_PORT));+ });+ waitForPostedSwingRunnables();++ assertTrue(nextButton.isEnabled());+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton);++ // next panel should be the repository panel+ RepositoryPanel repPanel = findComponent(wm, RepositoryPanel.class);+ assertNotNull(repPanel);++ JRadioButton existingRb =+ (JRadioButton) findAbstractButtonByText(repPanel, "Existing Repository");+ assertNotNull(existingRb);+ assertTrue(existingRb.isSelected());++ // create a new repository+ final JRadioButton createRb =+ (JRadioButton) findAbstractButtonByText(repPanel, "Create Repository");+ assertNotNull(createRb);+ assertTrue(!createRb.isSelected());+ final JTextField repNameField = findComponent(repPanel, JTextField.class);+ assertNotNull(repNameField);+ assertTrue(!repNameField.isEnabled());++ JList repList = findComponent(repPanel, JList.class);+ assertNotNull(repList);+ assertTrue(repList.isEnabled());++ pressButton(createRb, true);+ assertTrue(!existingRb.isSelected());+ assertTrue(repNameField.isEnabled());+ assertTrue(!repList.isEnabled());+ assertTrue(!nextButton.isEnabled());+ assertTrue(!finishButton.isEnabled());++ SwingUtilities.invokeAndWait(() -> repNameField.setText("TestRepository"));+ waitForPostedSwingRunnables();+ assertTrue(nextButton.isEnabled());+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton, true);+ assertTrue(+ "Next button did not become enabled - status message: " + wm.getStatusMessage(),+ nextButton.isEnabled());++ // next panel should be user access panel+ ProjectAccessPanel accessPanel = findComponent(wm, ProjectAccessPanel.class);+ assertNotNull(accessPanel);++ assertTrue(nextButton.isEnabled());+ assertTrue(+ "Finish button did not become enabled - status message: " + wm.getStatusMessage(),+ finishButton.isEnabled());++ // next panel is project location panel+ pressButton(nextButton, true);+ assertTrue(!nextButton.isEnabled());++ SelectProjectPanel projPanel = findComponent(wm, SelectProjectPanel.class);+ assertNotNull(projPanel);++ JTextField dirField = (JTextField) findComponentByName(projPanel, "Project Directory");+ assertNotNull(dirField);+ assertTrue(dirField.getText().length() > 0);++ final JTextField projField =+ (JTextField) findComponentByName(projPanel, "Project Name");+ assertNotNull(projField);+ assertEquals("TestRepository", projField.getText());++ SwingUtilities.invokeAndWait(() -> projField.setText("ProjectTest"));+ waitForPostedSwingRunnables();+ assertTrue(finishButton.isEnabled());+ assertTrue(!nextButton.isEnabled());++ pressButton(finishButton, true);+ Thread.sleep(500);+ waitForPostedSwingRunnables();++ Project project = frontEndTool.getProject();+ assertNotNull(project);+ ProjectLocator url = project.getProjectLocator();+ assertEquals("ProjectTest", url.getName());+ }+ catch (Exception e) {+ e.printStackTrace();+ org.junit.Assert.fail(e.toString());+ }+ }++ @Test+ public void testCreateSharedProjectExisting() throws Exception {+ // create shared project against existing repository++ try {+ // start a local server+ startServer();++ DockingActionIf action = getAction("New Project");+ performAction(action, false);+ waitForPostedSwingRunnables();++ WizardManager wm =+ waitForDialogComponent(frontEndTool.getToolFrame(), WizardManager.class, 2000);+ assertNotNull(wm);++ ProjectTypePanel typePanel = findComponent(wm, ProjectTypePanel.class);+ assertNotNull(typePanel);+ final JRadioButton rb =+ (JRadioButton) findAbstractButtonByText(typePanel, "Shared Project");+ assertNotNull(rb);+ assertTrue(!rb.isSelected());++ SwingUtilities.invokeAndWait(() -> rb.setSelected(true));+ waitForPostedSwingRunnables();++ JButton nextButton = findButtonByText(wm, "Next >>");+ assertNotNull(nextButton);+ assertTrue(nextButton.isEnabled());+ JButton finishButton = findButtonByText(wm, "Finish");+ assertNotNull(finishButton);+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton, true);++ ServerInfoPanel serverPanel = findComponent(wm, ServerInfoPanel.class);+ assertNotNull(serverPanel);++ final JTextField serverField =+ (JTextField) findComponentByName(serverPanel, "Server Name");+ final JTextField portNumberField =+ (JTextField) findComponentByName(serverPanel, "Port Number");+ assertNotNull(serverField);+ assertNotNull(portNumberField);++ if (nextButton.isEnabled()) {+ // enabled because we have left over server info from previous test+ assertTrue(serverField.getText().length() > 0);+ assertTrue(portNumberField.getText().length() > 0);+ }++ SwingUtilities.invokeAndWait(() -> {+ serverField.setText(LOCALHOST);+ portNumberField.setText(Integer.toString(SERVER_PORT));+ });+ waitForPostedSwingRunnables();+ assertTrue(nextButton.isEnabled());+ assertTrue(!finishButton.isEnabled());++ pressButton(nextButton);++ // next panel should be the repository panel+ RepositoryPanel repPanel = findComponent(wm, RepositoryPanel.class);+ assertNotNull(repPanel);++ JRadioButton existingRb =+ (JRadioButton) findAbstractButtonByText(repPanel, "Existing Repository");+ assertNotNull(existingRb);+ assertTrue(existingRb.isSelected());++ // create a new repository+ final JRadioButton createRb =+ (JRadioButton) findAbstractButtonByText(repPanel, "Create Repository");+ assertNotNull(createRb);+ assertTrue(!createRb.isSelected());+ final JTextField repNameField = findComponent(repPanel, JTextField.class);+ assertNotNull(repNameField);+ assertTrue(!repNameField.isEnabled());++ final JList repList = findComponent(repPanel, JList.class);+ assertNotNull(repList);+ assertTrue(repList.isEnabled());++ assertTrue(!createRb.isSelected());+ assertTrue(!repNameField.isEnabled());+ assertTrue(repList.isEnabled());+ assertTrue(!nextButton.isEnabled());+ assertTrue(!finishButton.isEnabled());++ // select existing repository+ SwingUtilities.invokeAndWait(() -> repList.setSelectedIndex(0));+ waitForPostedSwingRunnables();+ assertTrue(nextButton.isEnabled());+ assertTrue(!finishButton.isEnabled());++ // next panel is project location panel+ pressButton(nextButton, true);+ assertTrue(!nextButton.isEnabled());++ SelectProjectPanel projPanel = findComponent(wm, SelectProjectPanel.class);+ assertNotNull(projPanel);++ JTextField dirField = (JTextField) findComponentByName(projPanel, "Project Directory");+ assertNotNull(dirField);+ assertTrue(dirField.getText().length() > 0);++ final JTextField projField =+ (JTextField) findComponentByName(projPanel, "Project Name");+ assertNotNull(projField);+ assertEquals("My_Repository", projField.getText());++ SwingUtilities.invokeAndWait(() -> projField.setText("ProjectTest"));+ waitForPostedSwingRunnables();+ assertTrue(createSelectProjectPanelOutputMessage(wm.getStatusMessage(), projPanel),+ finishButton.isEnabled());+ assertTrue(!nextButton.isEnabled());++ pressButton(finishButton, true);+ Thread.sleep(500);+ waitForPostedSwingRunnables();++ Project project = frontEndTool.getProject();+ assertNotNull(project);+ ProjectLocator url = project.getProjectLocator();+ assertEquals("ProjectTest", url.getName());+ }+ catch (Exception e) {+ e.printStackTrace();+ org.junit.Assert.fail(e.toString());+ }++ }++ ////////////////////////////////////////////////////////////////////++ private String createSelectProjectPanelOutputMessage(String statusMessage,+ SelectProjectPanel projectPanel) {++ JTextField dirField = (JTextField) findComponentByName(projectPanel, "Project Directory");+ JTextField projectField = (JTextField) findComponentByName(projectPanel, "Project Name");++ String message = "Finish button did not become enabled - status message: " + statusMessage ++ ".\n\tDirectory: " + dirField.getText() + "\n\tProject name: " + projectField.getText();+ return message;+ }++ private DockingActionIf getAction(String actionName) {++ DockingActionIf action = getAction(frontEndTool, "FrontEndPlugin", actionName);+ return action;+ }++ private void startServer() throws Exception {+ File parent = new File(AbstractGenericTest.getTestDirectoryPath());++ // Create server instance+ serverRoot = new File(parent, "My_Server");+ FileUtilities.deleteDir(serverRoot);++ repositoryServer = ServerTestUtil.getServerAdapter(serverRoot, new String[] { USER });++ if (repositoryServer == null || !repositoryServer.isConnected()) {+ ServerTestUtil.disposeServer();+ FileUtilities.deleteDir(serverRoot);+ serverRoot = null;+ Assert.fail("Server connect failed");+ }++ RepositoryAdapter repository = repositoryServer.createRepository("My_Repository");+ assertTrue(repository.getUser().isAdmin());+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ProjectInfoDialogTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ProjectInfoDialogTest.javanew file mode 100644index 0000000000..24f77e5e89--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ProjectInfoDialogTest.java@@ -0,0 +1,409 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main;++import static org.junit.Assert.*;++import java.io.IOException;+import java.util.concurrent.atomic.AtomicReference;++import javax.swing.*;++import org.junit.*;+import org.junit.experimental.categories.Category;++import docking.action.DockingActionIf;+import docking.widgets.OptionDialog;+import docking.wizard.WizardManager;+import generic.test.category.PortSensitiveCategory;+import ghidra.framework.client.RepositoryAdapter;+import ghidra.framework.model.*;+import ghidra.framework.preferences.Preferences;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.model.listing.Program;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.TestEnv;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++@Category(PortSensitiveCategory.class)+public class ProjectInfoDialogTest extends AbstractGhidraHeadedIntegrationTest {++ private TestEnv env;+ private FrontEndTool frontEndTool;+ private DomainFolder rootFolder;+ private ProjectInfoDialog dialog;++ public ProjectInfoDialogTest() {+ super();+ }++ @Before+ public void setUp() throws Exception {++ setErrorGUIEnabled(false);+ env = new TestEnv();++ frontEndTool = env.getFrontEndTool();+ env.showFrontEndTool();++ rootFolder = env.getProject().getProjectData().getRootFolder();++ DomainFile df;++ Program p = createDefaultProgram("testA", ProgramBuilder._TOY64_LE, this);+ try {+ df = rootFolder.createFile("testA", p, TaskMonitor.DUMMY);+ }+ finally {+ p.release(this);+ }++ df.addToVersionControl("This is a test", false, TaskMonitor.DUMMY);++ showViewProjectInfoDialog();++ RepositoryAdapter rep = null;+ try {+ // this can throw a NotConnectedException+ System.err.println(getClass().getName() + "\tstarting server...");+ rep = SharedProjectUtil.startServer();+ }+ catch (Exception e) {+ cleanupResources();+ throw e;+ }++ assertNotNull(rep);+ assertTrue(rep.isConnected());++ }++ @After+ public void tearDown() throws Exception {++ try {+ DockingActionIf saveAction = getAction("Save Project");+ System.err.println("\tsaving project");+ performAction(saveAction, true);+ System.err.println("\tclosing project");+ DockingActionIf action = getAction("Close Project");+ performAction(action, true);+ }+ finally {+ cleanupResources();+ }++ }++ private void cleanupResources() throws Exception {+ System.err.println(getClass().getName() + ".cleanupResources()...");+ try {+ System.err.println(getClass().getName() + "\tdisposing...");+ env.dispose();+ System.err.println(getClass().getName() + "\tstoring preferences...");+ Preferences.setProperty("ServerInfo", null);+ Preferences.store();+ }+ finally {+ System.err.println(getClass().getName() + "\tdeleting server root...");+ SharedProjectUtil.deleteServerRoot();+ System.err.println(getClass().getName() + "\tdeleting test project...");+ SharedProjectUtil.deleteTestProject("TestProject");+ }+ System.err.println(getClass().getName() + ".cleanupResources() done!s");+ }++ @Test+ public void testConvertProjectFilesCheckedOut() throws Exception {+ setErrorGUIEnabled(true); // we need the dialog below++ // check-out testA+ rootFolder = getProject().getProjectData().getRootFolder();+ DomainFile df = rootFolder.getFile("testA");+ assertTrue(df.checkout(false, TaskMonitor.DUMMY));++ // make simple change to checked-out file+ Program p = (Program) df.getDomainObject(this, false, false, TaskMonitor.DUMMY);+ try {++ int txId = p.startTransaction("test");+ try {+ p.setName("XYZ");+ }+ finally {+ p.endTransaction(txId, true);+ }+ p.save(null, TaskMonitor.DUMMY);+ }+ finally {+ p.release(this);+ }++ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);+ windowForComponent(dialog.getComponent());++ stepThroughWizard(true);++ OptionDialog opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ assertEquals("Confirm Convert Project", opt.getTitle());+ pressButtonByText(opt, "Convert");+ }++ @Test+ public void testOpenFiles() throws CancelledException, IOException {++ // cannot convert project if files are open+ DomainFile df = rootFolder.getFile("testA");+ assertTrue(df.checkout(false, TaskMonitor.DUMMY));++ env.launchTool("CodeBrowser", df);++ setErrorGUIEnabled(true);+ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);+ OptionDialog opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ assertEquals("Cannot Convert Project with Open Files", opt.getTitle());++ pressButtonByText(opt, "OK", true);+ }++ @Test+ public void testConvertProjectToShared() throws Exception {++ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);+ windowForComponent(dialog.getComponent());+ Project oldProject = getProject();+ stepThroughWizard(true);++ OptionDialog opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ pressButtonByText(opt, "Convert");++ waitForTasks();++ Project newProject = getProject();+ assertNotSame("Converting project failed", oldProject, newProject);+ assertNotNull(newProject.getRepository());++ checkProjectInfo("My_Repository");+ }++ @Test+ public void testConvertProjectCanceled() throws Exception {++ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);+ windowForComponent(dialog.getComponent());++ stepThroughWizard(true);+ OptionDialog opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ pressButtonByText(opt, "Cancel");++ assertNull(env.getProject().getRepository());+ }++ @Test+ public void testConvertProjectCanceled2() throws Exception {++ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);+ stepThroughWizard(false);+ assertNull(env.getProject().getRepository());+ }++ private Project getProject() {+ AtomicReference<Project> ref = new AtomicReference<>();+ runSwing(() -> ref.set(frontEndTool.getProject()));+ return ref.get();+ }++ @Test+ public void testUpdateSharedProjectInfo() throws Exception {++ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);++ stepThroughWizard(true);++ OptionDialog opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ pressButtonByText(opt, "Convert");+ waitForTasks();++ SharedProjectUtil.createRepository("AnotherRepository");++ dialog = waitForDialogComponent(ProjectInfoDialog.class);+ assertNotNull(dialog);++ pressButtonByText(dialog, ProjectInfoDialog.CHANGE, false);+ waitForSwing();++ // change project to use a different repository+ stepThroughWizard(true, "AnotherRepository");++ opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ assertEquals("Update Shared Project Info", opt.getTitle());+ pressButtonByText(opt, "Update");+ waitForTasks();++ checkProjectInfo("AnotherRepository");++ }++ @Test+ public void testUpdateSharedProjectInfoWithCheckouts() throws Exception {++ pressButtonByText(dialog, ProjectInfoDialog.CONVERT, false);++ stepThroughWizard(true);++ OptionDialog opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ pressButtonByText(opt, "Convert");+ waitForTasks();++ // check out file from shared project+ rootFolder = getProject().getProjectData().getRootFolder();+ DomainFile df = rootFolder.getFile("testA");+ df.addToVersionControl("test", true, TaskMonitor.DUMMY);+ assertTrue(df.isCheckedOut());++ setErrorGUIEnabled(true); // we need the dialog below++ SharedProjectUtil.createRepository("AnotherRepository");++ dialog = waitForDialogComponent(ProjectInfoDialog.class);++ pressButtonByText(dialog, ProjectInfoDialog.CHANGE, false);+ waitForSwing();++ // change project to use a different repository+ stepThroughWizard(true, "AnotherRepository");++ opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ assertEquals("Update Shared Project Info", opt.getTitle());+ pressButtonByText(opt, "Update");+ waitForTasks();++ opt = waitForDialogComponent(OptionDialog.class);+ assertNotNull(opt);+ assertEquals("Failed to Update Shared Project Info", opt.getTitle());+ opt.close();+ }++ private void checkProjectInfo(String expectedRepName) {+ dialog = waitForDialogComponent(ProjectInfoDialog.class);++ RepositoryAdapter repository = getProject().getRepository();+ assertEquals(expectedRepName, repository.getName());+ JLabel repLabel = (JLabel) findComponentByName(dialog.getComponent(), "Repository Name");+ assertNotNull(repLabel);+ assertEquals(expectedRepName, repLabel.getText());++ JLabel serverLabel = (JLabel) findComponentByName(dialog.getComponent(), "Server Name");+ assertNotNull(serverLabel);+ ServerInfo info = repository.getServerInfo();+ assertEquals(info.getServerName(), serverLabel.getText());++ JLabel portLabel = (JLabel) findComponentByName(dialog.getComponent(), "Port Number");+ assertNotNull(portLabel);+ assertEquals(Integer.toString(info.getPortNumber()), portLabel.getText());++ JLabel userLabel = (JLabel) findComponentByName(dialog.getComponent(), "User Access Level");+ assertNotNull(userLabel);+ assertEquals("Administrator", userLabel.getText());++ JButton button = (JButton) findComponentByName(dialog.getComponent(), "Connect Button");+ assertNotNull(button);+ assertTrue(button.isEnabled());+ assertEquals(FrontEndPlugin.CONNECTED_ICON, button.getIcon());+ }++ private void showViewProjectInfoDialog() {+ DockingActionIf action = getAction("View Project Info");+ assertNotNull(action);+ performAction(action, true);+ dialog = waitForDialogComponent(ProjectInfoDialog.class);+ assertNotNull(dialog);+ }++ private DockingActionIf getAction(String actionName) {+ DockingActionIf action = getAction(frontEndTool, "FrontEndPlugin", actionName);+ return action;+ }++ private void stepThroughWizard(boolean doFinish) throws Exception {+ stepThroughWizard(doFinish, null);+ }++ private void stepThroughWizard(boolean doFinish, final String repositoryName) throws Exception {+ System.err.println(getClass().getName() + ".stepThroughWizard()...");+ windowForComponent(dialog.getComponent());+ WizardManager wm = waitForDialogComponent(WizardManager.class);+ assertNotNull(wm);++ JButton nextButton = findButtonByText(wm, "Next >>");+ JButton finishButton = findButtonByText(wm, "Finish");+ JButton cancelButton = findButtonByText(wm, "Cancel");++ ServerInfoPanel serverPanel = findComponent(wm, ServerInfoPanel.class);++ final JTextField serverField = (JTextField) findComponentByName(serverPanel, "Server Name");+ final JTextField portNumberField =+ (JTextField) findComponentByName(serverPanel, "Port Number");++ runSwing(() -> {+ serverField.setText(SharedProjectUtil.LOCALHOST);+ portNumberField.setText(Integer.toString(SharedProjectUtil.SERVER_PORT));+ });++ System.err.println(getClass().getName() + ".stepThroughWizard()\tpressing next button...");+ pressButton(nextButton);++ // next panel should be the repository panel+ RepositoryPanel repPanel = findComponent(wm, RepositoryPanel.class);++ System.err.println(+ getClass().getName() + ".stepThroughWizard()\tfound repPanel: " + repPanel);+ final JList<?> repList = findComponent(repPanel, JList.class);+ ListModel<?> model = repList.getModel();+ int index = 0;+ if (repositoryName != null) {+ for (int i = 0; i < model.getSize(); i++) {+ if (repositoryName.equals(model.getElementAt(i))) {+ index = i;+ break;+ }++ }+ }+ final int selIndex = index;+ // select existing repository+ runSwing(() -> repList.setSelectedIndex(selIndex));+ if (doFinish) {+ pressButton(finishButton, true);+ }+ else {+ pressButton(cancelButton, true);+ }++ assertTrue("The wizard panel is not closed for some reason", !wm.isShowing());++ System.err.println(getClass().getName() + ".stepThroughWizard() done!");+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ProjectInfoFilesystemTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ProjectInfoFilesystemTest.javanew file mode 100644index 0000000000..8d2d7bf37b--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ProjectInfoFilesystemTest.java@@ -0,0 +1,375 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main;++import static org.junit.Assert.*;++import java.io.File;+import java.io.IOException;++import javax.swing.*;++import org.junit.*;++import docking.action.DockingActionIf;+import generic.test.TestUtils;+import ghidra.framework.data.ProjectFileManager;+import ghidra.framework.model.*;+import ghidra.framework.plugintool.PluginTool;+import ghidra.framework.store.ItemCheckoutStatus;+import ghidra.framework.store.Version;+import ghidra.framework.store.local.*;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.model.address.*;+import ghidra.program.model.listing.Program;+import ghidra.program.model.listing.ProgramUserData;+import ghidra.program.model.util.StringPropertyMap;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.TestEnv;+import ghidra.util.InvalidNameException;+import ghidra.util.task.TaskMonitorAdapter;+import utilities.util.FileUtilities;++public class ProjectInfoFilesystemTest extends AbstractGhidraHeadedIntegrationTest {++ private static final String PROJECT_NAME = "TestProject";++ private TestEnv env;++ private ProjectLocator projectLocator;+ private Project project;++ private FrontEndTool frontEndTool;+ private ProjectInfoDialog dialog;++ public ProjectInfoFilesystemTest() {+ super();+ }++ @Before+ public void setUp() throws Exception {++ env = new TestEnv();++ projectLocator = new ProjectLocator(getTestDirectoryPath(), PROJECT_NAME);+ projectLocator.getMarkerFile().delete();++ File projectDir = new File(getTestDirectoryPath(),+ PROJECT_NAME + ProjectLocator.getProjectDirExtension());+ if (projectDir.isDirectory()) {+ if (!FileUtilities.deleteDir(projectDir)) {+ Assert.fail("Cleanup of old test project failed");+ }+ }+ }++ @After+ public void tearDown() throws Exception {+ closeAllWindowsAndFrames();+ env.dispose();++ if (project != null) {+ project.close();+ }+ if (projectLocator != null) {+ projectLocator.getMarkerFile().delete();+ FileUtilities.deleteDir(projectLocator.getProjectDir());+ }+ }++ private void createMangledFilesystems(String... fsNames) throws IOException {+ for (String fsName : fsNames) {+ File rootDir = new File(projectLocator.getProjectDir(), fsName);+ LocalFilesystemTestUtils.createMangledFilesystem(rootDir.getAbsolutePath(), false,+ false, false).dispose();+ }+ }++ private void createIndexV0Filesystems(String... fsNames) throws IOException {+ for (String fsName : fsNames) {+ File rootDir = new File(projectLocator.getProjectDir(), fsName);+ LocalFilesystemTestUtils.createIndexedV0Filesystem(rootDir.getAbsolutePath(), false,+ false, false).dispose();+ }+ }++ private void createIndexV1Filesystems(String... fsNames) throws IOException {+ for (String fsName : fsNames) {+ File rootDir = new File(projectLocator.getProjectDir(), fsName);+ LocalFilesystemTestUtils.createIndexedV1Filesystem(rootDir.getAbsolutePath(), false,+ false, false).dispose();+ }+ }++ /**+ * Create project+ * @param filesystemVersion -1: mangled, 0... indexed version+ * @throws Exception+ */+ private void createProject(int filesystemVersion) throws Exception {++ if (filesystemVersion < 0) {+ createMangledFilesystems("data", "versioned", "user");+ }+ else if (filesystemVersion == 0) {+ createIndexV0Filesystems("idata", "versioned", "user");+ }+ else if (filesystemVersion == 1) {+ createIndexV1Filesystems("idata", "versioned", "user");+ }++ try {+ projectLocator.getMarkerFile().createNewFile();+ }+ catch (Exception e) {+ Assert.fail("Failed to open constructed project: " + projectLocator);+ }++ ProjectManager projectManager = env.getProjectManager();+ Project tesEnvProject = projectManager.getActiveProject();+ tesEnvProject.close();// close TestEnv project++ try {+ project = projectManager.openProject(projectLocator, true, false);+ }+ catch (Exception e) {+ Assert.fail("Failed to open fabricated project: " + projectLocator);+ }++ addVersionedProgram("/a", "testA");+ addVersionedProgram("/a/b", "testB");+ }++ private void verifyPrograms() throws Exception {+ verifyProgram("/a/testA");+ verifyProgram("/a/b/testB");+ }++ private DockingActionIf getAction(PluginTool tool, String actionName) {++ DockingActionIf action = getAction(frontEndTool, "FrontEndPlugin", actionName);+ return action;+ }++ /**+ * Create and open project in front-end and popup Project Info dialog+ * @param filesystemVersion -1: mangled, 0... indexed version+ * @throws Exception+ */+ private void openProjectAndInfo(int filesystemVersion) throws Exception {++ frontEndTool = env.getFrontEndTool();++ env.showFrontEndTool();++ runSwing(() -> {++ // TODO: Workaround for front-end failure to notify listeners+ // when closing program via setActiveProject method - only done by FileActionManager+ @SuppressWarnings("unchecked")+ Iterable<ProjectListener> listeners =+ (Iterable<ProjectListener>) TestUtils.invokeInstanceMethod("getListeners",+ frontEndTool);+ for (ProjectListener listener : listeners) {+ listener.projectClosed(project);+ }+ frontEndTool.setActiveProject(null);// remove TestEnv project+ });++ createProject(filesystemVersion);++ runSwing(() -> frontEndTool.setActiveProject(project));++ DockingActionIf action = getAction(frontEndTool, "View Project Info");+ assertNotNull(action);+ performAction(action, true);++ dialog = waitForDialogComponent(frontEndTool.getToolFrame(), ProjectInfoDialog.class, 2000);+ assertNotNull(dialog);+ }++ private DomainFolder getFolder(String folderPath, boolean create) throws IOException {+ ProjectData projectData = project.getProjectData();+ DomainFolder folder = projectData.getRootFolder();+ for (String folderName : folderPath.split("/")) {+ if (folderName.length() == 0) {+ continue;+ }+ DomainFolder f = folder.getFolder(folderName);+ if (f == null) {+ try {+ f = folder.createFolder(folderName);+ }+ catch (InvalidNameException e) {+ Assert.fail("Unexpected Exception");+ }+ }+ folder = f;+ }+ return folder;+ }++ private DomainFile addVersionedProgram(String folderPath, String name) throws Exception {+ DomainFile df;+ Program p = createDefaultProgram(name, ProgramBuilder._TOY64_LE, this);+ try {+ AddressFactory addressFactory = p.getAddressFactory();+ ProgramUserData programUserData = p.getProgramUserData();+ int txId = programUserData.startTransaction();+ try {+ StringPropertyMap propertyMap =+ programUserData.getStringPropery("TEST", "userProp1", true);+ propertyMap.add(addressFactory.getAddress("0100"), "userValue100");+ propertyMap.add(addressFactory.getAddress("0200"), "userValue200");+ }+ finally {+ programUserData.endTransaction(txId);+ }++ df = getFolder(folderPath, true).createFile(name, p, TaskMonitorAdapter.DUMMY_MONITOR);+ }+ finally {+ p.release(this);+ }++ df.addToVersionControl("Initial", true, TaskMonitorAdapter.DUMMY_MONITOR);+ return df;+ }++ private void verifyProgram(String path) throws Exception {++ DomainFile df = project.getProjectData().getFile(path);+ assertNotNull("Domain file not found: " + path);++ assertTrue(df.isVersioned());+ assertTrue(df.isCheckedOut());+ assertTrue(df.isCheckedOutExclusive());// non-shared version repo++ ItemCheckoutStatus[] checkouts = df.getCheckouts();+ assertEquals(1, checkouts.length);++ Version[] versionHistory = df.getVersionHistory();+ assertEquals(1, versionHistory.length);+ assertEquals("Initial", versionHistory[0].getComment());++ Program p =+ (Program) df.getDomainObject(this, false, false, TaskMonitorAdapter.DUMMY_MONITOR);+ try {+ AddressFactory addressFactory = p.getAddressFactory();+ ProgramUserData programUserData = p.getProgramUserData();+ StringPropertyMap propertyMap =+ programUserData.getStringPropery("TEST", "userProp1", false);+ AddressIterator propertyIterator = propertyMap.getPropertyIterator();+ Address addr = addressFactory.getAddress("0100");+ assertEquals(addr, propertyIterator.next());+ assertEquals("userValue100", propertyMap.getString(addr));+ addr = addressFactory.getAddress("0200");+ assertEquals(addr, propertyIterator.next());+ assertEquals("userValue200", propertyMap.getString(addr));+ }+ finally {+ p.release(this);+ }++ }++ private void checkProjectInfo(Class<?> filesystemClass, String storageType) {+ ProjectFileManager projectData = (ProjectFileManager) project.getProjectData();+ String msg = "Expected " + filesystemClass.getSimpleName() + ": ";+ assertTrue(msg + "Local FileSystem", filesystemClass.isInstance(+ TestUtils.invokeInstanceMethod("getLocalFileSystem", projectData)));+ assertTrue(msg + "Versioned FileSystem", filesystemClass.isInstance(+ TestUtils.invokeInstanceMethod("getVersionedFileSystem", projectData)));+ assertTrue(msg + "User FileSystem", filesystemClass.isInstance(+ TestUtils.invokeInstanceMethod("getUserFileSystem", projectData)));++ JLabel storageTypeLabel =+ (JLabel) findComponentByName(dialog.getComponent(), "Project Storage Type");+ assertNotNull(storageTypeLabel);+ assertEquals(storageType, storageTypeLabel.getText());++ JLabel nameLabel = (JLabel) findComponentByName(dialog.getComponent(), "Project Name");+ assertNotNull(nameLabel);+ assertEquals(PROJECT_NAME, nameLabel.getText());+ }++ private void doStorageConvert(String buttonText) {++ JButton button = findButtonByText(dialog, buttonText);+ assertNotNull("Could not find storage convert button", button);++ pressButton(button, false);++ JDialog confirmDialog =+ waitForJDialog(null, "Confirm Convert/Upgrade Project Storage", 2000);+ assertNotNull("Expected convert confirm dialog", confirmDialog);++ JButton confirmButton = findButtonByText(confirmDialog, "Convert");+ pressButton(confirmButton);++ waitForPostedSwingRunnables();++ dialog = waitForDialogComponent(frontEndTool.getToolFrame(), ProjectInfoDialog.class, 5000);+ assertNotNull("Expected to find Project Info dialog after conversion completed", dialog);++ ProjectManager projectManager = env.getProjectManager();+ project = projectManager.getActiveProject();+ }++ @Test+ public void testMangledFilesystemConversion() throws Exception {++ openProjectAndInfo(-1);++ checkProjectInfo(MangledLocalFileSystem.class, "Mangled Filesystem");++ doStorageConvert("Convert Project Storage to Indexed...");++ checkProjectInfo(IndexedV1LocalFileSystem.class, "Indexed Filesystem (V1)");++ pressButtonByText(dialog, "Dismiss");++ verifyPrograms();+ }++ @Test+ public void testIndexedV0FilesystemConversion() throws Exception {++ openProjectAndInfo(0);++ checkProjectInfo(IndexedLocalFileSystem.class, "Indexed Filesystem (V0)");++ doStorageConvert("Upgrade Project Storage Index...");++ checkProjectInfo(IndexedV1LocalFileSystem.class, "Indexed Filesystem (V1)");++ pressButtonByText(dialog, "Dismiss");++ verifyPrograms();+ }++ @Test+ public void testIndexedV1FilesystemConversion() throws Exception {++ openProjectAndInfo(1);++ checkProjectInfo(IndexedV1LocalFileSystem.class, "Indexed Filesystem (V1)");++ pressButtonByText(dialog, "Dismiss");++ verifyPrograms();+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ToolActionManagerTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ToolActionManagerTest.javanew file mode 100644index 0000000000..252a62741d--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ToolActionManagerTest.java@@ -0,0 +1,811 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main;++import static org.junit.Assert.*;++import java.awt.*;+import java.awt.event.MouseEvent;+import java.io.File;+import java.util.*;+import java.util.concurrent.atomic.AtomicReference;++import javax.swing.*;++import org.junit.*;++import docking.ActionContext;+import docking.action.DockingActionIf;+import docking.test.AbstractDockingTest;+import docking.tool.ToolConstants;+import docking.widgets.OptionDialog;+import docking.widgets.filechooser.GhidraFileChooser;+import docking.widgets.table.GTable;+import docking.widgets.tree.GTreeNode;+import docking.widgets.tree.GTreeRootNode;+import docking.wizard.WizardManager;+import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin;+import ghidra.framework.GenericRunInfo;+import ghidra.framework.data.ContentHandler;+import ghidra.framework.main.datatree.DataTree;+import ghidra.framework.model.*;+import ghidra.framework.plugintool.PluginTool;+import ghidra.framework.plugintool.dialog.SaveToolConfigDialog;+import ghidra.framework.plugintool.util.PluginException;+import ghidra.framework.preferences.Preferences;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.model.listing.Program;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.TestEnv;+import ghidra.util.task.TaskMonitor;+import resources.ResourceManager;++/**+ * Tests for tool actions on the front end (Ghidra project window)+ */+public class ToolActionManagerTest extends AbstractGhidraHeadedIntegrationTest {++ private FrontEndTool frontEndTool;+ private TestEnv env;++ @Before+ public void setUp() throws Exception {+ env = new TestEnv();+ env.resetDefaultTools();++ frontEndTool = env.getFrontEndTool();+ env.showFrontEndTool();+ }++ @After+ public void tearDown() throws Exception {+ closeAllWindows();+ env.dispose();+ }++ @Test+ public void testDeleteTool() throws Exception {+ // delete a tool from the tool chest+ // verify delete menu is updated+ // verify "open with" menu is updated+ createTool();+ DockingActionIf action = getAction("Untitled", "Delete Tool");+ assertNotNull(action);+ performAction(action, "Untitled", false);+ OptionDialog d = waitForDialogComponent(OptionDialog.class);+ assertNotNull(d);+ assertEquals("Confirm Delete", d.getTitle());+ pressButtonByText(d.getComponent(), "Delete");+ waitForSwing();++ assertNull(getAction("Untitled", "Delete Tool"));+ assertNull(getAction("Untitled", "Run Tool"));+ assertNull(getAction("Untitled", "Export Tool"));+ }++ @Test+ public void testDeleteToolFromIcon() throws Exception {+ createTool();++ DockingActionIf deleteAction = getAction("Delete Tool");+ performToolButtonAction(deleteAction, "Untitled", false, true);++ OptionDialog d = waitForDialogComponent(OptionDialog.class);+ assertNotNull(d);+ assertEquals("Confirm Delete", d.getTitle());+ pressButtonByText(d.getComponent(), "Delete");+ waitForSwing();++ assertNull(getAction("Untitled", "Delete Tool"));+ assertNull(getAction("Untitled", "Run Tool"));+ assertNull(getAction("Untitled", "Export Tool"));+ }++ @Test+ public void testCloseRunningToolIcon() throws Exception {+ // close tool from the icon in the running tools+ createTool();++ DockingActionIf closeAction = getAction("Close Tool");+ performToolButtonAction(closeAction, "Untitled", true, true);++ Tool[] tools = frontEndTool.getProject().getToolServices().getRunningTools();+ assertEquals(0, tools.length);+ }++ @Test+ public void testRunTool() throws Exception {+ // action for run tool+ createTool();++ DockingActionIf runAction = getAction("Untitled", "Run Tool");+ performAction(runAction, "Untitled", true);+ Tool[] tools = frontEndTool.getProject().getToolServices().getRunningTools();+ assertEquals(2, tools.length);+ }++ @Test+ public void testRunToolFromIcon() throws Exception {+ createTool();++ // verify there is a tool button for each config in the tool chest+ ToolTemplate[] configs = frontEndTool.getToolServices().getToolChest().getToolTemplates();+ for (ToolTemplate config : configs) {+ ToolButton b = findToolButton(frontEndTool.getToolFrame(), config.getName(), false);+ assertNotNull(b);+ }++ final ToolButton cbButton = findToolButton(frontEndTool.getToolFrame(), "Untitled", false);+ runSwing(() -> cbButton.doClick());++ // the button click triggers an animation, and then launches the tool, so we must wait+ // for the window to appear+ Window window = waitForWindow("Untitled(2)");+ assertNotNull(window);++ waitForCondition(() -> {+ Tool[] tools = frontEndTool.getToolServices().getRunningTools();+ return tools.length == 2;+ });++ ToolButton tb = findToolButton(frontEndTool.getToolFrame(), "Untitled", true);+ assertNotNull(tb);+ }++ @Test+ public void testImportTool() throws Exception {+ // action for import a tool+ final ToolChest tc = frontEndTool.getToolServices().getToolChest();+ int count = tc.getToolCount();++ String toolNamePrefix = "TestCodeBrowser";+ final File cbFile =+ ResourceManager.getResourceFile("defaultTools/" + toolNamePrefix + ".tool");+ assertNotNull(cbFile);++ DockingActionIf importAction = getAction("Import Tool");+ performAction(importAction, false);++ waitForSwing();+ JDialog d = waitForJDialog("Import Tool");+ assertNotNull(d);+ final GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);++ assertNotNull(chooser);+ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(cbFile));+ waitForUpdateOnChooser(chooser);++ pressButtonByText(chooser, "Import");+ waitForSwing();+ assertEquals(count + 1, tc.getToolCount());++ ToolTemplate[] configs = tc.getToolTemplates();+ final ArrayList<String> list = new ArrayList<>();+ for (ToolTemplate config : configs) {+ if (config.getName().startsWith(toolNamePrefix + "_")) {+ list.add(config.getName());+ }+ }+ assertTrue(list.size() > 0);+ Collections.sort(list);+ SwingUtilities.invokeAndWait(() -> tc.remove(list.get(list.size() - 1)));+ }++ private Program buildProgram(String programName) throws Exception {+ ProgramBuilder builder = new ProgramBuilder(programName, ProgramBuilder._TOY);+ builder.createMemory("test1", Long.toHexString(0x1001000), 0x2000);+ return builder.getProgram();+ }++ @Test+ public void testSetToolAssociation() throws Exception {++ //+ // verify the default tool is the 'CodeBrowser'+ // verify that the VT tool is not in the tool chest (has not been imported)+ //+ removePreferences();+ initializeToolChestToJustCodeBrowser();++ //+ // verify that double-clicking a program launches its default tool (the CodeBrowser)+ //+ Project project = frontEndTool.getProject();+ DataTree tree = findComponent(frontEndTool.getToolFrame(), DataTree.class);++// TODO: move to method+ DomainFolder rootFolder = project.getProjectData().getRootFolder();+ Program p = buildProgram("notepad");+ rootFolder.createFile("notepad", p, TaskMonitor.DUMMY);+ env.release(p);++ GTreeRootNode rootNode = tree.getRootNode();+ waitForTree(tree);+ waitForSwing();++ GTreeNode node = rootNode.getChild("notepad");+ Rectangle bounds = tree.getPathBounds(node.getTreePath());++ tree.setSelectedNode(node);+ waitForTree(tree);++ JTree jTree = (JTree) invokeInstanceMethod("getJTree", tree);+ clickMouse(jTree, MouseEvent.BUTTON1, bounds.x + 5, bounds.y + 5, 2, 0);+ waitForSwing();++ Tool tool = waitForTool("CodeBrowser", project);++ // close the CodeBrowser tool+ close(tool);+ waitForSwing();++ //+ // edit the association+ //+ DockingActionIf setAssociationsAction = getAction("Set Tool Associations");+ performAction(setAssociationsAction, false);++ SetToolAssociationsDialog associationDialog =+ waitForDialogComponent(SetToolAssociationsDialog.class);++ //+ // edit the association+ //+ // find the 'Program' entry+ GTable associationTable = findComponent(associationDialog.getComponent(), GTable.class);+ int rowCount = associationTable.getRowCount();+ int programRow = -1;+ for (int i = 0; i < rowCount; i++) {+ ContentHandler handler = (ContentHandler) associationTable.getValueAt(i, 0);+ if ("Program".equals(handler.getContentType())) {+ programRow = i;+ break;+ }+ }+ assertTrue("Unable to find the 'Program' entry in the associations table",+ programRow != -1);++ // select the program entry in the table+ final int finalProgramRow = programRow;+ runSwing(() -> associationTable.selectRow(finalProgramRow));++ // click the edit button+ JButton editButton = findButtonByText(associationDialog, "Edit");+ pressButton(editButton, false);++ // grab the new dialog+ PickToolDialog pickToolDialog = waitForDialogComponent(PickToolDialog.class);++ // select the VT tool+ String VTToolName = "Version Tracking";+ final GTable pickTable = findComponent(pickToolDialog.getComponent(), GTable.class);+ rowCount = pickTable.getRowCount();+ int toolRow = -1;+ for (int i = 0; i < rowCount; i++) {+ ToolTemplate template = (ToolTemplate) pickTable.getValueAt(i, 0);+ if (VTToolName.equals(template.getName())) {+ toolRow = i;+ break;+ }+ }+ assertTrue("Unable to find the 'Version Tracking' entry in the pick tool table",+ toolRow != -1);++ final int finalToolRow = toolRow;+ runSwing(() -> pickTable.selectRow(finalToolRow));++ // press OK+ JButton okButton = findButtonByText(pickToolDialog.getComponent(), "OK");+ pressButton(okButton);+ waitForSwing();++ // verify the new association is the VT tool+ ToolTemplate template = (ToolTemplate) associationTable.getValueAt(finalProgramRow, 1);+ assertEquals(VTToolName + " tool not made the association for Program", VTToolName,+ template.getName());++ // close the dialog+ final JButton associationDialogOKButton =+ findButtonByText(associationDialog.getComponent(), "OK");+ pressButton(associationDialogOKButton);++ //+ // Verify the new association+ //++ // verify the VT tool is now in the tool chest (has been imported as a result of the user+ // choice)+ ToolServices toolServices = frontEndTool.getToolServices();+ ToolChest toolChest = toolServices.getToolChest();+ ToolTemplate toolTemplate = toolChest.getToolTemplate(VTToolName);+ assertNotNull("Default tool not imported when chosen as the associated tool", toolTemplate);++ // double-click a program in the Front End+ clickMouse(jTree, MouseEvent.BUTTON1, bounds.x + 5, bounds.y + 5, 2, 0);+ waitForSwing();++ // make sure the VT tool is launched+ tool = waitForTool(VTToolName, project);++ // close the VT tool+ // we first have to close the wizard...+ final WizardManager wizard = waitForDialogComponent(WizardManager.class);+ runSwing(() -> wizard.close());++ // ...then the tool+ close(tool);+ waitForSwing();++ //+ // edit the association+ //+ // find the 'Program' entry+ rowCount = associationTable.getRowCount();+ programRow = -1;+ for (int i = 0; i < rowCount; i++) {+ ContentHandler handler = (ContentHandler) associationTable.getValueAt(i, 0);+ if ("Program".equals(handler.getContentType())) {+ programRow = i;+ break;+ }+ }+ assertTrue("Unable to find the 'Program' entry in the associations table",+ programRow != -1);++ // select the program entry in the table+ final int newFinalProgramRow = programRow;+ runSwing(() -> associationTable.selectRow(newFinalProgramRow));++ // click the restore button+ JButton restoreButton =+ findButtonByText(associationDialog.getComponent(), "Restore Default");+ pressButton(restoreButton);++ // press OK+ JButton associationDialogOKButton2 =+ findButtonByText(associationDialog.getComponent(), "OK");+ pressButton(associationDialogOKButton2);++ //+ // Verify the new association+ //+ // double-click a program in the Front End+ clickMouse(jTree, MouseEvent.BUTTON1, bounds.x + 5, bounds.y + 5, 2, 0);+ waitForSwing();++ // make sure the 'CodeBrowser' tool is launched+ tool = waitForTool("CodeBrowser", project);++ // close the 'CodeBrowser' tool+ close(tool);+ waitForSwing();+ }++ private void close(final Tool tool) {+ runSwing(() -> tool.close());+ }++ private void removePreferences() {+ Preferences.clear();+ }++ private Tool waitForTool(String toolName, Project project) {+ Tool tool = null;+ int sleepTime = 100;+ int waitCount = 0;+ while (tool == null && waitCount < 300) {+ waitForSwing();+ sleep(sleepTime);+ ToolManager toolManager = project.getToolManager();+ Tool[] runningTools = toolManager.getRunningTools();+ if (runningTools != null && runningTools.length > 0) {+ tool = runningTools[0];+ }+ }++ assertNotNull("Did not find a single running " + toolName + " tool", tool);+ assertEquals("Running tool is not " + toolName, toolName, tool.getName());++ return tool;+ }++ private void initializeToolChestToJustCodeBrowser() {+ final ToolServices toolServices = frontEndTool.getToolServices();+ final ToolChest toolChest = toolServices.getToolChest();++ final AtomicReference<String> failedTool = new AtomicReference<>();+ runSwing(() -> {+ ToolTemplate[] toolTemplates = toolChest.getToolTemplates();+ for (ToolTemplate toolTemplate : toolTemplates) {+ String name = toolTemplate.getName();+ if (!name.equals("CodeBrowser")) {+ if (!toolChest.remove(name)) {+ failedTool.set(name);+ return;+ }+ }+ }++ });++ String toolName = failedTool.get();+ assertNull("Failed to remove tool: " + toolName, toolName);+ assertEquals("Did not remove tools as expected", 1, toolChest.getToolCount());+ }++ @Test+ public void testImportDefaultTools() throws Exception {+ final ToolChest tc = frontEndTool.getToolServices().getToolChest();+ int count = tc.getToolCount();+ ToolTemplate[] origConfigs = tc.getToolTemplates();++ Set<String> defaultTools = ResourceManager.getResourceNames("defaultTools", ".tool");+ Set<String> extraToolsList = ResourceManager.getResourceNames("extraTools", ".tool");++ DockingActionIf importAction = getAction("Import Ghidra Tools");+ performAction(importAction, false);+ waitForSwing();+ ImportGhidraToolsDialog d = waitForDialogComponent(ImportGhidraToolsDialog.class);+ assertNotNull(d);++ JList<?> defList = findComponent(d, JList.class);+ assertNotNull(defList);++ @SuppressWarnings("rawtypes")+ ListCellRenderer renderer = defList.getCellRenderer();+ for (int i = 0; i < defaultTools.size(); i++) {+ @SuppressWarnings("unchecked")+ JCheckBox cb =+ (JCheckBox) renderer.getListCellRendererComponent(defList, null, i, false, false);+ assertTrue(!cb.isSelected());+ }++ final JButton selectAllButton = (JButton) getInstanceField("selectAllButton", d);+ runSwing(() -> selectAllButton.doClick());++ pressButtonByText(d, "OK");+ waitForSwing();+ assertEquals(count + defaultTools.size() + extraToolsList.size(), tc.getToolCount());++ ToolTemplate[] configs = tc.getToolTemplates();++ // remove default tools that were just added+ ArrayList<String> origList = new ArrayList<>();+ for (ToolTemplate origConfig : origConfigs) {+ origList.add(origConfig.getName());+ }+ final ArrayList<String> newList = new ArrayList<>();+ for (ToolTemplate config : configs) {+ newList.add(config.getName());+ }+ newList.removeAll(origList);+ SwingUtilities.invokeAndWait(() -> {+ for (int i = 0; i < newList.size(); i++) {+ tc.remove(newList.get(i));+ }+ });+ assertEquals(origList.size(), tc.getToolCount());+ }++ @Test+ public void testImportSomeDefaultTools() throws Exception {+ final ToolChest tc = frontEndTool.getToolServices().getToolChest();+ final ToolTemplate[] origConfigs = tc.getToolTemplates();+ runSwing(() -> {+ for (ToolTemplate origConfig : origConfigs) {+ tc.remove(origConfig.getName());+ }+ });++ DockingActionIf importAction = getAction("Import Ghidra Tools");+ performAction(importAction, false);+ waitForSwing();+ ImportGhidraToolsDialog d = waitForDialogComponent(ImportGhidraToolsDialog.class);+ assertNotNull(d);++ pressButtonByText(d, "Select None");+ @SuppressWarnings("unchecked")+ JList<Object> defList = findComponent(d, JList.class);+ assertNotNull(defList);++ ListCellRenderer<Object> renderer = defList.getCellRenderer();+ JCheckBox cb =+ (JCheckBox) renderer.getListCellRendererComponent(defList, null, 0, false, false);+ Rectangle rect = defList.getCellBounds(0, 0);+ clickMouse(defList, 1, rect.x + 10, rect.y + 10, 1, 0);+ assertTrue(cb.isSelected());++ pressButtonByText(d, "OK");+ waitForSwing();++ ToolTemplate[] configs = tc.getToolTemplates();+ assertEquals(1, configs.length);+ }++ @Test+ public void testExportTool() throws Exception {++ // export using the menu action+ createTool();++ DockingActionIf exportAction = getAction("Untitled", "Export Tool");+ performAction(exportAction, "Untitled", false);++ waitForSwing();+ JDialog d = waitForJDialog("Export Untitled");+ assertNotNull(d);+ final GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);++ assertNotNull(chooser);+ final File file = new File(GenericRunInfo.getProjectsDirPath(), "untitled.tool");++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);++ pressButtonByText(chooser, "Export");+ waitForSwing();+ assertTrue(file.exists());+ file.delete();+ }++ @Test+ public void testExportToolOverwrite() throws Exception {+ // export using the menu action+ createTool();++ DockingActionIf exportAction = getAction("Untitled", "Export Tool");+ performAction(exportAction, "Untitled", false);++ waitForSwing();+ JDialog d = waitForJDialog("Export Untitled");+ assertNotNull(d);+ final GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(chooser);+ final File file = new File(GenericRunInfo.getProjectsDirPath(), "untitled.tool");++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ pressButtonByText(chooser, "Export");+ waitForSwing();++ performAction(exportAction, "Untitled", false);++ waitForSwing();+ d = waitForJDialog("Export Untitled");+ assertNotNull(d);++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ final JButton b = findButtonByText(chooser, "Export");+ SwingUtilities.invokeLater(() -> b.getActionListeners()[0].actionPerformed(null));+ waitForSwing();+ OptionDialog optD = waitForDialogComponent(OptionDialog.class);+ assertNotNull(optD);+ assertEquals("Overwrite?", optD.getTitle());++ pressButtonByText(optD.getComponent(), "Yes");+ waitForSwing();+ assertTrue(file.exists());++ file.delete();+ }++ @Test+ public void testExportToolOverwriteNo() throws Exception {+ // export using the menu action+ createTool();++ DockingActionIf exportAction = getAction("Untitled", "Export Tool");+ performAction(exportAction, "Untitled", false);++ waitForSwing();+ JDialog d = waitForJDialog("Export Untitled");+ assertNotNull(d);+ final GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(chooser);+ final File file = new File(GenericRunInfo.getProjectsDirPath(), "untitled.tool");++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ pressButtonByText(chooser, "Export");+ waitForSwing();++ performAction(exportAction, "Untitled", false);++ waitForSwing();+ d = waitForJDialog("Export Untitled");+ assertNotNull(d);++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ final JButton b = findButtonByText(chooser, "Export");+ SwingUtilities.invokeLater(() -> b.getActionListeners()[0].actionPerformed(null));+ waitForSwing();+ OptionDialog optD = waitForDialogComponent(OptionDialog.class);+ assertNotNull(optD);+ assertEquals("Overwrite?", optD.getTitle());++ pressButtonByText(optD.getComponent(), "No");+ waitForSwing();+ d = waitForJDialog("Export Untitled");+ final GhidraFileChooser ch = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(ch);+ pressButtonByText(ch, "Cancel");+ assertTrue(!d.isVisible());+ file.delete();+ }++ @Test+ public void testExportToolOverwriteCancel() throws Exception {+ // export using the menu action+ createTool();++ DockingActionIf exportAction = getAction("Untitled", "Export Tool");+ performAction(exportAction, "Untitled", false);++ waitForSwing();+ JDialog d = waitForJDialog("Export Untitled");+ assertNotNull(d);+ final GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(chooser);+ final File file = new File(GenericRunInfo.getProjectsDirPath(), "untitled.tool");++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ pressButtonByText(chooser, "Export");+ waitForSwing();++ performAction(exportAction, "Untitled", false);++ waitForSwing();+ d = waitForJDialog("Export Untitled");+ assertNotNull(d);++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ final JButton b = findButtonByText(chooser, "Export");+ SwingUtilities.invokeLater(() -> b.getActionListeners()[0].actionPerformed(null));+ waitForSwing();+ OptionDialog optD = waitForDialogComponent(OptionDialog.class);+ assertNotNull(optD);+ assertEquals("Overwrite?", optD.getTitle());++ pressButtonByText(optD.getComponent(), "Cancel");++ file.delete();+ }++ @Test+ public void testExportToolFromIcon() throws Exception {+ createTool();++ DockingActionIf exportAction = getAction("Export Tool");+ performToolButtonAction(exportAction, "Untitled", false, false);+ waitForSwing();+ JDialog d = waitForJDialog("Export Untitled");+ assertNotNull(d);+ final GhidraFileChooser chooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(chooser);+ final File file = new File(GenericRunInfo.getProjectsDirPath(), "untitled.tool");++ SwingUtilities.invokeAndWait(() -> chooser.setSelectedFile(file));+ waitForUpdateOnChooser(chooser);+ pressButtonByText(chooser, "Export");+ waitForSwing();+ assertTrue(file.exists());+ file.delete();+ }++ @Test+ public void testCloseTool() throws Exception {+ // action on tool button for running tool+ createTool();++ DockingActionIf closeAction = getAction("Close Tool");+ performToolButtonAction(closeAction, "Untitled", false, true);++ assertEquals(0, frontEndTool.getToolServices().getRunningTools().length);+ }++ private DockingActionIf getAction(String toolName, String action) {+ Set<DockingActionIf> actions =+ getActionsByOwnerAndName(frontEndTool, "FrontEndPlugin", toolName);+ for (DockingActionIf a : actions) {+ String[] menuPath = a.getMenuBarData().getMenuPath();+ if (menuPath.length > 2) {+ if (menuPath[1].indexOf(action) >= 0) {+ return a;+ }+ }+ }+ return null;+ }++ private DockingActionIf getAction(String actionName) {+ DockingActionIf action =+ AbstractDockingTest.getAction(frontEndTool, "FrontEndPlugin", actionName);+ return action;+ }++ private PluginTool createTool() throws Exception {+ DockingActionIf createAction = getAction("Create Tool");+ performAction(createAction, true);+ Tool[] tools = frontEndTool.getProject().getToolManager().getRunningTools();+ final PluginTool tool = (PluginTool) tools[0];+ runSwing(() -> {+ try {+ tool.addPlugin(CodeBrowserPlugin.class.getName());+ }+ catch (PluginException e) {+ e.printStackTrace();+ }+ });++ DockingActionIf action = getAction(tool, ToolConstants.TOOL_OWNER, "Save Tool As");+ performAction(action, false);++ waitForSwing();+ SaveToolConfigDialog saveDialog = waitForDialogComponent(SaveToolConfigDialog.class);+ pressButtonByText(saveDialog, "Save");+ waitForSwing();+ return tool;+ }++ private void performToolButtonAction(final DockingActionIf action, String name, boolean doWait,+ boolean runningTool) throws Exception {+ final ToolButton tb = findToolButton(frontEndTool.getToolFrame(), name, runningTool);+ Runnable r = () -> action.actionPerformed(new ActionContext(null, tb, tb));+ if (doWait) {+ SwingUtilities.invokeAndWait(r);+ }+ else {+ SwingUtilities.invokeLater(r);+ }+ waitForSwing();+ }++ private ToolButton findToolButton(Container parent, String toolName, boolean runningTool) {+ Component[] comps = parent.getComponents();+ for (Component comp : comps) {+ if (comp instanceof ToolButton) {+ ToolButton tb = (ToolButton) comp;+ if (tb.getToolTemplate().getName().equals(toolName) &&+ (tb.isRunningTool() == runningTool)) {+ return tb;+ }+ }+ else if (comp instanceof Container) {+ ToolButton tb = findToolButton((Container) comp, toolName, runningTool);+ if (tb != null) {+ return tb;+ }+ }+ }+ return null;+ }++ private void performAction(final DockingActionIf action, String name, boolean doWait)+ throws Exception {++ runSwing(() -> {+ JMenuItem item = new JMenuItem(name);+ action.actionPerformed(new ActionContext(null, null, item));+ }, doWait);++ waitForSwing();+ }++}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ToolConnectionTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ToolConnectionTest.javanew file mode 100644index 0000000000..04a5eaf6fe--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/ToolConnectionTest.java@@ -0,0 +1,248 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main;++import static org.junit.Assert.*;++import java.awt.Rectangle;+import java.util.Set;+import java.util.concurrent.atomic.AtomicReference;++import javax.swing.*;++import org.junit.*;++import docking.ActionContext;+import docking.action.DockingActionIf;+import ghidra.app.plugin.core.byteviewer.ByteViewerPlugin;+import ghidra.app.services.ProgramManager;+import ghidra.framework.model.Tool;+import ghidra.framework.plugintool.Plugin;+import ghidra.framework.plugintool.PluginTool;+import ghidra.framework.plugintool.util.PluginException;+import ghidra.program.database.ProgramBuilder;+import ghidra.program.model.listing.Program;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.TestEnv;++public class ToolConnectionTest extends AbstractGhidraHeadedIntegrationTest {++ private FrontEndTool frontEndTool;+ private TestEnv env;+ private ToolConnectionDialog dialog;+ private JList<?> producerList;+ private JList<?> consumerList;+ private JList<?> eventList;++ private PluginTool tool1;+ private PluginTool tool2;++ @Before+ public void setUp() throws Exception {+ env = new TestEnv();+ env.resetDefaultTools();+ frontEndTool = env.getFrontEndTool();+ env.showFrontEndTool();+ setErrorGUIEnabled(false);++ tool1 = runTool("CodeBrowser");+ tool2 = runTool("CodeBrowser");+ }++ private Program buildNotepad() throws Exception {+ ProgramBuilder builder = new ProgramBuilder("notepad", ProgramBuilder._TOY);+ builder.createMemory("test2", "0x1001000", 0x2000);+ Program p = builder.getProgram();+ p.clearUndo();+ return p;+ }++ @After+ public void tearDown() throws Exception {+ if (dialog != null) {+ close(dialog);+ }++ closeAllWindows();++ env.dispose();+ }++ @Test+ public void testConnectToolsDialog() throws Exception {++ connectTools();++ clickListRow(eventList, 1);+ pressButtonByText(dialog, "OK");++ Program p = buildNotepad();++ ProgramManager pm = tool1.getService(ProgramManager.class);+ ProgramManager pm2 = tool2.getService(ProgramManager.class);+ runSwing(() -> pm.openProgram(p.getDomainFile()));++ waitForCondition(() -> pm2.getCurrentProgram() != null,+ "Tool 2 did not open a proagram when one was opened in tool1");++ assertEquals(p, pm2.getCurrentProgram());++ env.release(p);+ }++ @Test+ public void testPluginsRemoved() throws Exception {++ connectTools();++ JCheckBox cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(cb.getText().equals("ByteBlockChange"));+ close(dialog);++ Plugin p1 = getPlugin(tool1, ByteViewerPlugin.class);+ removePlugin(tool1, p1);++ Plugin p2 = getPlugin(tool2, ByteViewerPlugin.class);+ removePlugin(tool2, p2);++ connectTools();++ cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(!cb.getText().equals("ByteBlockChange"));+ }++ @Test+ public void testPluginsAdded() throws Exception {++ connectTools();++ JCheckBox cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(cb.getText().equals("ByteBlockChange"));+ close(dialog);++ Plugin p1 = getPlugin(tool1, ByteViewerPlugin.class);+ removePlugin(tool1, p1);++ Plugin p2 = getPlugin(tool2, ByteViewerPlugin.class);+ removePlugin(tool2, p2);++ connectTools();++ cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(!cb.getText().equals("ByteBlockChange"));+ close(dialog);++ // add ByteViewer back in+ addPlugin(tool1, ByteViewerPlugin.class.getName());+ addPlugin(tool2, ByteViewerPlugin.class.getName());++ connectTools();++ cb = (JCheckBox) eventList.getModel().getElementAt(0);+ assertTrue(cb.getText().equals("ByteBlockChange"));+ close(dialog);+ }++//==================================================================================================+// Private Methods+//==================================================================================================++ private void clickListRow(JList<?> list, int row) {++ AtomicReference<Rectangle> ref = new AtomicReference<>();+ runSwing(() -> ref.set(list.getCellBounds(row, row)));++ Rectangle rect = ref.get();+ clickMouse(list, 1, rect.x + 5, rect.y + 5, 1, 0);+ }++ private void connectTools() throws Exception {+ DockingActionIf connectAction = getAction("Connect Tools");+ performAction(connectAction, true);+ dialog = waitForDialogComponent(ToolConnectionDialog.class);+ producerList = (JList<?>) findComponentByName(dialog, "Producers");+ consumerList = (JList<?>) findComponentByName(dialog, "Consumers");+ eventList = (JList<?>) findComponentByName(dialog, "Events");++ assertNotNull(producerList);+ assertNotNull(consumerList);+ assertNotNull(eventList);++ selectListItem(producerList, 0);+ selectListItem(consumerList, 1);+ }++ private void selectListItem(JList<?> list, final int index) throws Exception {+ runSwing(() -> list.setSelectedIndex(index));+ }++ private void addPlugin(final PluginTool tool, final String className) throws Exception {+ runSwing(() -> {+ try {+ tool.addPlugin(className);+ }+ catch (PluginException e) {+ e.printStackTrace();+ }+ tool.getProject().getToolManager().toolChanged(tool);+ });+ }++ private void removePlugin(final PluginTool tool, final Plugin plugin) throws Exception {+ runSwing(() -> {+ tool.removePlugins(new Plugin[] { plugin });+ tool.getProject().getToolManager().toolChanged(tool);+ });+ }++ private DockingActionIf getAction(String actionName) {+ DockingActionIf action = getAction(frontEndTool, "FrontEndPlugin", actionName);+ return action;+ }++ private DockingActionIf getAction(String toolName, String action) {++ Set<DockingActionIf> actions =+ getActionsByOwnerAndName(frontEndTool, "FrontEndPlugin", toolName);+ for (DockingActionIf a : actions) {+ String[] menuPath = a.getMenuBarData().getMenuPath();+ if (menuPath.length > 2) {+ if (menuPath[1].indexOf(action) >= 0) {+ return a;+ }+ }+ }+ return null;+ }++ private PluginTool runTool(String toolName) throws Exception {+ DockingActionIf runAction = getAction(toolName, "Run Tool");+ assertNotNull(runAction);// if action is null, the name of the tool changed+ performAction(runAction, toolName, true);+ Tool[] tools = frontEndTool.getToolServices().getRunningTools();+ return (PluginTool) tools[tools.length - 1];+ }++ private void performAction(final DockingActionIf action, String name, boolean doWait)+ throws Exception {++ JMenuItem item = new JMenuItem(name);+ Runnable r = () -> action.actionPerformed(new ActionContext(null, null, item));+ runSwing(r, doWait);+ waitForSwing();+ }++}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/AbstractVersionControlActionTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/AbstractVersionControlActionTest.javanew file mode 100644index 0000000000..34bdabe493--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/AbstractVersionControlActionTest.java@@ -0,0 +1,237 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main.datatree;++import static org.junit.Assert.*;++import java.awt.Window;+import java.io.IOException;+import java.util.Set;+import java.util.concurrent.atomic.AtomicReference;++import javax.swing.*;++import org.junit.After;+import org.junit.Before;++import docking.ActionContext;+import docking.action.DockingActionIf;+import docking.widgets.table.GTable;+import docking.widgets.table.threaded.ThreadedTableModel;+import docking.widgets.tree.GTreeNode;+import ghidra.framework.model.DomainFolder;+import ghidra.framework.store.Version;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.SourceType;+import ghidra.program.model.symbol.SymbolTable;+import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.test.FrontEndTestEnv;+import ghidra.test.FrontEndTestEnv.ModifyProgramCallback;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.InvalidInputException;+import ghidra.util.task.TaskMonitor;++public class AbstractVersionControlActionTest extends AbstractGhidraHeadedIntegrationTest {++ protected static final String PROGRAM_A = FrontEndTestEnv.PROGRAM_A;+ protected static final String PROGRAM_B = "Program_B";+ protected static final String PROGRAM_C = "Program_C";+ protected FrontEndTestEnv frontEnd;++ @Before+ public void setUp() throws Exception {++ frontEnd = new FrontEndTestEnv();++ Program p1 = frontEnd.buildProgram(this);+ DomainFolder rootFolder = frontEnd.getRootFolder();++ // Program A created by the FrontEndTestEnv+ rootFolder.createFile(PROGRAM_B, p1, TaskMonitor.DUMMY);++ Program p2 = frontEnd.buildProgram(this);+ rootFolder.createFile(PROGRAM_C, p2, TaskMonitor.DUMMY);++ p1.release(this);+ p2.release(this);++ waitForTree();+ frontEnd.waitForTreeNode(PROGRAM_C);+ }++ @After+ public void tearDown() throws Exception {+ frontEnd.dispose();+ }++ protected void addToVersionControl(GTreeNode node, boolean keepCheckedOut) throws Exception {+ frontEnd.addToVersionControl(node, keepCheckedOut);+ }++ protected void assertVersionAtRow(final VersionHistoryTableModel model, final int row,+ int expectedVersion, String comment) {++ final AtomicReference<Version> ref = new AtomicReference<>();+ runSwing(() -> {+ Version version = model.getVersionAt(row);+ ref.set(version);+ });++ Version version = ref.get();+ assertEquals("Version number is wrong for row " + row, expectedVersion,+ version.getVersion());+ assertEquals("Version comment is wrong: ", comment, version.getComment());+ }++ protected void checkout(final GTreeNode node) throws Exception {+ frontEnd.checkout((DomainFileNode) node);+ }++ protected void clearSelectionPaths() throws Exception {+ frontEnd.clearTreeSelection();+ }++ protected void createHistoryEntry(Program program, String symbolName)+ throws InvalidInputException, IOException, CancelledException {+ int transactionID = program.startTransaction("test");+ try {+ SymbolTable symTable = program.getSymbolTable();+ symTable.createLabel(program.getMinAddress().getNewAddress(0x010001000), symbolName,+ SourceType.USER_DEFINED);+ }+ finally {+ program.endTransaction(transactionID, true);+ program.save(null, TaskMonitor.DUMMY);+ }+ }++ protected void doCreateVersions() throws Exception {++ frontEnd.createMultipleCheckins();+ }++ protected void editProgram(Program program, ModifyProgramCallback modifyProgramCallback)+ throws CancelledException, IOException {+ frontEnd.editProgram(program, modifyProgramCallback);+ }++ // TODO delete this--do we need 'apply to all'?+ protected void fillOutCheckInDialog() {++ VersionControlDialog dialog = waitForDialogComponent(VersionControlDialog.class);+ assertNotNull(dialog);+ JTextArea textArea = findComponent(dialog, JTextArea.class);+ assertNotNull(textArea);+ JCheckBox cb = findComponent(dialog, JCheckBox.class);+ assertNotNull(cb);+ runSwing(() -> {+ textArea.setText("This is a test");+ cb.setSelected(false);+ });+ pressButtonByText(dialog, "Apply to All");+ }++ protected DockingActionIf getAction(String actionName) {+ return frontEnd.getAction(actionName);+ }++ protected DockingActionIf getDeleteAction(VersionHistoryDialog dialog) {+ waitForSwing();+ Set<DockingActionIf> dialogActions = dialog.getActions();+ for (DockingActionIf action : dialogActions) {+ if (action.getName().equals("Delete Version")) {+ return action;+ }+ }+ fail("Unable to find 'Delete Version' action");+ return null; // can't get here+ }++ protected ActionContext getDomainFileActionContext(GTreeNode... nodes) {+ return frontEnd.getDomainFileActionContext(nodes);+ }++ protected JPopupMenu getPopupMenu() {+ Set<Window> allWindows = getAllWindows();+ for (Window window : allWindows) {+ JPopupMenu popup = findComponent(window, JPopupMenu.class);+ if (popup != null) {+ return popup;+ }+ }+ return null;+ }++ protected void performFrontEndAction(DockingActionIf action) {+ frontEnd.performFrontEndAction(action);+ }++ protected void showHistory(final GTreeNode node) {+ final DockingActionIf historyAction = getAction("Show History");+ runSwing(() -> historyAction.actionPerformed(getDomainFileActionContext(node)));+ }++ ////////////////////////////////////////////////////////////////////+ protected void waitForBusyTable(GTable table) {+ ThreadedTableModel<?, ?> model = (ThreadedTableModel<?, ?>) table.getModel();+ waitForTableModel(model);+ }++ protected void waitForTree() {+ frontEnd.waitForTree();+ }++ protected DomainFileNode getNode(String name) {+ return frontEnd.getTreeNode(name);+ }++ protected DomainFolderNode getFolderNode(String name) {+ return frontEnd.waitForFolderNode(name);+ }++ protected void selectNode(GTreeNode node) {+ selectNodes(node);+ }++ protected void selectNodes(GTreeNode... nodes) {+ frontEnd.selectNodes(nodes);+ }++ protected void expandNode(GTreeNode node) {+ frontEnd.expandNode(node);+ }++ protected void selectInTable(GTable table, GTreeNode node) {++ // assume name is column 0+ String name = node.getName();+ int nameCol = 0;+ int n = table.getRowCount();+ for (int i = 0; i < n; i++) {+ int row = i;+ Object value = runSwing(() -> table.getValueAt(row, nameCol));+ if (value == null) {+ continue;+ }++ if (name.equals(value.toString())) {+ table.changeSelection(row, 0, false, false);+ return;+ }+ }++ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction1Test.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction1Test.javanew file mode 100644index 0000000000..7af8827267--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction1Test.java@@ -0,0 +1,664 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main.datatree;++import static org.junit.Assert.*;++import java.awt.Component;+import java.awt.Rectangle;+import java.awt.event.*;+import java.util.List;++import javax.swing.*;++import org.junit.Assert;+import org.junit.Test;++import docking.DialogComponentProvider;+import docking.action.DockingActionIf;+import docking.widgets.table.*;+import docking.widgets.tree.GTreeNode;+import ghidra.framework.model.*;+import ghidra.framework.store.ItemCheckoutStatus;+import ghidra.framework.store.Version;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.SourceType;+import ghidra.program.model.symbol.SymbolTable;+import ghidra.util.task.TaskMonitor;+import resources.MultiIcon;+import resources.ResourceManager;++/**+ * Tests for version control (not multi user).+ */+public class VersionControlAction1Test extends AbstractVersionControlActionTest {++ @Test+ public void testUndoCheckout() throws Exception {+ // add program to version control+ GTreeNode node = getNode(PROGRAM_A);+ addToVersionControl(node, false);++ selectNode(node);+ final DockingActionIf action = getAction("CheckOut");+ runSwing(() -> action.actionPerformed(getDomainFileActionContext(node)), false);+ waitForSwing();++ waitForTasks();+ final DockingActionIf undoAction = getAction("UndoCheckOut");+ runSwing(() -> undoAction.actionPerformed(getDomainFileActionContext(node)));++ waitForSwing();+ waitForTasks();++ DomainFile df = ((DomainFileNode) node).getDomainFile();+ assertTrue(!df.isCheckedOut());+ Icon icon = df.getIcon(false);+ Icon[] icons = ((MultiIcon) icon).getIcons();+ Icon checkOutIcon = ResourceManager.loadImage("images/checkex.png");+ for (Icon element : icons) {+ if (checkOutIcon.equals(element)) {+ Assert.fail("Found unexpected check out icon!");+ }+ }+ }++ @Test+ public void testUndoCheckOutModified() throws Exception {+ GTreeNode node = getNode(PROGRAM_A);+ addToVersionControl(node, false);++ selectNode(node);+ DockingActionIf action = getAction("CheckOut");+ performAction(action, getDomainFileActionContext(node), false);++ waitForTasks();++ // make a change to the program+ DomainFile df = ((DomainFileNode) node).getDomainFile();+ Program program = (Program) df.getDomainObject(this, true, false, TaskMonitor.DUMMY);+ int transactionID = program.startTransaction("test");+ try {+ program.getSymbolTable().createNameSpace(null, "myNamespace", SourceType.USER_DEFINED);+ }+ finally {+ program.endTransaction(transactionID, true);+ program.save(null, TaskMonitor.DUMMY);+ }+ program.release(this);+ program.flushEvents();++ DockingActionIf undoAction = getAction("UndoCheckOut");+ performAction(undoAction, getDomainFileActionContext(node), false);+ UndoActionDialog dialog = waitForDialogComponent(UndoActionDialog.class);+ assertNotNull(dialog);++ JCheckBox cb = (JCheckBox) findAbstractButtonByText(dialog.getComponent(),+ "Save copy of the file with a .keep extension");+ assertNotNull(cb);+ assertTrue(cb.isSelected());++ pressButtonByText(dialog, "OK");+ waitForTasks();++ df = ((DomainFileNode) node).getDomainFile();+ assertTrue(!df.isCheckedOut());+ Icon icon = df.getIcon(false);+ Icon[] icons = ((MultiIcon) icon).getIcons();+ Icon checkOutIcon = ResourceManager.loadImage("images/checkex.png");+ for (Icon element : icons) {+ if (checkOutIcon.equals(element)) {+ Assert.fail("Found unexpected check out icon!");+ }+ }++ DomainFileNode keepNode = getNode(PROGRAM_A + ".keep");+ assertNotNull(keepNode);+ }++ @Test+ public void testUndoHijack() throws Exception {++ // check out a file+ GTreeNode node = getNode(PROGRAM_A);+ addToVersionControl(node, false);++ selectNode(node);+ final DockingActionIf action = getAction("CheckOut");+ SwingUtilities.invokeLater(() -> action.actionPerformed(getDomainFileActionContext(node)));+ waitForSwing();++ waitForTasks();++ DockingActionIf undoHijackAction = getAction("Undo Hijack");+ assertTrue(!undoHijackAction.isEnabledForContext(getDomainFileActionContext(node)));++ // make a change to the program+ DomainFile df = ((DomainFileNode) node).getDomainFile();+ Program program = (Program) df.getDomainObject(this, true, false, TaskMonitor.DUMMY);+ int transactionID = program.startTransaction("test");+ try {+ program.getSymbolTable().createNameSpace(null, "myNamespace", SourceType.USER_DEFINED);+ }+ finally {+ program.endTransaction(transactionID, true);+ program.save(null, TaskMonitor.DUMMY);+ }+ program.release(this);+ program.flushEvents();++ // terminate the checkout to get a hijacked file+ ItemCheckoutStatus[] items = df.getCheckouts();+ assertEquals(1, items.length);+ df.terminateCheckout(items[0].getCheckoutId());+ waitForSwing();++ clearSelectionPaths();++ selectNode(node);+ assertTrue(undoHijackAction.isEnabledForContext(getDomainFileActionContext(node)));+ waitForSwing();++ // undo the hijack+ performFrontEndAction(undoHijackAction);+ UndoActionDialog dialog = waitForDialogComponent(UndoActionDialog.class);+ assertNotNull(dialog);++ DomainFilesPanel panel = findComponent(dialog.getComponent(), DomainFilesPanel.class);+ assertNotNull(panel);++ DomainFile[] files = panel.getSelectedDomainFiles();+ assertEquals(1, files.length);+ assertEquals(df, files[0]);++ assertTrue(dialog.saveCopy());+ pressButtonByText(dialog.getComponent(), "OK");++ waitForSwing();+ waitForTasks();++ assertNotNull(getNode(PROGRAM_A + ".keep"));+ assertTrue(!undoHijackAction.isEnabledForContext(getDomainFileActionContext(node)));+ }++ @Test+ public void testMultipleCheckIns() throws Exception {+ GTreeNode node = getNode(PROGRAM_A);+ addToVersionControl(node, false);+ GTreeNode xnode = getNode(PROGRAM_B);+ addToVersionControl(xnode, false);++ selectNodes(node, xnode);++ DockingActionIf action = getAction("CheckOut");+ performAction(action, getDomainFileActionContext(node, xnode), false);++ DialogComponentProvider dialog = waitForDialogComponent("Confirm Bulk Checkout");+ pressButtonByText(dialog, "Yes");++ waitForTasks();++ // make some changes to check in+ Program program = (Program) ((DomainFileNode) node).getDomainFile().getDomainObject(this,+ true, false, TaskMonitor.DUMMY);+ editProgram(program, (p) -> {+ SymbolTable symTable = p.getSymbolTable();+ symTable.createLabel(p.getMinAddress().getNewAddress(0x010001000), "fred",+ SourceType.USER_DEFINED);+ });++ program = (Program) ((DomainFileNode) xnode).getDomainFile().getDomainObject(this, true,+ false, TaskMonitor.DUMMY);+ editProgram(program, (p) -> {+ SymbolTable symTable = p.getSymbolTable();+ symTable.createLabel(p.getMinAddress(), "bob", SourceType.USER_DEFINED);+ });++ DockingActionIf checkInAction = getAction("CheckIn");+ performAction(checkInAction, getDomainFileActionContext(node, xnode), false);++ fillOutCheckInDialog();++ waitForTasks();++ DomainFile df = ((DomainFileNode) node).getDomainFile();+ assertTrue(!df.isCheckedOut());+ df = ((DomainFileNode) xnode).getDomainFile();+ assertTrue(!df.isCheckedOut());+ }++ @Test+ public void testShowHistory() throws Exception {+ // create 3 versions of the program++ GTreeNode programNode = getNode(PROGRAM_A);+ addToVersionControl(programNode, false);++ checkout(programNode);++ Program program =+ (Program) ((DomainFileNode) programNode).getDomainFile().getDomainObject(this, true,+ false, TaskMonitor.DUMMY);++ createHistoryEntry(program, "Symbol1");+ frontEnd.checkIn(programNode, "This is checkin 1");++ // make another change+ createHistoryEntry(program, "Symbol2");+ frontEnd.checkIn(programNode, "This is checkin 2");++ // make one more change+ createHistoryEntry(program, "Symbol3");+ frontEnd.checkIn(programNode, "This is checkin 3");++ program.release(this);++ showHistory(programNode);++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);+ assertNotNull(dialog);++ VersionHistoryPanel panel = findComponent(dialog, VersionHistoryPanel.class);+ assertNotNull(panel);+ VersionHistoryTableModel model = panel.getVersionHistoryTableModel();+ assertEquals(4, model.getRowCount());++ JTable table = findComponent(dialog, JTable.class);+ AbstractSortedTableModel<?> m = (AbstractSortedTableModel<?>) table.getModel();+ assertEquals(VersionHistoryTableModel.VERSION_COL, m.getPrimarySortColumnIndex());++ TableSortState sortState = m.getTableSortState();+ assertEquals("More columns sorted than expected", 1, sortState.getSortedColumnCount());+ List<ColumnSortState> sortStates = sortState.getAllSortStates();+ ColumnSortState columnSortState = sortStates.get(0);+ int index = columnSortState.getColumnModelIndex();+ assertEquals("Model not sorted on correct column", VersionHistoryTableModel.VERSION_COL,+ index);+ assertFalse("Column not sorted descending", columnSortState.isAscending());++ // sorted descending, so row 0 is version 4, row 1 is version 3, etc+ assertVersionAtRow(model, 1, 3, "This is checkin 2");+ assertVersionAtRow(model, 2, 2, "This is checkin 1");++ runSwing(() -> dialog.close());+ }++ @Test+ public void testOpenVersionDoubleClick() throws Exception {++ // create 3 versions of the program+ doCreateVersions();++ DomainFileNode node = getNode(PROGRAM_A);+ selectNode(node);+ final DockingActionIf historyAction = getAction("Show History");+ runSwing(() -> historyAction.actionPerformed(getDomainFileActionContext(node)));++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);++ GTable table = findComponent(dialog, GTable.class);+ runSwing(() -> table.selectRow(0));++ VersionHistoryPanel panel = findComponent(dialog, VersionHistoryPanel.class);++ VersionHistoryTableModel tm = panel.getVersionHistoryTableModel();+ Version version = runSwing(() -> tm.getVersionAt(0));++ Rectangle rect = table.getCellRect(0, 0, true);+ final MouseEvent event = new MouseEvent(table, MouseEvent.MOUSE_CLICKED,+ System.currentTimeMillis(), 0, rect.x, rect.y, 2, false, MouseEvent.BUTTON1);++ runSwing(() -> {+ MouseListener[] mls = table.getMouseListeners();+ for (final MouseListener ml : mls) {+ ml.mouseClicked(event);+ if (event.isConsumed()) {+ break;+ }+ }+ });++ waitForSwing();++ List<Tool> tools = frontEnd.getTools();+ assertEquals(1, tools.size());++ DomainFile[] dfs = tools.get(0).getDomainFiles();+ assertEquals(1, dfs.length);++ assertTrue(dfs[0].isReadOnly());+ assertEquals(version.getVersion(), dfs[0].getVersion());++ runSwing(() -> dialog.close());++ }++ @Test+ public void testOpenVersion() throws Exception {++ // create 3 versions of the program+ doCreateVersions();+ GTreeNode node = getNode(PROGRAM_A);++ selectNode(node);+ DockingActionIf historyAction = getAction("Show History");+ performAction(historyAction, getDomainFileActionContext(node), true);++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);++ VersionHistoryPanel panel = findComponent(dialog, VersionHistoryPanel.class);++ JTable table = findComponent(dialog, JTable.class);+ VersionHistoryTableModel tm = panel.getVersionHistoryTableModel();+ Version version = runSwing(() -> tm.getVersionAt(0));++ runSwing(() -> table.setRowSelectionInterval(0, 0));++ Rectangle rect = table.getCellRect(0, 0, true);++ final MouseEvent event = new MouseEvent(table, MouseEvent.MOUSE_PRESSED,+ System.currentTimeMillis(), 0, rect.x, rect.y, 1, true);++ runSwing(() -> {+ MouseListener[] mls = table.getMouseListeners();+ for (final MouseListener ml : mls) {+ ml.mousePressed(event);+ if (event.isConsumed()) {+ break;+ }+ }+ });++ JPopupMenu popup = getPopupMenu();+ assertNotNull(popup);++ int n = popup.getComponentCount();+ for (int i = 0; i < n; i++) {+ Component comp = popup.getComponent(i);+ if (comp instanceof JMenuItem) {+ if (((JMenuItem) comp).getText().equals("Open in Default Tool")) {+ final ActionListener al = ((JMenuItem) comp).getActionListeners()[0];+ runSwing(new Runnable() {+ @Override+ public void run() {+ al.actionPerformed(new ActionEvent(this, 0, null));+ }+ });+ break;+ }+ }+ }++ waitForSwing();++ List<Tool> tools = frontEnd.getTools();+ assertEquals(1, tools.size());++ DomainFile[] dfs = tools.get(0).getDomainFiles();+ assertEquals(1, dfs.length);++ assertTrue(dfs[0].isReadOnly());+ assertEquals(version.getVersion(), dfs[0].getVersion());++ runSwing(() -> dialog.close());++ }++ @Test+ public void testOpenVersionWith() throws Exception {++ // create 3 versions of the program+ doCreateVersions();++ GTreeNode node = getNode(PROGRAM_A);+ selectNode(node);++ DockingActionIf historyAction = getAction("Show History");+ performAction(historyAction, getDomainFileActionContext(node), true);++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);++ GTable table = findComponent(dialog, GTable.class);+ runSwing(() -> table.selectRow(0));++ VersionHistoryPanel panel = findComponent(dialog, VersionHistoryPanel.class);+ VersionHistoryTableModel tm = panel.getVersionHistoryTableModel();+ Version version = runSwing(() -> tm.getVersionAt(0));++ Rectangle rect = table.getCellRect(0, 0, true);+ final MouseEvent event = new MouseEvent(table, MouseEvent.MOUSE_PRESSED,+ System.currentTimeMillis(), 0, rect.x, rect.y, 1, true);++ runSwing(() -> {+ MouseListener[] mls = table.getMouseListeners();+ for (final MouseListener ml : mls) {+ ml.mousePressed(event);+ if (event.isConsumed()) {+ break;+ }+ }+ });++ JPopupMenu popup = getPopupMenu();+ assertNotNull(popup);++ int n = popup.getComponentCount();+ for (int i = 0; i < n; i++) {+ Component comp = popup.getComponent(i);+ if (comp instanceof JMenu) {+ JMenu menu = (JMenu) comp;+ int nItems = menu.getItemCount();+ for (int j = 0; j < nItems; j++) {+ Component item = menu.getMenuComponent(j);+ if (item instanceof JMenuItem) {+ if (((JMenuItem) item).getText().equals("CodeBrowser")) {+ final ActionListener al = ((JMenuItem) item).getActionListeners()[0];+ runSwing(new Runnable() {+ @Override+ public void run() {+ al.actionPerformed(new ActionEvent(this, 0, null));+ }+ });+ break;+ }+ }+ }+ }+ }++ waitForSwing();++ List<Tool> tools = frontEnd.getTools();+ assertEquals(1, tools.size());++ DomainFile[] dfs = tools.get(0).getDomainFiles();+ assertEquals(1, dfs.length);++ assertTrue(dfs[0].isReadOnly());+ assertEquals(version.getVersion(), dfs[0].getVersion());++ runSwing(() -> dialog.close());++ }++ @Test+ public void testRefreshFolder() throws Exception {++ doCreateVersions();++ DomainFolder rootFolder = frontEnd.getRootFolder();+ DomainFolder folder = rootFolder.createFolder("myFolder");++ Program p = frontEnd.buildProgram(this);+ folder.createFile("My_Program", p, TaskMonitor.DUMMY);+ p.release(this);++ waitForSwing();++ GTreeNode node = getNode(PROGRAM_A);+ DomainFile df = ((DomainFileNode) node).getDomainFile();+ df.copyTo(folder, TaskMonitor.DUMMY);++ waitForSwing();++ final GTreeNode fnode = getFolderNode("myFolder");+ assertNotNull(fnode);+ expandNode(fnode);+ assertEquals(2, fnode.getChildCount());+ selectNode(fnode);++ DockingActionIf action = getAction("Refresh");+ performFrontEndAction(action);+ assertEquals(2, fnode.getChildCount());+ }++ @Test+ public void testFindMyCheckouts() throws Exception {+ doCreateVersions();++ DomainFolder rootFolder = frontEnd.getRootFolder();+ DomainFolder folder = rootFolder.createFolder("myFolder_1");+ folder = folder.createFolder("myFolder_2");+ Program p = frontEnd.buildProgram(this);+ folder.createFile("My_Program", p, TaskMonitor.DUMMY);+ p.release(this);++ GTreeNode node = getFolderNode("myFolder_1");+ assertNotNull(node);+ node = node.getChild("myFolder_2");+ assertNotNull(node);+ node = node.getChild("My_Program");+ assertNotNull(node);+ addToVersionControl(node, true);++ GTreeNode rootNode = frontEnd.getRootNode();+ selectNode(rootNode);+ DockingActionIf action = getAction("Find Checkouts");+ performFrontEndAction(action);++ FindCheckoutsDialog dialog = waitForDialogComponent(FindCheckoutsDialog.class);+ assertNotNull(dialog);++ final GTable table = findComponent(dialog.getComponent(), GTable.class);+ assertNotNull(table);+ waitForBusyTable(table);++ FindCheckoutsTableModel model = (FindCheckoutsTableModel) table.getModel();++ assertEquals(2, model.getRowCount());++ assertEquals(4, model.getColumnCount());++ JButton checkInButton =+ findButtonByIcon(dialog, ResourceManager.loadImage("images/vcCheckIn.png"));++ assertNotNull(checkInButton);++ JButton undoCheckoutButton =+ findButtonByIcon(dialog, ResourceManager.loadImage("images/vcUndoCheckOut.png"));+ assertNotNull(undoCheckoutButton);++ assertTrue(!checkInButton.isEnabled());+ assertTrue(!undoCheckoutButton.isEnabled());++ // make a selection in the table+ selectInTable(table, node);+ assertTrue(checkInButton.isEnabled());+ assertTrue(undoCheckoutButton.isEnabled());++ CheckoutInfo checkoutInfo = model.getRowObject(0);+ DomainFile file = checkoutInfo.getFile();+ DomainFolder parent = file.getParent();+ assertEquals("/myFolder_1/myFolder_2", parent.getPathname());+ pressButtonByText(dialog, "Dismiss");+ }++ @Test+ public void testUndoCheckoutFromFindDialog() throws Exception {+ GTreeNode node = getNode(PROGRAM_B);+ addToVersionControl(node, true);+ node = getNode(PROGRAM_C);+ addToVersionControl(node, true);++ GTreeNode rootNode = frontEnd.getRootNode();+ selectNode(rootNode);++ DockingActionIf action = getAction("Find Checkouts");+ performFrontEndAction(action);++ FindCheckoutsDialog dialog = waitForDialogComponent(FindCheckoutsDialog.class);+ assertNotNull(dialog);++ final GTable table = findComponent(dialog.getComponent(), GTable.class);+ assertNotNull(table);+ waitForBusyTable(table);++ FindCheckoutsTableModel model = (FindCheckoutsTableModel) table.getModel();+ assertEquals(2, model.getRowCount());++ selectInTable(table, node);++ JButton undoCheckoutButton =+ findButtonByIcon(dialog, ResourceManager.loadImage("images/vcUndoCheckOut.png"));+ assertNotNull(undoCheckoutButton);+ assertTrue(undoCheckoutButton.isEnabled());+ pressButton(undoCheckoutButton);++ waitForBusyTable(table);+ assertEquals(1, model.getRowCount());+ runSwing(() -> dialog.close());+ }++ @Test+ public void testUndoCheckoutFromFindDialogMultiSelection() throws Exception {+ GTreeNode node = getNode(PROGRAM_B);+ addToVersionControl(node, true);+ node = getNode(PROGRAM_C);+ addToVersionControl(node, true);++ GTreeNode rootNode = frontEnd.getRootNode();+ selectNode(rootNode);++ DockingActionIf action = getAction("Find Checkouts");+ performFrontEndAction(action);++ FindCheckoutsDialog dialog = waitForDialogComponent(FindCheckoutsDialog.class);++ assertNotNull(dialog);++ final GTable table = findComponent(dialog.getComponent(), GTable.class);+ assertNotNull(table);+ waitForBusyTable(table);++ FindCheckoutsTableModel model = (FindCheckoutsTableModel) table.getModel();+ assertEquals(2, model.getRowCount());++ runSwing(() -> {+ ListSelectionModel selectionModel = table.getSelectionModel();+ selectionModel.setSelectionInterval(0, 1); // both rows+ });++ JButton undoCheckoutButton =+ findButtonByIcon(dialog, ResourceManager.loadImage("images/vcUndoCheckOut.png"));+ assertNotNull(undoCheckoutButton);+ assertTrue(undoCheckoutButton.isEnabled());+ pressButton(undoCheckoutButton);++ waitForBusyTable(table);+ assertEquals(0, model.getRowCount());+ runSwing(() -> dialog.close());+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.javanew file mode 100644index 0000000000..39b24dc9db--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/framework/main/datatree/VersionControlAction2Test.java@@ -0,0 +1,436 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.framework.main.datatree;++import static org.junit.Assert.*;++import java.util.Set;++import javax.swing.*;++import org.junit.Assert;+import org.junit.Test;++import docking.ActionContext;+import docking.action.DockingActionIf;+import docking.widgets.MultiLineLabel;+import docking.widgets.OptionDialog;+import docking.widgets.table.GTable;+import docking.widgets.tree.GTreeNode;+import ghidra.framework.main.projectdata.actions.VersionControlAction;+import ghidra.framework.model.DomainFile;+import ghidra.framework.model.DomainFolder;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.SourceType;+import ghidra.program.model.symbol.SymbolTable;+import ghidra.util.task.TaskMonitor;+import resources.MultiIcon;+import resources.ResourceManager;++/**+ * Tests for version control (not multi user).+ */+public class VersionControlAction2Test extends AbstractVersionControlActionTest {++ @Test+ public void testActionsEnabledForFile() throws Exception {++ GTreeNode node = getNode(PROGRAM_C);+ selectNode(node);++ Set<DockingActionIf> actions = frontEnd.getFrontEndActions();+ for (DockingActionIf action : actions) {++ if (!(action instanceof VersionControlAction)) {+ continue;+ }+ String actionName = action.getName();+ ActionContext context = getDomainFileActionContext(node);+ if (actionName.equals("Add to Version Control")) {+ assertTrue(action.isEnabledForContext(context));+ }+ else {+ assertTrue(!action.isEnabledForContext(context));+ }+ if (actionName.equals("Find Checkouts")) {+ assertTrue(!action.isAddToPopup(context));+ }+ else {+ assertTrue(action.isAddToPopup(context));+ }+ }+ }++ @Test+ public void testActionsEnabledForFolder() throws Exception {++ DomainFolder rootFolder = frontEnd.getRootFolder();+ DomainFolder f = rootFolder.createFolder("myFolder");+ waitForSwing();++ Program p = frontEnd.buildProgram(this);+ f.createFile("Sample", p, TaskMonitor.DUMMY);+ p.release(this);++ waitForSwing();+ GTreeNode node = getFolderNode("myFolder");+ assertNotNull(node);++ expandNode(node);+ selectNode(node);++ Set<DockingActionIf> actions = frontEnd.getFrontEndActions();+ for (DockingActionIf action : actions) {+ if (!(action instanceof VersionControlAction)) {+ continue;+ }+ if (action.getName().equals("Find Checkouts")) {+ assertTrue(action.isEnabledForContext(getDomainFileActionContext(node)));+ }+ else {+ assertTrue(!action.isEnabledForContext(getDomainFileActionContext(node)));+ }+ }+ }++ @Test+ public void testAddToVersionControlKeepCheckedOut() throws Exception {+ GTreeNode node = getNode(PROGRAM_C);+ selectNode(node);++ DockingActionIf action = getAction("Add to Version Control");++ performAction(action, getDomainFileActionContext(node), false);++ VersionControlDialog dialog = waitForDialogComponent(VersionControlDialog.class);+ assertNotNull(dialog);+ JTextArea textArea = findComponent(dialog, JTextArea.class);+ assertNotNull(textArea);+ runSwing(() -> textArea.setText("This is a test"));+ pressButtonByText(dialog, "OK");+ waitForTasks();+ DomainFile df = ((DomainFileNode) node).getDomainFile();+ assertTrue(df.isVersioned());+ assertTrue(df.isCheckedOut());+ assertEquals(1, df.getLatestVersion());+ }++ @Test+ public void testAddToVersionControl() throws Exception {+ GTreeNode node = getNode(PROGRAM_C);++ frontEnd.addToVersionControl(node, false);++ DomainFile df = ((DomainFileNode) node).getDomainFile();+ assertTrue(!df.isCheckedOut());+ assertEquals(1, df.getLatestVersion());+ }++ @Test+ public void testAddMultipleToVersionControl() throws Exception {+ GTreeNode nodeA = getNode(PROGRAM_A);+ GTreeNode nodeC = getNode(PROGRAM_C);+ selectNodes(nodeA, nodeC);++ final DockingActionIf action = getAction("Add to Version Control");+ SwingUtilities.invokeLater(+ () -> action.actionPerformed(getDomainFileActionContext(nodeA, nodeC)));+ waitForSwing();+ VersionControlDialog dialog = waitForDialogComponent(VersionControlDialog.class);+ assertNotNull(dialog);+ final JTextArea textArea = findComponent(dialog, JTextArea.class);+ assertNotNull(textArea);+ final JCheckBox cb = findComponent(dialog, JCheckBox.class);+ assertNotNull(cb);+ runSwing(() -> {+ textArea.setText("This is a test");+ cb.setSelected(false);+ });+ pressButtonByText(dialog, "Apply to All");+ waitForTasks();+ DomainFile df = ((DomainFileNode) nodeC).getDomainFile();+ assertTrue(df.isVersioned());+ assertTrue(!df.isCheckedOut());+ assertEquals(1, df.getLatestVersion());++ df = ((DomainFileNode) nodeA).getDomainFile();+ assertTrue(df.isVersioned());+ assertTrue(!df.isCheckedOut());+ assertEquals(1, df.getLatestVersion());+ }++ @Test+ public void testCheckOut() throws Exception {+ // add program to version control+ final GTreeNode node = getNode(PROGRAM_A);+ addToVersionControl(node, false);++ selectNode(node);+ final DockingActionIf action = getAction("CheckOut");+ SwingUtilities.invokeLater(() -> action.actionPerformed(getDomainFileActionContext(node)));+ waitForSwing();+ waitForTasks();+ DomainFile df = ((DomainFileNode) node).getDomainFile();+ assertTrue(df.isCheckedOut());+ Icon icon = df.getIcon(false);+ assertTrue(icon instanceof MultiIcon);+ Icon[] icons = ((MultiIcon) icon).getIcons();+ Icon checkOutIcon = ResourceManager.loadImage("images/checkex.png");+ boolean found = false;+ for (Icon element : icons) {+ if (checkOutIcon.equals(element)) {+ found = true;+ break;+ }+ }+ if (!found) {+ Assert.fail("Did not find checkout icon!");+ }+ }++ @Test+ public void testCheckIn() throws Exception {+ final GTreeNode node = getNode(PROGRAM_A);+ addToVersionControl(node, false);++ selectNode(node);+ final DockingActionIf action = getAction("CheckOut");+ runSwing(() -> action.actionPerformed(getDomainFileActionContext(node)), false);+ waitForSwing();+ waitForTasks();++ Program program = (Program) ((DomainFileNode) node).getDomainFile().getDomainObject(this,+ true, false, TaskMonitor.DUMMY);+ int transactionID = program.startTransaction("test");+ try {+ SymbolTable symTable = program.getSymbolTable();+ symTable.createLabel(program.getMinAddress().getNewAddress(0x010001000), "fred",+ SourceType.USER_DEFINED);+ }+ finally {+ program.endTransaction(transactionID, true);+ program.save(null, TaskMonitor.DUMMY);+ }+ program.release(this);+ final DockingActionIf checkInAction = getAction("CheckIn");+ runSwing(() -> checkInAction.actionPerformed(getDomainFileActionContext(node)), false);+ waitForSwing();+ VersionControlDialog dialog = waitForDialogComponent(VersionControlDialog.class);+ assertNotNull(dialog);+ final JTextArea textArea = findComponent(dialog, JTextArea.class);+ assertNotNull(textArea);+ final JCheckBox cb = findComponent(dialog, JCheckBox.class);+ assertNotNull(cb);+ runSwing(() -> {+ textArea.setText("This is a test");+ cb.setSelected(false);+ });+ pressButtonByText(dialog, "OK");+ waitForTasks();+ DomainFile df = ((DomainFileNode) node).getDomainFile();+ assertTrue(!df.isCheckedOut());++ }++ @Test+ public void testDeleteVersionCheckedOut() throws Exception {+ // cannot delete a version that is checked out+ setErrorGUIEnabled(true);// expect an error dialog+ // create 3 versions of the program+ doCreateVersions();+ final GTreeNode node = getNode(PROGRAM_A);++ selectNode(node);+ final DockingActionIf historyAction = getAction("Show History");+ runSwing(() -> historyAction.actionPerformed(getDomainFileActionContext(node)));++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);+ DockingActionIf deleteAction = getDeleteAction(dialog);++ GTable table = findComponent(dialog, GTable.class);+ runSwing(() -> table.selectRow(0));+ performAction(deleteAction, false);++ // cannot delete a file that is checked out+ OptionDialog d = waitForDialogComponent(OptionDialog.class);+ assertNotNull(d);++ MultiLineLabel label = findComponent(d.getComponent(), MultiLineLabel.class);+ assertNotNull(label);+ assertEquals("File version has one or more checkouts.", label.getLabel());++ runSwing(() -> d.close());+ }++ @Test+ public void testDeleteVersionNotFirstOrLast() throws Exception {+ // can delete only the first or last version of the file+ setErrorGUIEnabled(true);// expect an error dialog++ doCreateVersions();+ final GTreeNode node = getNode(PROGRAM_A);+ selectNode(node);++ final DockingActionIf historyAction = getAction("Show History");+ runSwing(() -> historyAction.actionPerformed(getDomainFileActionContext(node)));++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);+ DockingActionIf deleteAction = getDeleteAction(dialog);++ GTable table = findComponent(dialog, GTable.class);+ runSwing(() -> table.selectRow(1));+ performAction(deleteAction, false);++ // can delete only the first or last version of the file+ OptionDialog d = waitForDialogComponent(OptionDialog.class);+ assertNotNull(d);++ MultiLineLabel label = findComponent(d.getComponent(), MultiLineLabel.class);+ assertNotNull(label);+ assertEquals("Only first and last version may be deleted.", label.getLabel());++ runSwing(() -> {+ d.close();+ dialog.close();+ });+ }++ @Test+ public void testDeleteVersion() throws Exception {+ doCreateVersions();++ GTreeNode node = getNode(PROGRAM_A);+ selectNode(node);++ DockingActionIf undoAction = getAction("UndoCheckOut");+ performAction(undoAction, getDomainFileActionContext(node), true);++ selectNode(node);+ DockingActionIf historyAction = getAction("Show History");+ performAction(historyAction, getDomainFileActionContext(node), true);++ VersionHistoryDialog dialog = waitForDialogComponent(VersionHistoryDialog.class);+ DockingActionIf deleteAction = getDeleteAction(dialog);++ GTable table = findComponent(dialog, GTable.class);+ runSwing(() -> table.selectRow(0));+ int rowCount = table.getRowCount();++ performAction(deleteAction, false);++ OptionDialog confirmDialog = waitForDialogComponent(OptionDialog.class);+ assertNotNull(confirmDialog);+ pressButtonByText(confirmDialog, "Delete");++ waitForTasks();++ assertEquals(rowCount - 1, table.getRowCount());++ runSwing(() -> dialog.close());+ }++ @Test+ public void testFindCheckoutsInSubFolder() throws Exception {++ DomainFolder rootFolder = frontEnd.getRootFolder();+ DomainFolder folder = rootFolder.createFolder("myFolder_1");+ folder = folder.createFolder("myFolder_2");++ Program p = frontEnd.buildProgram(this);+ folder.createFile("My_Program", p, TaskMonitor.DUMMY);+ p.release(this);+ waitForSwing();++ GTreeNode node = getFolderNode("myFolder_1");+ assertNotNull(node);+ node = node.getChild("myFolder_2");+ assertNotNull(node);+ node = node.getChild("My_Program");+ assertNotNull(node);+ addToVersionControl(node, true);++ selectNode(getFolderNode("myFolder_1"));+ DockingActionIf action = getAction("Find Checkouts");+ performFrontEndAction(action);++ FindCheckoutsDialog dialog = waitForDialogComponent(FindCheckoutsDialog.class);+ assertNotNull(dialog);++ final GTable table = findComponent(dialog.getComponent(), GTable.class);+ assertNotNull(table);+ waitForBusyTable(table);++ FindCheckoutsTableModel model = (FindCheckoutsTableModel) table.getModel();++ assertEquals(1, model.getRowCount());+ CheckoutInfo checkoutInfo = model.getRowObject(0);+ DomainFile file = checkoutInfo.getFile();+ DomainFolder parent = file.getParent();+ assertEquals("/myFolder_1/myFolder_2", parent.getPathname());+ pressButtonByText(dialog, "Dismiss");+ }++ @Test+ public void testCheckInFromFindDialog() throws Exception {+ // verify that you get the Check In dialog to popup+ GTreeNode node = getNode(PROGRAM_B);+ addToVersionControl(node, true);+ node = getNode(PROGRAM_C);+ addToVersionControl(node, true);++ DomainFile df = ((DomainFileNode) node).getDomainFile();+ Program p = (Program) df.getDomainObject(this, true, false, TaskMonitor.DUMMY);+ editProgram(p, program -> {+ CodeUnit cu = program.getListing().getCodeUnitAt(program.getMinAddress());+ cu.setComment(CodeUnit.PLATE_COMMENT, "my Plate Comment");+ });+ p.release(this);++ GTreeNode rootNode = frontEnd.getRootNode();+ selectNode(rootNode);++ DockingActionIf action = getAction("Find Checkouts");+ performFrontEndAction(action);++ FindCheckoutsDialog dialog = waitForDialogComponent(FindCheckoutsDialog.class);++ assertNotNull(dialog);++ final GTable table = findComponent(dialog.getComponent(), GTable.class);+ assertNotNull(table);+ waitForBusyTable(table);++ FindCheckoutsTableModel model = (FindCheckoutsTableModel) table.getModel();+ assertEquals(2, model.getRowCount());++ selectInTable(table, node);++ JButton checkInButton =+ findButtonByIcon(dialog, ResourceManager.loadImage("images/vcCheckIn.png"));++ assertNotNull(checkInButton);+ assertTrue(checkInButton.isEnabled());+ pressButton(checkInButton, false);+ VersionControlDialog d = waitForDialogComponent(VersionControlDialog.class);+ assertNotNull(d);++ pressButtonByText(d, "Cancel");++ pressButtonByText(dialog, "Dismiss");+ waitForTasks();+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/PcodeParserTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/PcodeParserTest.javanew file mode 100644index 0000000000..85d40692bc--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/PcodeParserTest.java@@ -0,0 +1,67 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.pcodeCPort.slgh_compile;++import static org.junit.Assert.*;++import java.io.*;+import java.util.List;++import org.junit.Test;++import ghidra.app.plugin.processors.sleigh.SleighLanguage;+import ghidra.sleigh.grammar.Location;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;++public class PcodeParserTest extends AbstractGhidraHeadlessIntegrationTest {++ private void compare(String actual, String expectedFilename) throws IOException {++ List<String> expectedList = loadTextResource(getClass(), expectedFilename);++ BufferedReader actualRdr = new BufferedReader(new StringReader(actual));++ for (String expectedLine : expectedList) {+ String actualLine = actualRdr.readLine();+ assertEquals(expectedLine, actualLine);+ }++ assertNull(actualRdr.readLine());+ }++ @Test+ public void testCompilePcode() throws Exception {++ SleighLanguage lang = (SleighLanguage) getSLEIGH_X86_LANGUAGE();++ long uniqueBase = 0x1000000; // make sure we avoid the decompiler range+ String sleighSpec =+ lang.buildTranslatorTag(lang.getAddressFactory(), uniqueBase, lang.getSymbolTable());++ String pcodeStatements = "tmp:1 = inst_next;\n" + "if (AX == 0) goto inst_next;\n" ++ "call [ECX];\n" + "if (BX != 1) goto <lab>;\n" + "CX = 0;\n" + "<lab>\n" ++ "BX = CX << 2;\n" + "in1 = in2 + 7;";++ PcodeParser parser = new PcodeParser(sleighSpec);+ Location loc = new Location("pcodetest", 5);+ parser.addOperand(loc, "in1", 0);+ parser.addOperand(loc, "in2", 1);+ String contructTplXml =+ PcodeParser.stringifyTemplate(parser.compilePcode(pcodeStatements, "test", 200));+ assertNotNull("Pcode compile failed (see log)", contructTplXml);+ compare(contructTplXml, "pcode1.xml");+ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/WithBlockTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/WithBlockTest.javanew file mode 100644index 0000000000..d6e5a09be9--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/WithBlockTest.java@@ -0,0 +1,177 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.pcodeCPort.slgh_compile;++import static org.junit.Assert.assertEquals;++import java.util.concurrent.atomic.AtomicReference;++import org.apache.commons.lang3.tuple.ImmutablePair;+import org.apache.commons.lang3.tuple.Pair;+import org.junit.Before;+import org.junit.Test;++import ghidra.app.plugin.languages.sleigh.ConstructorEntryVisitor;+import ghidra.app.plugin.languages.sleigh.SleighLanguages;+import ghidra.app.plugin.processors.sleigh.*;+import ghidra.app.plugin.processors.sleigh.pattern.DisjointPattern;+import ghidra.app.plugin.processors.sleigh.symbol.SubtableSymbol;+import ghidra.program.model.lang.LanguageID;+import ghidra.test.AbstractGhidraHeadlessIntegrationTest;++public class WithBlockTest extends AbstractGhidraHeadlessIntegrationTest {++ protected static boolean setupDone;+ protected static LanguageID langID;+ protected static SleighLanguageProvider provider;+ protected static SleighLanguage lang;++ @Before+ public void setUp() throws Exception {+ if (!setupDone) {+ langID = new LanguageID("TestWith:BE:32:default");+ provider = new SleighLanguageProvider();+ lang = (SleighLanguage) provider.getLanguage(langID);+ setupDone = true;+ }+ }++ protected String opnd(int n) {+ return "\n" + (char) ('A' + n);+ }++ protected Pair<DisjointPattern, Constructor> findConstructor(String table, String firstPrint) {+ AtomicReference<DisjointPattern> fpat = new AtomicReference<>(null);+ AtomicReference<Constructor> fcon = new AtomicReference<>(null);+ SleighLanguages.traverseConstructors(lang, new ConstructorEntryVisitor() {+ @Override+ public int visit(SubtableSymbol subtable, DisjointPattern pattern, Constructor cons) {+ if (table.equals(subtable.getName()) &&+ firstPrint.equals(cons.getPrintPieces().get(0))) {+ if (null != fpat.get()) {+ throw new AssertionError("Multiple constructors found. " ++ "Write the test slaspec such that no two constructors in the same " ++ "table share the same first printpiece.");+ }+ fpat.set(pattern);+ fcon.set(cons);+ }+ return CONTINUE;+ }+ });+ if (null == fpat.get()) {+ throw new AssertionError(+ "No such constructor found: " + table + ":" + firstPrint + "...");+ }+ return new ImmutablePair<>(fpat.get(), fcon.get());+ }++ @Test+ public void testNOP1_NoWith() {+ Pair<DisjointPattern, Constructor> NOP1 = findConstructor("instruction", "NOP1");+ assertEquals("ins:SS:XF:XX:XX:XX", NOP1.getLeft().toString());+ assertEquals(0, NOP1.getRight().getContextChanges().size());+ }++ @Test+ public void testRel8addr_WithTabRel8_WithChgPhase3() {+ Pair<DisjointPattern, Constructor> Rel8addr = findConstructor("Rel8", opnd(1));+ assertEquals("always", Rel8addr.getLeft().toString());+ assertEquals(1, Rel8addr.getRight().getContextChanges().size());+ assertEquals("ctx&F0:00:00:00 := 0x3( << 28)",+ Rel8addr.getRight().getContextChanges().get(0).toString());+ }++ @Test+ public void testOP1r0_WithTabOp1() {+ Pair<DisjointPattern, Constructor> OP1r0 = findConstructor("OP1", "r0");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:X0:XX:XX:XX)", OP1r0.getLeft().toString());+ assertEquals(1, OP1r0.getRight().getContextChanges().size());+ assertEquals("ctx&F0:00:00:00 := 0x2( << 28)",+ OP1r0.getRight().getContextChanges().get(0).toString());+ }++ @Test+ public void testOP1r1_WithPatPhase1() {+ Pair<DisjointPattern, Constructor> OP1r1 = findConstructor("OP1", "r1");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:X1:XX:XX:XX)", OP1r1.getLeft().toString());+ assertEquals(1, OP1r1.getRight().getContextChanges().size());+ assertEquals("ctx&F0:00:00:00 := 0x2( << 28)",+ OP1r1.getRight().getContextChanges().get(0).toString());+ }++ @Test+ public void testOP1r2_WithChgPhase2() {+ Pair<DisjointPattern, Constructor> OP1r2 = findConstructor("OP1", "r2");+ assertEquals("ins:X2:XX:XX:XX", OP1r2.getLeft().toString());+ assertEquals(2, OP1r2.getRight().getContextChanges().size());+ assertEquals("ctx&F0:00:00:00 := 0x2( << 28)",+ OP1r2.getRight().getContextChanges().get(0).toString());+ assertEquals("ctx&F0:00:00:00 := 0x1( << 28)",+ OP1r2.getRight().getContextChanges().get(1).toString());+ }++ @Test+ public void testDSTr0_WithPatPhase1_WithTabDST() {+ Pair<DisjointPattern, Constructor> DSTr0 = findConstructor("DST", "r0");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:SS:0X:XX:XX:XX)", DSTr0.getLeft().toString());+ assertEquals(0, DSTr0.getRight().getContextChanges().size());+ }++ @Test+ public void testOP1r3_WithPatPhase1_WithTabOP1() {+ Pair<DisjointPattern, Constructor> OP1r3 = findConstructor("OP1", "r3");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:X3:XX:XX:XX)", OP1r3.getLeft().toString());+ assertEquals(0, OP1r3.getRight().getContextChanges().size());+ }++ @Test+ public void testOP2r1_WithPatPhase1_WithTabOP1() {+ Pair<DisjointPattern, Constructor> OP2r1 = findConstructor("OP2", "r1");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:1X:XX:XX:XX)", OP2r1.getLeft().toString());+ assertEquals(0, OP2r1.getRight().getContextChanges().size());+ }++ @Test+ public void testOP2r0_WithPatPhase1_WithTabOP2() {+ Pair<DisjointPattern, Constructor> OP2r0 = findConstructor("OP2", "r0");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:0X:XX:XX:XX)", OP2r0.getLeft().toString());+ assertEquals(0, OP2r0.getRight().getContextChanges().size());+ }++ @Test+ public void testNOP2_NoWith() {+ Pair<DisjointPattern, Constructor> NOP2 = findConstructor("instruction", "NOP2");+ assertEquals("ins:SS:XE:XX:XX:XX", NOP2.getLeft().toString());+ assertEquals(0, NOP2.getRight().getContextChanges().size());+ }++ @Test+ public void testADD_NoWith() {+ Pair<DisjointPattern, Constructor> ADD = findConstructor("instruction", "ADD");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:SS:X0:XX:XX:XX)", ADD.getLeft().toString());+ assertEquals(0, ADD.getRight().getContextChanges().size());+ }++ @Test+ public void testLD_NoWith() {+ Pair<DisjointPattern, Constructor> LD = findConstructor("instruction", "LD");+ assertEquals("cmb:(ctx:1X:XX:XX:XX,ins:SS:X8:XX:XX:XX)", LD.getLeft().toString());+ assertEquals(0, LD.getRight().getContextChanges().size());+ }++ // TODO: Explicit override of subtable in with+}diff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/pcode1.xml b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/pcode1.xmlnew file mode 100644index 0000000000..3d776d944a--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/pcodeCPort/slgh_compile/pcode1.xml@@ -0,0 +1,38 @@+<construct_tpl labels="1">+<null/><op_tpl code="COPY"><varnode_tpl><const_tpl type="spaceid" name="unique"/><const_tpl type="real" val="0x1000000"/><const_tpl type="real" val="0x1"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="next"/><const_tpl type="real" val="0x1"/></varnode_tpl>+</op_tpl>+<op_tpl code="INT_EQUAL"><varnode_tpl><const_tpl type="spaceid" name="unique"/><const_tpl type="real" val="0x1000010"/><const_tpl type="real" val="0x1"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="register"/><const_tpl type="real" val="0x0"/><const_tpl type="real" val="0x2"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="real" val="0x0"/><const_tpl type="real" val="0x2"/></varnode_tpl>+</op_tpl>+<op_tpl code="CBRANCH"><null/>+<varnode_tpl><const_tpl type="curspace"/><const_tpl type="next"/><const_tpl type="curspace_size"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="unique"/><const_tpl type="real" val="0x1000010"/><const_tpl type="real" val="0x1"/></varnode_tpl>+</op_tpl>+<op_tpl code="CALLIND"><null/>+<varnode_tpl><const_tpl type="spaceid" name="register"/><const_tpl type="real" val="0x4"/><const_tpl type="real" val="0x4"/></varnode_tpl>+</op_tpl>+<op_tpl code="INT_NOTEQUAL"><varnode_tpl><const_tpl type="spaceid" name="unique"/><const_tpl type="real" val="0x1000020"/><const_tpl type="real" val="0x1"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="register"/><const_tpl type="real" val="0xc"/><const_tpl type="real" val="0x2"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="real" val="0x1"/><const_tpl type="real" val="0x2"/></varnode_tpl>+</op_tpl>+<op_tpl code="CBRANCH"><null/>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="relative" val="0x0"/><const_tpl type="real" val="0x4"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="unique"/><const_tpl type="real" val="0x1000020"/><const_tpl type="real" val="0x1"/></varnode_tpl>+</op_tpl>+<op_tpl code="COPY"><varnode_tpl><const_tpl type="spaceid" name="register"/><const_tpl type="real" val="0x4"/><const_tpl type="real" val="0x2"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="real" val="0x0"/><const_tpl type="real" val="0x2"/></varnode_tpl>+</op_tpl>+<op_tpl code="LABEL"><null/>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="real" val="0x0"/><const_tpl type="real" val="0x4"/></varnode_tpl>+</op_tpl>+<op_tpl code="INT_LEFT"><varnode_tpl><const_tpl type="spaceid" name="register"/><const_tpl type="real" val="0xc"/><const_tpl type="real" val="0x2"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="register"/><const_tpl type="real" val="0x4"/><const_tpl type="real" val="0x2"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="real" val="0x2"/><const_tpl type="real" val="0x4"/></varnode_tpl>+</op_tpl>+<op_tpl code="INT_ADD"><varnode_tpl><const_tpl type="handle" val="0" s="space"/><const_tpl type="handle" val="0" s="offset"/><const_tpl type="handle" val="0" s="size"/></varnode_tpl>+<varnode_tpl><const_tpl type="handle" val="1" s="space"/><const_tpl type="handle" val="1" s="offset"/><const_tpl type="handle" val="1" s="size"/></varnode_tpl>+<varnode_tpl><const_tpl type="spaceid" name="const"/><const_tpl type="real" val="0x7"/><const_tpl type="handle" val="0" s="size"/></varnode_tpl>+</op_tpl>+</construct_tpl>diff --git a/Ghidra/Test/IntegrationTest/src/test/java/ghidra/server/RepositoryFileSystemTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/server/RepositoryFileSystemTest.javasimilarity index 100%rename from Ghidra/Test/IntegrationTest/src/test/java/ghidra/server/RepositoryFileSystemTest.javarename to Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/server/RepositoryFileSystemTest.javadiff --git a/Ghidra/Test/IntegrationTest/src/test/java/ghidra/server/RepositoryManagerTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/server/RepositoryManagerTest.javasimilarity index 100%rename from Ghidra/Test/IntegrationTest/src/test/java/ghidra/server/RepositoryManagerTest.javarename to Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/server/RepositoryManagerTest.javadiff --git a/Ghidra/Test/IntegrationTest/src/test/java/ghidra/server/RepositoryTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/server/RepositoryTest.javasimilarity index 100%rename from Ghidra/Test/IntegrationTest/src/test/java/ghidra/server/RepositoryTest.javarename to Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/server/RepositoryTest.javadiff --git a/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/util/task/RunManagerTest.java b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/util/task/RunManagerTest.javanew file mode 100644index 0000000000..7de5b555a8--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test.slow/java/ghidra/util/task/RunManagerTest.java@@ -0,0 +1,716 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.util.task;++import static org.junit.Assert.assertEquals;+import static org.junit.Assert.assertTrue;++import java.awt.Container;+import java.util.Random;+import java.util.concurrent.*;++import javax.swing.JComponent;+import javax.swing.JFrame;++import org.junit.Assert;+import org.junit.Test;++import ghidra.test.AbstractGhidraHeadedIntegrationTest;+import ghidra.util.Msg;++public class RunManagerTest extends AbstractGhidraHeadedIntegrationTest {++ private static final int THREADED_TEST_COUNT = 4;+ public static final int MAX_RUNNABLES_FROM_THREAD = 15;+ public static final int MAX_THREAD_DELAY_MILLIS = 150;+ public static final int MAX_WAIT_TIME =+ (MAX_RUNNABLES_FROM_THREAD * MAX_THREAD_DELAY_MILLIS) * THREADED_TEST_COUNT + 500;++ private volatile boolean failed = false;++ private volatile TestRunnable lastCreatedMultiThreadedTestRunner;++ public RunManagerTest() {+ super();+ }++ @Override+ protected void testFailed(Throwable e) {+ failed = true;+ }++ @Test+ public void testRunNow() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);+ BasicTestRunnable runnable = new BasicTestRunnable();++ runManager.runNow(runnable, "Test Runnable", 500);++ waitForRunManagerToFinish(runManager);++ waitForPostedSwingRunnables();++ assertEquals(0, listener.taskCancelled);+ assertEquals(1, listener.taskCompleted);+ }++ @Test+ public void testRunNext() {+ //+ // Test that posting a runnable when one is currently running will not cancel the+ // currently running runnable, but will clear the queue of any other pending+ // runnables+ //++ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);+ TimeSpecificTestRunnable firstRunnable = new TimeSpecificTestRunnable(3000);++ // this first call to runNext() should start the runnable instantly+ trace(testName.getMethodName() + "starting first runnable");+ runManager.runNext(firstRunnable, "Test Runnable", 500);++ waitForRunManagerToStart(runManager, firstRunnable);++ // this call to runNext() should allow the first runnable to finish+ trace(testName.getMethodName() + "starting second runnable");+ BasicTestRunnable secondRunnable = new BasicTestRunnable();+ runManager.runNext(secondRunnable, "Test Runnable", 500);++ trace(testName.getMethodName() + "waiting for run manager");+ waitForRunManagerToFinish(runManager);++ waitForPostedSwingRunnables();++ assertEquals(2, listener.taskCompleted);+ assertEquals(0, listener.taskCancelled);// no cancel (only internal cancel)++ assertTrue(firstRunnable.hasCompleted());+ assertTrue(secondRunnable.hasCompleted());+ }++ @Test+ public void testCancel_SingleRunnable() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);++ TimeSpecificTestRunnable runnable = new TimeSpecificTestRunnable(10000);++ runManager.runNow(runnable, "Test Runnable", 500);++ waitForRunManagerToStart(runManager, runnable);++ runManager.cancelAllRunnables();++ waitForRunnableToFinish(runManager, runnable);++ assertTrue(!runnable.hasCompleted());+ }++ @Test+ public void testCancel_MultipleRunnables() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);++ TimeSpecificTestRunnable runnable = new TimeSpecificTestRunnable(10000);++ runManager.runLater(runnable, "Test Runnable", 500);++ waitForRunManagerToStart(runManager, runnable);++ BasicTestRunnable secondRunnable = new BasicTestRunnable();+ BasicTestRunnable thirdRunnable = new BasicTestRunnable();+ BasicTestRunnable fourthRunnable = new BasicTestRunnable();++ runManager.runLater(secondRunnable, "Test Runnable", 500);+ runManager.runLater(thirdRunnable, "Test Runnable", 500);+ runManager.runLater(fourthRunnable, "Test Runnable", 500);++ runManager.cancelAllRunnables();++ waitForRunManagerToFinish(runManager);++ assertTrue(!secondRunnable.hasCompleted());+ assertTrue(!thirdRunnable.hasCompleted());+ assertTrue(!fourthRunnable.hasCompleted());+ }++ @Test+ public void testRunLater() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);++ BasicTestRunnable runnable = new BasicTestRunnable();++ runManager.runLater(runnable, "Test Runnable", 500);++ waitForRunManagerToFinish(runManager);++ assertTrue(runnable.hasCompleted());+ }++ @Test+ public void testSchedule_CancelOnlyStopsCurrentRunnable() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);++ TimeSpecificTestRunnable runnable = new TimeSpecificTestRunnable(10000);++ runManager.runLater(runnable, "Test Runnable", 500);++ waitForRunManagerToStart(runManager, runnable);++ BasicTestRunnable secondRunnable = new BasicTestRunnable();+ BasicTestRunnable thirdRunnable = new BasicTestRunnable();+ BasicTestRunnable fourthRunnable = new BasicTestRunnable();++ runManager.runLater(secondRunnable, "Test Runnable", 500);+ runManager.runLater(thirdRunnable, "Test Runnable", 500);+ runManager.runLater(fourthRunnable, "Test Runnable", 500);++ trace("Cancelling monitor!");+ TaskMonitor monitor = (TaskMonitor) getInstanceField("monitor", runManager);+ monitor.cancel();++ waitForRunnableToFinish(runManager, fourthRunnable);++ assertTrue(secondRunnable.hasCompleted());+ assertTrue(thirdRunnable.hasCompleted());+ assertTrue(fourthRunnable.hasCompleted());+ }++ @Test+ public void testManyRunCallsFromMultipleThreads() {+ RunManager runManager = new RunManager();++ CyclicBarrier startBarrier = new CyclicBarrier(THREADED_TEST_COUNT);+ CountDownLatch finishedLatch = new CountDownLatch(THREADED_TEST_COUNT);++ for (int i = 0; i < THREADED_TEST_COUNT; i++) {+ new RunnerThread("Thread " + (i + 1), runManager, startBarrier, finishedLatch).start();+ }++ try {+ finishedLatch.await();+ }+ catch (InterruptedException e) {+ Assert.fail("Unable to wait for worker threads to finish!");+ }++ // make sure the last runnable in actually completed+ waitForRunnableToFinish(runManager, lastCreatedMultiThreadedTestRunner);+ assertTrue(lastCreatedMultiThreadedTestRunner.hasCompleted());+ }++ @Test+ public void testSwingRunnerCallback() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);+ TestSwingRunnable runnable = new TestSwingRunnable();++ runManager.runNow(runnable, "Test Swing Runnable");++ waitForRunManagerToFinish(runManager);++ waitForPostedSwingRunnables();++ assertTrue(runnable.hasCompleted());+ assertTrue(runnable.swingRunRan());+ }++ @Test+ public void testTaskListenerTaskCompleted() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);+ BasicTestRunnable runnable = new BasicTestRunnable();++ runManager.runNow(runnable, "Test Runnable");++ waitForRunManagerToFinish(runManager);++ waitForPostedSwingRunnables();++ assertEquals(0, listener.taskCancelled);+ assertEquals(1, listener.taskCompleted);+ }++ @Test+ public void testTaskListenerTaskCancelled() {+ TestTaskListener listener = new TestTaskListener();+ RunManager runManager = new RunManager(listener);+ RunUntilCancelledTestRunnable runnable = new RunUntilCancelledTestRunnable();++ runManager.runNow(runnable, "Test Runnable");++ waitForRunManagerToStart(runManager, runnable);++ runManager.cancelAllRunnables();++ waitForRunnableToFinish(runManager, runnable);++ Msg.debug(this, "before waiting");+ waitForPostedSwingRunnables();+ Msg.debug(this, "after waiting");++ assertEquals(0, listener.taskCompleted);+ assertEquals(1, listener.taskCancelled);+ }++ @Test+ public void testProgressBarShowsAfterDelay_NoCancel() {+ //+ // Test that the progress bar will be shown after the defined delay and will be hidden+ // when completed.+ //+ RunManager runManager = new RunManager();++ JFrame frame = new JFrame("Progress Panel Test Frame");+ Container contentPane = frame.getContentPane();+ contentPane.add(runManager.getMonitorComponent());+ frame.setSize(200, 200);+ frame.setVisible(true);++ JComponent component = runManager.getMonitorComponent();+ CountDownLatch startLatch = new CountDownLatch(1);+ LatchRunnable runnable = new LatchRunnable(startLatch);+ assertTrue(!component.isShowing());++ // long enough that our two threads will have time to start and sleep without the+ // thread schedule causing spurious failures+ int delay = 2500;+ runManager.runNow(runnable, "Test of Progress Bar Runnable", delay);++ waitForRunManagerToStart(runManager, runnable);++ try {+ Thread.sleep(delay / 3);+ }+ catch (InterruptedException e) {+ Assert.fail("Interrupted while sleeping for test");+ }++ assertTrue(!component.isShowing());++ try {+ Thread.sleep(delay);+ }+ catch (InterruptedException e) {+ Assert.fail("Interrupted while sleeping for test");+ }++ waitForPostedSwingRunnables();+ assertTrue(component.isShowing());++ startLatch.countDown();++ waitForRunManagerToFinish(runManager);++ waitForPostedSwingRunnables();+ waitForComponentToBeHidden(component);+ frame.setVisible(false);+ }++ private void waitForComponentToBeHidden(JComponent component) {+ int numWaits = 0;+ int sleepyTime = 100;+ int maxWaits = 20;++ while (component.isShowing() && maxWaits > numWaits++) {+ sleep(sleepyTime);+ }++ if (numWaits >= maxWaits) {+ Assert.fail("Component not hidden!");+ }+ }++ @Test+ public void testProgressBarShowsAfterDelay_WithCancel() {+ //+ // Test that the progress bar will be shown after the defined delay and will be hidden+ // when cancelled.+ //+ RunManager runManager = new RunManager();++ JFrame frame = new JFrame("Progress Panel Test Frame");+ Container contentPane = frame.getContentPane();+ contentPane.add(runManager.getMonitorComponent());+ frame.setSize(200, 200);+ frame.setVisible(true);++ RunUntilCancelledTestRunnable runnable = new RunUntilCancelledTestRunnable();++ JComponent component = runManager.getMonitorComponent();+ assertTrue(!component.isShowing());++ // long enough that our two threads will have time to start and sleep without the+ // thread schedule causing spurious failures+ int delay = 5000;+ runManager.runNow(runnable, "Test of Progress Bar Runnable", delay);++ waitForRunManagerToStart(runManager, runnable);++ try {+ Thread.sleep(delay / 3);+ }+ catch (InterruptedException e) {+ Assert.fail("Interrupted while sleeping for test");+ }++ assertTrue(!component.isShowing());++ try {+ Thread.sleep(delay);+ }+ catch (InterruptedException e) {+ Assert.fail("Interrupted while sleeping for test");+ }++ waitForPostedSwingRunnables();+ assertTrue(component.isShowing());++ runManager.cancelAllRunnables();+ runManager.waitForNotBusy(DEFAULT_WINDOW_TIMEOUT);++ waitForPostedSwingRunnables();+ assertTrue(!component.isShowing());+ frame.setVisible(false);+ }++//==================================================================================================+// Private Methods+//==================================================================================================++ private void waitForRunManagerToStart(RunManager runManager, TestRunnable runnable) {+ assertTrue("Failed waiting for runnable to start", runnable.waitForStart(MAX_WAIT_TIME));+ }++ private void waitForRunnableToFinish(RunManager runManager, TestRunnable runnable) {++ waitForRunManagerToStart(runManager, runnable);++ assertTrue("Timed out waiting for runnable to finish",+ runnable.waitForFinished(MAX_WAIT_TIME));+ }++ private void waitForRunManagerToFinish(RunManager runManager) {+ runManager.waitForNotBusy(MAX_WAIT_TIME);+ }++ private void trace(String message) {+ System.err.println(message);+ }++//==================================================================================================+// Inner Classes+//==================================================================================================++ private class RunnerThread extends Thread {++ private final RunManager runManager;+ private final Random random = new Random();++ private final CountDownLatch finishedLatch;+ private final CyclicBarrier startBarrier;++ RunnerThread(String name, RunManager runManager, CyclicBarrier startBarrier,+ CountDownLatch finishedLatch) {+ super(name);+ this.runManager = runManager;+ this.startBarrier = startBarrier;+ this.finishedLatch = finishedLatch;+ }++ @Override+ public void run() {+ try {+ // wait for all threads to start+ startBarrier.await();+ }+ catch (Exception e1) {+ System.err.println("Interrupted while waiting to begin: " + getName());+ e1.printStackTrace();+ }++ int runnableCount = random.nextInt(MAX_RUNNABLES_FROM_THREAD);+ trace(getName() + " - running runnables: " + runnableCount);+ for (int i = 0; i < runnableCount; i++) {++ int sleepyTime = random.nextInt(MAX_THREAD_DELAY_MILLIS);+ try {+ Thread.sleep(sleepyTime);+ }+ catch (InterruptedException e) {+ // don't care; we tried+ }++ synchronized (RunManagerTest.this) {+ lastCreatedMultiThreadedTestRunner =+ new NotExpectedToBeInterruptedTestRunnable();+ runManager.runNow(lastCreatedMultiThreadedTestRunner,+ "Thread Runnable " + i + " (" + getName() + ")");+ }+ }++ finishedLatch.countDown();+ }+ }++ private class TestTaskListener implements TaskListener {+ private volatile int taskCancelled;+ private volatile int taskCompleted;++ @Override+ public void taskCancelled(Task task) {+ trace("taskCancelled() - " + task);+ taskCancelled++;+ }++ @Override+ public void taskCompleted(Task task) {+ trace("taskCompleted()");+ taskCompleted++;+ }+ }++ private abstract class TestRunnable implements MonitoredRunnable {+ protected volatile boolean completedNormally;+ protected CountDownLatch startLatch = new CountDownLatch(1);+ protected CountDownLatch doneLatch = new CountDownLatch(1);++ boolean waitForStart(int timeout) {+ try {+ return startLatch.await(timeout, TimeUnit.MILLISECONDS);+ }+ catch (InterruptedException e) {+ trace("Interrupted waiting for start on latch");+ return false;+ }+ }++ boolean waitForFinished(int timeout) {+ try {+ return doneLatch.await(timeout, TimeUnit.MILLISECONDS);+ }+ catch (InterruptedException e) {+ trace("Interrupted waiting for finish on latch");+ return false;+ }+ }++ boolean hasCompleted() {+ return completedNormally;+ }+ }++ private class LatchRunnable extends TestRunnable {++ private final CountDownLatch delayLatch;++ LatchRunnable(CountDownLatch delayLatch) {+ this.delayLatch = delayLatch;+ }++ @Override+ public void monitoredRun(TaskMonitor monitor) {+ trace(getClass().getSimpleName() + " - started");+ startLatch.countDown();++ try {+ delayLatch.await();+ }+ catch (Exception e) {+ System.err.println(+ "Interrupted while waiting to begin: " + testName.getMethodName());+ e.printStackTrace();+ }++ try {+ trace("\t" + getClass().getSimpleName() + " - sleeping");+ Thread.sleep(250);+ completedNormally = true;+ }+ catch (InterruptedException e) {+ // don't care; we are fake+ }++ trace("\t" + getClass().getSimpleName() + " - finished");+ doneLatch.countDown();+ }++ }++ private class TestSwingRunnable extends TestRunnable implements SwingRunnable {++ private volatile boolean swingRunRan;++ @Override+ public void swingRun(boolean isCancelled) {+ swingRunRan = true;+ }++ @Override+ public void monitoredRun(TaskMonitor monitor) {+ trace(getClass().getSimpleName() + " - started");+ startLatch.countDown();+ try {+ trace("\t" + getClass().getSimpleName() + " - sleeping");+ Thread.sleep(250);+ completedNormally = true;+ }+ catch (InterruptedException e) {+ // don't care; we are fake+ }+ trace("\t" + getClass().getSimpleName() + " - finished");+ doneLatch.countDown();+ }++ boolean swingRunRan() {+ return swingRunRan;+ }+ }++ private class TimeSpecificTestRunnable extends TestRunnable {+ private final long timeInMillis;++ TimeSpecificTestRunnable(long timeInMillis) {+ this.timeInMillis = timeInMillis;+ }++ @Override+ public void monitoredRun(TaskMonitor monitor) {+ trace(getClass().getSimpleName() + " - started");++ startLatch.countDown();++ int totalTime = 0;+ while (totalTime < timeInMillis && !monitor.isCancelled()) {+ try {+ trace("\t" + getClass().getSimpleName() + " - sleeping");+ Thread.sleep(250);+ }+ catch (InterruptedException e) {+ // don't care; we are fake+ }+ totalTime += 250;+ }++ if (monitor.isCancelled()) {+ trace("\t" + getClass().getSimpleName() + " - cancelled");+ doneLatch.countDown();+ return;+ }++ completedNormally = true;+ trace("\t" + getClass().getSimpleName() + " - finished");+ doneLatch.countDown();+ }+ }++ private class BasicTestRunnable extends TestRunnable {++ @Override+ public void monitoredRun(TaskMonitor monitor) {+ trace(getClass().getSimpleName() + " - started");+ startLatch.countDown();++ if (monitor.isCancelled()) {+ trace("\t" + getClass().getSimpleName() + " - cancelled");+ doneLatch.countDown();+ return;+ }++ try {+ trace("\t" + getClass().getSimpleName() + " - sleeping");+ Thread.sleep(250);+ completedNormally = true;+ }+ catch (InterruptedException e) {+ // don't care; we are fake+ }+ trace("\t" + getClass().getSimpleName() + " - finished");+ doneLatch.countDown();+ }+ }++ private class NotExpectedToBeInterruptedTestRunnable extends TestRunnable {++ @Override+ public void monitoredRun(TaskMonitor monitor) {+ trace(getClass().getSimpleName() + " - started");+ startLatch.countDown();++ int numWaits = 0;+ int sleepyTime = 500;+ int maxWaits = 10;++ while (!failed && !monitor.isCancelled() && maxWaits > numWaits++) {+ try {+ trace("\t" + getClass().getSimpleName() + " - sleeping");+ Thread.sleep(sleepyTime);+ }+ catch (InterruptedException e) {+ trace("\t" + getClass().getSimpleName() + " - interrupted - " ++ monitor.isCancelled());+ doneLatch.countDown();+ return;+ }+ }++ if (!monitor.isCancelled()) {+ completedNormally = true;+ trace("\t" + getClass().getSimpleName() + " - completed normally");+ }+ else {+ trace("\t" + getClass().getSimpleName() + " - completed - cancelled");+ }+ doneLatch.countDown();+ }+ }++ private class RunUntilCancelledTestRunnable extends TestRunnable {++ @Override+ public void monitoredRun(TaskMonitor monitor) {+ trace(getClass().getSimpleName() + " - started");+ startLatch.countDown();++ while (!failed && !monitor.isCancelled()) {+ try {+ trace("\t" + getClass().getSimpleName() + " - sleeping");+ Thread.sleep(250);+ }+ catch (InterruptedException e) {+ // don't care; we will check the monitor above to know if we+ // were cancelled+ trace("\t" + getClass().getSimpleName() + " - interrupted - " ++ monitor.isCancelled());+ }+ }++ if (!monitor.isCancelled()) {+ completedNormally = true;+ trace("\t" + getClass().getSimpleName() + " - completed normally");+ }+ else {+ trace("\t" + getClass().getSimpleName() + " - completed - cancelled");+ }+ doneLatch.countDown();+ }++ }+}diff --git a/Ghidra/Test/IntegrationTest/src/test/java/ghidra/util/bean/PathManagerTest.java b/Ghidra/Test/IntegrationTest/src/test/java/ghidra/util/bean/PathManagerTest.javanew file mode 100644index 0000000000..9020a44b75--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test/java/ghidra/util/bean/PathManagerTest.java@@ -0,0 +1,259 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.util.bean;++import static org.junit.Assert.*;++import java.io.File;+import java.util.ArrayList;+import java.util.List;++import javax.swing.*;++import org.junit.*;++import docking.test.AbstractDockingTest;+import docking.widgets.filechooser.GhidraFileChooser;+import docking.widgets.filechooser.GhidraFileChooserMode;+import docking.widgets.pathmanager.PathManager;+import docking.widgets.pathmanager.PathManagerListener;+import docking.widgets.table.GTable;+import generic.util.Path;+import ghidra.framework.preferences.Preferences;+import ghidra.util.filechooser.ExtensionFileFilter;+import resources.ResourceManager;++public class PathManagerTest extends AbstractDockingTest {++ private PathManager pathManager;+ private GTable table;+ private JFrame frame;+ private boolean wasListenerNotified = false;++ @Before+ public void setUp() throws Exception {+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());+ List<Path> paths = new ArrayList<>();+ paths.add(new Path(new File("c:\\path_one")));+ paths.add(new Path(new File("c:\\path_two")));+ paths.add(new Path(new File("c:\\path_three")));+ paths.add(new Path(new File("c:\\path_four")));+ paths.add(new Path(new File("c:\\path_four")));++ runSwing(() -> {+ pathManager = new PathManager(paths, true, true);+ table = (GTable) findComponentByName(pathManager.getComponent(), "PATH_TABLE");+ frame = new JFrame("Test");+ frame.getContentPane().add(pathManager.getComponent());+ frame.pack();+ });+ frame.setVisible(true);+ }++ @After+ public void tearDown() throws Exception {+ frame.setVisible(false);+ wasListenerNotified = false;+ }++ @Test+ public void testUpArrow() throws Exception {+ selectRow(3);+ JButton upButton = findButtonByIcon(pathManager.getComponent(),+ ResourceManager.loadImage("images/up.png"));+ assertNotNull(upButton);+ pressButton(upButton, true);+ waitForSwing();++ int row = table.getSelectedRow();+ assertEquals(2, row);+ assertEquals(new Path("c:\\path_four"), table.getModel().getValueAt(row, 1));++ pressButton(upButton, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(1, row);+ assertEquals(new Path("c:\\path_four"), table.getModel().getValueAt(row, 1));++ pressButton(upButton, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(0, row);+ assertEquals(new Path("c:\\path_four"), table.getModel().getValueAt(row, 1));++ pressButton(upButton, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(3, row);+ assertEquals(new Path("c:\\path_four"), table.getModel().getValueAt(row, 1));+ }++ @Test+ public void testDownArrow() throws Exception {+ selectRow(2);++ JButton downButton = findButtonByIcon(pathManager.getComponent(),+ ResourceManager.loadImage("images/down.png"));+ assertNotNull(downButton);+ pressButton(downButton, true);+ waitForSwing();++ int row = table.getSelectedRow();+ assertEquals(3, row);+ assertEquals(new Path("c:\\path_three"), table.getModel().getValueAt(row, 1));++ pressButton(downButton, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(0, row);+ assertEquals(new Path("c:\\path_three"), table.getModel().getValueAt(row, 1));++ pressButton(downButton, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(1, row);+ assertEquals(new Path("c:\\path_three"), table.getModel().getValueAt(row, 1));++ pressButton(downButton, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(2, row);+ assertEquals(new Path("c:\\path_three"), table.getModel().getValueAt(row, 1));+ }++ @Test+ public void testRemove() throws Exception {+ selectRow(3);++ JButton button = findButtonByIcon(pathManager.getComponent(),+ ResourceManager.loadImage("images/edit-delete.png"));+ assertNotNull(button);+ pressButton(button, true);+ waitForSwing();+ int row = table.getSelectedRow();+ assertEquals(2, row);++ pressButton(button, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(1, row);++ pressButton(button, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(0, row);++ pressButton(button, true);+ waitForSwing();+ row = table.getSelectedRow();+ assertEquals(-1, row);++ assertTrue(!button.isEnabled());+ }++ @Test+ public void testAddButton() throws Exception {++ PathManagerListener listener = new PathManagerListener() {+ @Override+ public void pathsChanged() {+ wasListenerNotified = true;+ }++ @Override+ public void pathMessage(String message) {+ // don't care+ }+ };++ pathManager.addListener(listener);++ File temp = createTempFileForTest();++ Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());+ pathManager.setFileChooserProperties("Select Source Files",+ Preferences.LAST_IMPORT_DIRECTORY, GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,+ new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));++ JButton button = findButtonByIcon(pathManager.getComponent(),+ ResourceManager.loadImage("images/Plus.png"));+ assertNotNull(button);+ pressButton(button, false);++ waitForSwing();+ GhidraFileChooser fileChooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(fileChooser);++ JButton chooseButton = findButtonByText(fileChooser, "OK");+ assertNotNull(chooseButton);++ runSwing(() -> fileChooser.setSelectedFile(new File(temp.getParent(), "fred.h")));+ waitForUpdateOnChooser(fileChooser);++ pressButton(chooseButton);+ assertTrue("The file chooser did not close as expected", !fileChooser.isVisible());+ waitForSwing();++ assertEquals(5, table.getRowCount());++ Path filename = (Path) table.getModel().getValueAt(0, 1);+ assertTrue(filename.getPathAsString().endsWith("fred.h"));++ assertTrue(wasListenerNotified);+ pathManager.removeListener(listener);+ }++ @Test+ public void testCancelAdd() throws Exception {++ File temp = createTempFileForTest();++ Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());+ pathManager.setFileChooserProperties("Select Source Files",+ Preferences.LAST_IMPORT_DIRECTORY, GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,+ new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));++ JButton button = findButtonByIcon(pathManager.getComponent(),+ ResourceManager.loadImage("images/Plus.png"));+ assertNotNull(button);+ pressButton(button, false);++ waitForSwing();+ GhidraFileChooser fileChooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(fileChooser);++ assertEquals(temp.getParentFile().getName(), fileChooser.getCurrentDirectory().getName());+ assertTrue(fileChooser.isMultiSelectionEnabled());++ File f = new File("c:\\temp\\myInclude.h");+ assertTrue(fileChooser.accept(f));+ f = new File("c:\\temp\\myFile.c");+ assertTrue(!fileChooser.accept(f));++ pressButtonByText(fileChooser, "Cancel", true);+ }++ @Test+ public void testClear() throws Exception {+ runSwing(() -> pathManager.clear());+ assertEquals(0, table.getRowCount());+ }++ private void selectRow(final int row) throws Exception {+ runSwing(() -> table.setRowSelectionInterval(row, row));+ }++}diff --git a/Ghidra/Test/IntegrationTest/src/test/java/ghidra/util/bean/PathnameTablePanelTest.java b/Ghidra/Test/IntegrationTest/src/test/java/ghidra/util/bean/PathnameTablePanelTest.javanew file mode 100644index 0000000000..0cd1c8019c--- /dev/null+++ b/Ghidra/Test/IntegrationTest/src/test/java/ghidra/util/bean/PathnameTablePanelTest.java@@ -0,0 +1,330 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.util.bean;++import static org.junit.Assert.*;++import java.io.File;++import javax.swing.*;++import org.junit.*;++import docking.test.AbstractDockingTest;+import docking.widgets.OptionDialog;+import docking.widgets.filechooser.GhidraFileChooser;+import docking.widgets.filechooser.GhidraFileChooserMode;+import docking.widgets.pathmanager.PathnameTablePanel;+import ghidra.app.util.importer.LibrarySearchPathManager;+import ghidra.framework.preferences.Preferences;+import ghidra.util.filechooser.ExtensionFileFilter;+import resources.ResourceManager;++/**+ *+ *+ *+ */+public class PathnameTablePanelTest extends AbstractDockingTest {++ private PathnameTablePanel panel;+ private JTable table;+ private JFrame frame;+ private String[] tablePaths =+ { "c:\\path_one", "c:\\path_two", "c:\\path_three", "c:\\path_four", "c:\\path_five" };++ @Before+ public void setUp() throws Exception {+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());+ panel = new PathnameTablePanel(tablePaths, true, false, () -> reset());+ table = panel.getTable();+ frame = new JFrame("Test");+ frame.getContentPane().add(panel);+ runSwing(() -> frame.setVisible(true));+ }++ @After+ public void tearDown() throws Exception {+ frame.setVisible(false);+ }++ @Test+ public void testUpArrow() throws Exception {+ selectRow(3);+ JButton upButton = findButtonByIcon(panel, ResourceManager.loadImage("images/up.png"));+ assertNotNull(upButton);+ pressButton(upButton, true);+ waitForPostedSwingRunnables();++ int row = table.getSelectedRow();+ assertEquals(2, row);+ assertEquals("c:\\path_four", table.getModel().getValueAt(row, 0));++ pressButton(upButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(1, row);+ assertEquals("c:\\path_four", table.getModel().getValueAt(row, 0));++ pressButton(upButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(0, row);+ assertEquals("c:\\path_four", table.getModel().getValueAt(row, 0));++ pressButton(upButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(4, row);+ assertEquals("c:\\path_four", table.getModel().getValueAt(row, 0));+ }++ @Test+ public void testDownArrow() throws Exception {+ selectRow(2);++ JButton downButton = findButtonByIcon(panel, ResourceManager.loadImage("images/down.png"));+ assertNotNull(downButton);+ pressButton(downButton, true);+ waitForPostedSwingRunnables();++ int row = table.getSelectedRow();+ assertEquals(3, row);+ assertEquals("c:\\path_three", table.getModel().getValueAt(row, 0));++ pressButton(downButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(4, row);+ assertEquals("c:\\path_three", table.getModel().getValueAt(row, 0));++ pressButton(downButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(0, row);+ assertEquals("c:\\path_three", table.getModel().getValueAt(row, 0));++ pressButton(downButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(1, row);+ assertEquals("c:\\path_three", table.getModel().getValueAt(row, 0));+ }++ @Test+ public void testRemove() throws Exception {+ selectRow(4);++ JButton button =+ findButtonByIcon(panel, ResourceManager.loadImage("images/edit-delete.png"));+ assertNotNull(button);+ pressButton(button, true);+ waitForPostedSwingRunnables();+ int row = table.getSelectedRow();+ assertEquals(3, row);++ pressButton(button, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(2, row);++ pressButton(button, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(1, row);++ pressButton(button, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(0, row);++ pressButton(button, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(-1, row);++ assertTrue(!button.isEnabled());+ }++ @Test+ public void testAddButton() throws Exception {+ File temp = createTempFileForTest();++ Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());+ panel.setFileChooserProperties("Select Source Files", Preferences.LAST_IMPORT_DIRECTORY,+ GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,+ new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));++ JButton button = findButtonByIcon(panel, ResourceManager.loadImage("images/Plus.png"));+ assertNotNull(button);+ pressButton(button, false);++ waitForPostedSwingRunnables();+ selectFromFileChooser();++ assertEquals(6, table.getRowCount());++ String filename = (String) table.getModel().getValueAt(5, 0);+ assertTrue(filename.endsWith("fred.h"));+ }++ @Test+ public void testCancelAdd() throws Exception {++ File temp = createTempFileForTest();++ Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());+ panel.setFileChooserProperties("Select Source Files", Preferences.LAST_IMPORT_DIRECTORY,+ GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,+ new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));++ JButton button = findButtonByIcon(panel, ResourceManager.loadImage("images/Plus.png"));+ assertNotNull(button);+ pressButton(button, false);++ waitForPostedSwingRunnables();+ GhidraFileChooser fileChooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(fileChooser);++ assertEquals(temp.getParentFile().getName(), fileChooser.getCurrentDirectory().getName());+ assertTrue(fileChooser.isMultiSelectionEnabled());++ File f = new File("c:\\temp\\myInclude.h");+ assertTrue(fileChooser.accept(f));+ f = new File("c:\\temp\\myFile.c");+ assertTrue(!fileChooser.accept(f));++ pressButtonByText(fileChooser, "Cancel", true);+ }++ @Test+ public void testClear() throws Exception {+ SwingUtilities.invokeAndWait(() -> panel.clear());+ assertEquals(0, table.getRowCount());+ }++ @Test+ public void testAddToTop() throws Exception {++ panel.setAddToTop(true);+ File temp = createTempFileForTest();+ Preferences.setProperty(Preferences.LAST_IMPORT_DIRECTORY, temp.getParent());+ panel.setFileChooserProperties("Select Source Files", Preferences.LAST_IMPORT_DIRECTORY,+ GhidraFileChooserMode.FILES_AND_DIRECTORIES, true,+ new ExtensionFileFilter(new String[] { "h" }, "C Header Files"));++ JButton button = findButtonByIcon(panel, ResourceManager.loadImage("images/Plus.png"));+ assertNotNull(button);+ pressButton(button, false);++ waitForPostedSwingRunnables();+ selectFromFileChooser();++ assertEquals(6, table.getRowCount());++ String filename = (String) table.getModel().getValueAt(0, 0);+ assertTrue(filename.endsWith("fred.h"));++ }++ @Test+ public void testReset() throws Exception {+ JButton removeButton =+ findButtonByIcon(panel, ResourceManager.loadImage("images/edit-delete.png"));+ JButton addButton = findButtonByIcon(panel, ResourceManager.loadImage("images/Plus.png"));+ JButton resetButton =+ findButtonByIcon(panel, ResourceManager.loadImage("images/trash-empty.png"));++ assertNotNull(removeButton);+ assertNotNull(addButton);+ assertNotNull(resetButton);++ selectRow(4);++ pressButton(removeButton, true);+ waitForPostedSwingRunnables();+ int row = table.getSelectedRow();+ assertEquals(3, row);++ pressButton(removeButton, true);+ waitForPostedSwingRunnables();+ row = table.getSelectedRow();+ assertEquals(2, row);++ pressButton(resetButton, false);+ waitForPostedSwingRunnables();++ pressResetConfirmation();++ int rowCount = table.getRowCount();+ assertEquals(5, rowCount);++ pressButton(addButton, false);+ waitForPostedSwingRunnables();++ selectFromFileChooser();++ rowCount = table.getRowCount();+ assertEquals(6, rowCount);++ pressButton(resetButton, false);+ waitForPostedSwingRunnables();++ pressResetConfirmation();++ rowCount = table.getRowCount();+ assertEquals(5, rowCount);+ }++ private void selectRow(final int row) throws Exception {+ runSwing(() -> table.setRowSelectionInterval(row, row));+ }++ private void pressResetConfirmation() {+ OptionDialog popup = waitForDialogComponent(OptionDialog.class);+ assertNotNull(popup);++ JButton yesButton = findButtonByText(popup, "Yes");+ assertNotNull(yesButton);++ pressButton(yesButton, true);+ waitForPostedSwingRunnables();+ }++ private void selectFromFileChooser() throws Exception {+ final GhidraFileChooser fileChooser = waitForDialogComponent(GhidraFileChooser.class);+ assertNotNull(fileChooser);++ JButton chooseButton = findButtonByText(fileChooser, "OK");+ assertNotNull(chooseButton);++ //JTextField filenameTextField = (JTextField)findComponentByName(fileChooser.getComponent(), "filenameTextField");+ //setJTextField(filenameTextField, "fred.h");+ runSwing(() -> fileChooser.setSelectedFile(+ new File(fileChooser.getCurrentDirectory(), "fred.h")));++ waitForUpdateOnChooser(fileChooser);++ pressButton(chooseButton, true);+ waitForPostedSwingRunnables();+ }++ private void reset() {+ LibrarySearchPathManager.reset();+ panel.setPaths(tablePaths);+ }++}