ghidra.program.model.lang.Language Java Examples

The following examples show how to use ghidra.program.model.lang.Language. 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: ShowInstructionInfoPluginTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testShowProcessorManual() throws Exception {

	changeLocationToAddress(beyondAddressString);

	ManualEntry manualEntry = plugin.locateManualEntry(null, null);
	assertNull(manualEntry);

	ListingActionContext context = getCurrentContext();
	Instruction currentInstruction = plugin.getInstructionForContext(context);
	assertNull("The current Instruction is not null as expected", currentInstruction);

	// now try the calling the method with an invalid Instruction
	Language language = program.getLanguage();
	manualEntry = plugin.locateManualEntry(context, language);
	assertNotNull(manualEntry);

	// now move to a valid Instruction to test that condition
	currentInstruction = changeLocationToAddress("01000000");
	assertNotNull("Found a null Instruction at a point in the program " +
		"where we expected a valid Instruction.", currentInstruction);

	// now try the calling the method with an valid Instruction
	context = getCurrentContext();
	manualEntry = plugin.locateManualEntry(context, language);
}
 
Example #2
Source File: ShowInstructionInfoPlugin.java    From ghidra with Apache License 2.0 6 votes vote down vote up
void showProcessorManual(ProgramActionContext context) {
	Language lang = currentProgram.getLanguage();
	File wrapperFile = null;
	try {
		URL fileURL = getValidUrl(context, lang);
		if (fileURL == null) {
			return;
		}
		wrapperFile = writeWrapperFile(fileURL);
		BrowserLoader.display(wrapperFile.toURI().toURL(), fileURL, tool);
	}
	catch (Exception e) {
		Msg.showError(this, null, "Exception Locating Manual",
			"Exception locating/displaying processor manual for language: " + lang, e);
	}
}
 
Example #3
Source File: ReloadSleighLangauge.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void run() throws Exception {
	if (currentProgram == null) {
		return;
	}
	Language language = currentProgram.getLanguage();
	try {
		language.reloadLanguage(monitor);
	}
	catch (IOException e) {
		Msg.showError(this, this.state.getParamPanel(), "Reload Sleigh Language Failed",
			e.getMessage());
		return;
	}
	currentProgram.setLanguage(language, currentProgram.getCompilerSpec().getCompilerSpecID(),
		true, monitor);
}
 
Example #4
Source File: GNUExternalDisassembler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private static void reportMultipleMappings(Language language) {
	List<String> externalNames = language.getLanguageDescription().getExternalNames("gnu");
	if (externalNames != null && externalNames.size() > 1) {
		LanguageID currentLanguageID = language.getLanguageID();
		StringBuilder sb = new StringBuilder();
		boolean prependSeparator = false;
		for (String name : externalNames) {
			if (prependSeparator)
				sb.append(", ");
			sb.append(name);
			prependSeparator = true;
		}
		Msg.warn(GNUExternalDisassembler.class,
			"Language " + currentLanguageID + " illegally maps to multiple (" +
				externalNames.size() + ") external gnu names: " + sb.toString() +
				".  The first external name will be used.");
	}
}
 
Example #5
Source File: GNUExternalDisassembler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public String getDisassemblyOfBytes(Language language, boolean isBigEndian, long addressOffset,
		byte[] bytes) throws Exception {

	GdisConfig gdisConfig = new GdisConfig(language, isBigEndian);
	if (gdisConfig.architecture == UNSUPPORTED || gdisConfig.gdisExecFile == null) {
		return null;
	}

	String bytesString = converBytesToString(bytes);

	String address = "0x" + Long.toHexString(addressOffset);

	List<GnuDisassembledInstruction> disassembly =
		runDisassembler(gdisConfig, address, bytesString);

	if (disassembly == null || disassembly.isEmpty() || disassembly.get(0) == null) {
		return "(bad)";
	}
	return disassembly.get(0).toString();
}
 
Example #6
Source File: ScalarOperandAnalyzer.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected boolean getDefaultEnablement2(Program program) {
	// don't do risc processors, their addresses don't appear directly in code
	Language language = program.getLanguage();
	if (language.getPropertyAsBoolean(
		GhidraLanguagePropertyKeys.ADDRESSES_DO_NOT_APPEAR_DIRECTLY_IN_CODE, false)) {
		return false;
	}

	// don't analyze programs starting at 0
	Address min = program.getMinAddress();
	if (min == null || min.getOffset() == 0) {
		return false;
	}

	// languages that are alligned, tend not to have direct addresses.
	if (program.getLanguage().getInstructionAlignment() != 1) {
		return false;
	}

	// only analyze programs with address spaces > 16 bits
	return program.getAddressFactory().getDefaultAddressSpace().getSize() >= 32;
}
 
