decompiler  1.0.0
Public Member Functions | Static Public Member Functions | Private Member Functions | Private Attributes | List of all members
ArchitectureGhidra Class Reference

An implementation of the Architecture interface and connection to a Ghidra client. More...

#include <ghidra_arch.hh>

Inheritance diagram for ArchitectureGhidra:
Architecture AddrSpaceManager

Public Member Functions

 ArchitectureGhidra (const string &pspec, const string &cspec, const string &tspec, const string &corespec, istream &i, ostream &o)
 Construct given specification files and i/o streams. More...
 
const string & getWarnings (void) const
 Get warnings produced by the last decompilation.
 
void clearWarnings (void)
 Clear warnings.
 
DocumentgetRegister (const string &regname)
 Retrieve a register description given a name. More...
 
string getRegisterName (const VarnodeData &vndata)
 Retrieve a register name given its storage location. More...
 
DocumentgetTrackedRegisters (const Address &addr)
 Retrieve tracked register values at the given address. More...
 
string getUserOpName (int4 index)
 Get the name of a user-defined p-code op. More...
 
uint1 * getPcodePacked (const Address &addr)
 Get p-code for a single instruction. More...
 
DocumentgetMappedSymbolsXML (const Address &addr)
 Get symbols associated with the given address. More...
 
DocumentgetExternalRefXML (const Address &addr)
 Retrieve a description of an external function. More...
 
DocumentgetNamespacePath (uint8 id)
 Get a description of a namespace path. More...
 
bool isNameUsed (const string &nm, uint8 startId, uint8 stopId)
 Is given name used along namespace path.
 
string getCodeLabel (const Address &addr)
 Retrieve a label at the given address. More...
 
DocumentgetType (const string &name, uint8 id)
 Retrieve a data-type description for the given name and id. More...
 
DocumentgetComments (const Address &fad, uint4 flags)
 Retrieve comments for a particular function. More...
 
void getBytes (uint1 *buf, int4 size, const Address &inaddr)
 Retrieve bytes in the LoadImage at the given address. More...
 
DocumentgetPcodeInject (const string &name, int4 type, const InjectContext &con)
 Retrieve p-code to inject for a specific context. More...
 
DocumentgetCPoolRef (const vector< uintb > &refs)
 Resolve a constant pool reference. More...
 
void setSendSyntaxTree (bool val)
 Toggle whether the data-flow and control-flow is emitted as part of the main decompile action. More...
 
bool getSendSyntaxTree (void) const
 Get the current setting for emitting data/control-flow.
 
void setSendCCode (bool val)
 Toggle whether the recovered source code is emitted as part of the main decompile action. More...
 
bool getSendCCode (void) const
 Get the current setting for emitting source code.
 
void setSendParamMeasures (bool val)
 Toggle whether recovered parameter information is emitted as part of the main decompile action. More...
 
bool getSendParamMeasures (void) const
 Get the current setting for emitting parameter info.
 
virtual void getStringData (vector< uint1 > &buffer, const Address &addr, Datatype *ct, int4 maxBytes, bool &isTrunc)
 
virtual void printMessage (const string &message) const
 Print an error message to console. More...
 
- Public Member Functions inherited from Architecture
 Architecture (void)
 Construct an uninitialized Architecture. More...
 
void init (DocumentStorage &store)
 Load the image and configure architecture. More...
 
void resetDefaultsInternal (void)
 Reset default values for options specific to Architecture.
 
void resetDefaults (void)
 Reset defaults values for options owned by this. More...
 
ProtoModelgetModel (const string &nm) const
 Get a specific PrototypeModel. More...
 
bool hasModel (const string &nm) const
 Does this Architecture have a specific PrototypeModel. More...
 
bool highPtrPossible (const Address &loc, int4 size) const
 Are pointers possible to the given location? More...
 
AddrSpacegetSpaceBySpacebase (const Address &loc, int4 size) const
 Get space associated with a spacebase register. More...
 
const LanedRegistergetLanedRegister (const Address &loc, int4 size) const
 Get LanedRegister associated with storage. More...
 
int4 getMinimumLanedRegisterSize (void) const
 Get the minimum size of a laned register in bytes. More...
 
void setDefaultModel (const string &nm)
 Set the default PrototypeModel. More...
 
void clearAnalysis (Funcdata *fd)
 Clear analysis specific to a function. More...
 
