ghidra.program.model.listing.ProgramFragment Java Examples

The following examples show how to use ghidra.program.model.listing.ProgramFragment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TreeManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Get the fragment that contains the given address within the tree
 * identified by the treeName.
 * @param treeName name of the tree
 * @param addr address contained within some fragment
 * @return fragment containing addr, or null if addr does not
 * exist in memory
 */
public ProgramFragment getFragment(String treeName, Address addr) {
	lock.acquire();
	try {
		ModuleManager m = treeMap.get(treeName);
		if (m != null) {
			return m.getFragment(addr);
		}

	}
	catch (IOException e) {
		errHandler.dbError(e);

	}
	finally {
		lock.release();
	}
	return null;
}
 
Example #2
Source File: ReorderManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
   * Add the given data to the destination node.
   * @param destNode destination node for the data.
   * @param dropNode data to add
   */
  void add(ProgramNode destNode, ProgramNode[] dropNodes, int dropAction, int relativeMousePos) 
          throws NotFoundException, CircularDependencyException, DuplicateGroupException {

      ProgramModule targetModule = destNode.getModule();
      ProgramFragment targetFrag = destNode.getFragment();
      if (targetModule == null && targetFrag == null) {
          tree.clearDragData();
          return; // ignore the drop
      }

int transactionID = tree.startTransaction("Reorder");
if (transactionID < 0) {
	return;
}

try {
          for ( int i = 0; i < dropNodes.length; i++ ) {
              ProgramNode parentNode = (ProgramNode)destNode.getParent();
              reorderNode( destNode, dropAction, relativeMousePos, parentNode, dropNodes[i] );
          }
} finally {
	tree.endTransaction(transactionID, true);
}			
  }
 
Example #3
Source File: TreeManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Get the fragment with the given name that is in the tree identified
 * by the treeName.
 * @param treeName name of the tree
 * @param name name of fragment to look for
 * @return null if there is no fragment with the given name in the tree
 */
public ProgramFragment getFragment(String treeName, String name) {
	lock.acquire();
	try {
		ModuleManager m = treeMap.get(treeName);
		if (m != null) {
			return m.getFragment(name);
		}
	}
	catch (IOException e) {
		errHandler.dbError(e);

	}
	finally {
		lock.release();
	}
	return null;
}
 
Example #4
Source File: AutoRenamePlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Perform Fragment Rename based upon the active LabelFieldLocation object.
 */
void autoLabelRenameCallback(ListingActionContext context) {

    // Get selected fragment
	ProgramLocation location = context.getLocation();
    if (location instanceof LabelFieldLocation && currentProgram != null) {

        LabelFieldLocation labelField = (LabelFieldLocation) location;
        String label = labelField.getName();
        String treeName = treeService.getViewedTreeName();
        ProgramFragment fragment = currentProgram.getListing().getFragment(treeName, labelField.getAddress());
        if (!label.equals(fragment.getName())) {
            RenameCmd cmd = new RenameCmd(treeName, false, fragment.getName(), label);
            if (!tool.execute(cmd, currentProgram)) {
                tool.setStatusInfo("Error renaming fragment: " + cmd.getStatusMsg());
            }
        }
    }
}
 
Example #5
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoubleClick2() {
	setTreeView("Main Tree");
	ProgramNode node = root.getChild(".data");
	TreePath[] paths = new TreePath[] { node.getTreePath() };
	setViewPaths(paths);

	int row = getRowForPath(paths[0]);

	Rectangle rect = tree.getRowBounds(row);
	clickMouse(tree, MouseEvent.BUTTON1, rect.x, rect.y, 2, 0);
	node = (ProgramNode) tree.getPathForRow(3).getLastPathComponent();
	ProgramFragment fragment = node.getFragment();
	Address address = fragment.getMinAddress();
	assertEquals(address, cbPlugin.getCurrentAddress());
}
 
