ghidra.app.plugin.processors.sleigh.SleighLanguage Java Examples

The following examples show how to use ghidra.app.plugin.processors.sleigh.SleighLanguage. 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: OperandSymbol.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage lang) {
	XmlElement el = parser.start("operand_sym");
	defexp = null;
	triple = null;
	codeaddress = false;

	hand = SpecXmlUtils.decodeInt(el.getAttribute("index"));

	reloffset = SpecXmlUtils.decodeInt(el.getAttribute("off"));
	offsetbase = SpecXmlUtils.decodeInt(el.getAttribute("base"));
	minimumlength = SpecXmlUtils.decodeInt(el.getAttribute("minlen"));
	String attrstr = el.getAttribute("subsym");
	if (attrstr != null) {
		int id = SpecXmlUtils.decodeInt(attrstr);
		triple = (TripleSymbol) lang.getSymbolTable().findSymbol(id);
	}
	codeaddress = SpecXmlUtils.decodeBoolean(el.getAttribute("code"));

	localexp = (OperandValue) PatternExpression.restoreExpression(parser, lang);
	if (!parser.peek().isEnd())
		defexp = PatternExpression.restoreExpression(parser, lang);
	parser.end(el);
}
 
Example #2
Source File: VarnodeListSymbol.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage sleigh) {
	XmlElement el = parser.start("varlist_sym");
	patval = (PatternValue) PatternExpression.restoreExpression(parser, sleigh);
	ArrayList<VarnodeSymbol> varnodes = new ArrayList<>();
	SymbolTable symtab = sleigh.getSymbolTable();
	while (!parser.peek().isEnd()) {
		XmlElement subel = parser.start();
		if (subel.getName().equals("var")) {
			int id = SpecXmlUtils.decodeInt(subel.getAttribute("id"));
			varnodes.add((VarnodeSymbol) symtab.findSymbol(id));
		}
		else
			varnodes.add(null);
		parser.end(subel);
	}
	varnode_table = new VarnodeSymbol[varnodes.size()];

	for (int i = 0; i < varnode_table.length; ++i) {
		varnode_table[i] = varnodes.get(i);
	}
	checkTableFill();
	parser.end(el);
}
 
Example #3
Source File: PcodeParserTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #4
Source File: PcodeFormatter.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void formatCallOtherName(Language language, VarnodeTpl input0,
		List<AttributedString> lineList) {

	if (!input0.getSpace().isConstSpace() || input0.getOffset().getType() != ConstTpl.REAL) {
		throw new RuntimeException("Expected constant input[0] for CALLOTHER pcode op");
	}

	if (!(language instanceof SleighLanguage)) {
		throw new RuntimeException("Expected Sleigh language for CALLOTHER op");
	}

	int id = (int) input0.getOffset().getReal();
	String psuedoOp = ((SleighLanguage) language).getUserDefinedOpName(id);
	if (psuedoOp == null) {
		Msg.error(PcodeFormatter.class, "Psuedo-op index not found: " + id);
		psuedoOp = "unknown";
	}
	lineList.add(QUOTE);
	lineList.add(new AttributedString(psuedoOp, Color.BLUE, metrics));
	lineList.add(QUOTE);
}
 
Example #5
Source File: Emulate.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public Emulate(SleighLanguage lang, MemoryState s, BreakTable b) {
		memstate = s;
		this.language = lang;
		this.addrFactory = lang.getAddressFactory();
		pcReg = lang.getProgramCounter();
		breaktable = b;
		breaktable.setEmulate(this);
		memBuffer =
			new EmulateMemoryStateBuffer(s, addrFactory.getDefaultAddressSpace().getMinAddress());

		uniqueBank =
			new UniqueMemoryBank(lang.getAddressFactory().getUniqueSpace(), lang.isBigEndian());
		memstate.setMemoryBank(uniqueBank);

//		emitterContext = new EmulateDisassemblerContext(lang, s);

		pseudoDisassembler =
			Disassembler.getDisassembler(lang, addrFactory, TaskMonitorAdapter.DUMMY_MONITOR, null);

		initInstuctionStateModifier();
	}
 
