decompiler  1.0.0
Public Member Functions | Public Attributes | Private Member Functions | Static Private Member Functions | Private Attributes | Friends | List of all members
ghidra::SleighCompile Class Reference

SLEIGH specification compiling. More...

#include <slgh_compile.hh>

Inheritance diagram for ghidra::SleighCompile:
ghidra::SleighBase ghidra::Translate ghidra::AddrSpaceManager

Public Member Functions

 SleighCompile (void)
 Constructor.
 
const Location * getLocation (Constructor *ctor) const
 Get the source location of the given Constructor's definition. More...
 
const Location * getLocation (SleighSymbol *sym) const
 Get the source location of the given symbol's definition. More...
 
void reportError (const string &msg)
 Issue a fatal error message. More...
 
void reportError (const Location *loc, const string &msg)
 Issue a fatal error message with a source location. More...
 
void reportWarning (const string &msg)
 Issue a warning message. More...
 
void reportWarning (const Location *loc, const string &msg)
 Issue a warning message with a source location. More...
 
int4 numErrors (void) const
 Return the current number of fatal errors.
 
uint4 getUniqueAddr (void)
 Get the next available temporary register offset. More...
 
void setUnnecessaryPcodeWarning (bool val)
 Set whether unnecessary truncation and extension operators generate warnings individually. More...
 
void setDeadTempWarning (bool val)
 Set whether dead temporary registers generate warnings individually. More...
 
void setEnforceLocalKeyWord (bool val)
 Set whether named temporary registers must be defined using the local keyword. More...
 
void setLargeTemporaryWarning (bool val)
 Set whether too large temporary registers generate warnings individually. More...
 
void setLenientConflict (bool val)
 Set whether indistinguishable Constructor patterns generate fatal errors. More...
 
void setLocalCollisionWarning (bool val)
 Set whether collisions in exported locals generate warnings individually. More...
 
void setAllNopWarning (bool val)
 Set whether NOP Constructors generate warnings individually. More...
 
void setInsensitiveDuplicateError (bool val)
 Set whether case insensitive duplicates of register names cause an error. More...
 
void calcContextLayout (void)
 Calculate the internal context field layout. More...
 
string grabCurrentFilePath (void) const
 Get the path to the current source file. More...
 
void parseFromNewFile (const string &fname)
 Push a new source file to the current parse stack. More...
 
void parsePreprocMacro (void)
 Mark start of parsing for an expanded preprocessor macro. More...
 
void parseFileFinished (void)
 Mark end of parsing for the current file or macro. More...
 
void nextLine (void)
 Indicate parsing proceeded to the next line of the current file.
 
bool getPreprocValue (const string &nm, string &res) const
 Retrieve a given preprocessor variable. More...
 
void setPreprocValue (const string &nm, const string &value)
 Set a given preprocessor variable. More...
 
bool undefinePreprocValue (const string &nm)
 Remove the value associated with the given preprocessor variable. More...
 
TokenSymbol * defineToken (string *name, uintb *sz, int4 endian)
 Define a new SLEIGH token. More...
 
void addTokenField (TokenSymbol *sym, FieldQuality *qual)
 Add a new field definition to the given token. More...
 
bool addContextField (VarnodeSymbol *sym, FieldQuality *qual)
 Add a new context field definition to the given backing Varnode. More...
 
void newSpace (SpaceQuality *qual)
 Define a new addresds space. More...
 
SectionSymbol * newSectionSymbol (const string &nm)
 Start a new named p-code section and define the associated section symbol. More...
 
void setEndian (int4 end)
 Set the global endianness of the SLEIGH specification. More...
 
void setAlignment (int4 val)
 Set instruction alignment for the SLEIGH specification. More...
 
void defineVarnodes (SpaceSymbol *spacesym, uintb *off, uintb *size, vector< string > *names)
 Definition a set of Varnodes. More...
 
void defineBitrange (string *name, VarnodeSymbol *sym, uint4 bitoffset, uint4 numb)
 Define a new Varnode symbol as a subrange of bits within another symbol. More...
 
void addUserOp (vector< string > *names)
 Define a list of new user-defined operators. More...
 
void attachValues (vector< SleighSymbol *> *symlist, vector< intb > *numlist)
 Attach a list integer values, to each value symbol in the given list. More...
 
void attachNames (vector< SleighSymbol *> *symlist, vector< string > *names)
 Attach a list of display names to the given list of value symbols. More...
 
void attachVarnodes (vector< SleighSymbol *> *symlist, vector< SleighSymbol *> *varlist)
 Attach a list of Varnodes to the given list of value symbols. More...
 
SubtableSymbol * newTable (string *nm)
 Define a new SLEIGH subtable. More...
 
void newOperand (Constructor *ct, string *nm)
 Define a new operand for the given Constructor. More...
 
PatternEquation * constrainOperand (OperandSymbol *sym, PatternExpression *patexp)
 Create a new constraint equation based on the given operand. More...
 
void defineOperand (OperandSymbol *sym, PatternExpression *patexp)
 Map the local operand symbol to a PatternExpression. More...
 
PatternEquation * defineInvisibleOperand (TripleSymbol *sym)
 Define a new invisible operand based on an existing symbol. More...
 
void selfDefine (OperandSymbol *sym)
 Map given operand to a global symbol of same name. More...
 
ConstructTpl * setResultVarnode (ConstructTpl *ct, VarnodeTpl *vn)
 Set export of a Constructor to the given Varnode. More...
 
ConstructTpl * setResultStarVarnode (ConstructTpl *ct, StarQuality *star, VarnodeTpl *vn)
 Set a Constructor export to be the location pointed to by the given Varnode. More...
 
bool contextMod (vector< ContextChange *> *vec, ContextSymbol *sym, PatternExpression *pe)
 Create a change operation that makes a temporary change to a context variable. More...
 
void contextSet (vector< ContextChange *> *vec, TripleSymbol *sym, ContextSymbol *cvar)
 Create a change operation that makes a context variable change permanent. More...
 
MacroSymbol * createMacro (string *name, vector< string > *param)
 Create a macro symbol (with parameter names) More...
 
void compareMacroParams (MacroSymbol *sym, const vector< ExprTree *> &param)
 Pass through operand properties of an invoked macro to the parent operands. More...
 
vector< OpTpl * > * createMacroUse (MacroSymbol *sym, vector< ExprTree *> *param)
 Create a p-code sequence that invokes a macro. More...
 
SectionVectorstandaloneSection (ConstructTpl *main)
 Create a SectionVector containing just the main p-code section with no named sections. More...
 
SectionVectorfirstNamedSection (ConstructTpl *main, SectionSymbol *sym)
 Start a new named p-code section after the given main p-code section. More...
 
SectionVectornextNamedSection (SectionVector *vec, ConstructTpl *section, SectionSymbol *sym)
 Complete a named p-code section and prepare for a new named section. More...
 
SectionVectorfinalNamedSection (SectionVector *vec, ConstructTpl *section)
 Fill-in final named section to match the previous SectionSymbol. More...
 
vector< OpTpl * > * createCrossBuild (VarnodeTpl *addr, SectionSymbol *sym)
 Create the crossbuild directive as a p-code template. More...
 
Constructor * createConstructor (SubtableSymbol *sym)
 Create a new Constructor under the given subtable. More...
 
bool isInRoot (Constructor *ct) const
 Is the Constructor in the root table?
 
void resetConstructors (void)
 Reset state after a parsing error in the previous Constructor.
 
void pushWith (SubtableSymbol *ss, PatternEquation *pateq, vector< ContextChange *> *contvec)
 Add a new with block to the current stack. More...
 
void popWith (void)
 Pop the current with block from the stack.
 
void buildConstructor (Constructor *big, PatternEquation *pateq, vector< ContextChange *> *contvec, SectionVector *vec)
 Finish building a given Constructor after all its pieces have been parsed. More...
 
void buildMacro (MacroSymbol *sym, ConstructTpl *rtl)
 Finish defining a macro given a set of p-code templates for its body. More...
 
void recordNop (void)
 Record a NOP constructor at the current location. More...
 
virtual void initialize (DocumentStorage &store)
 Initialize the translator given XML configuration documents. More...
 