Example #6
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testGoToViewIcon() {
	setTreeView("Main Tree");

	actionMgr.setProgramTreeView("Main Tree", tree);

	clearView();

	runSwing(() -> viewMgrService.addToView(new ProgramLocation(program, getAddr(0x01001000))));

	ProgramFragment f = program.getListing().getFragment("Main Tree", getAddr(0x01001000));
	ProgramNode[] nodes = findNodes(f.getName());
	assertTrue(nodes.length > 0);

	int row = getRowForPath(nodes[0].getTreePath());
	Component comp = getCellRendererComponentForLeaf(nodes[0], row);
	assertEquals(ResourceManager.loadImage(DnDTreeCellRenderer.VIEWED_FRAGMENT),
		((JLabel) comp).getIcon());
}
 
Example #7
Source File: SymbolLoader.java    From Ghidra-GameCube-Loader with Apache License 2.0 5 votes vote down vote up
private void renameFragment(Address blockStart, String blockName) {
	String[] treeNames = this.program.getListing().getTreeNames();
	for (int i = 0; i < treeNames.length; ++i) {
		ProgramFragment frag = this.program.getListing().getFragment(treeNames[i], blockStart);
		
		try {
			frag.setName(blockName);
		}
		catch (DuplicateNameException e) {
			e.printStackTrace();
		}
	}
}
 
Example #8
Source File: Fragment20BitTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
   public void testMoveCodeUnit() throws Exception {
	ProgramFragment frag = root.createFragment("testFrag");
	frag.move(addr("0d43:0000"), addr("0000:e517"));

	ProgramFragment sf = root.createFragment("SingleCU");
	sf.move(addr("0000:e517"), addr("0000:e517"));

	assertTrue(sf.contains(addr("0000:e517")));
}
 
Example #9
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testToolTip() throws Exception {
	setTreeView("Main Tree");
	ProgramNode node = root.getChild(".data");
	ProgramFragment f = node.getFragment();
	AddressRange range = f.getFirstRange();
	assertEquals(range.toString(), tree.getToolTipText(node));
}
 
Example #10
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoubleClickOnFragment() {

	setTreeView("Main Tree");
	Rectangle rect = tree.getRowBounds(2);
	clickMouse(tree, MouseEvent.BUTTON1, rect.x, rect.y, 2, 0);

	ProgramNode node = (ProgramNode) tree.getPathForRow(2).getLastPathComponent();
	ProgramFragment fragment = node.getFragment();
	Address address = fragment.getMinAddress();
	assertEquals(address, cbPlugin.getCurrentAddress());
}
 
Example #11
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenameDuplicateFragment() throws Exception {

	int transactionID = program.startTransaction("Test");
	ProgramModule m = createModule(root, "Module-1");
	ProgramFragment f = m.createFragment("strcpy");
	program.endTransaction(transactionID, true);
	program.flushEvents();

	expandRoot();

	buildNodeList();
	final ProgramNode[] nodes = findNodes("strcpy");
	setSelectionPath(nodes[0].getTreePath());
	final DockingActionIf action = getAction(plugin, "Rename folder/fragment");
	assertTrue(action.isEnabled());

	runSwing(() -> {
		action.actionPerformed(new ActionContext());
		int row = tree.getRowForPath(nodes[0].getTreePath());
		DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor();
		Container container = (Container) cellEditor.getTreeCellEditorComponent(tree, nodes[0],
			true, true, true, row);
		textField = (JTextField) container.getComponent(0);
		textField.setText(".data");
		tree.stopEditing();
	});
	waitForPostedSwingRunnables();
	assertEquals(f.getName(), textField.getText());
}
 