void readLoaderSymbols (const string &delim)
 Read any symbols from loader into database. More...
 
void collectBehaviors (vector< OpBehavior * > &behave) const
 Provide a list of OpBehavior objects. More...
 
SegmentOpgetSegmentOp (AddrSpace *spc) const
 Retrieve the segment op for the given space if any. More...
 
void setPrototype (const PrototypePieces &pieces)
 Set the prototype for a particular function. More...
 
void setPrintLanguage (const string &nm)
 Establish a particular output language. More...
 
void globalify (void)
 Mark all spaces as global. More...
 
void restoreFlowOverride (const Element *el)
 Set flow overrides from XML. More...
 
virtual ~Architecture (void)
 Destructor. More...
 
virtual string getDescription (void) const
 Get a string describing this architecture.
 
virtual void saveXml (ostream &s) const
 Serialize this architecture to XML. More...
 
virtual void restoreXml (DocumentStorage &store)
 Restore the Architecture state from an XML stream. More...
 
virtual void nameFunction (const Address &addr, string &name) const
 Pick a default name for a function. More...
 
- Public Member Functions inherited from 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...
 

Static Public Member Functions

static void segvHandler (int4 sig)
 Handler for a segment violation (SIGSEGV) signal. More...
 
static int4 readToAnyBurst (istream &s)
 Read the next message protocol marker. More...
 
static bool readBoolStream (istream &s)
 Read a boolean value from the client. More...
 
static void readStringStream (istream &s, string &res)
 Receive a string from the client. More...
 
static void writeStringStream (ostream &s, const string &msg)
 Send a string to the client. More...
 
static void readToResponse (istream &s)
 Read the query response protocol marker. More...
 
static void readResponseEnd (istream &s)
 Read the ending query response protocol marker. More...
 
static DocumentreadXMLAll (istream &s)
 Read a whole response as an XML document. More...
 
static DocumentreadXMLStream (istream &s)
 Receive an XML document from the client. More...
 
static uint1 * readPackedStream (istream &s)
 Read packed p-code op information. More...
 
static uint1 * readPackedAll (istream &s)
 Read a whole response as packed p-code op information. More...
 
static void passJavaException (ostream &s, const string &tp, const string &msg)
 Send an exception message to the Ghidra client. More...
 
static bool isDynamicSymbolName (const string &nm)
 Check if name is of form FUN_.. or DAT_..
 

Private Member Functions

virtual ScopebuildDatabase (DocumentStorage &store)
 Build the database and global scope for this executable. More...
 
virtual TranslatebuildTranslator (DocumentStorage &store)
 Build the Translator object. More...
 
virtual void buildLoader (DocumentStorage &store)
 Build the LoadImage object and load the executable image. More...
 
virtual PcodeInjectLibrarybuildPcodeInjectLibrary (void)
 Build the injection library. More...
 
virtual void buildTypegrp (DocumentStorage &store)
 Build the data-type factory/container. More...
 
virtual void buildCommentDB (DocumentStorage &store)
 Build the comment database. More...
 
virtual void buildStringManager (DocumentStorage &store)
 Build the string manager. More...
 
virtual void buildConstantPool (DocumentStorage &store)
 Build the constant pool. More...
 
virtual void buildContext (DocumentStorage &store)
 Build the Context database. More...
 
virtual void buildSpecFile (DocumentStorage &store)
 Load any relevant specification files. More...
 
virtual void modifySpaces (Translate *trans)
 Modify address spaces as required by this Architecture. More...
 
virtual void postSpecFile (void)
 Let components initialize after Translate is built.
 
virtual void resolveArchitecture (void)
 Figure out the processor and compiler of the target executable.
 

Private Attributes

istream & sin
 Input stream for interfacing with Ghidra.
 
ostream & sout
 Output stream for interfacing with Ghidra.
 
string warnings
 Warnings accumulated by the decompiler.
 
string pspecxml
 XML pspec passed from Ghidra.
 
string cspecxml
 XML cspec passed from Ghidra.
 
string tspecxml
 Stripped down .sla file passed from Ghidra.
 
string corespecxml
 A specification of the core data-types.
 
bool sendsyntaxtree
 True if the syntax tree should be sent with function output.
 
bool sendCcode
 True if C code should be sent with function output.
 
bool sendParamMeasures
 True if measurements for argument and return parameters should be sent.
 

Additional Inherited Members