virtual int4 instructionLength (const Address &baseaddr) const
 Get the length of a machine instruction. More...
 
virtual int4 oneInstruction (PcodeEmit &emit, const Address &baseaddr) const
 Transform a single machine instruction into pcode. More...
 
virtual int4 printAssembly (AssemblyEmit &emit, const Address &baseaddr) const
 Disassemble a single machine instruction. More...
 
void setAllOptions (const map< string, string > &defines, bool unnecessaryPcodeWarning, bool lenientConflict, bool allCollisionWarning, bool allNopWarning, bool deadTempWarning, bool enforceLocalKeyWord, bool largeTemporaryWarning, bool caseSensitiveRegisterNames)
 Set all compiler options at the same time. More...
 
int4 run_compilation (const string &filein, const string &fileout)
 Run the full compilation process, given a path to the specification file. More...
 
- Public Member Functions inherited from ghidra::SleighBase
 SleighBase (void)
 Construct an uninitialized translator.
 
bool isInitialized (void) const
 Return true if this is initialized.
 
virtual ~SleighBase (void)
 Destructor.
 
virtual const VarnodeDatagetRegister (const string &nm) const
 Get a register as VarnodeData given its name. More...
 
virtual string getRegisterName (AddrSpace *base, uintb off, int4 size) const
 Get the name of a register given its location. More...
 
virtual void getAllRegisters (map< VarnodeData, string > &reglist) const
 Get a list of all register names and the corresponding location. More...
 
virtual void getUserOpNames (vector< string > &res) const
 Get a list of all user-defined pcode ops. More...
 
SleighSymbol * findSymbol (const string &nm) const
 Find a specific SLEIGH symbol by name in the current scope.
 
SleighSymbol * findSymbol (uintm id) const
 Find a specific SLEIGH symbol by id.
 
SleighSymbol * findGlobalSymbol (const string &nm) const
 Find a specific global SLEIGH symbol by name.
 
void saveXml (ostream &s) const
 Write out the SLEIGH specification as an XML <sleigh> tag. More...
 
- Public Member Functions inherited from ghidra::Translate
 Translate (void)
 Constructor for the translator. More...
 
void setDefaultFloatFormats (void)
 If no explicit float formats, set up default formats. More...
 
bool isBigEndian (void) const
 Is the processor big endian? More...
 
const FloatFormatgetFloatFormat (int4 size) const
 Get format for a particular floating point encoding. More...
 
int4 getAlignment (void) const
 Get the instruction alignment for the processor. More...
 
uint4 getUniqueBase (void) const
 Get the base offset for new temporary registers. More...
 
uint4 getUniqueStart (UniqueLayout layout) const
 Get a tagged address within the unique space. More...
 
virtual void registerContext (const string &name, int4 sbit, int4 ebit)
 Add a new context variable to the model for this processor. More...
 
virtual void setContextDefault (const string &name, uintm val)
 Set the default value for a particular context variable. More...
 
virtual void allowContextSet (bool val) const
 Toggle whether disassembly is allowed to affect context. More...
 
- Public Member Functions inherited from ghidra::AddrSpaceManager
 AddrSpaceManager (void)
 Construct an empty address space manager. More...
 
virtual ~AddrSpaceManager (void)
 Destroy the manager. More...
 
int4 getDefaultSize (void) const
 Get size of addresses for the default space. More...
 
AddrSpacegetSpaceByName (const string &nm) const
 Get address space by name. More...
 
AddrSpacegetSpaceByShortcut (char sc) const
 Get address space from its shortcut. More...
 
AddrSpacegetIopSpace (void) const
 Get the internal pcode op space. More...
 
AddrSpacegetFspecSpace (void) const
 Get the internal callspec space. More...
 
AddrSpacegetJoinSpace (void) const
 Get the joining space. More...
 
AddrSpacegetStackSpace (void) const
 Get the stack space for this processor. More...
 
AddrSpacegetUniqueSpace (void) const
 Get the temporary register space for this processor. More...
 
AddrSpacegetDefaultCodeSpace (void) const
 Get the default address space of this processor. More...
 
AddrSpacegetDefaultDataSpace (void) const
 Get the default address space where data is stored. More...
 
AddrSpacegetConstantSpace (void) const
 Get the constant space. More...
 
Address getConstant (uintb val) const
 Get a constant encoded as an Address. More...
 
Address createConstFromSpace (AddrSpace *spc) const
 Create a constant address encoding an address space. More...
 
Address resolveConstant (AddrSpace *spc, uintb val, int4 sz, const Address &point, uintb &fullEncoding) const
 Resolve a native constant into an Address. More...
 
int4 numSpaces (void) const
 Get the number of address spaces for this processor. More...
 
AddrSpacegetSpace (int4 i) const
 Get an address space via its index. More...
 
AddrSpacegetNextSpaceInOrder (AddrSpace *spc) const
 Get the next contiguous address space. More...
 
JoinRecordfindAddJoin (const vector< VarnodeData > &pieces, uint4 logicalsize)
 Get (or create) JoinRecord for pieces. More...
 
JoinRecordfindJoin (uintb offset) const
 Find JoinRecord for offset in the join space. More...
 
void setDeadcodeDelay (AddrSpace *spc, int4 delaydelta)
 Set the deadcodedelay for a specific space. More...
 
void truncateSpace (const TruncationTag &tag)
 Mark a space as truncated from its original size. More...
 
Address constructFloatExtensionAddress (const Address &realaddr, int4 realsize, int4 logicalsize)
 Build a logically lower precision storage location for a bigger floating point register. More...
 
Address constructJoinAddress (const Translate *translate, const Address &hiaddr, int4 hisz, const Address &loaddr, int4 losz)
 Build a logical whole from register pairs. More...
 
void renormalizeJoinAddress (Address &addr, int4 size)
 Make sure a possibly offset join address has a proper JoinRecord. More...
 
Address parseAddressSimple (const string &val)
 Parse a string with just an address space name and a hex offset. More...
 

Public Attributes

SleighPcode pcode
 The p-code parsing (sub)engine.
 

Private Member Functions

const Location * getCurrentLocation (void) const
 Get the current file and line number being parsed. More...
 
void predefinedSymbols (void)
 Get SLEIGHs predefined address spaces and symbols. More...
 
int4 calcContextVarLayout (int4 start, int4 sz, int4 numbits)
 Calculate the complete context layout for all definitions sharing the same backing storage Varnode. More...
 
void buildDecisionTrees (void)
 Build decision trees for all subtables. More...
 
void buildPatterns (void)
 Generate final match patterns based on parse constraint equations. More...
 
void checkConsistency (void)
 Perform final consistency checks on the SLEIGH definitions. More...
 
bool checkLocalExports (Constructor *ct)
 Check for operands that might export the same local variable. More...
 
void checkLocalCollisions (void)
 Check all Constructors for local export collisions between operands. More...
 
void checkNops (void)
 Report on all Constructors with empty semantic sections. More...
 
void checkCaseSensitivity (void)
 Check that register names can be treated as case insensitive. More...
 
string checkSymbols (SymbolScope *scope)
 Make sure label symbols are both defined and used. More...
 
void addSymbol (SleighSymbol *sym)
 Add a new symbol to the current scope. More...
 
SleighSymbol * dedupSymbolList (vector< SleighSymbol *> *symlist)
 Deduplicate the given list of symbols. More...
 
bool expandMacros (ConstructTpl *ctpl)
 Expand any formal SLEIGH macros in the given section of p-code. More...
 
bool finalizeSections (Constructor *big, SectionVector *vec)
 Do final checks, expansions, and linking for p-code sections. More...
 
void checkUniqueAllocation (void)
 Modify temporary Varnode offsets to support crossbuilds. More...
 
void process (void)
 Do all post processing on the parsed data structures. More...
 

Static Private Member Functions

static int4 findCollision (map< uintb, int4 > &local2Operand, const vector< uintb > &locals, int operand)
 Search for offset matches between a previous set and the given current set. More...
 
static VarnodeTpl * findSize (const ConstTpl &offset, const ConstructTpl *ct)
 Find a defining instance of the local variable with the given offset. More...
 
