Java Code Examples for ghidra.program.model.address.Address#addNoWrap()

The following examples show how to use ghidra.program.model.address.Address#addNoWrap() . 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: NXProgramBuilder.java    From Ghidra-Switch-Loader with ISC License 6 votes vote down vote up
protected void setupStringTable() throws AddressOverflowException, CodeUnitInsertionException, DataTypeConflictException
{
   NXOAdapter adapter = this.nxo.getAdapter();
   ElfStringTable stringTable = adapter.getStringTable(this.program);
   
   if (stringTable == null)
       return;
   
   long stringTableAddrOffset = stringTable.getAddressOffset();
    
    Address address = this.aSpace.getAddress(stringTableAddrOffset);
    Address end = address.addNoWrap(stringTable.getLength() - 1);
    
    while (address.compareTo(end) < 0) 
    {
        int length = this.createString(address);
        address = address.addNoWrap(length);
    }
}
 
Example 2
Source File: ByteMappingScheme.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the mapped source address for a specified offset with the mapped sub-block.
 * @param mappedSourceBaseAddress mapped source base address for sub-block
 * @param offsetInSubBlock byte offset within sub-block to be mapped into source
 * @return mapped source address
 * @throws AddressOverflowException if offset in sub-block produces a wrap condition in
 * the mapped source address space.
 */
public Address getMappedSourceAddress(Address mappedSourceBaseAddress,
		long offsetInSubBlock)
		throws AddressOverflowException {
	if (offsetInSubBlock < 0) {
		throw new IllegalArgumentException("negative offset");
	}
	long sourceOffset = offsetInSubBlock;
	if (!isOneToOneMapping()) {
		sourceOffset = (mappedSourceByteCount * (offsetInSubBlock / mappedByteCount)) +
			(offsetInSubBlock % mappedByteCount);
	}
	return mappedSourceBaseAddress.addNoWrap(sourceOffset);
}
 
Example 3
Source File: ByteMappingScheme.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Write an array of bytes to memory utilizing this mapping scheme.  
 * @param memory program memory
 * @param mappedSourceBaseAddress base source memory address for byte-mapped subblock
 * @param offsetInSubBlock byte offset from start of subblock where writing should begin
 * @param b an array to get bytes from
 * @param off start source index within byte array b where bytes should be read
 * @param len number of bytes to be written
 * @throws MemoryAccessException if write of uninitialized or non-existing memory occurs
 * @throws AddressOverflowException if address computation error occurs
 */
void setBytes(Memory memory, Address mappedSourceBaseAddress, long offsetInSubBlock,
		byte[] b,
		int off, int len) throws MemoryAccessException, AddressOverflowException {

	if (isOneToOneMapping()) {
		memory.setBytes(mappedSourceBaseAddress.addNoWrap(offsetInSubBlock), b, off, len);
		return;
	}

	long patternCount = offsetInSubBlock / mappedByteCount;
	int partialByteCount = (int) (offsetInSubBlock % mappedByteCount);
	long mappedOffset = (mappedSourceByteCount * patternCount) + partialByteCount;

	Address destAddr = mappedSourceBaseAddress.addNoWrap(mappedOffset);

	int index = off;
	int cnt = 0;
	int i = mappedByteCount - partialByteCount;
	while (cnt < len) {
		memory.setBytes(destAddr, b, index, i);
		index += i;
		cnt += i;
		destAddr = destAddr.addNoWrap(i + nonMappedByteCount);
		i = mappedByteCount;
	}
}
 