Example #7
Source File: AnalysisScheduler.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private boolean getEnableOverride(boolean defaultEnable) {
	Language language = analysisMgr.getProgram().getLanguage();

	// get the overall disable property
	boolean allOverriden = false;
	if (language.hasProperty("DisableAllAnalyzers")) {
		allOverriden = true;
	}
	boolean overrideEnable = defaultEnable;
	// let individual analyzers be turned off or on
	String propertyName = "Analyzers." + analyzer.getName();
	if (language.hasProperty(propertyName)) {
		overrideEnable = language.getPropertyAsBoolean(propertyName, defaultEnable);
	}
	else if (allOverriden) {
		overrideEnable = false;
	}

	return overrideEnable;
}
 
Example #8
Source File: CoffSectionHeader.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an input stream that will supply the bytes
 * for this section.
 * @return the input stream 
 * @throws IOException if an I/O error occurs
 */
public InputStream getRawDataStream(ByteProvider provider, Language language)
		throws IOException {

	// XXX XXX XXX XXX
	// XXX XXX XXX XXX
	// It is NOT CLEAR AT ALL that all big endian, > 1-byte wordsize executables should be BYTE-SWAPPED!!!
	// XXX XXX XXX XXX
	// XXX XXX XXX XXX

	int addressableUnitSize =
		language.getAddressFactory().getDefaultAddressSpace().getAddressableUnitSize();
	if (addressableUnitSize > 1 && language.isBigEndian()) {
		return new BigEndianUnitSizeByteSwapperInputStream(provider.getInputStream(s_scnptr),
			addressableUnitSize);
	}
	return provider.getInputStream(s_scnptr);
}
 
Example #9
Source File: PowerPCDisassembleAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isEnabledForContext(ListingActionContext context) {

	Address address = context.getAddress();
	if (address == null) {
		return false;
	}

	// Action only intended for use where PowerPC VLE instructions are available.
	// The presence of the VLE variant indicator in the language ID can be used for this 
	// determination.

	Program program = context.getProgram();
	Language lang = program.getLanguage();
	Processor proc = lang.getProcessor();

	if (!proc.equals(Processor.findOrPossiblyCreateProcessor("PowerPC")) ||
		lang.getLanguageID().toString().indexOf(":VLE") < 0) {
		return false;
	}

	return plugin.checkDisassemblyEnabled(context, address, true);
}
 
Example #10
Source File: PIC30_ElfExtension.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getFilteredLoadInputStream(ElfLoadHelper elfLoadHelper,
		MemoryLoadable loadable, Address start, long dataLength, InputStream dataInput) {
	Language language = elfLoadHelper.getProgram().getLanguage();
	if (!isDataLoad(loadable) && !language.getDefaultDataSpace().equals(start.getAddressSpace().getPhysicalSpace())) {
		return dataInput;
	}

	if (loadable instanceof ElfSectionHeader) {
		ElfSectionHeader section = (ElfSectionHeader) loadable;
		if (!elfLoadHelper.getElfHeader().isRelocatable() && (section.getFlags() & SHF_PSV) != 0) {
			// TODO: this is really mapped into ROM space where PT_LOAD was done to physical memory
			// In the absence of suitable mapping, we will load into RAM space
			return new PIC30FilteredPSVDataInputStream(dataInput);
		}
	}
	else {
		return new PIC30FilteredPSVDataInputStream(dataInput);
	}

	// Data space loading pads after every byte with Microchip toolchain 
	// NOTE: this could vary and we may need to improve detection of this situation

	return new PIC30FilteredDataInputStream(dataInput, !isDebugSection(loadable));
}
 
Example #11
Source File: OverlaySpaceAdapterDB.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Translate overlay address spaces for a new language provider
 * and initialize the new addrFactory with the translated overlay spaces.
 * All non-overlay address spaces within the address factory should already
 * have been mapped to the new language. 
 * @param newLanguage new language to be used
 * @param addrFactory old address factory
 * @param translator language translator to assist with mapping of address spaces
 * @throws IOException
 */