static bool forceExportSize (ConstructTpl *ct)
 Propagate local variable sizes into an export statement. More...
 
static void shiftUniqueVn (VarnodeTpl *vn, int4 sa)
 If the given Varnode is in the unique space, shift its offset up by sa bits. More...
 
static void shiftUniqueOp (OpTpl *op, int4 sa)
 Shift the offset up by sa bits for any Varnode used by the given op in the unique space. More...
 
static void shiftUniqueHandle (HandleTpl *hand, int4 sa)
 Shift the offset up for both dynamic or static Varnode aspects in the unique space. More...
 
static void shiftUniqueConstruct (ConstructTpl *tpl, int4 sa)
 Shift the offset up for any Varnode in the unique space for all p-code in the given section. More...
 
static string formatStatusMessage (const Location *loc, const string &msg)
 Format an error or warning message given an optional source location. More...
 

Private Attributes

map< string, string > preproc_defines
 Defines for the preprocessor.
 
vector< FieldContextcontexttable
 Context field definitions (prior to defining ContextField and ContextSymbol)
 
vector< ConstructTpl * > macrotable
 SLEIGH macro definitions.
 
vector< Token * > tokentable
 SLEIGH token definitions.
 
vector< SubtableSymbol * > tables
 SLEIGH subtables.
 
vector< SectionSymbol * > sections
 Symbols defining Constructor sections.
 
list< WithBlockwithstack
 Current stack of with blocks.
 
Constructor * curct
 Current Constructor being defined.
 
MacroSymbol * curmacro
 Current macro being defined.
 
bool contextlock
 If the context layout has been established yet.
 
vector< string > relpath
 Relative path (to cwd) for each filename.
 
vector< string > filename
 Stack of current files being parsed.
 
vector< int4 > lineno
 Current line number for each file in stack.
 
map< Constructor *, Location > ctorLocationMap
 Map each Constructor to its defining parse location.
 
map< SleighSymbol *, Location > symbolLocationMap
 Map each symbol to its defining parse location.
 
int4 userop_count
 Number of userops defined.
 
bool warnunnecessarypcode
 true if we warn of unnecessary ZEXT or SEXT
 
bool warndeadtemps
 true if we warn of temporaries that are written but not read
 
bool lenientconflicterrors
 true if we ignore most pattern conflict errors
 
bool largetemporarywarning
 true if we warn about temporaries larger than SleighBase::MAX_UNIQUE_SIZE
 
bool warnalllocalcollisions
 true if local export collisions generate individual warnings
 
bool warnallnops
 true if pcode NOPs generate individual warnings
 
bool failinsensitivedups
 true if case insensitive register duplicates cause error
 
vector< string > noplist
 List of individual NOP warnings.
 
Location currentLocCache
 Location for (last) request of current location.
 
int4 errors
 Number of fatal errors encountered.
 

Friends

class SleighPcode
 

Additional Inherited Members

- Public Types inherited from ghidra::Translate
enum  UniqueLayout {
  RUNTIME_BOOLEAN_INVERT =0, RUNTIME_RETURN_LOCATION =0x80, RUNTIME_BITRANGE_EA =0x100, INJECT =0x200,
  ANALYSIS =0x10000000
}
 Tagged addresses in the unique address space. More...
 
- Static Public Attributes inherited from ghidra::SleighBase
static const uint4 MAX_UNIQUE_SIZE = 128
 Maximum size of a varnode in the unique space (should match value in SleighBase.java)
 
- Protected Member Functions inherited from ghidra::SleighBase
void buildXrefs (vector< string > &errorPairs)
 Build register map. Collect user-ops and context-fields. More...
 
void reregisterContext (void)
 Reregister context fields for a new executable. More...
 
void restoreXml (const Element *el)
 Read a SLEIGH specification from XML. More...
 
- Protected Member Functions inherited from ghidra::Translate
void setBigEndian (bool val)
 Set general endianness to big if val is true. More...
 
void setUniqueBase (uint4 val)
 Set the base offset for new temporary registers. More...
 
- Protected Member Functions inherited from ghidra::AddrSpaceManager
AddrSpacedecodeSpace (Decoder &decoder, const Translate *trans)
 Add a space to the model based an on XML tag. More...
 
void decodeSpaces (Decoder &decoder, const Translate *trans)
 Restore address spaces in the model from an XML tag. More...
 
void setDefaultCodeSpace (int4 index)
 Set the default address space (for code) More...
 
void setDefaultDataSpace (int4 index)
 Set the default address space for data. More...
 
void setReverseJustified (AddrSpace *spc)
 Set reverse justified property on this space. More...
 
void assignShortcut (AddrSpace *spc)
 Select a shortcut character for a new space. More...
 
void markNearPointers (AddrSpace *spc, int4 size)
 Mark that given space can be accessed with near pointers. More...
 
void insertSpace (AddrSpace *spc)
 Add a new address space to the model. More...
 
void copySpaces (const AddrSpaceManager *op2)
 Copy spaces from another manager. More...
 
void addSpacebasePointer (SpacebaseSpace *basespace, const VarnodeData &ptrdata, int4 truncSize, bool stackGrowth)
 Set the base register of a spacebase space. More...
 
void insertResolver (AddrSpace *spc, AddressResolver *rsolv)
 Override the base resolver for a space. More...
 
void setInferPtrBounds (const Range &range)
 Set the range of addresses that can be inferred as pointers. More...
 
JoinRecordfindJoinInternal (uintb offset) const
 Find JoinRecord for offset in the join space. More...
 
- Protected Attributes inherited from ghidra::SleighBase
SubtableSymbol * root
 The root SLEIGH decoding symbol.
 
SymbolTable symtab
 The SLEIGH symbol table.
 
uint4 maxdelayslotbytes
 Maximum number of bytes in a delay-slot directive.
 
uint4 unique_allocatemask
 Bits that are guaranteed to be zero in the unique allocation scheme.
 
uint4 numSections
 Number of named sections.
 
SourceFileIndexer indexer
 source file index used when generating SLEIGH constructor debug info
 
- Protected Attributes inherited from ghidra::Translate
int4 alignment
 Byte modulo on which instructions are aligned.
 
vector< FloatFormatfloatformats
 Floating point formats utilized by the processor.
 

Detailed Description

SLEIGH specification compiling.

Class for parsing SLEIGH specifications (.slaspec files) and producing the compiled form (.sla file), which can then be loaded by a SLEIGH disassembly and p-code generation engine. This full parser contains the p-code parser SleighPcode within it. The main entry point is run_compilation(), which takes the input and output file paths as parameters. Various options and preprocessor macros can be set using the various set*() methods prior to calling run_compilation.

Member Function Documentation

◆ addContextField()

bool ghidra::SleighCompile::addContextField ( VarnodeSymbol *  sym,
FieldQuality qual 
)

Add a new context field definition to the given backing Varnode.

Parameters
symis the given Varnode providing backing storage for the context field
qualis the set of parsed qualities to associate with the new field

References contextlock, contexttable, getCurrentLocation(), ghidra::FieldQuality::high, ghidra::FieldQuality::low, ghidra::FieldQuality::name, and reportError().

◆ addSymbol()

void ghidra::SleighCompile::addSymbol ( SleighSymbol *  sym)
private

Add a new symbol to the current scope.

The symbol definition is assumed to have just been parsed. It is added to the table within the current scope as determined by the parse state and is cross referenced with the current parse location. Duplicate symbol exceptions are caught and reported as a parse error.

Parameters
symis the new symbol

References getCurrentLocation(), reportError(), symbolLocationMap, and ghidra::SleighBase::symtab.

Referenced by addTokenField(), addUserOp(), calcContextVarLayout(), createMacro(), defineBitrange(), defineInvisibleOperand(), defineToken(), defineVarnodes(), newOperand(), newSpace(), and newTable().

◆ addTokenField()

void ghidra::SleighCompile::addTokenField ( TokenSymbol *  sym,
FieldQuality qual 
)

Add a new field definition to the given token.

Parameters
symis the given token
qualis the set of parsed qualities to associate with the new field