- Public Attributes inherited from Architecture
string archid
 ID string uniquely describing this architecture.
 
int4 trim_recurse_max
 How many levels to let parameter trims recurse.
 
int4 max_implied_ref
 Maximum number of references to an implied var.
 
int4 max_term_duplication
 Max terms duplicated without a new variable.
 
int4 max_basetype_size
 Maximum size of an "integer" type before creating an array type.
 
int4 min_funcsymbol_size
 Minimum size of a function symbol.
 
bool aggressive_ext_trim
 Aggressively trim inputs that look like they are sign extended.
 
bool readonlypropagate
 true if readonly values should be treated as constants
 
bool infer_pointers
 True if we should infer pointers from constants that are likely addresses.
 
vector< AddrSpace * > inferPtrSpaces
 Set of address spaces in which a pointer constant is inferable.
 
int4 funcptr_align
 How many bits of alignment a function ptr has.
 
uint4 flowoptions
 options passed to flow following engine
 
uint4 max_instructions
 Maximum instructions that can be processed in one function.
 
int4 alias_block_level
 Aliases blocked by 0=none, 1=struct, 2=array, 3=all.
 
vector< Rule * > extra_pool_rules
 Extra rules that go in the main pool (cpu specific, experimental)
 
Databasesymboltab
 Memory map of global variables and functions.
 
ContextDatabasecontext
 Map from addresses to context settings.
 
map< string, ProtoModel * > protoModels
 Parsed forms of possible prototypes.
 
ProtoModeldefaultfp
 Parsed form of default prototype.
 
VarnodeData defaultReturnAddr
 Default storage location of return address (for current function)
 
ProtoModelevalfp_current
 Function proto to use when evaluating current function.
 
ProtoModelevalfp_called
 Function proto to use when evaluating called functions.
 
TypeFactorytypes
 List of types for this binary.
 
const Translatetranslate
 Translation method for this binary.
 
LoadImageloader
 Method for loading portions of binary.
 
PcodeInjectLibrarypcodeinjectlib
 Pcode injection manager.
 
RangeList nohighptr
 Ranges for which high-level pointers are not possible.
 
CommentDatabasecommentdb
 Comments for this architecture.
 
StringManagerstringManager
 Manager of decoded strings.
 
ConstantPoolcpool
 Deferred constant values.
 
PrintLanguageprint
 Current high-level language printer.
 
vector< PrintLanguage * > printlist
 List of high-level language printers supported.
 
OptionDatabaseoptions
 Options that can be configured.
 
vector< TypeOp * > inst
 Registered p-code instructions.
 
UserOpManage userops
 Specifically registered user-defined p-code ops.
 
vector< PreferSplitRecordsplitrecords
 registers that we would prefer to see split for this processor
 
vector< LanedRegisterlanerecords
 Vector registers that have preferred lane sizes.
 
ActionDatabase allacts
 Actions that can be applied in this architecture.
 
bool loadersymbols_parsed
 True if loader symbols have been read.
 
- Protected Member Functions inherited from Architecture
void addSpacebase (AddrSpace *basespace, const string &nm, const VarnodeData &ptrdata, int4 truncSize, bool isreversejustified, bool stackGrowth)
 Create a new space and associated pointer. More...
 
void addNoHighPtr (const Range &rng)
 Add a new region where pointers do not exist. More...
 
virtual void buildInstructions (DocumentStorage &store)
 Register the p-code operations. More...
 
virtual void buildAction (DocumentStorage &store)
 Build the Action framework. More...
 
void restoreFromSpec (DocumentStorage &store)
 Fully initialize the Translate object. More...
 
void fillinReadOnlyFromLoader (void)
 Load info about read-only sections. More...
 
void initializeSegments ()
 Set up segment resolvers. More...
 
void cacheAddrSpaceProperties (void)
 Calculate some frequently used space properties and cache them. More...
 
void parseProcessorConfig (DocumentStorage &store)
 Apply processor specific configuration. More...
 
void parseCompilerConfig (DocumentStorage &store)
 Apply compiler specific configuration. More...
 
void parseExtraRules (DocumentStorage &store)
 Apply any Rule tags. More...
 
void parseDynamicRule (const Element *el)
 Apply details of a dynamic Rule object. More...
 
ProtoModelparseProto (const Element *el)
 Build a proto-type model from an XML tag. More...
 
void parseProtoEval (const Element *el)
 Apply prototype evaluation configuration. More...
 