void setLanguage(Language newLanguage, ProgramAddressFactory addrFactory,
		LanguageTranslator translator) throws IOException {

	Table table = db.getTable(TABLE_NAME);
	if (table != null) {
		RecordIterator it = table.iterator();
		while (it.hasNext()) {
			Record rec = it.next();
			String oldUnderlyingSpaceName = rec.getString(OV_SPACE_BASE_COL);
			AddressSpace space = addrFactory.getAddressSpace(oldUnderlyingSpaceName);
			if (space != null && space.isNonLoadedMemorySpace()) {
				// skip overlays associated with non-loaded spaces such as OTHER space
				continue;
			}
			AddressSpace newSpace = translator.getNewAddressSpace(oldUnderlyingSpaceName);
			if (newSpace == null) {
				throw new IOException(
					"Failed to map old address space: " + oldUnderlyingSpaceName);
			}
			rec.setString(OV_SPACE_BASE_COL, newSpace.getName());
			table.putRecord(rec);
		}
	}
	initializeOverlaySpaces(addrFactory);
}
 
Example #12
Source File: Varnode.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Convert this varnode to an alternate String representation based on a specified language.
 * @param language
 * @return string representation
 */
public String toString(Language language) {
	if (isAddress() || isRegister()) {
		Register reg = language.getRegister(address, size);
		if (reg != null) {
			return reg.getName();
		}
	}
	if (isUnique()) {
		return "u_" + Long.toHexString(offset) + ":" + size;
	}
	if (isConstant()) {
		return "0x" + Long.toHexString(offset);
	}
	return "A_" + address + ":" + size;
}
 
Example #13
Source File: UniqueAddressFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public UniqueAddressFactory(AddressFactory addrFactory, Language language) {
	this.addrFactory = addrFactory;
	this.uniqueSpace = addrFactory.getUniqueSpace();
	if (language instanceof SleighLanguage) {
		firstAvailableOffset = ((SleighLanguage) language).getUniqueBase();
	}
	else {
		firstAvailableOffset = 0;
	}
	nextOffset = firstAvailableOffset;
}
 
Example #14
Source File: CoffSectionHeader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the number of bytes of data stored in the file for this section.
 * NOTE: This value does not strictly indicate size in bytes.
 *       For word-oriented machines, this value is represents
 *       size in words.
 * @return the number of bytes of data stored in the file for this section
 */
public int getSize(Language language) {
	if (isExplicitlyByteAligned()) {
		return s_size;
	}
	Address physicalAddr = getPhysicalAddress(language);
	return s_size * physicalAddr.getAddressSpace().getAddressableUnitSize();
}
 
Example #15
Source File: OmfSegmentHeader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @param language is the Program language for this binary
 * @return the starting Address for this segment
 */
public Address getAddress(Language language) {
	AddressSpace addrSpace;

	if (isCode) {
		addrSpace = language.getDefaultSpace();
	} else {
		addrSpace = language.getDefaultDataSpace();
	}
	return addrSpace.getAddress(vma);		
}
 
Example #16
Source File: CoffLoader.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private MemoryBlock createInitializedBlock(ByteProvider provider, Program program,
		FileBytes fileBytes, TaskMonitor monitor, MessageLog log, final Language language,
		int sectionNumber, CoffSectionHeader section, final int sectionSize,
		Address sectionAddr, boolean isOverlay) throws AddressOverflowException, IOException {

	String name = section.getName();
	if (isOverlay) {
		name += "-" + sectionNumber;
	}
	MemoryBlock block = null;
	try {
		if (section.isProcessedBytes(language)) {
			try (InputStream dataStream = section.getRawDataStream(provider, language)) {
				block = MemoryBlockUtils.createInitializedBlock(program, isOverlay, name,
					sectionAddr, dataStream, sectionSize,
					"PhysAddr:0x" + Integer.toHexString(section.getPhysicalAddress()) + " " +
						"Size:0x" + Integer.toHexString(sectionSize) + " " + "Flags:0x" +
						Integer.toHexString(section.getFlags()),
					null/*source*/, section.isReadable(), section.isWritable(),
					section.isExecutable(), log, monitor);
			}
		}
		else {
			block = MemoryBlockUtils.createInitializedBlock(program, isOverlay, name,
				sectionAddr, fileBytes, section.getPointerToRawData(), sectionSize,
				"PhysAddr:0x" + Integer.toHexString(section.getPhysicalAddress()) + " " +
					"Size:0x" + Integer.toHexString(sectionSize) + " " + "Flags:0x" +
					Integer.toHexString(section.getFlags()),
				null/*source*/, section.isReadable(), section.isWritable(),
				section.isExecutable(), log);
		}
	}
	catch (RuntimeException e) {
		log.appendMsg(
			"Unable to create non-loaded block " + section + ". No memory block was created.");
		log.appendException(e);
	}
	return block;
}
 