References addSymbol(), getCurrentLocation(), ghidra::FieldQuality::high, ghidra::FieldQuality::low, ghidra::FieldQuality::name, reportError(), and ghidra::FieldQuality::signext.

◆ addUserOp()

void ghidra::SleighCompile::addUserOp ( vector< string > *  names)

Define a list of new user-defined operators.

A new symbol is created for each name.

Parameters
namesis the list of names

References addSymbol(), and userop_count.

◆ attachNames()

void ghidra::SleighCompile::attachNames ( vector< SleighSymbol *> *  symlist,
vector< string > *  names 
)

Attach a list of display names to the given list of value symbols.

Each symbol's original bit representation is no longer used as the display name for the symbol. Instead it is used to map into this list of display names.

Parameters
symlistis the given list of value symbols
namesis the list of display names to attach

References dedupSymbolList(), getCurrentLocation(), reportError(), reportWarning(), and ghidra::SleighBase::symtab.

◆ attachValues()

void ghidra::SleighCompile::attachValues ( vector< SleighSymbol *> *  symlist,
vector< intb > *  numlist 
)

Attach a list integer values, to each value symbol in the given list.

Each symbol's original bit representation is no longer used as the absolute integer value associated with the symbol. Instead it is used to map into this integer list.

Parameters
symlistis the given list of value symbols
numlistis the list of integer values to attach

References dedupSymbolList(), getCurrentLocation(), reportError(), reportWarning(), and ghidra::SleighBase::symtab.

◆ attachVarnodes()

void ghidra::SleighCompile::attachVarnodes ( vector< SleighSymbol *> *  symlist,
vector< SleighSymbol *> *  varlist 
)

Attach a list of Varnodes to the given list of value symbols.

Each symbol's original bit representation is no longer used as the display name and semantic value of the symbol. Instead it is used to map into this list of Varnodes.

Parameters
symlistis the given list of value symbols
varlistis the list of Varnodes to attach

References dedupSymbolList(), getCurrentLocation(), reportError(), reportWarning(), and ghidra::SleighBase::symtab.

◆ buildConstructor()

void ghidra::SleighCompile::buildConstructor ( Constructor *  big,
PatternEquation *  pateq,
vector< ContextChange *> *  contvec,
SectionVector vec 
)

Finish building a given Constructor after all its pieces have been parsed.

The constraint pattern and context changes are modified by the current with block. The result along with any p-code sections are registered with the Constructor object.

Parameters
bigis the given Constructor
pateqis the parsed pattern equation
contvecis the list of context changes or null
vecis the collection of p-code sections, or null

References ghidra::WithBlock::collectAndPrependContext(), ghidra::WithBlock::collectAndPrependPattern(), finalizeSections(), ghidra::SectionVector::getMainSection(), ghidra::SectionVector::getMaxId(), ghidra::SectionVector::getNamedSection(), ghidra::SleighBase::symtab, and withstack.

◆ buildDecisionTrees()

void ghidra::SleighCompile::buildDecisionTrees ( void  )
private

Build decision trees for all subtables.

A separate decision tree is calculated for each subtable, and information about conflicting patterns is accumulated. Identical pattern pairs are reported as errors, and indistinguishable pattern pairs are reported as errors depending on the lenientconflicterrors setting.

References errors, getLocation(), lenientconflicterrors, reportError(), ghidra::SleighBase::root, and tables.

Referenced by process().

◆ buildMacro()

void ghidra::SleighCompile::buildMacro ( MacroSymbol *  sym,
ConstructTpl *  rtl 
)

Finish defining a macro given a set of p-code templates for its body.

Try to propagate sizes through the templates, expand any (sub)macros and make sure any label symbols are defined and used.

Parameters
symis the macro being defined
rtlis the set of p-code templates

References checkSymbols(), expandMacros(), getCurrentLocation(), macrotable, reportError(), and ghidra::SleighBase::symtab.

◆ buildPatterns()

void ghidra::SleighCompile::buildPatterns ( void  )
private

Generate final match patterns based on parse constraint equations.

For each Constructor, generate the final pattern (TokenPattern) used to match it from the parsed constraints (PatternEquation). Accumulated error messages are reported.

References errors, getLocation(), reportError(), reportWarning(), ghidra::SleighBase::root, and tables.

Referenced by process().

◆ calcContextLayout()

void ghidra::SleighCompile::calcContextLayout ( void  )

Calculate the internal context field layout.

All current context field definitions are analyzed, the internal packing of the fields is determined, and the final symbols (ContextSymbol) are created and added to the symbol table. No new context fields can be defined once this method is called.

References calcContextVarLayout(), contextlock, and contexttable.

◆ calcContextVarLayout()

int4 ghidra::SleighCompile::calcContextVarLayout ( int4  start,
int4  sz,
int4  numbits 
)
private

Calculate the complete context layout for all definitions sharing the same backing storage Varnode.

Internally context is stored in an array of (32-bit) words. The bit-range for each field definition is adjusted to pack the fields within this array, but overlapping bit-ranges between definitions are preserved. Due to the internal storage word size, the covering range across a set of overlapping definitions cannot exceed the word size (of 32-bits). Within the sorted list of all context definitions, the subset sharing the same backing storage is provided to this method as a starting index and a size (of the subset), along with the total number of context bits already allocated.

Parameters
startis the provided starting index of the definition subset
szis the provided number of definitions in the subset
numbitsis the number of previously allocated context bits
Returns
the total number of allocated bits (after the new allocations)

References addSymbol(), contexttable, ghidra::FieldQuality::flow, getCurrentLocation(), ghidra::FieldQuality::high, ghidra::FieldQuality::low, ghidra::FieldQuality::name, reportError(), and ghidra::FieldQuality::signext.

Referenced by calcContextLayout().

◆ checkCaseSensitivity()

void ghidra::SleighCompile::checkCaseSensitivity ( void  )
private

Check that register names can be treated as case insensitive.

Treating names as case insensitive, look for duplicate register names and report as errors. For this method, register means any global Varnode defined using SLEIGH's define <address space> directive, in an address space of type IPTR_PROCESSOR (either RAM or REGISTER)

References failinsensitivedups, getLocation(), ghidra::AddrSpace::getName(), ghidra::AddrSpace::getType(), ghidra::IPTR_PROCESSOR, reportError(), and ghidra::SleighBase::symtab.

Referenced by process().

◆ checkConsistency()

void ghidra::SleighCompile::checkConsistency ( void  )
private

◆ checkLocalCollisions()

void ghidra::SleighCompile::checkLocalCollisions ( void  )
private

Check all Constructors for local export collisions between operands.

Check each Constructor for collisions in turn. If there are any collisions report a warning indicating the number of Construtors with collisions. Optionally generate a warning for each colliding Constructor.

References checkLocalExports(), reportWarning(), ghidra::SleighBase::root, tables, and warnalllocalcollisions.

Referenced by process().

◆ checkLocalExports()

bool ghidra::SleighCompile::checkLocalExports ( Constructor *  ct)
private

Check for operands that might export the same local variable.

Because local variables can be exported and subtable symbols can be reused as operands across multiple Constructors, its possible for different operands in the same Constructor to be assigned the same exported local variable. As this is a potential spec design problem, this method searches for these collisions and potentially reports a warning. For each operand of the given Constructor, the potential local variable exports are collected and compared with the other operands. Any potential collision may generate a warning and causes false to be returned.

Parameters
ctis the given Constructor
Returns
true if there are no potential collisions between operands

References findCollision(), getLocation(), reportWarning(), and warnalllocalcollisions.

Referenced by checkLocalCollisions().

◆ checkNops()

void ghidra::SleighCompile::checkNops ( void  )
private

Report on all Constructors with empty semantic sections.

The number of empty Constructors, with no p-code and no export, is always reported. Optionally, empty Constructors are reported individually.

References noplist, reportWarning(), and warnallnops.

Referenced by process().

◆ checkSymbols()

string ghidra::SleighCompile::checkSymbols ( SymbolScope *  scope)
private

Make sure label symbols are both defined and used.

Each label symbol define which operator is being labeled and must also be used as a jump destination by at least 1 operator. A description of each symbol violating this is accumulated in a string returned by this method.