void parseDefaultProto (const Element *el)
 Apply default prototype model configuration. More...
 
void parseGlobal (const Element *el)
 Apply global space configuration. More...
 
void addOtherSpace (void)
 Add OTHER space and all of its overlays to the symboltab.
 
void parseReadOnly (const Element *el)
 Apply read-only region configuration. More...
 
void parseVolatile (const Element *el)
 Apply volatile region configuration. More...
 
void parseReturnAddress (const Element *el)
 Apply return address configuration. More...
 
void parseIncidentalCopy (const Element *el)
 Apply incidental copy configuration. More...
 
void parseLaneSizes (const Element *el)
 Apply lane size configuration. More...
 
void parseStackPointer (const Element *el)
 Apply stack pointer configuration. More...
 
void parseDeadcodeDelay (const Element *el)
 Apply dead-code delay configuration. More...
 
void parseInferPtrBounds (const Element *el)
 Apply pointer inference bounds. More...
 
void parseFuncPtrAlign (const Element *el)
 Apply function pointer alignment configuration. More...
 
void parseSpacebase (const Element *el)
 Create an additional indexed space. More...
 
void parseNoHighPtr (const Element *el)
 Apply memory alias configuration. More...
 
void parsePreferSplit (const Element *el)
 Designate registers to be split. More...
 
void parseAggressiveTrim (const Element *el)
 Designate how to trim extension p-code ops. More...
 
- Protected Member Functions inherited from AddrSpaceManager
AddrSpacerestoreXmlSpace (const Element *el, const Translate *trans)
 Add a space to the model based an on XML tag. More...
 