Example 4
Source File: DisassembledViewPlugin.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the {@link DisassembledAddressInfo}s for the given address.  
 * This method will disassamble {@link #LOOK_AHEAD_COUNT a few} addresses 
 * after the one that is passed in.
 * 
 * @param  address The address for which an info object will be obtained.
 * @return An array of info objects describing the initial address and any
 *         others that could be obtained.
 */
private DisassembledAddressInfo[] getAddressInformation(Address address) {
	List<DisassembledAddressInfo> infoList = new ArrayList<>();

	if (address != null) {
		try {
			DisassembledAddressInfo addressInfo = new DisassembledAddressInfo(address);

			// Now get some follow-on addresses to provide a small level of 
			// context.  This loop will stop if we cannot find an Address
			// or a CodeUnit for a given address.
			for (int i = 0; (i < LOOK_AHEAD_COUNT) && (address != null) &&
				addressInfo.isValidAddress(); i++) {
				infoList.add(addressInfo);

				// Increment the address for the next code unit preview.
				// This call throws an AddressOverflowException
				address = address.addNoWrap(addressInfo.getCodeUnitLength());

				if (address != null) {
					addressInfo = new DisassembledAddressInfo(address);
				}
			}
		}
		catch (AddressOverflowException aoe) {
			// we don't really care because there is nothing left to show
			// here, as we've reached the end of the address space
		}
	}

	return infoList.toArray(new DisassembledAddressInfo[infoList.size()]);
}
 
Example 5
Source File: CreateStringScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void run() throws Exception {

	Address addr = find(null, TERMINATOR);
	while (addr != null) {
		createString(addr);
		try {
			addr = addr.addNoWrap(1);
			addr = find(addr, TERMINATOR);
		}
		catch (AddressOverflowException e) {
			// must be at largest possible address - so we are done
		}
	}
}
 
Example 6
Source File: DisassembledViewPluginTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the plugins response to 
 * {@link ghidra.app.events.ProgramLocationPluginEvent}s.  This plugin is
 * driven off of these events.
 * 
 * @throws Exception If there is a problem opening the program.
 */
@Test
public void testProcessingOnLocationChanged() throws Exception {
	openProgram("notepad");

	// get the list hiding inside of the component provider
	JList list = (JList) getInstanceField("contentList", componentProvider);

	// sanity check
	assertEquals("The component provider has data when it is not visible.", 0,
		list.getModel().getSize());

	// show the plugin and make sure it is visible before we continue
	tool.showComponentProvider(componentProvider, true);
	waitForPostedSwingRunnables();

	ListModel modelOne = list.getModel();

	// now the list should have data, as it will populate itself off of the
	// current program location of the plugin
	assertTrue("The component provider does not have data when it " + "should.",
		(modelOne.getSize() != 0));

	// make sure we process the event in order to show the user the 
	// preview
	CodeBrowserPlugin cbPlugin = getPlugin(tool, CodeBrowserPlugin.class);

	// scroll the display and force a new selection
	pageDown(cbPlugin.getFieldPanel());
	simulateButtonPress(cbPlugin);
	waitForPostedSwingRunnables();

	// get the data
	ListModel modelTwo = list.getModel();

	boolean sameData = compareListData(modelOne, modelTwo);
	assertTrue("The contents of the two lists are the same when they " + "should not be.",
		!sameData);

	// make sure no work is done when we are not visible
	tool.showComponentProvider(componentProvider, false);
	waitForPostedSwingRunnables();

	assertEquals("The component provider has data when it is not visible.", 0,
		list.getModel().getSize());

	// show the plugin so that it will get the program location change 
	// data
	tool.showComponentProvider(componentProvider, true);
	waitForPostedSwingRunnables();

	// test that sending a bad address will not return any results or 
	// throw any exceptions
	Memory memory = program.getMemory();
	MemoryBlock textBlock = memory.getBlock(".text");
	Address endAddress = textBlock.getEnd();

	// creating a program location based upon the end address should result
	// in only one item in the disassembled list
	ProgramLocation location = new ProgramLocation(program, endAddress);

	// call the locationChanged() method
	invokeInstanceMethod("locationChanged", plugin, new Class[] { ProgramLocation.class },
		new Object[] { location });

	assertTrue(
		"The plugin's display list has more than 1 element when " +
			"at the end address of a memory block.  List size: " + list.getModel().getSize(),
		(list.getModel().getSize() == 1));

	Listing listing = program.getListing();
	CodeUnit codeUnit = listing.getCodeUnitAt(endAddress);
	Address invalidAddress = endAddress.addNoWrap(codeUnit.getLength());
	ProgramLocation newLocation = new ProgramLocation(program, invalidAddress);

	invokeInstanceMethod("locationChanged", plugin, new Class[] { ProgramLocation.class },
		new Object[] { newLocation });

	assertEquals("The plugin's display list has data when there is an " +
		"invalid address at the current program location.", list.getModel().getSize(), 0);
}
 
Example 7
Source File: CondenseRepeatingBytes.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
   public void run() throws Exception {
	
	if (currentAddress == null) {
            println("No Location.");
            return;
        }
	MemoryBlock currentMemoryBlock = currentProgram.getMemory().getBlock(currentAddress);
	if(!currentMemoryBlock.isInitialized()){
		println("Script cannot run in uninitialized memory.");
		return;
	}
		
	Listing listing = currentProgram.getListing();
	Address currentAddr = currentAddress;
	byte repeatingByte = currentProgram.getMemory().getByte(currentAddr);
	int repeatLen = 1;
	currentAddr = currentAddr.addNoWrap(1);
	byte nextByte;		
	boolean sameMemoryBlock;
	if(currentProgram.getMemory().getBlock(currentAddr).equals(currentMemoryBlock)) {
		nextByte = currentProgram.getMemory().getByte(currentAddr);
		sameMemoryBlock = true;
	}
	else{
		sameMemoryBlock = false;
		return;
	}
	
	boolean noCollisions = true;
	
	while((sameMemoryBlock) && (nextByte == repeatingByte) && (noCollisions)){
		repeatLen++;
		currentAddr = currentAddr.addNoWrap(1);
		if(currentProgram.getMemory().getBlock(currentAddr) != currentMemoryBlock){
			sameMemoryBlock = false;				
		}
		else{
			nextByte = currentProgram.getMemory().getByte(currentAddr);
			noCollisions = listing.isUndefined(currentAddr,currentAddr);
		}			
	}
	

	listing.createData(currentAddress, new AlignmentDataType(), repeatLen);				
	
	println("Applied Alignment datatype at " + currentAddress.toString());				
		
}
 
Example 8
Source File: CondenseRepeatingBytesAtEndOfMemory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Override
   public void run() throws Exception {		
		
	if (currentAddress == null) {
		println("No Location.");
	    return;
	}
	MemoryBlock memoryBlock = currentProgram.getMemory().getBlock(currentAddress);
	if(!memoryBlock.isInitialized()){
		println("Script cannot run in uninitialized memory.");
		return;
	}
	Listing listing = currentProgram.getListing();
	

	Address currentAddr = currentAddress;        
	
	boolean isInitializedBlock = memoryBlock.isInitialized();
	if(isInitializedBlock){
		currentAddr = memoryBlock.getEnd();
		println("end of byte addr is " + currentAddr);
		byte repeatingByte = currentProgram.getMemory().getByte(currentAddr);
		
	
		MemoryBlock currentMemoryBlock = null;		
	
		
		// search for next repeatedByte from the end of memory
		// until it hits defined area or different byte		
					
		byte prevByte = repeatingByte;
		int repeatLen = 0;
		boolean noCollisions = listing.isUndefined(currentAddr,currentAddr);
		boolean hasLabels = currentProgram.getSymbolTable().hasSymbol(currentAddr);
		println("no collisions at end = " + noCollisions);
		currentMemoryBlock = currentProgram.getMemory().getBlock(currentAddr);
		while((prevByte == repeatingByte) && (noCollisions) && (currentMemoryBlock.equals(memoryBlock)) && (!hasLabels)){
			repeatLen++;
			currentAddr = currentAddr.addNoWrap(-1);
			prevByte = currentProgram.getMemory().getByte(currentAddr);
			noCollisions = listing.isUndefined(currentAddr,currentAddr);
			hasLabels = currentProgram.getSymbolTable().hasSymbol(currentAddr);
			currentMemoryBlock = currentProgram.getMemory().getBlock(currentAddr);					
		}
		if(repeatLen > 0){
		// this takes care of the last one tested that failed
		currentAddr = currentAddr.addNoWrap(1);												
		listing.createData(currentAddr, new AlignmentDataType(), repeatLen);				
		
		println("Applied Alignment datatype at " + currentAddr.toString());												
		 
		}
		else{
			println("No repeating bytes OR data already defined at end of " + memoryBlock);
		}
	}
	else{
		println("Cannot condense uninitialized memory.");
	}		
}