Example #17
Source File: ExternalDisassemblyFieldFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String getDisassemblyText(CodeUnit cu) throws Exception {
	Language language = cu.getProgram().getLanguage();
	ExternalDisassembler disassembler = getDisassembler(language);
	if (disassembler == null) {
		return null;
	}
	String disassembly = disassembler.getDisassembly(cu);
	if (disassembly == null) {
		return null;
	}

	return disassembly;
}
 
Example #18
Source File: FunctionUtility.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether or not the two programs are considered to have the same processor
 * language and compiler specification.
 * @param program1 the first program
 * @param program2 the second program
 * @return true if the two programs have the same processor language and compiler spec.
 */
public static boolean isSameLanguage(Program program1, Program program2) {
	Language language1 = program1.getLanguage();
	Language language2 = program2.getLanguage();
	if (language1.getLanguageID() != language2.getLanguageID()) {
		return false;
	}
	CompilerSpec compilerSpec1 = program1.getCompilerSpec();
	CompilerSpec compilerSpec2 = program2.getCompilerSpec();
	if (compilerSpec1.getCompilerSpecID() != compilerSpec2.getCompilerSpecID()) {
		return false;
	}
	return true;
}
 
Example #19
Source File: VarnodeOperation.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private String getIndirectString(Language language) {
	Varnode output = pcodeOp.getOutput();
	if (language == null) {
		return pcodeOp.getMnemonic() + "[" + output.toString() + ", @" +
			pcodeOp.getSeqnum().getTarget() + "]";
	}
	return pcodeOp.getMnemonic() + "[" + output.toString(language) + ", @" +
		pcodeOp.getSeqnum().getTarget() + "]";
}
 
Example #20
Source File: VarnodeOperation.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public String toString(Language language) {
	if (pcodeOp.getOpcode() == PcodeOp.INDIRECT) {
		return getIndirectString(language);
	}
	String s = pcodeOp.getMnemonic() + " ";
	for (int i = 0; i < inputValues.length; i++) {
		if (i == 0 &&
			(pcodeOp.getOpcode() == PcodeOp.LOAD || pcodeOp.getOpcode() == PcodeOp.STORE)) {
			AddressSpace space =
				language.getAddressFactory().getAddressSpace((int) inputValues[0].getOffset());
			if (space != null) {
				s += "[" + space.getName() + "], ";
				continue;
			}
		}
		if (inputValues[i] == null) {
			s += "null";
		}
		else if (inputValues[i] instanceof VarnodeOperation) {
			s += "{" + inputValues[i].toString(language) + "}";
		}
		else {
			s += inputValues[i].toString(language);
		}
		if (i < inputValues.length - 1) {
			s += ", ";
		}
	}
	return s;
}
 
Example #21
Source File: OmfFixupRecord.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public FixupState(OmfFileHeader header,ArrayList<OmfSymbol> externsyms,Language lang) {
	for(int i=0;i<4;++i) {
		frameThreads[i] = null;
		targetThreads[i] = null;
	}
	this.header = header;
	groups = header.getGroups();
	externals = externsyms;
	language = lang;
}
 
Example #22
Source File: DataOrganizationImpl.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new default DataOrganization. This has a mapping which defines the alignment
 * of a data type based on its size. The map defines pairs for data types that are
 * 1, 2, 4, and 8 bytes in length.
 * @param language optional language used to initialize defaults (pointer size, endianess, etc.) (may be null)
 * @return a new default DataOrganization.
 */
public static DataOrganizationImpl getDefaultOrganization(Language language) {
	DataOrganizationImpl dataOrganization = new DataOrganizationImpl();
	dataOrganization.setSizeAlignment(1, 1);
	dataOrganization.setSizeAlignment(2, 2);
	dataOrganization.setSizeAlignment(4, 4);
	dataOrganization.setSizeAlignment(8, 4);
	if (language != null) {
		dataOrganization.setPointerSize(language.getDefaultSpace().getPointerSize());
		dataOrganization.setBigEndian(language.isBigEndian());
	}
	return dataOrganization;
}
 