Parameters
scopeis the scope across which to look for label symbols
Returns
the accumulated error messages

Referenced by buildMacro(), and finalizeSections().

◆ checkUniqueAllocation()

void ghidra::SleighCompile::checkUniqueAllocation ( void  )
private

Modify temporary Varnode offsets to support crossbuilds.

With crossbuilds, temporaries may need to survive across instructions in a packet, so here we provide space in the offset of the temporary (within the unique space) so that the run-time SLEIGH engine can alter the value to prevent collisions with other nearby instructions

References ghidra::Translate::getUniqueBase(), ghidra::SleighBase::root, sections, ghidra::Translate::setUniqueBase(), shiftUniqueConstruct(), tables, and ghidra::SleighBase::unique_allocatemask.

Referenced by process().

◆ compareMacroParams()

void ghidra::SleighCompile::compareMacroParams ( MacroSymbol *  sym,
const vector< ExprTree *> &  param 
)

Pass through operand properties of an invoked macro to the parent operands.

Match up any qualities of the macro's OperandSymbols with any OperandSymbol passed into the macro.

Parameters
symis the macro being invoked
paramis the list of expressions passed to the macro

References curct, and curmacro.

Referenced by createMacroUse().

◆ constrainOperand()

PatternEquation * ghidra::SleighCompile::constrainOperand ( OperandSymbol *  sym,
PatternExpression *  patexp 
)

Create a new constraint equation based on the given operand.

The constraint forces the operand to match the specified expression

Parameters
symis the given operand
patexpis the specified expression
Returns
the new constraint equation

◆ contextMod()

bool ghidra::SleighCompile::contextMod ( vector< ContextChange *> *  vec,
ContextSymbol *  sym,
PatternExpression *  pe 
)

Create a change operation that makes a temporary change to a context variable.

The new change operation is added to the current list. When executed, the change operation will assign a new value to the given context variable using the specified expression. The change only applies within the parsing of a single instruction. Because we are in the middle of parsing, the inst_next and inst_next2 values have not been computed yet. So we check to make sure the value expression doesn't use this symbol.

Parameters
vecis the current list of change operations
symis the given context variable affected by the operation
peis the specified expression
Returns
true if the expression does not use the inst_next or inst_next2 symbol

◆ contextSet()

void ghidra::SleighCompile::contextSet ( vector< ContextChange *> *  vec,
TripleSymbol *  sym,
ContextSymbol *  cvar 
)

Create a change operation that makes a context variable change permanent.

The new change operation is added to the current list. When executed, the operation makes the final value of the given context variable permanent, starting at the specified address symbol. This value is set for contexts starting at the specified symbol address and may flow to following addresses depending on the variable settings.

Parameters
vecis the current list of change operations
symis the specified address symbol
cvaris the given context variable

◆ createConstructor()

Constructor * ghidra::SleighCompile::createConstructor ( SubtableSymbol *  sym)

Create a new Constructor under the given subtable.

Create the object and initialize parsing for the new definition

Parameters
symis the given subtable or null for the root table
Returns
the new Constructor

References ctorLocationMap, curct, curmacro, getCurrentLocation(), ghidra::WithBlock::getCurrentSubtable(), ghidra::SourceFileIndexer::index(), ghidra::SleighBase::indexer, lineno, pcode, ghidra::SleighBase::root, ghidra::SleighBase::symtab, and withstack.

◆ createCrossBuild()

vector< OpTpl * > * ghidra::SleighCompile::createCrossBuild ( VarnodeTpl *  addr,
SectionSymbol *  sym 
)

Create the crossbuild directive as a p-code template.

Parameters
addris the address symbol indicating the instruction to crossbuild
symis the symbol indicating the p-code to be build
Returns
the p-code template

References ghidra::AddrSpaceManager::getConstantSpace(), and ghidra::SleighBase::unique_allocatemask.

◆ createMacro()

MacroSymbol * ghidra::SleighCompile::createMacro ( string *  name,
vector< string > *  params 
)

Create a macro symbol (with parameter names)

An uninitialized symbol is defined and a macro table entry assigned. The body of the macro must be provided later with the buildMacro method.

Parameters
nameis the name of the macro
paramsis the list of parameter names for the macro
Returns
the new macro symbol

References addSymbol(), curct, curmacro, macrotable, pcode, and ghidra::SleighBase::symtab.

◆ createMacroUse()

vector< OpTpl * > * ghidra::SleighCompile::createMacroUse ( MacroSymbol *  sym,
vector< ExprTree *> *  param 
)

Create a p-code sequence that invokes a macro.

The given parameter expressions are expanded first into the p-code sequence, followed by a final macro build directive.

Parameters
symis the macro being invoked
paramis the sequence of parameter expressions passed to the macro
Returns
the p-code sequence

References compareMacroParams(), ghidra::AddrSpaceManager::getConstantSpace(), getCurrentLocation(), and reportError().

◆ dedupSymbolList()

SleighSymbol * ghidra::SleighCompile::dedupSymbolList ( vector< SleighSymbol *> *  symlist)
private

Deduplicate the given list of symbols.

Find duplicates in the list and null out any entry but the first. Return an example of a symbol with duplicates or null if there are no duplicates.

Parameters
symlistis the given list of symbols (which may contain nulls)
Returns
an example symbol with a duplicate are null

Referenced by attachNames(), attachValues(), and attachVarnodes().

◆ defineBitrange()

void ghidra::SleighCompile::defineBitrange ( string *  name,
VarnodeSymbol *  sym,
uint4  bitoffset,
uint4  numb 
)

Define a new Varnode symbol as a subrange of bits within another symbol.

If the ends of the range fall on byte boundaries, we simply define a normal VarnodeSymbol, otherwise we create a special symbol which is a place holder for the bitrange operator

Parameters
nameis the name of the new Varnode
symis the parent Varnode
bitoffsetis the (least significant) starting bit of the new Varnode within the parent
numbis the number of bits in the new Varnode

References addSymbol(), getCurrentLocation(), ghidra::Translate::isBigEndian(), and reportError().

◆ defineInvisibleOperand()

PatternEquation * ghidra::SleighCompile::defineInvisibleOperand ( TripleSymbol *  sym)

Define a new invisible operand based on an existing symbol.

A new symbol is defined that is considered an operand of the current Constructor, but its display does not contribute to the display of the Constructor. The new symbol may still contribute matching patterns and p-code

Parameters
symis the existing symbol that the new operand maps to
Returns
an (unconstrained) operand pattern

References addSymbol(), curct, getCurrentLocation(), and reportError().

◆ defineOperand()

void ghidra::SleighCompile::defineOperand ( OperandSymbol *  sym,
PatternExpression *  patexp 
)

Map the local operand symbol to a PatternExpression.

The operand symbol's display string and semantic value are calculated at disassembly time based on the specified expression.

Parameters
symis the local operand
patexpis the expression to map to the operand

References getCurrentLocation(), and reportError().

◆ defineToken()

TokenSymbol * ghidra::SleighCompile::defineToken ( string *  name,
uintb *  sz,
int4  endian 
)

Define a new SLEIGH token.

In addition to the name and size, an endianness code is provided, with the possible values:

  • -1 indicates a little endian interpretation is forced on the token
  • 0 indicates the global endianness setting is used for the token
  • 1 indicates a big endian interpretation is forced on the token
Parameters
nameis the name of the token
szis the number of bits in the token
endianis the endianness code
Returns
the new token symbol

References addSymbol(), getCurrentLocation(), ghidra::Translate::isBigEndian(), reportError(), and tokentable.

◆ defineVarnodes()

void ghidra::SleighCompile::defineVarnodes ( SpaceSymbol *  spacesym,
uintb *  off,
uintb *  size,
vector< string > *  names 
)

Definition a set of Varnodes.

Storage for each Varnode is allocated in sequence from the given address space, starting from the specified offset.

Parameters
spacesymis the given address space
offis the starting offset
sizeis the size (in bytes) to allocate for each Varnode
namesis the list of Varnode names to define

References addSymbol().

◆ expandMacros()

bool ghidra::SleighCompile::expandMacros ( ConstructTpl *  ctpl)
private