Example #12
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenameFragment() throws Exception {
	ProgramNode node = (ProgramNode) root.getChildAt(0);
	ProgramFragment f = node.getFragment();

	int transactionID = program.startTransaction("Test");
	ProgramModule m = createModule(root, "Module-1");
	m.add(f);
	m = m.createModule("Module-2");
	m.add(f);
	m = m.createModule("Module-3");
	m.add(f);

	program.endTransaction(transactionID, true);
	waitForPostedSwingRunnables();

	// wait for events to get processed
	program.flushEvents();

	expandRoot();

	buildNodeList();
	ProgramNode[] nodes = findNodes(f.getName());
	assertEquals(4, nodes.length);

	transactionID = program.startTransaction("Test");
	f.setName("MyFragment");
	program.endTransaction(transactionID, true);
	program.flushEvents();

	buildNodeList();
	nodes = findNodes(f.getName());
	assertEquals(4, nodes.length);
}
 
Example #13
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateFragFromCUwithLabel() throws Exception {
	SymbolTable symbolTable = program.getSymbolTable();

	Address start = getAddr(0x0100101c);
	Address end = getAddr(0x0100101f);

	AddressSet set = new AddressSet();
	set.addRange(start, end);

	int transactionID = program.startTransaction("Test");
	symbolTable.createLabel(start, "MyLabel", SourceType.USER_DEFINED);
	program.endTransaction(transactionID, true);

	set.addRange(getAddr(0x01001190), getAddr(0x01001193));

	int childCount = root.getChildCount();

	addCodeUnits(root, set);

	program.flushEvents();

	assertEquals(childCount + 1, root.getChildCount());
	ProgramNode node = (ProgramNode) root.getChildAt(childCount);
	assertEquals("MyLabel", node.getName());

	ProgramFragment f = node.getFragment();
	assertTrue(f.hasSameAddresses(set));

	undo();
	assertEquals(childCount, root.getChildCount());
	redo();
	assertEquals(childCount + 1, root.getChildCount());
	node = (ProgramNode) root.getChildAt(childCount);
	assertEquals("MyLabel", node.getName());
}
 
Example #14
Source File: TwoLevelHintsCommand.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void markup(MachHeader header, FlatProgramAPI api, Address baseAddress, boolean isBinary,
		ProgramModule parentModule, TaskMonitor monitor, MessageLog log) {
	updateMonitor(monitor);
	try {
		if (isBinary) {
			ProgramFragment fragment = createFragment(api, baseAddress, parentModule);
			Address addr = baseAddress.getNewAddress(getStartIndex());
			api.createData(addr, toDataType());

			Address hintStartAddress = baseAddress.add(getOffset());
			Address hintAddress = hintStartAddress;
			for (TwoLevelHint hint : hints) {
				if (monitor.isCancelled()) {
					return;
				}
				DataType hintDT = hint.toDataType();
				api.createData(hintAddress, hintDT);
				api.setPlateComment(hintAddress,
					"Sub-image Index: 0x" + Integer.toHexString(hint.getSubImageIndex()) +
						'\n' + "      TOC Index: 0x" +
						Integer.toHexString(hint.getTableOfContentsIndex()));
				hintAddress = hintAddress.add(hintDT.getLength());
			}
			fragment.move(hintStartAddress, hintAddress.subtract(1));
		}
	}
	catch (Exception e) {
		log.appendMsg("Unable to create " + getCommandName() + " - " + e.getMessage());
	}
}
 
Example #15
Source File: AutoRenamePlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Perform Fragment Auto-Rename on selected Fragments.
 * Rename is performed on all selected Fragments within Program Tree.
 */
void autoRenameCallback(ActionContext context) {

    Object obj = context.getContextObject();
    if (obj instanceof ProgramNode) {
        ProgramNode node = (ProgramNode) obj;

        CompoundCmd cmd = new CompoundCmd("Auto Rename Fragment(s)");
        SymbolTable symTable = currentProgram.getSymbolTable();

        // Find selected Fragments
        TreePath[] selectedPaths = node.getTree().getSelectionPaths();
        boolean ignoreDuplicateNames = (selectedPaths.length > 1);
        for (int i = 0; i < selectedPaths.length; i++) {
            ProgramNode n = (ProgramNode) selectedPaths[i].getLastPathComponent();
            if (!n.isFragment())
                continue;

            // Rename Fragment using minimum address label	
            ProgramFragment f = n.getFragment();
            Address a = f.getMinAddress();
            if (a == null)
                continue; // empty Fragment
            Symbol s = symTable.getPrimarySymbol(a);
            if (s != null) {
                cmd.add(new RenameCmd(f.getTreeName(), false, f.getName(), s.getName(), 
                	ignoreDuplicateNames));
            }
        }

        if (cmd.size() > 0 && !tool.execute(cmd, currentProgram)) {
            tool.setStatusInfo("Error renaming fragment: " + cmd.getStatusMsg());
        }
    }
}
 
