ghidra.program.model.mem.Memory Java Examples
The following examples show how to use
ghidra.program.model.mem.Memory.
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: MergeProgram.java From ghidra with Apache License 2.0 | 6 votes |
public void addMemory(String name, String address, int size) { startTransactions(); try { for (Program p : programs) { Address startAddress = addr(p, address); Memory memory = p.getMemory(); try { memory.createInitializedBlock(name, startAddress, size, (byte) 0, TaskMonitorAdapter.DUMMY_MONITOR, false); } catch (Exception e) { throw new RuntimeException("Exception building memory", e); } } } finally { endTransations(); } }
Example #2
Source File: SampleLocationGenerator.java From ghidra with Apache License 2.0 | 6 votes |
@Override public ProgramLocation[] getBytesLocations() { Memory mem = program.getMemory(); ProgramLocation[] locs = new ProgramLocation[3]; try { Address a = addr(0x1006420); byte[] bytes = new byte[1]; mem.getBytes(a, bytes); locs[0] = new BytesFieldLocation(program, a); a = addr(0x100643d); bytes = new byte[3]; mem.getBytes(a, bytes); locs[1] = new BytesFieldLocation(program, a.add(2), a.add(2), null, 4); a = addr(0x10064f1); bytes = new byte[5]; mem.getBytes(a, bytes); locs[2] = new BytesFieldLocation(program, a.add(1)); } catch (MemoryAccessException e) { throw new RuntimeException("Unexpected exception reading bytes!", e); } return locs; }
Example #3
Source File: ElfBinaryAnalysisCommand.java From ghidra with Apache License 2.0 | 6 votes |
@Override public boolean canApply(Program program) { try { Options options = program.getOptions("Program Information"); String format = options.getString("Executable Format", null); if (!BinaryLoader.BINARY_NAME.equals(format)) { return false; } Memory memory = program.getMemory(); byte[] magicBytes = new byte[ElfConstants.MAGIC_BYTES.length]; memory.getBytes(program.getAddressFactory().getDefaultAddressSpace().getAddress(0), magicBytes); return Arrays.equals(magicBytes, ElfConstants.MAGIC_BYTES); } catch (Exception e) { return false; } }
Example #4
Source File: FindAudioInProgramScript.java From ghidra with Apache License 2.0 | 6 votes |
List<Address> scanForAudioData(byte[] imageBytes, byte[] mask) { Memory memory = currentProgram.getMemory(); MemoryBlock[] blocks = memory.getBlocks(); List<Address> foundImages = new ArrayList<Address>(); for (int i = 0; i < blocks.length; i++) { if (blocks[i].isInitialized()) { Address start = blocks[i].getStart(); Address found = null; while (true) { if (monitor.isCancelled()) { break; } found = memory.findBytes(start, blocks[i].getEnd(), imageBytes, mask, true, monitor); if (found != null) { foundImages.add(found); start = found.add(1); } else break; } } } return foundImages; }
Example #5
Source File: ControlFlowGuard.java From ghidra with Apache License 2.0 | 6 votes |
/** * Performs markup on the ControlFlowGuard dispatch function, if it exists. * * @param lcd The PE LoadConfigDirectory. * @param is64bit True if the PE is 64-bit; false if it's 32-bit. * @param space The program's address space. * @param mem The program's memory. * @param symbolTable The program's symbol table. */ private static void markupCfgDispatchFunction(LoadConfigDirectory lcd, boolean is64bit, AddressSpace space, Memory mem, SymbolTable symbolTable) { if (lcd.getCfgDispatchFunctionPointer() == 0) { return; } try { Address functionPointerAddr = space.getAddress(lcd.getCfgDispatchFunctionPointer()); Address functionAddr = space.getAddress( is64bit ? mem.getLong(functionPointerAddr) : mem.getInt(functionPointerAddr)); symbolTable.createLabel(functionAddr, "_guard_dispatch_icall", SourceType.IMPORTED); } catch (MemoryAccessException | AddressOutOfBoundsException | InvalidInputException e) { Msg.warn(ControlFlowGuard.class, "Unable to label ControlFlowGuard dispatch function.", e); } }
Example #6
Source File: SplitBlockDialog.java From ghidra with Apache License 2.0 | 6 votes |
/** * @see ghidra.util.bean.GhidraDialog#okCallback() */ @Override protected void okCallback() { // call plugin to do the work String newBlockName = blockTwoNameField.getText(); if (newBlockName.length() == 0) { newBlockName = block.getName() + ".split"; blockTwoNameField.setText(newBlockName); } if (!Memory.isValidAddressSpaceName(newBlockName)) { setStatusText("Invalid Block Name: " + newBlockName); return; } if (plugin.getMemoryMapManager().isDuplicateName(newBlockName)) { setStatusText("Address space/overlay named " + newBlockName + " already exists."); return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); plugin.getMemoryMapManager().splitBlock(block, blockTwoStart.getAddress(), newBlockName); close(); }
Example #7
Source File: RelocationFixupHandler.java From ghidra with Apache License 2.0 | 6 votes |
protected boolean process32BitRelocation(Program program, Relocation relocation, Address oldImageBase, Address newImageBase) throws MemoryAccessException, CodeUnitInsertionException { long diff = newImageBase.subtract(oldImageBase); Address address = relocation.getAddress(); Memory memory = program.getMemory(); int value = memory.getInt(address); int newValue = (int) (value + diff); InstructionStasher instructionStasher = new InstructionStasher(program, address); memory.setInt(address, newValue); instructionStasher.restore(); return true; }
Example #8
Source File: AppleSingleDoubleBinaryAnalysisCommand.java From ghidra with Apache License 2.0 | 6 votes |
@Override public boolean canApply(Program program) { try { Memory memory = program.getMemory(); int magicNumber = memory.getInt(program.getAddressFactory().getDefaultAddressSpace().getAddress(0)); if (magicNumber == AppleSingleDouble.SINGLE_MAGIC_NUMBER || magicNumber == AppleSingleDouble.DOUBLE_MAGIC_NUMBER) { return true; } } catch (Exception e) { // expected, ignore } return false; }
Example #9
Source File: PseudoDisassembler.java From ghidra with Apache License 2.0 | 6 votes |
/** * Apply a dataType to the program at the given address. The program is * not affected. A PseudoData item that acts like a Data item retrieved from * a program is returned. This is useful if you have a datatype and you * want to use it to get values from the program at a given address. * * @param addr location to get a PseudoData item for * @param dt the data type to be applied * @return PsuedoData that acts like Data */ public PseudoData applyDataType(Address addr, DataType dt) { Memory memory = program.getMemory(); MemBuffer memBuffer = new DumbMemBufferImpl(memory, addr); // check that address is defined in memory try { memBuffer.getByte(0); return new PseudoData(program, addr, dt, memBuffer); } catch (Exception e) { // ignore } return null; }
Example #10
Source File: GenericRefernenceBaseRelocationFixupHandler.java From ghidra with Apache License 2.0 | 6 votes |
private boolean handleGenerically64(Program program, Relocation relocation, Address oldImageBase, Address newImageBase) throws MemoryAccessException, CodeUnitInsertionException { long diff = newImageBase.subtract(oldImageBase); Address address = relocation.getAddress(); Memory memory = program.getMemory(); long value = memory.getLong(address); long newValue = value + diff; Address candiateRelocationValue = newImageBase.getNewAddress(newValue); if (hasMatchingReference(program, address, candiateRelocationValue)) { return process64BitRelocation(program, relocation, oldImageBase, newImageBase); } return false; }
Example #11
Source File: ControlFlowGuard.java From ghidra with Apache License 2.0 | 6 votes |
/** * Performs markup on the ReturnFlowGuard verify stack pointer function, if it exists. * * @param lcd The PE LoadConfigDirectory. * @param is64bit True if the PE is 64-bit; false if it's 32-bit. * @param space The program's address space. * @param mem The program's memory. * @param symbolTable The program's symbol table. */ private static void markupRfgDefaultStackPointerFunction(LoadConfigDirectory lcd, boolean is64bit, AddressSpace space, Memory mem, SymbolTable symbolTable) { if (lcd.getRfgVerifyStackPointerFunctionPointer() == 0) { return; } try { Address functionPointerAddr = space.getAddress(lcd.getRfgVerifyStackPointerFunctionPointer()); Address functionAddr = space.getAddress( is64bit ? mem.getLong(functionPointerAddr) : mem.getInt(functionPointerAddr)); symbolTable.createLabel(functionAddr, "_guard_ss_verify_sp_default", SourceType.IMPORTED); } catch (MemoryAccessException | AddressOutOfBoundsException | InvalidInputException e) { Msg.warn(ControlFlowGuard.class, "Unable to label ReturnFlowGuard verify stack pointer function.", e); } }
Example #12
Source File: ReferencesPluginScreenShots.java From ghidra with Apache License 2.0 | 6 votes |
@Test public void testOffsetRefsExample() throws MemoryAccessException { // gif removeFlowArrows(); goToListing(0x0400280); int id = program.startTransaction("Test"); Memory memory = program.getMemory(); memory.setByte(addr(0x400284), (byte) 0x14); memory.setByte(addr(0x400288), (byte) 0x18); memory.setByte(addr(0x40028c), (byte) 0x1c); memory.setByte(addr(0x400290), (byte) 0x20); program.endTransaction(id, true); makeSelection(0x400284, 0x400293); performAction("Create Offset References", "OffsetTablePlugin", false); runSwing(() -> { OffsetTableDialog dialog = (OffsetTableDialog) getDialog(); dialog.setBaseAddress(addr(0x4f5000)); }); pressOkOnDialog(); captureIsolatedProvider(CodeViewerProvider.class, 800, 600); }
Example #13
Source File: SearchInfo.java From ghidra with Apache License 2.0 | 6 votes |
/** * Generate an address set which only includes initialized memory * * @param program the program * @param startAddress starting point for search or null to start from the top of memory * @param selection addresses to be searched or null to search all memory * @return searchable address set */ protected AddressSetView getSearchableAddressSet(Program program, Address startAddress, ProgramSelection selection) { if (startAddress == null) { return new AddressSet(); // special case if we are at the first address going backwards // or the last address going forwards } Memory memory = program.getMemory(); AddressSetView set = includeNonLoadedBlocks ? memory.getAllInitializedAddressSet() : memory.getLoadedAndInitializedAddressSet(); if (searchSelection && selection != null && !selection.isEmpty()) { set = set.intersect(selection); } Address start = forwardSearch ? startAddress : memory.getMinAddress(); Address end = forwardSearch ? memory.getMaxAddress() : startAddress; if (start.compareTo(end) > 0) { return new AddressSet(); } AddressSet addressSet = program.getAddressFactory().getAddressSet(start, end); return set.intersect(addressSet); }
Example #14
Source File: ObjectiveC1_ClassAnalyzer.java From ghidra with Apache License 2.0 | 6 votes |
private void setDataAndRefBlocksReadOnly(ObjectiveC1_State state) { Memory memory = state.program.getMemory(); MemoryBlock dataBlock = memory.getBlock(ObjectiveC1_Constants.OBJC_SECTION_DATA); if (dataBlock != null) { dataBlock.setWrite(false); } MemoryBlock classRefsBlock = memory.getBlock(ObjectiveC1_Constants.OBJC_SECTION_CLASS_REFS); if (classRefsBlock != null) { classRefsBlock.setWrite(false); } MemoryBlock messageRefsBlock = memory.getBlock(ObjectiveC1_Constants.OBJC_SECTION_MESSAGE_REFS); if (messageRefsBlock != null) { messageRefsBlock.setWrite(false); } }
Example #15
Source File: FindAndReplaceCommentScriptTest.java From ghidra with Apache License 2.0 | 6 votes |
private void assertCommentDoesNotExists(String comment) { Memory memory = program.getMemory(); Iterator<Address> addressIterator = listing.getCommentAddressIterator(memory, true); boolean commentExists = false; while (addressIterator.hasNext()) { Address address = addressIterator.next(); for (int i : COMMENT_TYPES) { String foundComment = listing.getComment(i, address); if (foundComment != null && foundComment.equals(comment)) { commentExists = true; } } } assertFalse(commentExists); }
Example #16
Source File: MemoryBlockHelper.java From Ghidra-Switch-Loader with ISC License | 6 votes |
private void addUniqueSection(String name, long addressOffset, long offset, long length, boolean read, boolean write, boolean execute) { Memory memory = this.program.getMemory(); Address startAddr = this.program.getImageBase().add(addressOffset); Address endAddr = startAddr.add(length); String newBlockName = name; int nameCounter = 0; while (memory.getBlock(newBlockName) != null) { nameCounter++; newBlockName = name + "." + nameCounter; } Msg.info(this, "Adding unique section " + newBlockName + " from " + startAddr.toString() + " to " + endAddr.toString()); this.addSection(newBlockName, offset, offset, length, read, write, execute); }
Example #17
Source File: FollowFlow.java From ghidra with Apache License 2.0 | 6 votes |
private Address getNextSymbolAddress(Address curAddr, Address curNext) { if (curAddr == null) { return null; } // once there is no next function, don't return one. if (curNext == Address.NO_ADDRESS) { return curNext; } if (curNext == null || curNext.compareTo(curAddr) < 0) { // find the next function symbol from curAddr to end of current space SymbolTable symbolTable = program.getSymbolTable(); Memory memory = program.getMemory(); SymbolIterator symbols = symbolTable.getSymbolIterator(curAddr, true); if (symbols.hasNext()) { Symbol symbol = symbols.next(); Address addr = symbol.getAddress(); if (addr.getAddressSpace().equals(curAddr.getAddressSpace()) && memory.contains(addr)) { return addr; } } return Address.NO_ADDRESS; } return curNext; }
Example #18
Source File: IntRangeMapTest.java From ghidra with Apache License 2.0 | 6 votes |
@Test public void testDeleteBlockRange() throws Exception { Memory memory = program.getMemory(); MemoryBlock block = memory.createInitializedBlock(".test", getAddr(5), 0x20, (byte) 0xa, TaskMonitorAdapter.DUMMY_MONITOR, false); AddressSet set = new AddressSet(); set.addRange(getAddr(0), getAddr(0x10)); set.addRange(getAddr(0x20), getAddr(0x25)); set.addRange(getAddr(0x26), getAddr(0x30)); IntRangeMap map = program.createIntRangeMap("MyMap"); int value = 0x11223344; map.setValue(set, value); // remove the block memory.removeBlock(block, TaskMonitorAdapter.DUMMY_MONITOR); // [0,4], [25,30] should still exist // [5,24] should have been removed AddressSet s = new AddressSet(); s.addRange(getAddr(0), getAddr(0x4)); s.addRange(getAddr(0x25), getAddr(0x30)); AddressSet mapSet = map.getAddressSet(); assertEquals(s, mapSet); }
Example #19
Source File: SymbolManagerTest.java From ghidra with Apache License 2.0 | 6 votes |
@Test public void testGetDefaultFunctionInOverlaySymbolByName() throws Exception { Memory memory = program.getMemory(); MemoryBlock block = memory.createInitializedBlock("ov_12", addr(0), 5000, (byte) 0, TaskMonitorAdapter.DUMMY_MONITOR, true); Address ovAddress = block.getStart(); assertEquals("ov_12::00000000", ovAddress.toString()); Listing listing = program.getListing(); AddressSet set = new AddressSet(ovAddress, ovAddress); Function f = listing.createFunction("fredFunc", ovAddress, set, SourceType.DEFAULT); assertNotNull(f); String defaultName = "FUN_ov_12__00000000"; Symbol s1 = st.getPrimarySymbol(ovAddress); assertNotNull(s1); assertEquals(defaultName, s1.getName()); assertTrue(s1.isPrimary()); Symbol s = getUniqueSymbol(program, defaultName); assertNotNull(s); assertEquals(ovAddress, s.getAddress()); }
Example #20
Source File: ControlFlowGuard.java From ghidra with Apache License 2.0 | 6 votes |
/** * Perform markup on the supported ControlFlowGuard and ReturnFlowGuard functions and * tables, if they exist. * * @param lcd The PE LoadConfigDirectory. * @param program The program. * @param log The log. * @param ntHeader The PE NTHeader. */ public static void markup(LoadConfigDirectory lcd, Program program, MessageLog log, NTHeader ntHeader) { boolean is64bit = ntHeader.getOptionalHeader().is64bit(); AddressSpace space = program.getAddressFactory().getDefaultAddressSpace(); Memory mem = program.getMemory(); SymbolTable symbolTable = program.getSymbolTable(); // ControlFlowGuard markupCfgCheckFunction(lcd, is64bit, space, mem, symbolTable); markupCfgDispatchFunction(lcd, is64bit, space, mem, symbolTable); markupCfgFunctionTable(lcd, program, log); // ReturnFlowGuard markupRfgFailureRoutine(lcd, space, symbolTable); markupRfgDefaultFailureRoutine(lcd, is64bit, space, mem, symbolTable); markupRfgDefaultStackPointerFunction(lcd, is64bit, space, mem, symbolTable); }
Example #21
Source File: NextPrevCodeUnitPluginTest.java From ghidra with Apache License 2.0 | 6 votes |
private Address addInstructions(String addr) throws Exception { Address address = program.getAddressFactory().getAddress(addr); int txID = program.startTransaction("Add Test Instruction"); try { // these bytes create a couple instructions in x86 Memory memory = program.getMemory(); memory.setBytes(address, new byte[] { 0x55, (byte) 0x8b, (byte) 0xec }); AddressSet set = new AddressSet(address, address.add(4)); DisassembleCommand cmd = new DisassembleCommand(set, set); cmd.applyTo(program); } finally { program.endTransaction(txID, true); } return address; }
Example #22
Source File: AbstractRttiTest.java From ghidra with Apache License 2.0 | 6 votes |
protected void checkVfTableData(ProgramDB program, long metaPointerAddress, long rtti4Address, long vfTableAddress, long[] vfAddresses) { PointerDataType pointerDataType = new PointerDataType(program.getDataTypeManager()); checkSimpleData(program, metaPointerAddress, pointerDataType); checkSimpleData(program, rtti4Address, Rtti4Model.getDataType(program)); checkArrayData(program, vfTableAddress, pointerDataType, vfAddresses.length); // Check for specific function pointer values? Memory memory = program.getMemory(); AddressSetView loadedAndInitializedAddressSet = memory.getLoadedAndInitializedAddressSet(); for (long vfAddress : vfAddresses) { Address vfAddr = addr(program, vfAddress); String failureMessage = "VF Address " + vfAddr + " isn't in loaded and initialized memory of program " + program.getName() + "."; assertTrue(failureMessage, loadedAndInitializedAddressSet.contains(vfAddr)); } }
Example #23
Source File: RegisterMergeManager.java From ghidra with Apache License 2.0 | 6 votes |
/** * * @param monitor */ private void determineConflicts(TaskMonitor monitor) throws CancelledException { if (conflictSet != null) { return; //This method only needs to be called once. } RegisterConflicts rc = new RegisterConflicts(registerName, originalContext, latestContext, myContext, resultContext); Memory resultMem = resultPgm.getMemory(); AddressSetView myDiffs = rc.getRegisterDifferences(registerName, originalContext, myContext, mySet, monitor); AddressSet setToCheck = resultMem.intersect(myDiffs); conflictSet = new AddressSet(); rvrs = rc.getConflicts(setToCheck, monitor); if (rvrs.length > 0) { for (int j = 0; j < rvrs.length; j++) { conflictSet.add(rvrs[j]); } } autoSet = setToCheck.subtract(conflictSet); }
Example #24
Source File: GhidraTableCellRenderer.java From ghidra with Apache License 2.0 | 6 votes |
private boolean isValueOutOfMemoryAddress(TableModel model, Object value) { if (!(value instanceof Address)) { return false; } if (!(model instanceof ProgramTableModel)) { return false; } ProgramTableModel programTableModel = (ProgramTableModel) model; Program program = programTableModel.getProgram(); if (program == null) { return false; // can happen when program closed } Address address = (Address) value; Memory memory = program.getMemory(); return !memory.contains(address); }
Example #25
Source File: Rtti2Model.java From ghidra with Apache License 2.0 | 6 votes |
private boolean validRefData(Memory memory, Address addr) { Program program = memory.getProgram(); boolean is64Bit = MSDataTypeUtils.is64Bit(program); DumbMemBufferImpl refBuffer = new DumbMemBufferImpl(memory, addr); Settings settings = simpleIndividualEntryDataType.getDefaultSettings(); Object value = simpleIndividualEntryDataType.getValue(refBuffer, settings, 4); if (value instanceof Address) { Address address = (Address) value; if (is64Bit && program.getImageBase().equals(address)) { return false; // zero value. } if (!is64Bit && address.getOffset() == 0L) { return false; // zero value. } return memory.getLoadedAndInitializedAddressSet().contains(address); } return false; }
Example #26
Source File: GetSymbolForDynamicAddress.java From ghidra with Apache License 2.0 | 6 votes |
private void processProgram(Program program) throws Exception { if (foundSymbol) { return; } if (!program.getLanguageID().equals(currentProgram.getLanguageID())) { return; } Memory memory = program.getMemory(); if (memory.contains(addressToLookFor)) { programsWithAddress.add(program.getName()); Listing listing = program.getListing(); Function function = listing.getFunctionAt(addressToLookFor); if (function == null) { return; } String functionName = function.getName(); demangleAndCreateSymbol(functionName); foundSymbol = true; } }
Example #27
Source File: AddressSetPropertyMapTest.java From ghidra with Apache License 2.0 | 6 votes |
@Test public void testDeleteBlockRange() throws Exception { Memory memory = program.getMemory(); MemoryBlock block = memory.createInitializedBlock(".test", getAddr(5), 0x20, (byte) 0xa, TaskMonitorAdapter.DUMMY_MONITOR, false); AddressSet set = new AddressSet(); set.addRange(getAddr(0), getAddr(0x10)); set.addRange(getAddr(0x20), getAddr(0x25)); set.addRange(getAddr(0x26), getAddr(0x30)); AddressSetPropertyMap pm = program.createAddressSetPropertyMap("MyMap"); pm.add(set); // remove the block memory.removeBlock(block, TaskMonitorAdapter.DUMMY_MONITOR); // [0,4], [25,30] should still exist // [5,24] should have been removed AddressSet s = new AddressSet(); s.addRange(getAddr(0), getAddr(0x4)); s.addRange(getAddr(0x25), getAddr(0x30)); AddressSet pmSet = pm.getAddressSet(); assertEquals(s, pmSet); }
Example #28
Source File: MachoBinaryAnalysisCommand.java From ghidra with Apache License 2.0 | 6 votes |
@Override public boolean canApply(Program program) { try { Options options = program.getOptions("Program Information"); String format = options.getString("Executable Format", null); if (!BinaryLoader.BINARY_NAME.equals(format)) { return false; } Memory memory = program.getMemory(); Address address = getAddress(program); int magic = memory.getInt(address); return MachConstants.isMagic(magic); } catch (Exception e) { } return false; }
Example #29
Source File: ProgramBuilder.java From ghidra with Apache License 2.0 | 6 votes |
/** * Sets the bytes starting at {@code stringAddress} to the byte values in {@code bytes} * and then optionally disassembling. * <p> * @param stringAddress String containing numeric value, preferably hex encoded: "0x1004000" * @param bytes array of bytes to copy into the memory buffer at the addresss. * @param disassemble boolean flag. See {@link #disassemble(String, int)} * @throws Exception */ public void setBytes(String stringAddress, byte[] bytes, boolean disassemble) throws Exception { Address address = addr(stringAddress); startTransaction(); MemoryBlock block = program.getMemory().getBlock(address); if (block == null) { createMemory("Block_" + stringAddress.toString().replace(':', '_'), stringAddress, bytes.length); } Memory memory = program.getMemory(); memory.setBytes(address, bytes); endTransaction(); if (disassemble) { disassemble(stringAddress, bytes.length); } }
Example #30
Source File: PEUtil.java From ghidra with Apache License 2.0 | 6 votes |
static boolean isValidGuidPointer(Program program, Address addr) { Memory memory = program.getMemory(); AddressFactory addressFactory = program.getAddressFactory(); AddressSpace defaultSpace = addressFactory.getDefaultAddressSpace(); try { int addrAsInt = memory.getInt(addr); Address pointedToAddr = addressFactory.getAddress(defaultSpace.getBaseSpaceID(), addrAsInt); if (memory.contains(pointedToAddr)) { GuidInfo guidInfo = GuidUtil.getKnownGuid(program, pointedToAddr); if (guidInfo != null) { return true; } } } catch (MemoryAccessException e) { } return false; }