Example #6
Source File: AssemblyDefaultContext.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Compute the default context at the given address for the given language
 * @param lang the language
 * @param at the address
 */

protected AssemblyDefaultContext(SleighLanguage lang, Address at) {
	this.lang = lang;
	this.at = at;
	Register ctxreg = lang.getContextBaseRegister();
	if (null == ctxreg) {
		this.defctx = AssemblyPatternBlock.nop();
		this.curctx = AssemblyPatternBlock.nop();
	}
	else {
		int size = ctxreg.getMinimumByteSize();
		this.defctx = AssemblyPatternBlock.fromLength(size);
		this.curctx = AssemblyPatternBlock.fromLength(size);
	}
	lang.applyContextSettings(this);
}
 
Example #7
Source File: AssemblyContextGraph.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Build the context change graph for a given language and grammar
 * 
 * The grammar must have been constructed from the given language. The language is used just to
 * obtain the most common default context.
 * 
 * At the moment, this graph only expands the recursive rules at the root constructor table,
 * i.e., "instruction". Thus, the assembler will not be able to process any language that has
 * <i>purely</i>-recursive rules at subconstructors.
 * @param lang the language
 * @param grammar the grammar derived from the given language
 */
public AssemblyContextGraph(SleighLanguage lang, AssemblyGrammar grammar) {
	this.grammar = grammar;
	this.lang = lang;

	gatherSemantics();

	AssemblyDefaultContext ctx = new AssemblyDefaultContext(lang);
	AssemblyPatternBlock defctx = ctx.getDefault();
	defctx = defctx.fillMask();

	Vertex v = new Vertex(defctx, grammar.getStartName());
	// Because this graph is potentially infinite, we must cap the distance.
	// Since we'd like to apply each constructor once, we can cap by the number of semantics.
	// Certainly this doesn't strictly enforce the apply once rule, but we do get an overset.
	dijkstra = new DijkstraShortestPathsAlgorithm<>(this,
		semantics.get(grammar.getStartName()).size(), GEdgeWeightMetric.unitMetric());

	// Pre-compute for the source we know we will always use
	dijkstra.getDistancesFromSource(v);
}
 
Example #8
Source File: Assemblers.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Get a builder for the given language, possibly using a cached one.
 * @param lang the language
 * @return the builder for that language, if successful
 */
protected static AssemblerBuilder getBuilderForLang(Language lang) {
	AssemblerBuilder ab = builders.get(lang.getLanguageID());
	if (ab != null) {
		return ab;
	}
	if (lang instanceof SleighLanguage) {
		ab = new SleighAssemblerBuilder((SleighLanguage) lang);
		builders.put(lang.getLanguageID(), ab);
		return ab;
	}
	throw new UnsupportedOperationException("Unsupported language type: " + lang.getClass());
}
 
Example #9
Source File: TokenField.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage lang) {
	XmlElement el = parser.start("tokenfield");
	bigendian = SpecXmlUtils.decodeBoolean(el.getAttribute("bigendian"));
	signbit = SpecXmlUtils.decodeBoolean(el.getAttribute("signbit"));
	bitstart = SpecXmlUtils.decodeInt(el.getAttribute("bitstart"));
	bitend = SpecXmlUtils.decodeInt(el.getAttribute("bitend"));
	bytestart = SpecXmlUtils.decodeInt(el.getAttribute("bytestart"));
	byteend = SpecXmlUtils.decodeInt(el.getAttribute("byteend"));
	shift = SpecXmlUtils.decodeInt(el.getAttribute("shift"));
	parser.end(el);
}
 
Example #10
Source File: PcodeInjectLibraryVu.java    From ghidra-emotionengine with Apache License 2.0 5 votes vote down vote up
public PcodeInjectLibraryVu(SleighLanguage l) {
      super(l);
      language = l;
      String translateSpec = l.buildTranslatorTag(l.getAddressFactory(),
	getUniqueBase(), l.getSymbolTable());
parser = null;
try {
	parser = new PcodeParser(translateSpec);
}
catch (JDOMException e1) {
	Msg.error(this, e1);
}
  }
 