Example #23
Source File: ShowInstructionInfoPluginTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testShowProcessorManual_ErrorDialog() throws Exception {

	changeLocationToAddress(beyondAddressString);

	Language language = program.getLanguage();
	ListingActionContext context = getCurrentContext();
	context = getCurrentContext();
	callGetUrl(context, language);
	DialogComponentProvider dialog = waitForDialogComponent("Missing Processor Manual");
	close(dialog);
}
 
Example #24
Source File: ProgramContextTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
	Language lang = getSLEIGH_8051_LANGUAGE();
	space = lang.getAddressFactory().getDefaultAddressSpace();

	program = new ProgramDB("8051", lang, lang.getDefaultCompilerSpec(), this);
	mem = program.getMemory();
}
 
Example #25
Source File: Pe32RelocationFixupHandler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handlesProgram(Program program) {
	if (!PeLoader.PE_NAME.equals(program.getExecutableFormat())) {
		return false;
	}
	Language language = program.getLanguage();
	if (language.getLanguageDescription().getSize() != 32) {
		return false;
	}
	Processor processor = language.getProcessor();
	return (processor.equals(Processor.findOrPossiblyCreateProcessor("x86")));
}
 
Example #26
Source File: Pe64RelocationFixupHandler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handlesProgram(Program program) {
	if (!PeLoader.PE_NAME.equals(program.getExecutableFormat())) {
		return false;
	}
	Language language = program.getLanguage();
	if (language.getLanguageDescription().getSize() != 64) {
		return false;
	}
	Processor processor = language.getProcessor();
	return (processor.equals(Processor.findOrPossiblyCreateProcessor("x86")));
}
 
Example #27
Source File: HighFunction.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * @param function  function associated with the higher level function abstraction.
 * @param language  description of the processor language of the function
 * @param compilerSpec description of the compiler that produced the function
 * @param dtManager data type manager
 * @param showNamespace true signals to print function names with their namespace
 */
public HighFunction(Function function, Language language, CompilerSpec compilerSpec,
		PcodeDataTypeManager dtManager, boolean showNamespace) {
	super(function.getProgram().getAddressFactory(), dtManager);
	func = function;
	this.language = language;
	this.compilerSpec = compilerSpec;
	this.showNamespace = showNamespace;
	localSymbols = new LocalSymbolMap(this, "stack");
	globalSymbols = new GlobalSymbolMap(this);
	proto = new FunctionPrototype(localSymbols, function);
	jumpTables = null;
	protoOverrides = null;
}
 
Example #28
Source File: SharedReturnAnalyzer.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public boolean getDefaultEnablement(Program program) {
	Language language = program.getLanguage();

	boolean sharedReturnEnabled = language.getPropertyAsBoolean(
		GhidraLanguagePropertyKeys.ENABLE_SHARED_RETURN_ANALYSIS, true);

	return sharedReturnEnabled;
}
 
Example #29
Source File: SwitchLoader.java    From Ghidra-Switch-Loader with ISC License 5 votes vote down vote up
@Override
protected List<Program> loadProgram(ByteProvider provider, String programName,
        DomainFolder programFolder, LoadSpec loadSpec, List<Option> options, MessageLog log,
        Object consumer, TaskMonitor monitor)
                throws IOException, CancelledException 
{
    LanguageCompilerSpecPair pair = loadSpec.getLanguageCompilerSpec();
    Language importerLanguage = getLanguageService().getLanguage(pair.languageID);
    CompilerSpec importerCompilerSpec = importerLanguage.getCompilerSpecByID(pair.compilerSpecID);

    Address baseAddr = importerLanguage.getAddressFactory().getDefaultAddressSpace().getAddress(0);
    Program prog = createProgram(provider, programName, baseAddr, getName(), importerLanguage, importerCompilerSpec, consumer);
    boolean success = false;

    try 
    {
        success = this.loadInto(provider, loadSpec, options, log, prog, monitor);
    }
    finally 
    {
        if (!success) 
        {
            prog.release(consumer);
            prog = null;
        }
    }

    List<Program> results = new ArrayList<Program>();
    if (prog != null) results.add(prog);
    return results;
}
 
Example #30
Source File: FidFileManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if any FidFile database known to the application can support the given language.
 * @param language the language to test.
 * @return  true if any FidFile database known to the application can support the given language.
 */
public boolean canQuery(Language language) {
	loadFidFiles();
	for (FidFile file : fidFiles) {
		if (file.isActive() && file.canProcessLanguage(language)) {
			return true;
		}
	}
	return false;
}