Expand any formal SLEIGH macros in the given section of p-code.

Run through the section looking for MACRO directives. The directive includes an id for a specific macro in the table. Using the MacroBuilder class each directive is replaced with new sequence of OpTpls that tailors the macro with parameters in its invocation. Any errors encountered during expansion are reported. Other OpTpls in the section are unchanged.

Parameters
ctplis the given section of p-code to expand
Returns
true if there were no errors expanding a macro

References macrotable, and ghidra::MacroBuilder::setMacroOp().

Referenced by buildMacro(), and finalizeSections().

◆ finalizeSections()

bool ghidra::SleighCompile::finalizeSections ( Constructor *  big,
SectionVector vec 
)
private

Do final checks, expansions, and linking for p-code sections.

For each p-code section of the given Constructor:

  • Expand macros
  • Check that labels are both defined and referenced
  • Generate BUILD directives for subtable operands
  • Propagate Varnode sizes throughout the section

Each action may generate errors or warnings.

Parameters
bigis the given Constructor
vecis the list of p-code sections
Returns
true if there were no fatal errors

References checkSymbols(), errors, expandMacros(), forceExportSize(), ghidra::AddrSpaceManager::getConstantSpace(), getLocation(), ghidra::SectionVector::getMainPair(), ghidra::SectionVector::getMaxId(), ghidra::SectionVector::getNamedPair(), ghidra::SleighBase::maxdelayslotbytes, reportError(), reportWarning(), ghidra::SleighBase::root, ghidra::RtlPair::scope, ghidra::RtlPair::section, and sections.

Referenced by buildConstructor().

◆ finalNamedSection()

SectionVector * ghidra::SleighCompile::finalNamedSection ( SectionVector vec,
ConstructTpl *  section 
)

Fill-in final named section to match the previous SectionSymbol.

The provided p-code templates are assigned to the previously registered p-code section symbol, and the completed section is added to the SectionVector.

Parameters
vecis the existing SectionVector
sectioncontains the p-code templates to assign to the last section
Returns
the updated SectionVector

References ghidra::SectionVector::append(), and ghidra::SleighBase::symtab.

◆ findCollision()

int4 ghidra::SleighCompile::findCollision ( map< uintb, int4 > &  local2Operand,
const vector< uintb > &  locals,
int  operand 
)
staticprivate

Search for offset matches between a previous set and the given current set.

This method is given a collection of offsets, each mapped to a particular set index. A new set of offsets and set index is given. The new set is added to the collection. If any offset in the new set matches an offset in one of the old sets, the old matching set index is returned. Otherwise -1 is returned.

Parameters
local2Operandis the collection of previous offsets
localsis the new given set of offsets
operandis the new given set index
Returns
the set index of an old matching offset or -1

Referenced by checkLocalExports().

◆ findSize()

VarnodeTpl * ghidra::SleighCompile::findSize ( const ConstTpl &  offset,
const ConstructTpl *  ct 
)
staticprivate

Find a defining instance of the local variable with the given offset.

Parameters
offsetis the given offset
ctis the Constructor to search
Returns
the matchine local variable or null

Referenced by forceExportSize().

◆ firstNamedSection()

SectionVector * ghidra::SleighCompile::firstNamedSection ( ConstructTpl *  main,
SectionSymbol *  sym 
)

Start a new named p-code section after the given main p-code section.

The main p-code section must already be constructed, and the new named section symbol defined. A SectionVector is initialized with the main section, and a symbol scope is created for the new p-code section.

Parameters
mainis the existing main p-code section
symis the existing symbol for the new named p-code section
Returns
the new SectionVector

References ghidra::SectionVector::setNextIndex(), and ghidra::SleighBase::symtab.

◆ forceExportSize()

bool ghidra::SleighCompile::forceExportSize ( ConstructTpl *  ct)
staticprivate

Propagate local variable sizes into an export statement.

Look for zero size temporary Varnodes in export statements, search for the matching local Varnode symbol and force its size on the export.

Parameters
ctis the Constructor whose export is to be modified
Returns
false if a local zero size can't be updated

References findSize().

Referenced by finalizeSections().

◆ formatStatusMessage()

string ghidra::SleighCompile::formatStatusMessage ( const Location *  loc,
const string &  msg 
)
staticprivate

Format an error or warning message given an optional source location.

Parameters
locis the given source location (or null)
msgis the message
Returns
the formatted message

Referenced by recordNop(), reportError(), and reportWarning().

◆ getCurrentLocation()

const Location * ghidra::SleighCompile::getCurrentLocation ( void  ) const
private

Get the current file and line number being parsed.

The current filename and line number are placed into a Location object which is then returned.

Returns
the current Location

References currentLocCache, filename, and lineno.

Referenced by addContextField(), addSymbol(), addTokenField(), attachNames(), attachValues(), attachVarnodes(), buildMacro(), calcContextVarLayout(), createConstructor(), createMacroUse(), defineBitrange(), defineInvisibleOperand(), defineOperand(), defineToken(), newSectionSymbol(), newSpace(), recordNop(), and selfDefine().

◆ getLocation() [1/2]

const Location * ghidra::SleighCompile::getLocation ( Constructor *  ctor) const

Get the source location of the given Constructor's definition.

Parameters
ctoris the given Constructor
Returns
the filename and line number

References ctorLocationMap.

Referenced by buildDecisionTrees(), buildPatterns(), checkCaseSensitivity(), checkLocalExports(), and finalizeSections().

◆ getLocation() [2/2]

const Location * ghidra::SleighCompile::getLocation ( SleighSymbol *  sym) const

Get the source location of the given symbol's definition.

Parameters
symis the given symbol
Returns
the filename and line number or null if location not found

References symbolLocationMap.

◆ getPreprocValue()

bool ghidra::SleighCompile::getPreprocValue ( const string &  nm,
string &  res 
) const

Retrieve a given preprocessor variable.

Pass back the string associated with the variable name.

Parameters
nmis the name of the given preprocessor variable
reswill hold string value passed back
Returns
true if the variable was defined

References preproc_defines.

◆ getUniqueAddr()

uint4 ghidra::SleighCompile::getUniqueAddr ( void  )

Get the next available temporary register offset.

The unique space acts as a pool of temporary registers that are drawn as needed. As Varnode sizes are frequently inferred and not immediately available during the parse, this method does not make an assumption about the size of the requested temporary Varnode. It reserves a fixed amount of space and returns its starting offset.

Returns
the starting offset of the new temporary register

References ghidra::Translate::getUniqueBase(), ghidra::SleighBase::MAX_UNIQUE_SIZE, and ghidra::Translate::setUniqueBase().

Referenced by setResultStarVarnode().

◆ grabCurrentFilePath()

string ghidra::SleighCompile::grabCurrentFilePath ( void  ) const

Get the path to the current source file.

Get the path of the current file being parsed as either an absolute path, or relative to cwd

Returns
the path string

References filename, and relpath.

◆ initialize()

virtual void ghidra::SleighCompile::initialize ( DocumentStorage store)
inlinevirtual

Initialize the translator given XML configuration documents.

A translator gets initialized once, possibly using XML documents to configure it.

Parameters
storeis a set of configuration documents

Implements ghidra::Translate.

◆ instructionLength()

virtual int4 ghidra::SleighCompile::instructionLength ( const Address baseaddr) const
inlinevirtual

Get the length of a machine instruction.

This method decodes an instruction at a specific address just enough to find the number of bytes it uses within the instruction stream.

Parameters
baseaddris the Address of the instruction
Returns
the number of bytes in the instruction

Implements ghidra::Translate.

◆ newOperand()

void ghidra::SleighCompile::newOperand ( Constructor *  ct,
string *  nm 
)

Define a new operand for the given Constructor.

A symbol local to the Constructor is defined, which initially is unmapped. Operands are defined in order.

Parameters
ctis the given Constructor
nmis the name of the new operand

References addSymbol().

◆ newSectionSymbol()

SectionSymbol * ghidra::SleighCompile::newSectionSymbol ( const string &  nm)

Start a new named p-code section and define the associated section symbol.

Parameters
nmis the name of the section
Returns
the new section symbol