Example #11
Source File: ContextField.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage lang) {
	XmlElement el = parser.start("contextfield");
	signbit = SpecXmlUtils.decodeBoolean(el.getAttribute("signbit"));
	startbit = SpecXmlUtils.decodeInt(el.getAttribute("startbit"));
	endbit = SpecXmlUtils.decodeInt(el.getAttribute("endbit"));
	startbyte = SpecXmlUtils.decodeInt(el.getAttribute("startbyte"));
	endbyte = SpecXmlUtils.decodeInt(el.getAttribute("endbyte"));
	shift = SpecXmlUtils.decodeInt(el.getAttribute("shift"));
	parser.end(el);
}
 
Example #12
Source File: BinaryExpression.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage lang) {
	XmlElement el = parser.start();
	left = PatternExpression.restoreExpression(parser, lang);
	right = PatternExpression.restoreExpression(parser, lang);
	parser.end(el);
}
 
Example #13
Source File: SleighAssembler.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a SleighAssembler.
 * 
 * @param selector a method of selecting one result from many
 * @param program the program to bind to (must have same language as parser)
 * @param parser the parser for the SLEIGH language
 * @param defaultContext the default context for the language
 * @param ctxGraph the context graph
 */
protected SleighAssembler(AssemblySelector selector, Program program, AssemblyParser parser,
		AssemblyDefaultContext defaultContext, AssemblyContextGraph ctxGraph) {
	this(selector, (SleighLanguage) program.getLanguage(), parser, defaultContext, ctxGraph);
	this.program = program;

	this.listing = program.getListing();
	this.memory = program.getMemory();
	this.dis = Disassembler.getDisassembler(program, TaskMonitor.DUMMY,
		DisassemblerMessageListener.IGNORE);
}
 
Example #14
Source File: AssemblyTreeResolver.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a resolver for the given parse tree
 * 
 * @param lang
 * @param instStart the byte offset where the instruction will start
 * @param tree the parse tree
 * @param context the context expected at {@code instStart}
 * @param ctxGraph the context transition graph used to resolve purely-recursive productions
 */
public AssemblyTreeResolver(SleighLanguage lang, long instStart, AssemblyParseBranch tree,
		AssemblyPatternBlock context, AssemblyContextGraph ctxGraph) {
	this.lang = lang;
	this.instStart = instStart;
	this.vals.put(INST_START, lang.getDefaultSpace().getAddressableWordOffset(instStart));
	this.tree = tree;
	this.grammar = tree.getGrammar();
	this.context = context.fillMask();
	this.ctxGraph = ctxGraph;
}
 
Example #15
Source File: UnaryExpression.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage lang) {
	XmlElement el = parser.start();

	unary = PatternExpression.restoreExpression(parser, lang);
	parser.end(el);
}
 
Example #16
Source File: Emulator.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public Emulator(EmulatorConfiguration cfg) {

		this.faultHandler = cfg.getMemoryFaultHandler();

		pcName = cfg.getProgramCounterName();
		writeBack = cfg.isWriteBackEnabled();
		pageSize = cfg.getPreferredMemoryPageSize();

		Language lang = cfg.getLanguage();
		if (!(lang instanceof SleighLanguage)) {
			throw new IllegalArgumentException("Invalid configuartion language [" +
				lang.getLanguageID() + "]: only Sleigh languages are supported by emulator");
		}

		// TODO: The way this is currently done, we are unable to emulate within overlay spaces
		// The addrFactory should be obtained memState which is a reversal
		// When a program load image is used the addrFactory should come from the program and
		// not the language.  Things may also get complex in terms of handling loads/stores and
		// flow associated with overlays.

		language = (SleighLanguage) lang;
		addrFactory = lang.getAddressFactory();

		EmulatorLoadData load = cfg.getLoadData();
		loadImage.addProvider(load.getMemoryLoadImage(), load.getView());
		mstate = load.getInitialRegisterState();

		initMemState(mstate);

		breakTable = new BreakTableCallBack(language);
		emulator = new Emulate(language, memState, breakTable);

		try {
			setExecuteAddress(initialPC);
		}
		catch (LowlevelError lle) {
			Msg.warn(this, "pc is unmappable -- no execution possible");
		}
	}
 