void restoreXmlSpaces (const Element *el, 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...
 

Detailed Description

An implementation of the Architecture interface and connection to a Ghidra client.

In addition to managing the major pieces of the architecture (LoadImage, Translate, Database, TypeFactory, ContextDatbase, CommentDatabase etc.), this class manages a communication channel between the decompiler and a Ghidra client for a single executable. The protocol supports a simple query/response format with exceptions. On top of the low level protocol, this class manages a higher level interface that performs specific queries, providing addresses, names, and other info as input, and returning an XML document or other structure as a result.

This class overrides the build* methods to produce Architecture components that are also backed by the Ghidra client. These all use this same object to do their communication.

This class acts as a main control point for what information gets sent back to the Ghidra client when it requests the main decompilation action. Generally the decompiler sends back the recovered source representation of the function but optionally it can send back:

Constructor & Destructor Documentation

ArchitectureGhidra::ArchitectureGhidra ( const string &  pspec,
const string &  cspec,
const string &  tspec,
const string &  corespec,
istream &  i,
ostream &  o 
)

Construct given specification files and i/o streams.

Parameters
pspecis the processor specification presented as an XML string
cspecis the compiler specification presented as an XML string
tspecis a stripped down form of the SLEIGH specification presented as an XML string
corespecis a list of core data-types presented as a <coretypes> XML tag
iis the input stream from the Ghidra client
ois the output stream to the Ghidra client

References corespecxml, cspecxml, Architecture::print, pspecxml, sendCcode, sendParamMeasures, sendsyntaxtree, PrintLanguage::setOutputStream(), PrintLanguage::setXML(), sout, and tspecxml.

Member Function Documentation

void ArchitectureGhidra::buildCommentDB ( DocumentStorage store)
privatevirtual

Build the comment database.

Build the container that holds comments for executable in this Architecture.

Parameters
storemay hold configuration information

Reimplemented from Architecture.

References Architecture::commentdb.

void ArchitectureGhidra::buildConstantPool ( DocumentStorage store)
privatevirtual

Build the constant pool.

Some processor models (Java byte-code) need a database of constants. The database is always built, but may remain empty.

Parameters
storemay hold configuration information

Reimplemented from Architecture.

References Architecture::cpool.

void ArchitectureGhidra::buildContext ( DocumentStorage store)
privatevirtual

Build the Context database.

This builds the database which holds the status registers setings and other information that can affect disassembly depending on context.

Parameters
storemay hold configuration information

Reimplemented from Architecture.

References Architecture::context.

Scope * ArchitectureGhidra::buildDatabase ( DocumentStorage store)
privatevirtual

Build the database and global scope for this executable.

Create the database object, which currently doesn't not depend on any configuration data. Then create the root (global) scope and attach it to the database.

Parameters
storeis the storage for any configuration data
Returns
the global Scope object

Reimplemented from Architecture.

References Database::attachScope(), and Architecture::symboltab.

void ArchitectureGhidra::buildLoader ( DocumentStorage store)
privatevirtual

Build the LoadImage object and load the executable image.

Parameters
storemay hold configuration information

Implements Architecture.

References Architecture::loader.

PcodeInjectLibrary * ArchitectureGhidra::buildPcodeInjectLibrary ( void  )
privatevirtual

Build the injection library.

This creates the container for p-code injections. It is initially empty.

Returns
the PcodeInjectLibrary object

Implements Architecture.

void ArchitectureGhidra::buildSpecFile ( DocumentStorage store)
privatevirtual

Load any relevant specification files.

Processor/architecture specific configuration files are loaded into the XML store

Parameters
storeis the document store that will hold the configuration

Implements Architecture.

References corespecxml, cspecxml, Document::getRoot(), DocumentStorage::parseDocument(), pspecxml, DocumentStorage::registerTag(), and tspecxml.

void ArchitectureGhidra::buildStringManager ( DocumentStorage store)
privatevirtual

Build the string manager.

Build container that holds decoded strings

Parameters
storemay hold configuration information

Reimplemented from Architecture.

References Architecture::stringManager.

Translate * ArchitectureGhidra::buildTranslator ( DocumentStorage store)
privatevirtual

Build the Translator object.

This builds the main disassembly component for the Architecture This does not initially the engine for a specific processor.

Parameters
storemay hold configuration information
Returns
the Translate object

Implements Architecture.

void ArchitectureGhidra::buildTypegrp ( DocumentStorage store)
privatevirtual

Build the data-type factory/container.

This builds the TypeFactory object specific to this architecture and prepopulates it with the core types. Core types may be pulled from the configuration information, or default core types are used.

Parameters
storecontains possible configuration information

Reimplemented from Architecture.

References TypeFactory::cacheCoreTypes(), DocumentStorage::getTag(), TypeFactory::restoreXmlCoreTypes(), TypeFactory::setCoreType(), TYPE_BOOL, TYPE_CODE, TYPE_FLOAT, TYPE_INT, TYPE_UINT, TYPE_UNKNOWN, TYPE_VOID, and Architecture::types.

void ArchitectureGhidra::getBytes ( uint1 *  buf,
int4  size,
const Address inaddr 
)

Retrieve bytes in the LoadImage at the given address.

The Ghidra client is queried for a range of bytes, which are returned in the given array. This method throws a DataUnavailError if the provided address doesn't make sense.

Parameters
bufis the preallocated array in which to store the bytes
sizeis the number of bytes requested
inaddris the address in the LoadImage from which to grab bytes

References Datatype::getId(), Datatype::getName(), Address::getShortcut(), Address::printRaw(), readResponseEnd(), readToAnyBurst(), readToResponse(), Address::saveXml(), sin, sout, and writeStringStream().

Referenced by LoadImageGhidra::loadFill().

string ArchitectureGhidra::getCodeLabel ( const Address addr)

Retrieve a label at the given address.

Get the name of the primary symbol at the given address. This is used to fetch within function labels. Only a name is returned.

Parameters
addris the given address
Returns
the symbol name or ""

References readResponseEnd(), readStringStream(), readToResponse(), Address::saveXml(), sin, sout, and writeStringStream().

Referenced by ScopeGhidra::findCodeLabel().

Document * ArchitectureGhidra::getComments ( const Address fad,
uint4  flags 
)

Retrieve comments for a particular function.

Ask Ghidra client for all comments associated with one function. The caller must provide the sub-set of properties (Comment::comment_type) for the query to match. The client will return a <commentdb> tag with a <comment> tag child for each comment found.

Parameters
fadis the address of the function to query
flagsspecifies the properties the query will match (must be non-zero)
Returns
an XML document describing each comment

References readXMLAll(), Address::saveXml(), sin, sout, and writeStringStream().

Referenced by CommentDatabaseGhidra::fillCache().

Document * ArchitectureGhidra::getCPoolRef ( const vector< uintb > &  refs)

Resolve a constant pool reference.

The Ghidra client is provided a sequence of 1 or more integer values extracted from a CPOOLREF op. It returns an XML document describing the constant pool record referenced by the integer(s) or will throw an exception if record isn't properly referenced.

Parameters
refsis an array of 1 or more integer values referencing a constant pool record
Returns
a description of the record as a <cpoolrec> XML document.

References readXMLAll(), sin, sout, and writeStringStream().

Referenced by ConstantPoolGhidra::getRecord().

Document * ArchitectureGhidra::getExternalRefXML ( const Address addr)

Retrieve a description of an external function.

This asks the Ghidra client to resolve an external reference. This is an address for which the client holds a reference to a function that is elsewhere in memory or not in memory at all. The client should unravel the reference from the given address and return either a <function> tag describing the referred to function symbol or a <hole> tag if the reference can't be resolved

Parameters
addris the given address
Returns
a description of the referred to function

References readXMLAll(), Address::saveXml(), sin, sout, and writeStringStream().

Referenced by ScopeGhidra::resolveExternalRefFunction().

Document * ArchitectureGhidra::getMappedSymbolsXML ( const Address addr)

Get symbols associated with the given address.

The Ghidra client will return a <symbol> tag, <function> tag, or some other related Symbol information. If there no symbol at the address the client should return a <hole> tag describing the size of the memory region that is free of symbols.

Parameters
addris the given address
Returns
the symbol document

References readXMLAll(), Address::saveXml(), sin, sout, and writeStringStream().

Referenced by ScopeGhidra::removeQuery().

Document * ArchitectureGhidra::getNamespacePath ( uint8  id)

Get a description of a namespace path.

Ask the Ghidra client to list all namespace elements between the global root and the namespace of the given id. The client should return a <parent> tag with a <val> child for each namespace in the path.

Parameters
idis the given id of the namespace to resolve
Returns
the XML document

References readXMLAll(), sin, sout, and writeStringStream().

Referenced by ScopeGhidra::reresolveScope().

Document * ArchitectureGhidra::getPcodeInject ( const string &  name,
int4  type,
const InjectContext con 
)

Retrieve p-code to inject for a specific context.

The particular injection is named and is of one of the types:

  • CALLFIXUP_TYPE
  • CALLOTHERFIXUP_TYPE
  • CALLMECHANISM_TYPE
  • EXECUTABLEPCODE_TYPE

This and additional context is provided to the Ghidra client which returns an XML document describing the p-code. The document will be an <inst> tag containing individual <op> tags corresponding to individual p-code ops.

Parameters
nameis the name of the injection
typeis the type of injection
conis the context object
Returns
an XML document describing the p-code ops to inject

References InjectPayload::CALLFIXUP_TYPE, InjectPayload::CALLMECHANISM_TYPE, InjectPayload::CALLOTHERFIXUP_TYPE, readXMLAll(), InjectContext::saveXml(), sin, sout, and writeStringStream().

Referenced by InjectPayloadGhidra::inject(), and ExecutablePcodeGhidra::inject().

uint1 * ArchitectureGhidra::getPcodePacked ( const Address addr)

Get p-code for a single instruction.

Get a description of all the p-code ops for the instruction at the given address. The information is stored in a special compressed format. (See PcodeEmit::restorePackedOp)

Parameters
addris the address of the instruction
Returns
an array of the packed data

References readPackedAll(), Address::saveXml(), sin, sout, and writeStringStream().

Referenced by GhidraTranslate::oneInstruction().

Document * ArchitectureGhidra::getRegister ( const string &  regname)

Retrieve a register description given a name.

Ask the Ghidra client if it knows about a specific processor register. The client responds with a <addr> XML element describing the storage location of the register.

Parameters
regnameis the name to query for
Returns
the storage address as XML or NULL if the register is unknown

References readXMLAll(), sin, sout, and writeStringStream().

Referenced by GhidraTranslate::getRegister().

string ArchitectureGhidra::getRegisterName ( const VarnodeData vndata)

Retrieve a register name given its storage location.

Given a storage location and size, ask the Ghidra client if it knows of a register that occupies those bytes. The register name is passed back. The name may not exactly match the given memory range, it may contain it.

Parameters
vndatais the location and size
Returns
the register name or ""

References VarnodeData::offset, readResponseEnd(), readStringStream(), readToResponse(), Address::saveXml(), sin, VarnodeData::size, sout, VarnodeData::space, and writeStringStream().

Referenced by GhidraTranslate::getRegisterName().

Document * ArchitectureGhidra::getTrackedRegisters ( const Address addr)

Retrieve tracked register values at the given address.

The Ghidra client will return a description of registers that have known values at the given address. The response is generally a <tracked_pointset> which contains <set> children which contains a storage location and value.

Parameters
addris the given address
Returns
the response Document

References readXMLAll(), Address::saveXml(), sin, sout, and writeStringStream().

Document * ArchitectureGhidra::getType ( const string &  name,
uint8  id 
)

Retrieve a data-type description for the given name and id.

The Ghidra client should respond with a <type> tag giving details about the data-type.

Parameters
nameis the name of the data-type
idis a unique id associated with the data-type, pass 0 if unknown
Returns
the data-type XML element or NULL

References readXMLAll(), sin, sout, and writeStringStream().

string ArchitectureGhidra::getUserOpName ( int4  index)

Get the name of a user-defined p-code op.

The first operand to a CALLOTHER op indicates the specific user-defined op. This method queries the Ghidra client and passes back the name of the op.

Parameters
indexis the value of the CALLOTHER operand
Returns
the recovered name or ""

References readResponseEnd(), readStringStream(), readToResponse(), sin, sout, and writeStringStream().

Referenced by GhidraTranslate::getUserOpNames().

virtual void ArchitectureGhidra::modifySpaces ( Translate trans)
inlineprivatevirtual

Modify address spaces as required by this Architecture.

If spaces need to be truncated or otherwise changed from processor defaults, this routine performs the modification.

Parameters
transis the processor disassembly object

Implements Architecture.

void ArchitectureGhidra::passJavaException ( ostream &  s,
const string &  tp,
const string &  msg 
)
static

Send an exception message to the Ghidra client.

This generally called because of some sort of alignment issue in the message protocol and lets the client know to abort (and hopefully resync)

Parameters
sis the output stream to the client
tpis the type of exception
msgis the exception message

References writeStringStream().

Referenced by GhidraCommand::doit().

void ArchitectureGhidra::printMessage ( const string &  message) const
virtual

Print an error message to console.

Write the given message to whatever the registered error stream is

Parameters
messageis the error message

Implements Architecture.

References warnings.

Referenced by GhidraCommand::doit().

bool ArchitectureGhidra::readBoolStream ( istream &  s)
static

Read a boolean value from the client.

Read the string protocol start, a single character, then the protocol end. If the character is a 't', return true, otherwise false.

Parameters
sis the input stream from the client
Returns
the passed back boolean value

References readToAnyBurst().

Referenced by isNameUsed().

uint1 * ArchitectureGhidra::readPackedAll ( istream &  s)
static

Read a whole response as packed p-code op information.

Read up to the beginning of a query response, check for an exception record, otherwise read in packed p-code op data.

Parameters
sis the input stream from the client
Returns
the array of packed p-coded data

References readPackedStream(), readResponseEnd(), and readToResponse().

Referenced by getPcodePacked().

uint1 * ArchitectureGhidra::readPackedStream ( istream &  s)
static

Read packed p-code op information.

The method expects to see protocol markers indicating a string from the client, otherwise it throws and exception. An array size is encoded in the first 4 characters of the string. An array of this size is allocated and filled with the rest of the string.

Parameters
sis the input stream from the client
Returns
the array of packed p-code data

References readToAnyBurst().

Referenced by readPackedAll().

void ArchitectureGhidra::readResponseEnd ( istream &  s)
static

Read the ending query response protocol marker.

Read the next protocol marker. If it does not indicate the end of a query response, throw an exception

Parameters
sis the input stream from the client

References readToAnyBurst().

Referenced by getBytes(), getCodeLabel(), getRegisterName(), getUserOpName(), isNameUsed(), readPackedAll(), and readXMLAll().

void ArchitectureGhidra::readStringStream ( istream &  s,
string &  res 
)
static

Receive a string from the client.

Characters are read up to the next protocol marked and placed into a string. The protocol marker is consumed and must indicate the end of a string or an exception is thrown.

Parameters
sis the input stream from the client
reswill hold the string

References readToAnyBurst().

Referenced by getCodeLabel(), getRegisterName(), getUserOpName(), RegisterProgram::loadParameters(), SetAction::loadParameters(), GhidraCapability::readCommand(), and readToResponse().

int4 ArchitectureGhidra::readToAnyBurst ( istream &  s)
static

Read the next message protocol marker.

All communications between the Ghidra client and the decompiler are surrounded by alignment bursts. A burst is 1 or more zero bytes followed by an 0x01 byte, then followed by a code byte. Open alignment (as in open paren) is even. Close alignment is odd. Code bytes are as follows:

  • Command open=2 close=3
  • Query open=4 close=5
  • Command response open=6 close=7
  • Query response open=8 close=9
  • Exception open=a close=b
  • Byte stream open=c close=d
  • String stream open=e close=f

The protocol is as follows:

  • ghidra sends a command
    • [ decompiler sends a query
    • ghidra sends a query response ] zero or more occurences
  • decompiler sends a command response

Commands, queries, and responses all consist of zero or more string streams or byte streams.

In place of any response an exception can be sent. The decompiler can interrupt a command response with a query or exception once the query is finished the response picks up where it left off an exception however permanently cancels the query. Ghidra cannot interrupt either of its responses.

Parameters
sis the input stream from the client
Returns
the command code

Referenced by GhidraCommand::doit(), getBytes(), GhidraCommand::loadParameters(), DeregisterProgram::loadParameters(), readBoolStream(), GhidraCapability::readCommand(), readPackedStream(), readResponseEnd(), readStringStream(), readToResponse(), and readXMLStream().

void ArchitectureGhidra::readToResponse ( istream &  s)
static

Read the query response protocol marker.

Consume the query response header. If it indicates an exception, read details of the exception and throw JavaError.

Parameters
sis the input stream from the client

References readStringStream(), and readToAnyBurst().

Referenced by getBytes(), getCodeLabel(), getRegisterName(), getUserOpName(), isNameUsed(), readPackedAll(), and readXMLAll().

Document * ArchitectureGhidra::readXMLAll ( istream &  s)
static

Read a whole response as an XML document.

Read up to the beginning of a query response, check for an exception record, otherwise read in a string as an XML document.

Parameters
sis the input stream from the client
Returns
the XML document

References readResponseEnd(), readToResponse(), and readXMLStream().

Referenced by getComments(), getCPoolRef(), getExternalRefXML(), getMappedSymbolsXML(), getNamespacePath(), getPcodeInject(), getRegister(), getTrackedRegisters(), and getType().

Document * ArchitectureGhidra::readXMLStream ( istream &  s)
static

Receive an XML document from the client.

The method expects to see protocol markers indicating a string from the client, otherwise it throws and exception. The string is read in and then parsed as XML.

Parameters
sis the input stream from the client.
Returns
the XML document

References readToAnyBurst(), and xml_tree().

Referenced by DecompileAt::loadParameters(), StructureGraph::loadParameters(), SetOptions::loadParameters(), and readXMLAll().

void ArchitectureGhidra::segvHandler ( int4  sig)
static

Handler for a segment violation (SIGSEGV) signal.

Catch the signal so the OS doesn't pop up a dialog

Parameters
sigis the OS signal (should always be SIGSEGV)

Referenced by GhidraDecompCapability::initialize().

void ArchitectureGhidra::setSendCCode ( bool  val)
inline

Toggle whether the recovered source code is emitted as part of the main decompile action.

If the toggle is on, the decompiler will emit source code (marked up in an XML document)

Parameters
valis true to enable emitting

Referenced by SetAction::rawAction().

void ArchitectureGhidra::setSendParamMeasures ( bool  val)
inline

Toggle whether recovered parameter information is emitted as part of the main decompile action.

If the toggle is on, the decompiler will emit a more detailed description of what it thinks the input parameters to the function are.

Parameters
valis true enable emitting

Referenced by SetAction::rawAction().

void ArchitectureGhidra::setSendSyntaxTree ( bool  val)
inline

Toggle whether the data-flow and control-flow is emitted as part of the main decompile action.

If the toggle is on, the decompiler will emit complete descriptions of the graphs.

Parameters
valis true to enable emitting

Referenced by SetAction::rawAction().

void ArchitectureGhidra::writeStringStream ( ostream &  s,
const string &  msg 
)
static

Send a string to the client.

Write out a string with correct protocol markers

Parameters
sis the output stream to the client
msgis the string to send

Referenced by getBytes(), getCodeLabel(), getComments(), getCPoolRef(), getExternalRefXML(), getMappedSymbolsXML(), getNamespacePath(), getPcodeInject(), getPcodePacked(), getRegister(), getRegisterName(), getTrackedRegisters(), getType(), getUserOpName(), isNameUsed(), passJavaException(), SetAction::sendResult(), and SetOptions::sendResult().


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