References getCurrentLocation(), ghidra::SleighBase::numSections, reportError(), sections, and ghidra::SleighBase::symtab.

◆ newSpace()

void ghidra::SleighCompile::newSpace ( SpaceQuality qual)

◆ newTable()

SubtableSymbol * ghidra::SleighCompile::newTable ( string *  nm)

Define a new SLEIGH subtable.

A symbol and table entry are created.

Parameters
nmis the name of the new subtable

References addSymbol(), and tables.

◆ nextNamedSection()

SectionVector * ghidra::SleighCompile::nextNamedSection ( SectionVector vec,
ConstructTpl *  section,
SectionSymbol *  sym 
)

Complete a named p-code section and prepare for a new named section.

The actual p-code templates are assigned to a previously registered p-code section symbol and is added to the existing Section Vector. The old symbol scope is popped and another scope is created for the new named section.

Parameters
vecis the existing SectionVector
sectioncontains the p-code templates to assign to the previous section
symis the symbol describing the new named section being parsed
Returns
the updated SectionVector

References ghidra::SectionVector::append(), ghidra::SectionVector::setNextIndex(), and ghidra::SleighBase::symtab.

◆ oneInstruction()

virtual int4 ghidra::SleighCompile::oneInstruction ( PcodeEmit emit,
const Address baseaddr 
) const
inlinevirtual

Transform a single machine instruction into pcode.

This is the main interface to the pcode translation engine. The dump method in the emit object is invoked exactly once for each pcode operation in the translation for the machine instruction at the given address. This routine can throw either

Parameters
emitis the tailored pcode emitting object
baseaddris the Address of the machine instruction
Returns
the number of bytes in the machine instruction

Implements ghidra::Translate.

◆ parseFileFinished()

void ghidra::SleighCompile::parseFileFinished ( void  )

Mark end of parsing for the current file or macro.

Pop the current file off the included source file stack, indicating that parsing continues in the parent source file.

References filename, lineno, and relpath.

◆ parseFromNewFile()

void ghidra::SleighCompile::parseFromNewFile ( const string &  fname)

Push a new source file to the current parse stack.

The given filename can be absolute are relative to the current working directory. The directory containing the file is established as the new current working directory. The file is added to the current stack of included source files, and parsing is set to continue from the first line.

Parameters
fnameis the absolute or relative pathname of the new source file

References filename, lineno, and relpath.

Referenced by run_compilation().

◆ parsePreprocMacro()

void ghidra::SleighCompile::parsePreprocMacro ( void  )

Mark start of parsing for an expanded preprocessor macro.

Indicate to the location finder that parsing is currently in an expanded preprocessor macro.

References filename, lineno, and relpath.

◆ predefinedSymbols()

void ghidra::SleighCompile::predefinedSymbols ( void  )
private

Get SLEIGHs predefined address spaces and symbols.

Create the address spaces: const, unique, and other. Define the special symbols: inst_start, inst_next, inst_next2, epsilon. Define the root subtable symbol: instruction

References ghidra::AddrSpaceManager::getConstantSpace(), ghidra::AddrSpaceManager::getUniqueSpace(), ghidra::OtherSpace::INDEX, ghidra::AddrSpaceManager::insertSpace(), ghidra::AddrSpaceManager::numSpaces(), pcode, ghidra::SleighBase::root, and ghidra::SleighBase::symtab.

Referenced by setEndian().

◆ printAssembly()

virtual int4 ghidra::SleighCompile::printAssembly ( AssemblyEmit emit,
const Address baseaddr 
) const
inlinevirtual

Disassemble a single machine instruction.

This is the main interface to the disassembler for the processor. It disassembles a single instruction and returns the result to the application via the dump method in the emit object.

Parameters
emitis the disassembly emitting object
baseaddris the address of the machine instruction to disassemble

Implements ghidra::Translate.

References ghidra::yydebug.

◆ process()

void ghidra::SleighCompile::process ( void  )
private

Do all post processing on the parsed data structures.

This method is called after parsing is complete. It builds the final Constructor patterns, builds decision trees, does p-code optimization, and builds cross referencing structures. A number of checks are also performed, which may generate errors or warnings, including size restriction checks, pattern conflict checks, NOP constructor checks, and local collision checks. Once this method is run, this SleighCompile is ready for the saveXml method.

References buildDecisionTrees(), buildPatterns(), ghidra::SleighBase::buildXrefs(), checkCaseSensitivity(), checkConsistency(), checkLocalCollisions(), checkNops(), checkUniqueAllocation(), errors, ghidra::AddrSpaceManager::getDefaultCodeSpace(), reportError(), and ghidra::SleighBase::symtab.

Referenced by run_compilation().

◆ pushWith()

void ghidra::SleighCompile::pushWith ( SubtableSymbol *  ss,
PatternEquation *  pateq,
vector< ContextChange *> *  contvec 
)

Add a new with block to the current stack.

All subsequent Constructors adopt properties declared in the with header.

Parameters
ssthe subtable to assign to each Constructor, or null
pateqis an pattern equation constraining each Constructor, or null
contvecis a context change applied to each Constructor, or null

References withstack.

◆ recordNop()

void ghidra::SleighCompile::recordNop ( void  )

Record a NOP constructor at the current location.

The location is recorded and may be reported on after parsing.

References formatStatusMessage(), getCurrentLocation(), and noplist.

◆ reportError() [1/2]

void ghidra::SleighCompile::reportError ( const string &  msg)

Issue a fatal error message.

The message is formatted and displayed for the user and a count is incremented. If there are too many fatal errors, the entire compilation process is terminated. Otherwise, parsing can continue, but the compiler will not produce an output file.

Parameters
msgis the error message

References errors, filename, and lineno.

Referenced by addContextField(), addSymbol(), addTokenField(), attachNames(), attachValues(), attachVarnodes(), buildDecisionTrees(), buildMacro(), buildPatterns(), calcContextVarLayout(), checkCaseSensitivity(), createMacroUse(), defineBitrange(), defineInvisibleOperand(), defineOperand(), defineToken(), finalizeSections(), newSectionSymbol(), newSpace(), process(), reportError(), and selfDefine().

◆ reportError() [2/2]

void ghidra::SleighCompile::reportError ( const Location *  loc,
const string &  msg 
)

Issue a fatal error message with a source location.

The error message is formatted indicating the location of the error in source. The message is displayed for the user and a count is incremented. Otherwise, parsing can continue, but the compiler will not produce an output file.

Parameters
locis the location of the error
msgis the error message

References formatStatusMessage(), and reportError().

◆ reportWarning() [1/2]

void ghidra::SleighCompile::reportWarning ( const string &  msg)

Issue a warning message.

The message indicates a potential problem with the SLEIGH specification but does not prevent compilation from producing output.

Parameters
msgis the warning message

Referenced by attachNames(), attachValues(), attachVarnodes(), buildPatterns(), checkConsistency(), checkLocalCollisions(), checkLocalExports(), checkNops(), finalizeSections(), and reportWarning().

◆ reportWarning() [2/2]

void ghidra::SleighCompile::reportWarning ( const Location *  loc,
const string &  msg 
)

Issue a warning message with a source location.

The message indicates a potential problem with the SLEIGH specification but does not prevent compilation from producing output.

Parameters
locis the location of the problem in source
msgis the warning message

References formatStatusMessage(), and reportWarning().

◆ run_compilation()

int4 ghidra::SleighCompile::run_compilation ( const string &  filein,
const string &  fileout 
)

Run the full compilation process, given a path to the specification file.

The specification file is opened and a parse is started. Errors and warnings are printed to standard out, and if no fatal errors are encountered, the compiled form of the specification is written out.

Parameters
fileinis the given path to the specification file to compile
fileoutis the path to output file
Returns
an error code, where 0 indicates that a compiled file was successfully produced

References ghidra::LowlevelError::explain, ghidra::Element::getAttributeName(), ghidra::Element::getAttributeValue(), ghidra::Element::getChildren(), ghidra::Element::getContent(), ghidra::Element::getName(), ghidra::Element::getNumAttributes(), ghidra::Document::getRoot(), numErrors(), parseFromNewFile(), process(), run_compilation(), ghidra::SleighBase::saveXml(), setPreprocValue(), and ghidra::xml_tree().