Example #17
Source File: PcodeDataTypeManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PcodeDataTypeManager(Program prog) {

		program = prog;
		progDataTypes = prog.getDataTypeManager();
		dataOrganization = progDataTypes.getDataOrganization();
		voidInputIsVarargs = true;				// By default, do not lock-in void parameter lists
		displayLanguage = prog.getCompilerSpec().getDecompilerOutputLanguage(prog);
		if (displayLanguage != DecompilerLanguage.C_LANGUAGE) {
			voidInputIsVarargs = false;
		}
		generateCoreTypes();
		sortCoreTypes();
		pointerWordSize = ((SleighLanguage) prog.getLanguage()).getDefaultPointerWordSize();
	}
 
Example #18
Source File: PcodeInjectLibrary.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PcodeInjectLibrary(SleighLanguage l) {
	language = l;
	uniqueBase = language.getUniqueBase();
	callFixupMap = new TreeMap<String, InjectPayload>();
	callOtherFixupMap = new TreeMap<String, InjectPayload>();
	callMechFixupMap = new TreeMap<String, InjectPayload>();
	exePcodeMap = new TreeMap<String, InjectPayload>();
}
 
Example #19
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 #20
Source File: DecompileDebug.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private ArrayList<ContextSymbol> getContextSymbols() {
	Language lang = program.getLanguage();
	if (!(lang instanceof SleighLanguage)) {
		return null;
	}
	ArrayList<ContextSymbol> res = new ArrayList<ContextSymbol>();
	ghidra.app.plugin.processors.sleigh.symbol.Symbol[] list =
		((SleighLanguage) lang).getSymbolTable().getSymbolList();
	for (Symbol element : list) {
		if (element instanceof ContextSymbol) {
			res.add((ContextSymbol) element);
		}
	}
	return res;
}
 
Example #21
Source File: VarnodeContext.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public VarnodeContext(Program program, ProgramContext programContext,
		ProgramContext spaceProgramContext) {
	this.program = program;

	// make a copy, because we could be making new spaces.
	// TODO: This could be a problem if some of the Pcode comes up with Overlay Address Spaces.
	// TODO: This doesn't get Stack space, or other overlay spaces...
	this.addrFactory = new OffsetAddressFactory(program.getLanguage().getAddressFactory());

	BAD_ADDRESS = addrFactory.getAddress(getAddressSpace("BAD_ADDRESS_SPACE"), 0);

	this.programContext = programContext;

	offsetContext = new DisassemblerContextImpl(programContext);
	spaceContext = new DisassemblerContextImpl(spaceProgramContext);

	setupValidSymbolicStackNames(program);

	// get the return value location for functions
	trans = new VarnodeTranslator(program);

	Language language = program.getLanguage();
	if (language instanceof SleighLanguage) {
		// Must preserve temp values if named pcode sections exist (i.e., cross-builds are used)
		keepTempUniqueValues = ((SleighLanguage) language).numSections() != 0;
	}
}
 
Example #22
Source File: LanguagesAPIDemoScript.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() throws Exception {
	// The API is accessed using a callback, so instantiate the class to receive that callback.
	PcodeOpEntryVisitor visitor = new DumpPcodeOps();
	// Perform the iteration with the given callback visitor.
	int result = SleighLanguages.traverseAllPcodeOps(
		(SleighLanguage) currentProgram.getLanguage(), visitor);
	println("Result: " + result);
}
 
Example #23
Source File: InjectPayloadVu.java    From ghidra-emotionengine with Apache License 2.0 5 votes vote down vote up
public InjectPayloadVu(String sourceName, SleighLanguage language) {
	super(sourceName);
	this.language = language;
	try {
		saxParser = getSAXParser();
	}
	catch (PcodeXMLException e) {
		Msg.error(this, e);
	}
}
 
Example #24
Source File: PcodeInjectLibraryJava.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public PcodeInjectLibraryJava(SleighLanguage l) {
	super(l);
	language = l;
	implementedOps = new HashSet<>();
	implementedOps.add(GETFIELD);
	implementedOps.add(GETSTATIC);
	implementedOps.add(INVOKE_DYNAMIC);
	implementedOps.add(INVOKE_INTERFACE);
	implementedOps.add(INVOKE_SPECIAL);
	implementedOps.add(INVOKE_STATIC);
	implementedOps.add(INVOKE_VIRTUAL);
	implementedOps.add(LDC);
	implementedOps.add(LDC2_W);
	implementedOps.add(LDC_W);
	implementedOps.add(MULTIANEWARRAY);
	implementedOps.add(PUTFIELD);
	implementedOps.add(PUTSTATIC);

	String translateSpec = language.buildTranslatorTag(language.getAddressFactory(),
		getUniqueBase(), language.getSymbolTable());

	paramPayload = null;
	parser = null;
	try {
		parser = new PcodeParser(translateSpec);
	}
	catch (JDOMException e1) {
		e1.printStackTrace();
	}
}
 
Example #25
Source File: InjectPayloadJava.java    From ghidra with Apache License 2.0 5 votes vote down vote up
public InjectPayloadJava(String sourceName, SleighLanguage language) {
	super(sourceName);
	this.language = language;
	try {
		saxParser = getSAXParser();
	}
	catch (PcodeXMLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #26
Source File: InjectMultiANewArray.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public InjectMultiANewArray(String sourceName, SleighLanguage language) {
	super(sourceName, language);
}
 
Example #27
Source File: InjectPayloadVu.java    From ghidra-emotionengine with Apache License 2.0 4 votes vote down vote up
SleighLanguage getLanguage() {
	return language;
}
 
Example #28
Source File: InjectPutField.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public InjectPutField(String sourceName, SleighLanguage language) {
	super(sourceName, language);
}
 
Example #29
Source File: InjectPutStatic.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public InjectPutStatic(String sourceName, SleighLanguage language) {
	super(sourceName, language);
}
 
Example #30
Source File: DecompInterface.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * This call initializes a new decompiler process to do
 * decompilations for a new program. This method only
 * needs to be called once per program.  Even if the
 * underlying decompiler process crashes, the interface
 * will automatically restart and reinitialize a new
 * process when it needs it, and the openProgram call
 * does not need to be made again. The call can be made
 * multiple times, in which case, each call terminates
 * the process initialized the last time and starts a
 * new process
 * @param prog = the program on which to perform decompilations
 * @return true if the decompiler process is successfully initialized
 */
public synchronized boolean openProgram(Program prog) {
	decompileMessage = "";
	program = prog;
	Language lang = prog.getLanguage();
	if (!lang.supportsPcode()) {
		decompileMessage = "Language does not support PCode.";
		return false;
	}
	pcodelanguage = (SleighLanguage) lang;
	CompilerSpec spec = prog.getCompilerSpec();
	if (!(spec instanceof BasicCompilerSpec)) {
		decompileMessage =
			"Language has unsupported compiler spec: " + spec.getClass().getName();
		return false;
	}
	compilerSpec = (BasicCompilerSpec) spec;

	dtmanage = new PcodeDataTypeManager(prog);
	try {
		decompCallback =
			new DecompileCallback(prog, pcodelanguage, program.getCompilerSpec(), dtmanage);
		initializeProcess();
		if (!decompProcess.isReady()) {
			throw new IOException("Unable to start decompiler process");
		}
		decompileMessage = decompCallback.getNativeMessage();
		if (!isErrorMessage()) {
			return true;
		}
	}
	catch (Exception ex) {
		decompileMessage = ex.getMessage();
		if (decompProcess == null) {
			return false;
		}
		stopProcess();
	}
	program = null;
	decompCallback = null;

	return false;
}