Example #16
Source File: ProgramTreePlugin1Test.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testCollapseAll() throws Exception {

	ProgramNode node = (ProgramNode) root.getChildAt(0);

	final ProgramFragment f = node.getFragment();
	runSwing(() -> {
		int transactionID = program.startTransaction("Test");
		try {
			ProgramModule m = root.getModule().createModule("Module-1");

			ProgramModule m2 = root.getModule().createModule("submodule");
			m.add(m2);
			m.add(f);

			m = m.createModule("Module-2");
			m.add(m2);
			m.add(f);

			m = m.createModule("Module-3");
			m.add(m2);
			m.add(f);

			m = m.createModule("Module-4");
			m.add(m2);
			m.add(f);
			program.endTransaction(transactionID, true);
			// wait for events to get processed
		}
		catch (Exception e) {
			Assert.fail("Error modifying program: " + e);
		}
	});

	runSwing(() -> root = (ProgramNode) tree.getModel().getRoot());
	collapseNode(root);
	buildNodeList();
	ArrayList<?> nodeList = tree.getNodeList();
	for (int i = 0; i < nodeList.size(); i++) {
		node = (ProgramNode) nodeList.get(i);
		if (node.getAllowsChildren() && !node.isLeaf()) {
			assertTrue(!tree.isExpanded(node.getTreePath()));
		}
	}
}
 
Example #17
Source File: LoadCommand.java    From ghidra with Apache License 2.0 4 votes vote down vote up
protected final ProgramFragment createFragment(FlatProgramAPI api, Address baseAddress,
		ProgramModule module) throws Exception {
	Address start = baseAddress.getNewAddress(getStartIndex());
	return api.createFragment(module, getCommandName(), start, getCommandSize());
}
 
Example #18
Source File: ReorderManager.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Add a new group to the destNode or re-parent the drop Node to
 * the destNode's parent (or to root if destNode's parent is null).
 * @param destNode drop site for dropped node
 * @param dropNode node to drop at destNode
 * @param targetIndex new index for node that is added
 * @param dropAction DnDConstants.ACTION_COPY or ACTION_MOVE
 */
private void addGroup(ProgramNode destNode, ProgramNode dropNode,
                  int targetIndex, int dropAction) 
    throws NotFoundException, CircularDependencyException,
            DuplicateGroupException{
    Group group = null;
    ProgramNode targetParent = (ProgramNode)destNode.getParent();
    
    // first add drop fragment or module
    //  to target's parent
    ProgramModule targetParentModule = 
        (targetParent != null) ? targetParent.getModule() :
                                        destNode.getModule();

    ProgramFragment dropFragment = dropNode.getFragment();
    ProgramModule dropModule = dropNode.getModule();

    if (dropAction == DnDConstants.ACTION_COPY) {
        if (dropFragment!= null) {
            targetParentModule.add(dropFragment);
            group = dropFragment;
        }
        else {
            targetParentModule.add(dropModule);
            group = dropModule;
        }
    }
    else {
        targetParentModule.reparent(dropNode.getName(),
                                    dropNode.getParentModule());
        if (dropFragment != null) {
            group = dropFragment;
        }
        else {
            group = dropModule;
        }
    }
    tree.groupAdded(group);
    targetParentModule.moveChild(group.getName(),
                             targetIndex);
    tree.reorder(dropNode.getGroup(), targetParentModule,
                         targetIndex);
}