Referenced by run_compilation(), and setAllOptions().

◆ selfDefine()

void ghidra::SleighCompile::selfDefine ( OperandSymbol *  sym)

Map given operand to a global symbol of same name.

The operand symbol still acts as a local symbol but gets its display, pattern, and semantics from the global symbol.

Parameters
symis the given operand

References getCurrentLocation(), reportError(), and ghidra::SleighBase::symtab.

◆ setAlignment()

void ghidra::SleighCompile::setAlignment ( int4  val)
inline

Set instruction alignment for the SLEIGH specification.

Parameters
valis the alignment value in bytes. 1 is the default indicating no alignment

References ghidra::RtlPair::section.

◆ setAllNopWarning()

void ghidra::SleighCompile::setAllNopWarning ( bool  val)
inline

Set whether NOP Constructors generate warnings individually.

Parameters
valis true if warnings are generated individually. The default is false.

Referenced by setAllOptions().

◆ setAllOptions()

void ghidra::SleighCompile::setAllOptions ( const map< string, string > &  defines,
bool  unnecessaryPcodeWarning,
bool  lenientConflict,
bool  allCollisionWarning,
bool  allNopWarning,
bool  deadTempWarning,
bool  enforceLocalKeyWord,
bool  largeTemporaryWarning,
bool  caseSensitiveRegisterNames 
)

Set all compiler options at the same time.

Parameters
definesis map of variable to value that is passed to the preprocessor
unnecessaryPcodeWarningis true for individual warnings about unnecessary p-code ops
lenientConflictis false to report indistinguishable patterns as errors
allCollisionWarningis true for individual warnings about constructors with colliding operands
allNopWarningis true for individual warnings about NOP constructors
deadTempWarningis true for individual warnings about dead temporary varnodes
enforceLocalKeyWordis true to force all local variable definitions to use the local keyword
largeTemporaryWarningis true for individual warnings about temporary varnodes that are too large
caseSensitiveRegisterNamesis true if register names are allowed to be case sensitive

References run_compilation(), setAllNopWarning(), setAllOptions(), setDeadTempWarning(), setEnforceLocalKeyWord(), setInsensitiveDuplicateError(), setLargeTemporaryWarning(), setLenientConflict(), setLocalCollisionWarning(), setPreprocValue(), and setUnnecessaryPcodeWarning().

Referenced by setAllOptions().

◆ setDeadTempWarning()

void ghidra::SleighCompile::setDeadTempWarning ( bool  val)
inline

Set whether dead temporary registers generate warnings individually.

Parameters
valis true if warnings are generated individually. The default is false.

Referenced by setAllOptions().

◆ setEndian()

void ghidra::SleighCompile::setEndian ( int4  end)

Set the global endianness of the SLEIGH specification.

This must be called at the very beginning of the parse. This method additionally establishes predefined symbols for the specification.

Parameters
endis the endianness value (0=little 1=big)

References predefinedSymbols(), and ghidra::Translate::setBigEndian().

◆ setEnforceLocalKeyWord()

void ghidra::SleighCompile::setEnforceLocalKeyWord ( bool  val)
inline

Set whether named temporary registers must be defined using the local keyword.

Parameters
valis true if the local keyword must always be used. The default is false.

Referenced by setAllOptions().

◆ setInsensitiveDuplicateError()

void ghidra::SleighCompile::setInsensitiveDuplicateError ( bool  val)
inline

Set whether case insensitive duplicates of register names cause an error.

Parameters
valis true is duplicates cause an error.

Referenced by setAllOptions().

◆ setLargeTemporaryWarning()

void ghidra::SleighCompile::setLargeTemporaryWarning ( bool  val)
inline

Set whether too large temporary registers generate warnings individually.

Parameters
valis true if warnings are generated individually. The default is false.

Referenced by setAllOptions().

◆ setLenientConflict()

void ghidra::SleighCompile::setLenientConflict ( bool  val)
inline

Set whether indistinguishable Constructor patterns generate fatal errors.

Parameters
valis true if no error is generated. The default is true.

Referenced by setAllOptions().

◆ setLocalCollisionWarning()

void ghidra::SleighCompile::setLocalCollisionWarning ( bool  val)
inline

Set whether collisions in exported locals generate warnings individually.

Parameters
valis true if warnings are generated individually. The default is false.

Referenced by setAllOptions().

◆ setPreprocValue()

void ghidra::SleighCompile::setPreprocValue ( const string &  nm,
const string &  value 
)

Set a given preprocessor variable.

The string value is associated with the variable name.

Parameters
nmis the name of the given preprocessor variable
valueis the string value to associate

References preproc_defines.

Referenced by run_compilation(), and setAllOptions().

◆ setResultStarVarnode()

ConstructTpl * ghidra::SleighCompile::setResultStarVarnode ( ConstructTpl *  ct,
StarQuality *  star,
VarnodeTpl *  vn 
)

Set a Constructor export to be the location pointed to by the given Varnode.

SLEIGH symbols matching the Constructor use this dynamic location as their semantic storage/value.

Parameters
ctis the Constructor p-code section
stardescribes the pointer details
vnis the given Varnode pointer
Returns
the p-code section

References getUniqueAddr(), and ghidra::AddrSpaceManager::getUniqueSpace().

◆ setResultVarnode()

ConstructTpl * ghidra::SleighCompile::setResultVarnode ( ConstructTpl *  ct,
VarnodeTpl *  vn 
)

Set export of a Constructor to the given Varnode.

SLEIGH symbols matching the Constructor use this Varnode as their semantic storage/value.

Parameters
ctis the Constructor p-code section
vnis the given Varnode
Returns
the p-code section

◆ setUnnecessaryPcodeWarning()

void ghidra::SleighCompile::setUnnecessaryPcodeWarning ( bool  val)
inline

Set whether unnecessary truncation and extension operators generate warnings individually.

Parameters
valis true if warnings are generated individually. The default is false.

Referenced by setAllOptions().

◆ shiftUniqueConstruct()

void ghidra::SleighCompile::shiftUniqueConstruct ( ConstructTpl *  tpl,
int4  sa 
)
staticprivate

Shift the offset up for any Varnode in the unique space for all p-code in the given section.

Parameters
tplis the given p-code section
sais the number of bits to shift by

References shiftUniqueHandle(), and shiftUniqueOp().

Referenced by checkUniqueAllocation().

◆ shiftUniqueHandle()

void ghidra::SleighCompile::shiftUniqueHandle ( HandleTpl *  hand,
int4  sa 
)
staticprivate

Shift the offset up for both dynamic or static Varnode aspects in the unique space.

Parameters
handis a handle template whose aspects should be modified
sais the number of bits to shift by

Referenced by shiftUniqueConstruct().

◆ shiftUniqueOp()

void ghidra::SleighCompile::shiftUniqueOp ( OpTpl *  op,
int4  sa 
)
staticprivate

Shift the offset up by sa bits for any Varnode used by the given op in the unique space.

Parameters
opis the given op
sais the number of bits to shift by

References shiftUniqueVn().

Referenced by shiftUniqueConstruct().

◆ shiftUniqueVn()

void ghidra::SleighCompile::shiftUniqueVn ( VarnodeTpl *  vn,
int4  sa 
)
staticprivate

If the given Varnode is in the unique space, shift its offset up by sa bits.

Parameters
vnis the given Varnode
sais the number of bits to shift by

Referenced by shiftUniqueOp().

◆ standaloneSection()

SectionVector * ghidra::SleighCompile::standaloneSection ( ConstructTpl *  main)

Create a SectionVector containing just the main p-code section with no named sections.

Parameters
mainis the main p-code section
Returns
the new SectionVector

References ghidra::SleighBase::symtab.

◆ undefinePreprocValue()

bool ghidra::SleighCompile::undefinePreprocValue ( const string &  nm)

Remove the value associated with the given preprocessor variable.

Any existing string value associated with the variable is removed.

Parameters
nmis the name of the given preprocessor variable
Returns
true if the variable had a value (was defined) initially

References preproc_defines.


The documentation for this class was generated from the following files: